How to use state method in Cypress

Best JavaScript code snippet using cypress

loader.js

Source:loader.js Github

copy

Full Screen

1'use strict';2var common              = require('./common');3var YAMLException       = require('./exception');4var Mark                = require('./mark');5var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe');6var DEFAULT_FULL_SCHEMA = require('./schema/default_full');7var _hasOwnProperty = Object.prototype.hasOwnProperty;8var CONTEXT_FLOW_IN   = 1;9var CONTEXT_FLOW_OUT  = 2;10var CONTEXT_BLOCK_IN  = 3;11var CONTEXT_BLOCK_OUT = 4;12var CHOMPING_CLIP  = 1;13var CHOMPING_STRIP = 2;14var CHOMPING_KEEP  = 3;15var CHAR_TAB                  = 0x09;   /* Tab */16var CHAR_LINE_FEED            = 0x0A;   /* LF */17var CHAR_CARRIAGE_RETURN      = 0x0D;   /* CR */18var CHAR_SPACE                = 0x20;   /* Space */19var CHAR_EXCLAMATION          = 0x21;   /* ! */20var CHAR_DOUBLE_QUOTE         = 0x22;   /* " */21var CHAR_SHARP                = 0x23;   /* # */22var CHAR_PERCENT              = 0x25;   /* % */23var CHAR_AMPERSAND            = 0x26;   /* & */24var CHAR_SINGLE_QUOTE         = 0x27;   /* ' */25var CHAR_ASTERISK             = 0x2A;   /* * */26var CHAR_PLUS                 = 0x2B;   /* + */27var CHAR_COMMA                = 0x2C;   /* , */28var CHAR_MINUS                = 0x2D;   /* - */29var CHAR_DOT                  = 0x2E;   /* . */30var CHAR_SLASH                = 0x2F;   /* / */31var CHAR_DIGIT_ZERO           = 0x30;   /* 0 */32var CHAR_DIGIT_ONE            = 0x31;   /* 1 */33var CHAR_DIGIT_NINE           = 0x39;   /* 9 */34var CHAR_COLON                = 0x3A;   /* : */35var CHAR_LESS_THAN            = 0x3C;   /* < */36var CHAR_GREATER_THAN         = 0x3E;   /* > */37var CHAR_QUESTION             = 0x3F;   /* ? */38var CHAR_COMMERCIAL_AT        = 0x40;   /* @ */39var CHAR_CAPITAL_A            = 0x41;   /* A */40var CHAR_CAPITAL_F            = 0x46;   /* F */41var CHAR_CAPITAL_L            = 0x4C;   /* L */42var CHAR_CAPITAL_N            = 0x4E;   /* N */43var CHAR_CAPITAL_P            = 0x50;   /* P */44var CHAR_CAPITAL_U            = 0x55;   /* U */45var CHAR_LEFT_SQUARE_BRACKET  = 0x5B;   /* [ */46var CHAR_BACKSLASH            = 0x5C;   /* \ */47var CHAR_RIGHT_SQUARE_BRACKET = 0x5D;   /* ] */48var CHAR_UNDERSCORE           = 0x5F;   /* _ */49var CHAR_GRAVE_ACCENT         = 0x60;   /* ` */50var CHAR_SMALL_A              = 0x61;   /* a */51var CHAR_SMALL_B              = 0x62;   /* b */52var CHAR_SMALL_E              = 0x65;   /* e */53var CHAR_SMALL_F              = 0x66;   /* f */54var CHAR_SMALL_N              = 0x6E;   /* n */55var CHAR_SMALL_R              = 0x72;   /* r */56var CHAR_SMALL_T              = 0x74;   /* t */57var CHAR_SMALL_U              = 0x75;   /* u */58var CHAR_SMALL_V              = 0x76;   /* v */59var CHAR_SMALL_X              = 0x78;   /* x */60var CHAR_LEFT_CURLY_BRACKET   = 0x7B;   /* { */61var CHAR_VERTICAL_LINE        = 0x7C;   /* | */62var CHAR_RIGHT_CURLY_BRACKET  = 0x7D;   /* } */63var SIMPLE_ESCAPE_SEQUENCES = {};64SIMPLE_ESCAPE_SEQUENCES[CHAR_DIGIT_ZERO]   = '\x00';65SIMPLE_ESCAPE_SEQUENCES[CHAR_SMALL_A]      = '\x07';66SIMPLE_ESCAPE_SEQUENCES[CHAR_SMALL_B]      = '\x08';67SIMPLE_ESCAPE_SEQUENCES[CHAR_SMALL_T]      = '\x09';68SIMPLE_ESCAPE_SEQUENCES[CHAR_TAB]          = '\x09';69SIMPLE_ESCAPE_SEQUENCES[CHAR_SMALL_N]      = '\x0A';70SIMPLE_ESCAPE_SEQUENCES[CHAR_SMALL_V]      = '\x0B';71SIMPLE_ESCAPE_SEQUENCES[CHAR_SMALL_F]      = '\x0C';72SIMPLE_ESCAPE_SEQUENCES[CHAR_SMALL_R]      = '\x0D';73SIMPLE_ESCAPE_SEQUENCES[CHAR_SMALL_E]      = '\x1B';74SIMPLE_ESCAPE_SEQUENCES[CHAR_SPACE]        = ' ';75SIMPLE_ESCAPE_SEQUENCES[CHAR_DOUBLE_QUOTE] = '\x22';76SIMPLE_ESCAPE_SEQUENCES[CHAR_SLASH]        = '/';77SIMPLE_ESCAPE_SEQUENCES[CHAR_BACKSLASH]    = '\x5C';78SIMPLE_ESCAPE_SEQUENCES[CHAR_CAPITAL_N]    = '\x85';79SIMPLE_ESCAPE_SEQUENCES[CHAR_UNDERSCORE]   = '\xA0';80SIMPLE_ESCAPE_SEQUENCES[CHAR_CAPITAL_L]    = '\u2028';81SIMPLE_ESCAPE_SEQUENCES[CHAR_CAPITAL_P]    = '\u2029';82var HEXADECIMAL_ESCAPE_SEQUENCES = {};83HEXADECIMAL_ESCAPE_SEQUENCES[CHAR_SMALL_X]   = 2;84HEXADECIMAL_ESCAPE_SEQUENCES[CHAR_SMALL_U]   = 4;85HEXADECIMAL_ESCAPE_SEQUENCES[CHAR_CAPITAL_U] = 8;86var PATTERN_NON_PRINTABLE         = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uD800-\uDFFF\uFFFE\uFFFF]/;87var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;88var PATTERN_FLOW_INDICATORS       = /[,\[\]\{\}]/;89var PATTERN_TAG_HANDLE            = /^(?:!|!!|![a-z\-]+!)$/i;90var PATTERN_TAG_URI               = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;91function State(input, options) {92  this.input    = input;93  this.filename = options['filename'] || null;94  this.schema   = options['schema']   || DEFAULT_FULL_SCHEMA;95  this.strict   = options['strict']   || false;96  this.legacy   = options['legacy']   || false;97  this.implicitTypes     = this.schema.compiledImplicit;98  this.typeMap           = this.schema.compiledTypeMap;99  this.length     = input.length;100  this.position   = 0;101  this.line       = 0;102  this.lineStart  = 0;103  this.lineIndent = 0;104  this.character  = input.charCodeAt(0 /*position*/);105  /*106  this.version;107  this.checkLineBreaks;108  this.tagMap;109  this.anchorMap;110  this.tag;111  this.anchor;112  this.kind;113  this.result;*/114}115function generateError(state, message) {116  return new YAMLException(117    message,118    new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart)));119}120function throwError(state, message) {121  throw generateError(state, message);122}123function throwWarning(state, message) {124  var error = generateError(state, message);125  if (state.strict) {126    throw error;127  } else {128    console.warn(error.toString());129  }130}131var directiveHandlers = {132  'YAML': function handleYamlDirective(state, name, args) {133      var match, major, minor;134      if (null !== state.version) {135        throwError(state, 'duplication of %YAML directive');136      }137      if (1 !== args.length) {138        throwError(state, 'YAML directive accepts exactly one argument');139      }140      match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);141      if (null === match) {142        throwError(state, 'ill-formed argument of the YAML directive');143      }144      major = parseInt(match[1], 10);145      minor = parseInt(match[2], 10);146      if (1 !== major) {147        throwError(state, 'unacceptable YAML version of the document');148      }149      state.version = args[0];150      state.checkLineBreaks = (minor < 2);151      if (1 !== minor && 2 !== minor) {152        throwWarning(state, 'unsupported YAML version of the document');153      }154    },155  'TAG': function handleTagDirective(state, name, args) {156      var handle, prefix;157      if (2 !== args.length) {158        throwError(state, 'TAG directive accepts exactly two arguments');159      }160      handle = args[0];161      prefix = args[1];162      if (!PATTERN_TAG_HANDLE.test(handle)) {163        throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');164      }165      if (_hasOwnProperty.call(state.tagMap, handle)) {166        throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');167      }168      if (!PATTERN_TAG_URI.test(prefix)) {169        throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');170      }171      state.tagMap[handle] = prefix;172    }173};174function captureSegment(state, start, end, checkJson) {175  var _position, _length, _character, _result;176  if (start < end) {177    _result = state.input.slice(start, end);178    if (checkJson) {179      for (_position = 0, _length = _result.length;180           _position < _length;181           _position += 1) {182        _character = _result.charCodeAt(_position);183        if (!(0x09 === _character ||184              0x20 <= _character && _character <= 0x10FFFF)) {185          throwError(state, 'expected valid JSON character');186        }187      }188    }189    state.result += _result;190  }191}192function mergeMappings(state, destination, source) {193  var sourceKeys, key, index, quantity;194  if (!common.isObject(source)) {195    throwError(state, 'cannot merge mappings; the provided source object is unacceptable');196  }197  sourceKeys = Object.keys(source);198  for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {199    key = sourceKeys[index];200    if (!_hasOwnProperty.call(destination, key)) {201      destination[key] = source[key];202    }203  }204}205function storeMappingPair(state, _result, keyTag, keyNode, valueNode) {206  var index, quantity;207  keyNode = String(keyNode);208  if (null === _result) {209    _result = {};210  }211  if ('tag:yaml.org,2002:merge' === keyTag) {212    if (Array.isArray(valueNode)) {213      for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {214        mergeMappings(state, _result, valueNode[index]);215      }216    } else {217      mergeMappings(state, _result, valueNode);218    }219  } else {220    _result[keyNode] = valueNode;221  }222  return _result;223}224function readLineBreak(state) {225  if (CHAR_LINE_FEED === state.character) {226    state.position += 1;227  } else if (CHAR_CARRIAGE_RETURN === state.character) {228    if (CHAR_LINE_FEED === state.input.charCodeAt(state.position + 1)) {229      state.position += 2;230    } else {231      state.position += 1;232    }233  } else {234    throwError(state, 'a line break is expected');235  }236  state.line += 1;237  state.lineStart = state.position;238  state.character = state.input.charCodeAt(state.position);239}240function skipSeparationSpace(state, allowComments, checkIndent) {241  var lineBreaks = 0;242  while (state.position < state.length) {243    while (CHAR_SPACE === state.character || CHAR_TAB === state.character) {244      state.character = state.input.charCodeAt(++state.position);245    }246    if (allowComments && CHAR_SHARP === state.character) {247      do { state.character = state.input.charCodeAt(++state.position); }248      while (state.position < state.length &&249             CHAR_LINE_FEED !== state.character &&250             CHAR_CARRIAGE_RETURN !== state.character);251    }252    if (CHAR_LINE_FEED === state.character || CHAR_CARRIAGE_RETURN === state.character) {253      readLineBreak(state);254      lineBreaks += 1;255      state.lineIndent = 0;256      while (CHAR_SPACE === state.character) {257        state.lineIndent += 1;258        state.character = state.input.charCodeAt(++state.position);259      }260      if (state.lineIndent < checkIndent) {261        throwWarning(state, 'deficient indentation');262      }263    } else {264      break;265    }266  }267  return lineBreaks;268}269function testDocumentSeparator(state) {270  var _position, _character;271  if (state.position === state.lineStart &&272      (CHAR_MINUS === state.character || CHAR_DOT === state.character) &&273      state.input.charCodeAt(state.position + 1) === state.character &&274      state.input.charCodeAt(state.position + 2) === state.character) {275    _position = state.position + 3;276    _character = state.input.charCodeAt(_position);277    if (_position >= state.length ||278        CHAR_SPACE           === _character ||279        CHAR_TAB             === _character ||280        CHAR_LINE_FEED       === _character ||281        CHAR_CARRIAGE_RETURN === _character) {282      return true;283    }284  }285  return false;286}287function writeFoldedLines(state, count) {288  if (1 === count) {289    state.result += ' ';290  } else if (count > 1) {291    state.result += common.repeat('\n', count - 1);292  }293}294function readPlainScalar(state, nodeIndent, withinFlowCollection) {295  var preceding,296      following,297      captureStart,298      captureEnd,299      hasPendingContent,300      _line,301      _lineStart,302      _lineIndent,303      _kind = state.kind,304      _result = state.result;305  if (CHAR_SPACE                === state.character ||306      CHAR_TAB                  === state.character ||307      CHAR_LINE_FEED            === state.character ||308      CHAR_CARRIAGE_RETURN      === state.character ||309      CHAR_COMMA                === state.character ||310      CHAR_LEFT_SQUARE_BRACKET  === state.character ||311      CHAR_RIGHT_SQUARE_BRACKET === state.character ||312      CHAR_LEFT_CURLY_BRACKET   === state.character ||313      CHAR_RIGHT_CURLY_BRACKET  === state.character ||314      CHAR_SHARP                === state.character ||315      CHAR_AMPERSAND            === state.character ||316      CHAR_ASTERISK             === state.character ||317      CHAR_EXCLAMATION          === state.character ||318      CHAR_VERTICAL_LINE        === state.character ||319      CHAR_GREATER_THAN         === state.character ||320      CHAR_SINGLE_QUOTE         === state.character ||321      CHAR_DOUBLE_QUOTE         === state.character ||322      CHAR_PERCENT              === state.character ||323      CHAR_COMMERCIAL_AT        === state.character ||324      CHAR_GRAVE_ACCENT         === state.character) {325    return false;326  }327  if (CHAR_QUESTION === state.character ||328      CHAR_MINUS === state.character) {329    following = state.input.charCodeAt(state.position + 1);330    if (CHAR_SPACE                 === following ||331        CHAR_TAB                   === following ||332        CHAR_LINE_FEED             === following ||333        CHAR_CARRIAGE_RETURN       === following ||334        withinFlowCollection &&335        (CHAR_COMMA                === following ||336         CHAR_LEFT_SQUARE_BRACKET  === following ||337         CHAR_RIGHT_SQUARE_BRACKET === following ||338         CHAR_LEFT_CURLY_BRACKET   === following ||339         CHAR_RIGHT_CURLY_BRACKET  === following)) {340      return false;341    }342  }343  state.kind = 'scalar';344  state.result = '';345  captureStart = captureEnd = state.position;346  hasPendingContent = false;347  while (state.position < state.length) {348    if (CHAR_COLON === state.character) {349      following = state.input.charCodeAt(state.position + 1);350      if (CHAR_SPACE                 === following ||351          CHAR_TAB                   === following ||352          CHAR_LINE_FEED             === following ||353          CHAR_CARRIAGE_RETURN       === following ||354          withinFlowCollection &&355          (CHAR_COMMA                === following ||356           CHAR_LEFT_SQUARE_BRACKET  === following ||357           CHAR_RIGHT_SQUARE_BRACKET === following ||358           CHAR_LEFT_CURLY_BRACKET   === following ||359           CHAR_RIGHT_CURLY_BRACKET  === following)) {360        break;361      }362    } else if (CHAR_SHARP === state.character) {363      preceding = state.input.charCodeAt(state.position - 1);364      if (CHAR_SPACE           === preceding ||365          CHAR_TAB             === preceding ||366          CHAR_LINE_FEED       === preceding ||367          CHAR_CARRIAGE_RETURN === preceding) {368        break;369      }370    } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||371               withinFlowCollection &&372               (CHAR_COMMA                === state.character ||373                CHAR_LEFT_SQUARE_BRACKET  === state.character ||374                CHAR_RIGHT_SQUARE_BRACKET === state.character ||375                CHAR_LEFT_CURLY_BRACKET   === state.character ||376                CHAR_RIGHT_CURLY_BRACKET  === state.character)) {377      break;378    } else if (CHAR_LINE_FEED === state.character ||379               CHAR_CARRIAGE_RETURN === state.character) {380      _line = state.line;381      _lineStart = state.lineStart;382      _lineIndent = state.lineIndent;383      skipSeparationSpace(state, false, -1);384      if (state.lineIndent >= nodeIndent) {385        hasPendingContent = true;386        continue;387      } else {388        state.position = captureEnd;389        state.line = _line;390        state.lineStart = _lineStart;391        state.lineIndent = _lineIndent;392        state.character = state.input.charCodeAt(state.position);393        break;394      }395    }396    if (hasPendingContent) {397      captureSegment(state, captureStart, captureEnd, false);398      writeFoldedLines(state, state.line - _line);399      captureStart = captureEnd = state.position;400      hasPendingContent = false;401    }402    if (CHAR_SPACE !== state.character && CHAR_TAB !== state.character) {403      captureEnd = state.position + 1;404    }405    state.character = state.input.charCodeAt(++state.position);406  }407  captureSegment(state, captureStart, captureEnd, false);408  if (state.result) {409    return true;410  } else {411    state.kind = _kind;412    state.result = _result;413    return false;414  }415}416function readSingleQuotedScalar(state, nodeIndent) {417  var captureStart, captureEnd;418  if (CHAR_SINGLE_QUOTE !== state.character) {419    return false;420  }421  state.kind = 'scalar';422  state.result = '';423  state.character = state.input.charCodeAt(++state.position);424  captureStart = captureEnd = state.position;425  while (state.position < state.length) {426    if (CHAR_SINGLE_QUOTE === state.character) {427      captureSegment(state, captureStart, state.position, true);428      state.character = state.input.charCodeAt(++state.position);429      if (CHAR_SINGLE_QUOTE === state.character) {430        captureStart = captureEnd = state.position;431        state.character = state.input.charCodeAt(++state.position);432      } else {433        return true;434      }435    } else if (CHAR_LINE_FEED === state.character ||436               CHAR_CARRIAGE_RETURN === state.character) {437      captureSegment(state, captureStart, captureEnd, true);438      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));439      captureStart = captureEnd = state.position;440      state.character = state.input.charCodeAt(state.position);441    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {442      throwError(state, 'unexpected end of the document within a single quoted scalar');443    } else {444      state.character = state.input.charCodeAt(++state.position);445      captureEnd = state.position;446    }447  }448  throwError(state, 'unexpected end of the stream within a single quoted scalar');449}450function readDoubleQuotedScalar(state, nodeIndent) {451  var captureStart,452      captureEnd,453      hexLength,454      hexIndex,455      hexOffset,456      hexResult;457  if (CHAR_DOUBLE_QUOTE !== state.character) {458    return false;459  }460  state.kind = 'scalar';461  state.result = '';462  state.character = state.input.charCodeAt(++state.position);463  captureStart = captureEnd = state.position;464  while (state.position < state.length) {465    if (CHAR_DOUBLE_QUOTE === state.character) {466      captureSegment(state, captureStart, state.position, true);467      state.character = state.input.charCodeAt(++state.position);468      return true;469    } else if (CHAR_BACKSLASH === state.character) {470      captureSegment(state, captureStart, state.position, true);471      state.character = state.input.charCodeAt(++state.position);472      if (CHAR_LINE_FEED       === state.character ||473          CHAR_CARRIAGE_RETURN === state.character) {474        skipSeparationSpace(state, false, nodeIndent);475      } else if (SIMPLE_ESCAPE_SEQUENCES[state.character]) {476        state.result += SIMPLE_ESCAPE_SEQUENCES[state.character];477        state.character = state.input.charCodeAt(++state.position);478      } else if (HEXADECIMAL_ESCAPE_SEQUENCES[state.character]) {479        hexLength = HEXADECIMAL_ESCAPE_SEQUENCES[state.character];480        hexResult = 0;481        for (hexIndex = 1; hexIndex <= hexLength; hexIndex += 1) {482          hexOffset = (hexLength - hexIndex) * 4;483          state.character = state.input.charCodeAt(++state.position);484          if (CHAR_DIGIT_ZERO <= state.character && state.character <= CHAR_DIGIT_NINE) {485            hexResult |= (state.character - CHAR_DIGIT_ZERO) << hexOffset;486          } else if (CHAR_CAPITAL_A <= state.character && state.character <= CHAR_CAPITAL_F) {487            hexResult |= (state.character - CHAR_CAPITAL_A + 10) << hexOffset;488          } else if (CHAR_SMALL_A <= state.character && state.character <= CHAR_SMALL_F) {489            hexResult |= (state.character - CHAR_SMALL_A + 10) << hexOffset;490          } else {491            throwError(state, 'expected hexadecimal character');492          }493        }494        state.result += String.fromCharCode(hexResult);495        state.character = state.input.charCodeAt(++state.position);496      } else {497        throwError(state, 'unknown escape sequence');498      }499      captureStart = captureEnd = state.position;500    } else if (CHAR_LINE_FEED === state.character ||501               CHAR_CARRIAGE_RETURN === state.character) {502      captureSegment(state, captureStart, captureEnd, true);503      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));504      captureStart = captureEnd = state.position;505      state.character = state.input.charCodeAt(state.position);506    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {507      throwError(state, 'unexpected end of the document within a double quoted scalar');508    } else {509      state.character = state.input.charCodeAt(++state.position);510      captureEnd = state.position;511    }512  }513  throwError(state, 'unexpected end of the stream within a double quoted scalar');514}515function readFlowCollection(state, nodeIndent) {516  var readNext = true,517      _line,518      _tag     = state.tag,519      _result,520      following,521      terminator,522      isPair,523      isExplicitPair,524      isMapping,525      keyNode,526      keyTag,527      valueNode;528  switch (state.character) {529  case CHAR_LEFT_SQUARE_BRACKET:530    terminator = CHAR_RIGHT_SQUARE_BRACKET;531    isMapping = false;532    _result = [];533    break;534  case CHAR_LEFT_CURLY_BRACKET:535    terminator = CHAR_RIGHT_CURLY_BRACKET;536    isMapping = true;537    _result = {};538    break;539  default:540    return false;541  }542  if (null !== state.anchor) {543    state.anchorMap[state.anchor] = _result;544  }545  state.character = state.input.charCodeAt(++state.position);546  while (state.position < state.length) {547    skipSeparationSpace(state, true, nodeIndent);548    if (state.character === terminator) {549      state.character = state.input.charCodeAt(++state.position);550      state.tag = _tag;551      state.kind = isMapping ? 'mapping' : 'sequence';552      state.result = _result;553      return true;554    } else if (!readNext) {555      throwError(state, 'missed comma between flow collection entries');556    }557    keyTag = keyNode = valueNode = null;558    isPair = isExplicitPair = false;559    if (CHAR_QUESTION === state.character) {560      following = state.input.charCodeAt(state.position + 1);561      if (CHAR_SPACE === following ||562          CHAR_TAB === following ||563          CHAR_LINE_FEED === following ||564          CHAR_CARRIAGE_RETURN === following) {565        isPair = isExplicitPair = true;566        state.position += 1;567        state.character = following;568        skipSeparationSpace(state, true, nodeIndent);569      }570    }571    _line = state.line;572    composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);573    keyTag = state.tag;574    keyNode = state.result;575    skipSeparationSpace(state, true, nodeIndent);576    if ((isExplicitPair || state.line === _line) && CHAR_COLON === state.character) {577      isPair = true;578      state.character = state.input.charCodeAt(++state.position);579      skipSeparationSpace(state, true, nodeIndent);580      composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);581      valueNode = state.result;582    }583    if (isMapping) {584      storeMappingPair(state, _result, keyTag, keyNode, valueNode);585    } else if (isPair) {586      _result.push(storeMappingPair(state, null, keyTag, keyNode, valueNode));587    } else {588      _result.push(keyNode);589    }590    skipSeparationSpace(state, true, nodeIndent);591    if (CHAR_COMMA === state.character) {592      readNext = true;593      state.character = state.input.charCodeAt(++state.position);594    } else {595      readNext = false;596    }597  }598  throwError(state, 'unexpected end of the stream within a flow collection');599}600function readBlockScalar(state, nodeIndent) {601  var captureStart,602      folding,603      chomping       = CHOMPING_CLIP,604      detectedIndent = false,605      textIndent     = nodeIndent,606      emptyLines     = 0,607      atMoreIndented = false;608  switch (state.character) {609  case CHAR_VERTICAL_LINE:610    folding = false;611    break;612  case CHAR_GREATER_THAN:613    folding = true;614    break;615  default:616    return false;617  }618  state.kind = 'scalar';619  state.result = '';620  while (state.position < state.length) {621    state.character = state.input.charCodeAt(++state.position);622    if (CHAR_PLUS === state.character || CHAR_MINUS === state.character) {623      if (CHOMPING_CLIP === chomping) {624        chomping = (CHAR_PLUS === state.character) ? CHOMPING_KEEP : CHOMPING_STRIP;625      } else {626        throwError(state, 'repeat of a chomping mode identifier');627      }628    } else if (CHAR_DIGIT_ZERO <= state.character && state.character <= CHAR_DIGIT_NINE) {629      if (CHAR_DIGIT_ZERO === state.character) {630        throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');631      } else if (!detectedIndent) {632        textIndent = nodeIndent + (state.character - CHAR_DIGIT_ONE);633        detectedIndent = true;634      } else {635        throwError(state, 'repeat of an indentation width identifier');636      }637    } else {638      break;639    }640  }641  if (CHAR_SPACE === state.character || CHAR_TAB === state.character) {642    do { state.character = state.input.charCodeAt(++state.position); }643    while (CHAR_SPACE === state.character || CHAR_TAB === state.character);644    if (CHAR_SHARP === state.character) {645      do { state.character = state.input.charCodeAt(++state.position); }646      while (state.position < state.length &&647             CHAR_LINE_FEED !== state.character &&648             CHAR_CARRIAGE_RETURN !== state.character);649    }650  }651  while (state.position < state.length) {652    readLineBreak(state);653    state.lineIndent = 0;654    while ((!detectedIndent || state.lineIndent < textIndent) &&655           (CHAR_SPACE === state.character)) {656      state.lineIndent += 1;657      state.character = state.input.charCodeAt(++state.position);658    }659    if (!detectedIndent && state.lineIndent > textIndent) {660      textIndent = state.lineIndent;661    }662    if (CHAR_LINE_FEED === state.character || CHAR_CARRIAGE_RETURN === state.character) {663      emptyLines += 1;664      continue;665    }666    // End of the scalar.667    if (state.lineIndent < textIndent) {668      // Perform the chomping.669      switch (chomping) {670      case CHOMPING_KEEP:671        state.result += common.repeat('\n', emptyLines);672        break;673      case CHOMPING_CLIP:674        if (detectedIndent) { // i.e. only if the scalar is not empty.675          state.result += '\n';676        }677        break;678      }679      // Break this `while` cycle and go to the funciton's epilogue.680      break;681    }682    // Folded style: use fancy rules to handle line breaks.683    if (folding) {684      // Lines starting with white space characters (more-indented lines) are not folded.685      if (CHAR_SPACE === state.character || CHAR_TAB === state.character) {686        atMoreIndented = true;687        state.result += common.repeat('\n', emptyLines + 1);688      // End of more-indented block.689      } else if (atMoreIndented) {690        atMoreIndented = false;691        state.result += common.repeat('\n', emptyLines + 1);692      // Just one line break - perceive as the same line.693      } else if (0 === emptyLines) {694        if (detectedIndent) { // i.e. only if we have already read some scalar content.695          state.result += ' ';696        }697      // Several line breaks - perceive as different lines.698      } else {699        state.result += common.repeat('\n', emptyLines);700      }701    // Literal style: just add exact number of line breaks between content lines.702    } else {703      // If current line isn't the first one - count line break from the last content line.704      if (detectedIndent) {705        state.result += common.repeat('\n', emptyLines + 1);706      // In case of the first content line - count only empty lines.707      } else {708        state.result += common.repeat('\n', emptyLines);709      }710    }711    detectedIndent = true;712    emptyLines = 0;713    captureStart = state.position;714    do { state.character = state.input.charCodeAt(++state.position); }715    while (state.position < state.length &&716           CHAR_LINE_FEED !== state.character &&717           CHAR_CARRIAGE_RETURN !== state.character);718    captureSegment(state, captureStart, state.position, false);719  }720  return true;721}722function readBlockSequence(state, nodeIndent) {723  var _line,724      _tag      = state.tag,725      _result   = [],726      following,727      detected  = false;728  if (null !== state.anchor) {729    state.anchorMap[state.anchor] = _result;730  }731  while (state.position < state.length) {732    if (CHAR_MINUS !== state.character) {733      break;734    }735    following = state.input.charCodeAt(state.position + 1);736    if (CHAR_SPACE           !== following &&737        CHAR_TAB             !== following &&738        CHAR_LINE_FEED       !== following &&739        CHAR_CARRIAGE_RETURN !== following) {740      break;741    }742    detected = true;743    state.position += 1;744    state.character = following;745    if (skipSeparationSpace(state, true, -1)) {746      if (state.lineIndent <= nodeIndent) {747        _result.push(null);748        continue;749      }750    }751    _line = state.line;752    composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);753    _result.push(state.result);754    skipSeparationSpace(state, true, -1);755    if ((state.line === _line || state.lineIndent > nodeIndent) && state.position < state.length) {756      throwError(state, 'bad indentation of a sequence entry');757    } else if (state.lineIndent < nodeIndent) {758      break;759    }760  }761  if (detected) {762    state.tag = _tag;763    state.kind = 'sequence';764    state.result = _result;765    return true;766  } else {767    return false;768  }769}770function readBlockMapping(state, nodeIndent) {771  var following,772      allowCompact,773      _line,774      _tag          = state.tag,775      _result       = {},776      keyTag        = null,777      keyNode       = null,778      valueNode     = null,779      atExplicitKey = false,780      detected      = false;781  if (null !== state.anchor) {782    state.anchorMap[state.anchor] = _result;783  }784  while (state.position < state.length) {785    following = state.input.charCodeAt(state.position + 1);786    _line = state.line; // Save the current line.787    //788    // Explicit notation case. There are two separate blocks:789    // first for the key (denoted by "?") and second for the value (denoted by ":")790    //791    if ((CHAR_QUESTION        === state.character ||792         CHAR_COLON           === state.character) &&793        (CHAR_SPACE           === following ||794         CHAR_TAB             === following ||795         CHAR_LINE_FEED       === following ||796         CHAR_CARRIAGE_RETURN === following)) {797      if (CHAR_QUESTION === state.character) {798        if (atExplicitKey) {799          storeMappingPair(state, _result, keyTag, keyNode, null);800          keyTag = keyNode = valueNode = null;801        }802        detected = true;803        atExplicitKey = true;804        allowCompact = true;805      } else if (atExplicitKey) {806        // i.e. CHAR_COLON === character after the explicit key.807        atExplicitKey = false;808        allowCompact = true;809      } else {810        throwError(state, 'incomplete explicit mapping pair; a key node is missed');811      }812      state.position += 1;813      state.character = following;814    //815    // Implicit notation case. Flow-style node as the key first, then ":", and the value.816    //817    } else if (composeNode(state, nodeIndent, CONTEXT_FLOW_OUT, false, true)) {818      if (state.line === _line) {819        while (CHAR_SPACE === state.character ||820               CHAR_TAB === state.character) {821          state.character = state.input.charCodeAt(++state.position);822        }823        if (CHAR_COLON === state.character) {824          state.character = state.input.charCodeAt(++state.position);825          if (CHAR_SPACE           !== state.character &&826              CHAR_TAB             !== state.character &&827              CHAR_LINE_FEED       !== state.character &&828              CHAR_CARRIAGE_RETURN !== state.character) {829            throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');830          }831          if (atExplicitKey) {832            storeMappingPair(state, _result, keyTag, keyNode, null);833            keyTag = keyNode = valueNode = null;834          }835          detected = true;836          atExplicitKey = false;837          allowCompact = false;838          keyTag = state.tag;839          keyNode = state.result;840        } else if (detected) {841          throwError(state, 'can not read an implicit mapping pair; a colon is missed');842        } else {843          state.tag = _tag;844          return true; // Keep the result of `composeNode`.845        }846      } else if (detected) {847        throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');848      } else {849        state.tag = _tag;850        return true; // Keep the result of `composeNode`.851      }852    } else {853      break; // Reading is done. Go to the epilogue.854    }855    //856    // Common reading code for both explicit and implicit notations.857    //858    if (state.line === _line || state.lineIndent > nodeIndent) {859      if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {860        if (atExplicitKey) {861          keyNode = state.result;862        } else {863          valueNode = state.result;864        }865      }866      if (!atExplicitKey) {867        storeMappingPair(state, _result, keyTag, keyNode, valueNode);868        keyTag = keyNode = valueNode = null;869      }870      skipSeparationSpace(state, true, -1);871    }872    if (state.lineIndent > nodeIndent && state.position < state.length) {873      throwError(state, 'bad indentation of a mapping entry');874    } else if (state.lineIndent < nodeIndent) {875      break;876    }877  }878  //879  // Epilogue.880  //881  // Special case: last mapping's node contains only the key in explicit notation.882  if (atExplicitKey) {883    storeMappingPair(state, _result, keyTag, keyNode, null);884  }885  // Expose the resulting mapping.886  if (detected) {887    state.tag = _tag;888    state.kind = 'mapping';889    state.result = _result;890  }891  return detected;892}893function readTagProperty(state) {894  var _position,895      isVerbatim = false,896      isNamed    = false,897      tagHandle,898      tagName;899  if (CHAR_EXCLAMATION !== state.character) {900    return false;901  }902  if (null !== state.tag) {903    throwError(state, 'duplication of a tag property');904  }905  state.character = state.input.charCodeAt(++state.position);906  if (CHAR_LESS_THAN === state.character) {907    isVerbatim = true;908    state.character = state.input.charCodeAt(++state.position);909  } else if (CHAR_EXCLAMATION === state.character) {910    isNamed = true;911    tagHandle = '!!';912    state.character = state.input.charCodeAt(++state.position);913  } else {914    tagHandle = '!';915  }916  _position = state.position;917  if (isVerbatim) {918    do { state.character = state.input.charCodeAt(++state.position); }919    while (state.position < state.length && CHAR_GREATER_THAN !== state.character);920    if (state.position < state.length) {921      tagName = state.input.slice(_position, state.position);922      state.character = state.input.charCodeAt(++state.position);923    } else {924      throwError(state, 'unexpected end of the stream within a verbatim tag');925    }926  } else {927    while (state.position < state.length &&928           CHAR_SPACE           !== state.character &&929           CHAR_TAB             !== state.character &&930           CHAR_LINE_FEED       !== state.character &&931           CHAR_CARRIAGE_RETURN !== state.character) {932      if (CHAR_EXCLAMATION === state.character) {933        if (!isNamed) {934          tagHandle = state.input.slice(_position - 1, state.position + 1);935          if (!PATTERN_TAG_HANDLE.test(tagHandle)) {936            throwError(state, 'named tag handle cannot contain such characters');937          }938          isNamed = true;939          _position = state.position + 1;940        } else {941          throwError(state, 'tag suffix cannot contain exclamation marks');942        }943      }944      state.character = state.input.charCodeAt(++state.position);945    }946    tagName = state.input.slice(_position, state.position);947    if (PATTERN_FLOW_INDICATORS.test(tagName)) {948      throwError(state, 'tag suffix cannot contain flow indicator characters');949    }950  }951  if (tagName && !PATTERN_TAG_URI.test(tagName)) {952    throwError(state, 'tag name cannot contain such characters: ' + tagName);953  }954  if (isVerbatim) {955    state.tag = tagName;956  } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {957    state.tag = state.tagMap[tagHandle] + tagName;958  } else if ('!' === tagHandle) {959    state.tag = '!' + tagName;960  } else if ('!!' === tagHandle) {961    state.tag = 'tag:yaml.org,2002:' + tagName;962  } else {963    throwError(state, 'undeclared tag handle "' + tagHandle + '"');964  }965  return true;966}967function readAnchorProperty(state) {968  var _position;969  if (CHAR_AMPERSAND !== state.character) {970    return false;971  }972  if (null !== state.anchor) {973    throwError(state, 'duplication of an anchor property');974  }975  state.character = state.input.charCodeAt(++state.position);976  _position = state.position;977  while (state.position < state.length &&978         CHAR_SPACE                !== state.character &&979         CHAR_TAB                  !== state.character &&980         CHAR_LINE_FEED            !== state.character &&981         CHAR_CARRIAGE_RETURN      !== state.character &&982         CHAR_COMMA                !== state.character &&983         CHAR_LEFT_SQUARE_BRACKET  !== state.character &&984         CHAR_RIGHT_SQUARE_BRACKET !== state.character &&985         CHAR_LEFT_CURLY_BRACKET   !== state.character &&986         CHAR_RIGHT_CURLY_BRACKET  !== state.character) {987    state.character = state.input.charCodeAt(++state.position);988  }989  if (state.position === _position) {990    throwError(state, 'name of an anchor node must contain at least one character');991  }992  state.anchor = state.input.slice(_position, state.position);993  return true;994}995function readAlias(state) {996  var _position, alias;997  if (CHAR_ASTERISK !== state.character) {998    return false;999  }1000  state.character = state.input.charCodeAt(++state.position);1001  _position = state.position;1002  while (state.position < state.length &&1003         CHAR_SPACE                !== state.character &&1004         CHAR_TAB                  !== state.character &&1005         CHAR_LINE_FEED            !== state.character &&1006         CHAR_CARRIAGE_RETURN      !== state.character &&1007         CHAR_COMMA                !== state.character &&1008         CHAR_LEFT_SQUARE_BRACKET  !== state.character &&1009         CHAR_RIGHT_SQUARE_BRACKET !== state.character &&1010         CHAR_LEFT_CURLY_BRACKET   !== state.character &&1011         CHAR_RIGHT_CURLY_BRACKET  !== state.character) {1012    state.character = state.input.charCodeAt(++state.position);1013  }1014  if (state.position === _position) {1015    throwError(state, 'name of an alias node must contain at least one character');1016  }1017  alias = state.input.slice(_position, state.position);1018  if (!state.anchorMap.hasOwnProperty(alias)) {1019    throwError(state, 'unidentified alias "' + alias + '"');1020  }1021  state.result = state.anchorMap[alias];1022  skipSeparationSpace(state, true, -1);1023  return true;1024}1025function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {1026  var allowBlockStyles,1027      allowBlockScalars,1028      allowBlockCollections,1029      atNewLine  = false,1030      isIndented = true,1031      hasContent = false,1032      typeIndex,1033      typeQuantity,1034      type,1035      flowIndent,1036      blockIndent,1037      _result;1038  state.tag    = null;1039  state.anchor = null;1040  state.kind   = null;1041  state.result = null;1042  allowBlockStyles = allowBlockScalars = allowBlockCollections =1043    CONTEXT_BLOCK_OUT === nodeContext ||1044    CONTEXT_BLOCK_IN  === nodeContext;1045  if (allowToSeek) {1046    if (skipSeparationSpace(state, true, -1)) {1047      atNewLine = true;1048      if (state.lineIndent === parentIndent) {1049        isIndented = false;1050      } else if (state.lineIndent > parentIndent) {1051        isIndented = true;1052      } else {1053        return false;1054      }1055    }1056  }1057  if (isIndented) {1058    while (readTagProperty(state) || readAnchorProperty(state)) {1059      if (skipSeparationSpace(state, true, -1)) {1060        atNewLine = true;1061        if (state.lineIndent > parentIndent) {1062          isIndented = true;1063          allowBlockCollections = allowBlockStyles;1064        } else if (state.lineIndent === parentIndent) {1065          isIndented = false;1066          allowBlockCollections = allowBlockStyles;1067        } else {1068          return true;1069        }1070      } else {1071        allowBlockCollections = false;1072      }1073    }1074  }1075  if (allowBlockCollections) {1076    allowBlockCollections = atNewLine || allowCompact;1077  }1078  if (isIndented || CONTEXT_BLOCK_OUT === nodeContext) {1079    if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {1080      flowIndent = parentIndent;1081    } else {1082      flowIndent = parentIndent + 1;1083    }1084    blockIndent = state.position - state.lineStart;1085    if (isIndented) {1086      if (allowBlockCollections &&1087          (readBlockSequence(state, blockIndent) ||1088           readBlockMapping(state, blockIndent)) ||1089          readFlowCollection(state, flowIndent)) {1090        hasContent = true;1091      } else {1092        if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||1093            readSingleQuotedScalar(state, flowIndent) ||1094            readDoubleQuotedScalar(state, flowIndent)) {1095          hasContent = true;1096        } else if (readAlias(state)) {1097          hasContent = true;1098          if (null !== state.tag || null !== state.anchor) {1099            throwError(state, 'alias node should not have any properties');1100          }1101        } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {1102          hasContent = true;1103          if (null === state.tag) {1104            state.tag = '?';1105          }1106        }1107        if (null !== state.anchor) {1108          state.anchorMap[state.anchor] = state.result;1109        }1110      }1111    } else {1112      hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);1113    }1114  }1115  if (null !== state.tag && '!' !== state.tag) {1116    if ('?' === state.tag) {1117      for (typeIndex = 0, typeQuantity = state.implicitTypes.length;1118           typeIndex < typeQuantity;1119           typeIndex += 1) {1120        type = state.implicitTypes[typeIndex];1121        // Implicit resolving is not allowed for non-scalar types, and '?'1122        // non-specific tag is only assigned to plain scalars. So, it isn't1123        // needed to check for 'kind' conformity.1124        if (type.loadResolver && type.loadResolver(state)) { // `state.result` updated in resolver if matched1125          state.tag = type.tag;1126          break;1127        }1128      }1129    } else if (_hasOwnProperty.call(state.typeMap, state.tag)) {1130      type = state.typeMap[state.tag];1131      if (null !== state.result && type.loadKind !== state.kind) {1132        throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.loadKind + '", not "' + state.kind + '"');1133      }1134      if (type.loadResolver && !type.loadResolver(state)) { // `state.result` updated in resolver if matched1135        throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');1136      }1137    } else {1138      throwWarning(state, 'unknown tag !<' + state.tag + '>');1139    }1140  }1141  return null !== state.tag || null !== state.anchor || hasContent;1142}1143function readDocument(state, iterator) {1144  var documentStart = state.position,1145      _position,1146      directiveName,1147      directiveArgs,1148      hasDirectives = false;1149  state.version = null;1150  state.checkLineBreaks = state.legacy;1151  state.tagMap = {};1152  state.anchorMap = {};1153  while (state.position < state.length) {1154    skipSeparationSpace(state, true, -1);1155    if (state.lineIndent > 0 || CHAR_PERCENT !== state.character) {1156      break;1157    }1158    hasDirectives = true;1159    state.character = state.input.charCodeAt(++state.position);1160    _position = state.position;1161    while (state.position < state.length &&1162           CHAR_SPACE           !== state.character &&1163           CHAR_TAB             !== state.character &&1164           CHAR_LINE_FEED       !== state.character &&1165           CHAR_CARRIAGE_RETURN !== state.character) {1166      state.character = state.input.charCodeAt(++state.position);1167    }1168    directiveName = state.input.slice(_position, state.position);1169    directiveArgs = [];1170    if (directiveName.length < 1) {1171      throwError(state, 'directive name must not be less than one character in length');1172    }1173    while (state.position < state.length) {1174      while (CHAR_SPACE === state.character || CHAR_TAB === state.character) {1175        state.character = state.input.charCodeAt(++state.position);1176      }1177      if (CHAR_SHARP === state.character) {1178        do { state.character = state.input.charCodeAt(++state.position); }1179        while (state.position < state.length &&1180               CHAR_LINE_FEED !== state.character &&1181               CHAR_CARRIAGE_RETURN !== state.character);1182        break;1183      }1184      if (CHAR_LINE_FEED === state.character || CHAR_CARRIAGE_RETURN === state.character) {1185        break;1186      }1187      _position = state.position;1188      while (state.position < state.length &&1189             CHAR_SPACE           !== state.character &&1190             CHAR_TAB             !== state.character &&1191             CHAR_LINE_FEED       !== state.character &&1192             CHAR_CARRIAGE_RETURN !== state.character) {1193        state.character = state.input.charCodeAt(++state.position);1194      }1195      directiveArgs.push(state.input.slice(_position, state.position));1196    }1197    if (state.position < state.length) {1198      readLineBreak(state);1199    }1200    if (_hasOwnProperty.call(directiveHandlers, directiveName)) {1201      directiveHandlers[directiveName](state, directiveName, directiveArgs);1202    } else {1203      throwWarning(state, 'unknown document directive "' + directiveName + '"');1204    }1205  }1206  skipSeparationSpace(state, true, -1);1207  if (0 === state.lineIndent &&1208      CHAR_MINUS === state.character &&1209      CHAR_MINUS === state.input.charCodeAt(state.position + 1) &&1210      CHAR_MINUS === state.input.charCodeAt(state.position + 2)) {1211    state.position += 3;1212    state.character = state.input.charCodeAt(state.position);1213    skipSeparationSpace(state, true, -1);1214  } else if (hasDirectives) {1215    throwError(state, 'directives end mark is expected');1216  }1217  composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);1218  skipSeparationSpace(state, true, -1);1219  if (state.checkLineBreaks &&1220      PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {1221    throwWarning(state, 'non-ASCII line breaks are interpreted as content');1222  }1223  iterator(state.result);1224  if (state.position === state.lineStart && testDocumentSeparator(state)) {1225    if (CHAR_DOT === state.character) {1226      state.position += 3;1227      state.character = state.input.charCodeAt(state.position);1228      skipSeparationSpace(state, true, -1);1229    }1230    return;1231  }1232  if (state.position < state.length) {1233    throwError(state, 'end of the stream or a document separator is expected');1234  } else {1235    return;1236  }1237}1238function loadAll(input, iterator, options) {1239  options = options || {};1240  var state = new State(input, options);1241  if (PATTERN_NON_PRINTABLE.test(state.input)) {1242    throwError(state, 'the stream contains non-printable characters');1243  }1244  while (CHAR_SPACE === state.character) {1245    state.lineIndent += 1;1246    state.character = state.input.charCodeAt(++state.position);1247  }1248  while (state.position < state.length) {1249    readDocument(state, iterator);1250  }1251}1252function load(input, options) {1253  var result = null, received = false;1254  function iterator(data) {1255    if (!received) {1256      result = data;1257      received = true;1258    } else {1259      throw new YAMLException('expected a single document in the stream, but found more');1260    }1261  }1262  loadAll(input, iterator, options);1263  return result;1264}1265function safeLoadAll(input, output, options) {1266  loadAll(input, output, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));1267}1268function safeLoad(input, options) {1269  return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options));1270}1271module.exports.loadAll     = loadAll;1272module.exports.load        = load;1273module.exports.safeLoadAll = safeLoadAll;...

Full Screen

Full Screen

soy.js

Source:soy.js Github

copy

Full Screen

1// CodeMirror, copyright (c) by Marijn Haverbeke and others2// Distributed under an MIT license: https://codemirror.net/LICENSE3(function(mod) {4  if (typeof exports == "object" && typeof module == "object") // CommonJS5    mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"));6  else if (typeof define == "function" && define.amd) // AMD7    define(["../../lib/codemirror", "../htmlmixed/htmlmixed"], mod);8  else // Plain browser env9    mod(CodeMirror);10})(function(CodeMirror) {11  "use strict";12  var paramData = { noEndTag: true, soyState: "param-def" };13  var tags = {14    "alias": { noEndTag: true },15    "delpackage": { noEndTag: true },16    "namespace": { noEndTag: true, soyState: "namespace-def" },17    "@attribute": paramData,18    "@attribute?": paramData,19    "@param": paramData,20    "@param?": paramData,21    "@inject": paramData,22    "@inject?": paramData,23    "@state": paramData,24    "template": { soyState: "templ-def", variableScope: true},25    "extern": {soyState: "param-def"},26    "export": {soyState: "export"},27    "literal": { },28    "msg": {},29    "fallbackmsg": { noEndTag: true, reduceIndent: true},30    "select": {},31    "plural": {},32    "let": { soyState: "var-def" },33    "if": {},34    "javaimpl": {},35    "jsimpl": {},36    "elseif": { noEndTag: true, reduceIndent: true},37    "else": { noEndTag: true, reduceIndent: true},38    "switch": {},39    "case": { noEndTag: true, reduceIndent: true},40    "default": { noEndTag: true, reduceIndent: true},41    "foreach": { variableScope: true, soyState: "for-loop" },42    "ifempty": { noEndTag: true, reduceIndent: true},43    "for": { variableScope: true, soyState: "for-loop" },44    "call": { soyState: "templ-ref" },45    "param": { soyState: "param-ref"},46    "print": { noEndTag: true },47    "deltemplate": { soyState: "templ-def", variableScope: true},48    "delcall": { soyState: "templ-ref" },49    "log": {},50    "element": { variableScope: true },51    "velog": {},52    "const": { soyState: "const-def"},53  };54  var indentingTags = Object.keys(tags).filter(function(tag) {55    return !tags[tag].noEndTag || tags[tag].reduceIndent;56  });57  CodeMirror.defineMode("soy", function(config) {58    var textMode = CodeMirror.getMode(config, "text/plain");59    var modes = {60      html: CodeMirror.getMode(config, {name: "text/html", multilineTagIndentFactor: 2, multilineTagIndentPastTag: false, allowMissingTagName: true}),61      attributes: textMode,62      text: textMode,63      uri: textMode,64      trusted_resource_uri: textMode,65      css: CodeMirror.getMode(config, "text/css"),66      js: CodeMirror.getMode(config, {name: "text/javascript", statementIndent: 2 * config.indentUnit})67    };68    function last(array) {69      return array[array.length - 1];70    }71    function tokenUntil(stream, state, untilRegExp) {72      if (stream.sol()) {73        for (var indent = 0; indent < state.indent; indent++) {74          if (!stream.eat(/\s/)) break;75        }76        if (indent) return null;77      }78      var oldString = stream.string;79      var match = untilRegExp.exec(oldString.substr(stream.pos));80      if (match) {81        // We don't use backUp because it backs up just the position, not the state.82        // This uses an undocumented API.83        stream.string = oldString.substr(0, stream.pos + match.index);84      }85      var result = stream.hideFirstChars(state.indent, function() {86        var localState = last(state.localStates);87        return localState.mode.token(stream, localState.state);88      });89      stream.string = oldString;90      return result;91    }92    function contains(list, element) {93      while (list) {94        if (list.element === element) return true;95        list = list.next;96      }97      return false;98    }99    function prepend(list, element) {100      return {101        element: element,102        next: list103      };104    }105    function popcontext(state) {106      if (!state.context) return;107      if (state.context.scope) {108        state.variables = state.context.scope;109      }110      state.context = state.context.previousContext;111    }112    // Reference a variable `name` in `list`.113    // Let `loose` be truthy to ignore missing identifiers.114    function ref(list, name, loose) {115      return contains(list, name) ? "variable-2" : (loose ? "variable" : "variable-2 error");116    }117    // Data for an open soy tag.118    function Context(previousContext, tag, scope) {119      this.previousContext = previousContext;120      this.tag = tag;121      this.kind = null;122      this.scope = scope;123    }124    function expression(stream, state) {125      var match;126      if (stream.match(/[[]/)) {127        state.soyState.push("list-literal");128        state.context = new Context(state.context, "list-literal", state.variables);129        state.lookupVariables = false;130        return null;131      } else if (stream.match(/\bmap(?=\()/)) {132        state.soyState.push("map-literal");133        return "keyword";134      } else if (stream.match(/\brecord(?=\()/)) {135        state.soyState.push("record-literal");136        return "keyword";137      } else if (stream.match(/([\w]+)(?=\()/)) {138        return "variable callee";139      } else if (match = stream.match(/^["']/)) {140        state.soyState.push("string");141        state.quoteKind = match[0];142        return "string";143      } else if (stream.match(/^[(]/)) {144        state.soyState.push("open-parentheses");145        return null;146      } else if (stream.match(/(null|true|false)(?!\w)/) ||147          stream.match(/0x([0-9a-fA-F]{2,})/) ||148          stream.match(/-?([0-9]*[.])?[0-9]+(e[0-9]*)?/)) {149        return "atom";150      } else if (stream.match(/(\||[+\-*\/%]|[=!]=|\?:|[<>]=?)/)) {151        // Tokenize filter, binary, null propagator, and equality operators.152        return "operator";153      } else if (match = stream.match(/^\$([\w]+)/)) {154        return ref(state.variables, match[1], !state.lookupVariables);155      } else if (match = stream.match(/^\w+/)) {156        return /^(?:as|and|or|not|in|if)$/.test(match[0]) ? "keyword" : null;157      }158      stream.next();159      return null;160    }161    return {162      startState: function() {163        return {164          soyState: [],165          variables: prepend(null, 'ij'),166          scopes: null,167          indent: 0,168          quoteKind: null,169          context: null,170          lookupVariables: true, // Is unknown variables considered an error171          localStates: [{172            mode: modes.html,173            state: CodeMirror.startState(modes.html)174          }]175        };176      },177      copyState: function(state) {178        return {179          tag: state.tag, // Last seen Soy tag.180          soyState: state.soyState.concat([]),181          variables: state.variables,182          context: state.context,183          indent: state.indent, // Indentation of the following line.184          quoteKind: state.quoteKind,185          lookupVariables: state.lookupVariables,186          localStates: state.localStates.map(function(localState) {187            return {188              mode: localState.mode,189              state: CodeMirror.copyState(localState.mode, localState.state)190            };191          })192        };193      },194      token: function(stream, state) {195        var match;196        switch (last(state.soyState)) {197          case "comment":198            if (stream.match(/^.*?\*\//)) {199              state.soyState.pop();200            } else {201              stream.skipToEnd();202            }203            if (!state.context || !state.context.scope) {204              var paramRe = /@param\??\s+(\S+)/g;205              var current = stream.current();206              for (var match; (match = paramRe.exec(current)); ) {207                state.variables = prepend(state.variables, match[1]);208              }209            }210            return "comment";211          case "string":212            var match = stream.match(/^.*?(["']|\\[\s\S])/);213            if (!match) {214              stream.skipToEnd();215            } else if (match[1] == state.quoteKind) {216              state.quoteKind = null;217              state.soyState.pop();218            }219            return "string";220        }221        if (!state.soyState.length || last(state.soyState) != "literal") {222          if (stream.match(/^\/\*/)) {223            state.soyState.push("comment");224            return "comment";225          } else if (stream.match(stream.sol() ? /^\s*\/\/.*/ : /^\s+\/\/.*/)) {226            return "comment";227          }228        }229        switch (last(state.soyState)) {230          case "templ-def":231            if (match = stream.match(/^\.?([\w]+(?!\.[\w]+)*)/)) {232              state.soyState.pop();233              return "def";234            }235            stream.next();236            return null;237          case "templ-ref":238            if (match = stream.match(/(\.?[a-zA-Z_][a-zA-Z_0-9]+)+/)) {239              state.soyState.pop();240              // If the first character is '.', it can only be a local template.241              if (match[0][0] == '.') {242                return "variable-2"243              }244              // Otherwise245              return "variable";246            }247            if (match = stream.match(/^\$([\w]+)/)) {248              state.soyState.pop();249              return ref(state.variables, match[1], !state.lookupVariables);250            }251            stream.next();252            return null;253          case "namespace-def":254            if (match = stream.match(/^\.?([\w\.]+)/)) {255              state.soyState.pop();256              return "variable";257            }258            stream.next();259            return null;260          case "param-def":261            if (match = stream.match(/^\*/)) {262              state.soyState.pop();263              state.soyState.push("param-type");264              return "type";265            }266            if (match = stream.match(/^\w+/)) {267              state.variables = prepend(state.variables, match[0]);268              state.soyState.pop();269              state.soyState.push("param-type");270              return "def";271            }272            stream.next();273            return null;274          case "param-ref":275            if (match = stream.match(/^\w+/)) {276              state.soyState.pop();277              return "property";278            }279            stream.next();280            return null;281          case "open-parentheses":282            if (stream.match(/[)]/)) {283              state.soyState.pop();284              return null;285            }286            return expression(stream, state);287          case "param-type":288            var peekChar = stream.peek();289            if ("}]=>,".indexOf(peekChar) != -1) {290              state.soyState.pop();291              return null;292            } else if (peekChar == "[") {293              state.soyState.push('param-type-record');294              return null;295            } else if (peekChar == "(") {296              state.soyState.push('param-type-template');297              return null;298            } else if (peekChar == "<") {299              state.soyState.push('param-type-parameter');300              return null;301            } else if (match = stream.match(/^([\w]+|[?])/)) {302              return "type";303            }304            stream.next();305            return null;306          case "param-type-record":307            var peekChar = stream.peek();308            if (peekChar == "]") {309              state.soyState.pop();310              return null;311            }312            if (stream.match(/^\w+/)) {313              state.soyState.push('param-type');314              return "property";315            }316            stream.next();317            return null;318          case "param-type-parameter":319            if (stream.match(/^[>]/)) {320              state.soyState.pop();321              return null;322            }323            if (stream.match(/^[<,]/)) {324              state.soyState.push('param-type');325              return null;326            }327            stream.next();328            return null;329          case "param-type-template":330            if (stream.match(/[>]/)) {331              state.soyState.pop();332              state.soyState.push('param-type');333              return null;334            }335            if (stream.match(/^\w+/)) {336              state.soyState.push('param-type');337              return "def";338            }339            stream.next();340            return null;341          case "var-def":342            if (match = stream.match(/^\$([\w]+)/)) {343              state.variables = prepend(state.variables, match[1]);344              state.soyState.pop();345              return "def";346            }347            stream.next();348            return null;349          case "for-loop":350            if (stream.match(/\bin\b/)) {351              state.soyState.pop();352              return "keyword";353            }354            if (stream.peek() == "$") {355              state.soyState.push('var-def');356              return null;357            }358            stream.next();359            return null;360          case "record-literal":361            if (stream.match(/^[)]/)) {362              state.soyState.pop();363              return null;364            }365            if (stream.match(/[(,]/)) {366              state.soyState.push("map-value")367              state.soyState.push("record-key")368              return null;369            }370            stream.next()371            return null;372          case "map-literal":373            if (stream.match(/^[)]/)) {374              state.soyState.pop();375              return null;376            }377            if (stream.match(/[(,]/)) {378              state.soyState.push("map-value")379              state.soyState.push("map-value")380              return null;381            }382            stream.next()383            return null;384          case "list-literal":385            if (stream.match(']')) {386              state.soyState.pop();387              state.lookupVariables = true;388              popcontext(state);389              return null;390            }391            if (stream.match(/\bfor\b/)) {392              state.lookupVariables = true;393              state.soyState.push('for-loop');394              return "keyword";395            }396            return expression(stream, state);397          case "record-key":398            if (stream.match(/[\w]+/)) {399              return "property";400            }401            if (stream.match(/^[:]/)) {402              state.soyState.pop();403              return null;404            }405            stream.next();406            return null;407          case "map-value":408            if (stream.peek() == ")" || stream.peek() == "," || stream.match(/^[:)]/)) {409              state.soyState.pop();410              return null;411            }412            return expression(stream, state);413          case "import":414            if (stream.eat(";")) {415              state.soyState.pop();416              state.indent -= 2 * config.indentUnit;417              return null;418            }419            if (stream.match(/\w+(?=\s+as\b)/)) {420              return "variable";421            }422            if (match = stream.match(/\w+/)) {423              return /\b(from|as)\b/.test(match[0]) ? "keyword" : "def";424            }425            if (match = stream.match(/^["']/)) {426              state.soyState.push("string");427              state.quoteKind = match[0];428              return "string";429            }430            stream.next();431            return null;432          case "tag":433            var endTag;434            var tagName;435            if (state.tag === undefined) {436              endTag = true;437              tagName = '';438            } else {439              endTag = state.tag[0] == "/";440              tagName = endTag ? state.tag.substring(1) : state.tag;441            }442            var tag = tags[tagName];443            if (stream.match(/^\/?}/)) {444              var selfClosed = stream.current() == "/}";445              if (selfClosed && !endTag) {446                popcontext(state);447              }448              if (state.tag == "/template" || state.tag == "/deltemplate") {449                state.variables = prepend(null, 'ij');450                state.indent = 0;451              } else {452                state.indent -= config.indentUnit *453                    (selfClosed || indentingTags.indexOf(state.tag) == -1 ? 2 : 1);454              }455              state.soyState.pop();456              return "keyword";457            } else if (stream.match(/^([\w?]+)(?==)/)) {458              if (state.context && state.context.tag == tagName && stream.current() == "kind" && (match = stream.match(/^="([^"]+)/, false))) {459                var kind = match[1];460                state.context.kind = kind;461                var mode = modes[kind] || modes.html;462                var localState = last(state.localStates);463                if (localState.mode.indent) {464                  state.indent += localState.mode.indent(localState.state, "", "");465                }466                state.localStates.push({467                  mode: mode,468                  state: CodeMirror.startState(mode)469                });470              }471              return "attribute";472            }473            return expression(stream, state);474          case "template-call-expression":475            if (stream.match(/^([\w-?]+)(?==)/)) {476              return "attribute";477            } else if (stream.eat('>')) {478              state.soyState.pop();479              return "keyword";480            } else if (stream.eat('/>')) {481              state.soyState.pop();482              return "keyword";483            }484            return expression(stream, state);485          case "literal":486            if (stream.match('{/literal}', false)) {487              state.soyState.pop();488              return this.token(stream, state);489            }490            return tokenUntil(stream, state, /\{\/literal}/);491          case "export":492            if (match = stream.match(/\w+/)) {493              state.soyState.pop();494              if (match == "const") {495                state.soyState.push("const-def")496                return "keyword";497              } else if (match == "extern") {498                state.soyState.push("param-def")499                return "keyword";500              }501            } else {502              stream.next();503            }504            return null;505          case "const-def":506            if (stream.match(/^\w+/)) {507              state.soyState.pop();508              return "def";509            }510            stream.next();511            return null;512        }513        if (stream.match('{literal}')) {514          state.indent += config.indentUnit;515          state.soyState.push("literal");516          state.context = new Context(state.context, "literal", state.variables);517          return "keyword";518        // A tag-keyword must be followed by whitespace, comment or a closing tag.519        } else if (match = stream.match(/^\{([/@\\]?\w+\??)(?=$|[\s}]|\/[/*])/)) {520          var prevTag = state.tag;521          state.tag = match[1];522          var endTag = state.tag[0] == "/";523          var indentingTag = !!tags[state.tag];524          var tagName = endTag ? state.tag.substring(1) : state.tag;525          var tag = tags[tagName];526          if (state.tag != "/switch")527            state.indent += ((endTag || tag && tag.reduceIndent) && prevTag != "switch" ? 1 : 2) * config.indentUnit;528          state.soyState.push("tag");529          var tagError = false;530          if (tag) {531            if (!endTag) {532              if (tag.soyState) state.soyState.push(tag.soyState);533            }534            // If a new tag, open a new context.535            if (!tag.noEndTag && (indentingTag || !endTag)) {536              state.context = new Context(state.context, state.tag, tag.variableScope ? state.variables : null);537            // Otherwise close the current context.538            } else if (endTag) {539              var isBalancedForExtern = tagName == 'extern' && (state.context && state.context.tag == 'export');540              if (!state.context || ((state.context.tag != tagName) && !isBalancedForExtern)) {541                tagError = true;542              } else if (state.context) {543                if (state.context.kind) {544                  state.localStates.pop();545                  var localState = last(state.localStates);546                  if (localState.mode.indent) {547                    state.indent -= localState.mode.indent(localState.state, "", "");548                  }549                }550                popcontext(state);551              }552            }553          } else if (endTag) {554            // Assume all tags with a closing tag are defined in the config.555            tagError = true;556          }557          return (tagError ? "error " : "") + "keyword";558        // Not a tag-keyword; it's an implicit print tag.559        } else if (stream.eat('{')) {560          state.tag = "print";561          state.indent += 2 * config.indentUnit;562          state.soyState.push("tag");563          return "keyword";564        } else if (!state.context && stream.sol() && stream.match(/import\b/)) {565          state.soyState.push("import");566          state.indent += 2 * config.indentUnit;567          return "keyword";568        } else if (match = stream.match('<{')) {569          state.soyState.push("template-call-expression");570          state.indent += 2 * config.indentUnit;571          state.soyState.push("tag");572          return "keyword";573        } else if (match = stream.match('</>')) {574          state.indent -= 1 * config.indentUnit;575          return "keyword";576        }577        return tokenUntil(stream, state, /\{|\s+\/\/|\/\*/);578      },579      indent: function(state, textAfter, line) {580        var indent = state.indent, top = last(state.soyState);581        if (top == "comment") return CodeMirror.Pass;582        if (top == "literal") {583          if (/^\{\/literal}/.test(textAfter)) indent -= config.indentUnit;584        } else {585          if (/^\s*\{\/(template|deltemplate)\b/.test(textAfter)) return 0;586          if (/^\{(\/|(fallbackmsg|elseif|else|ifempty)\b)/.test(textAfter)) indent -= config.indentUnit;587          if (state.tag != "switch" && /^\{(case|default)\b/.test(textAfter)) indent -= config.indentUnit;588          if (/^\{\/switch\b/.test(textAfter)) indent -= config.indentUnit;589        }590        var localState = last(state.localStates);591        if (indent && localState.mode.indent) {592          indent += localState.mode.indent(localState.state, textAfter, line);593        }594        return indent;595      },596      innerMode: function(state) {597        if (state.soyState.length && last(state.soyState) != "literal") return null;598        else return last(state.localStates);599      },600      electricInput: /^\s*\{(\/|\/template|\/deltemplate|\/switch|fallbackmsg|elseif|else|case|default|ifempty|\/literal\})$/,601      lineComment: "//",602      blockCommentStart: "/*",603      blockCommentEnd: "*/",604      blockCommentContinue: " * ",605      useInnerComments: false,606      fold: "indent"607    };608  }, "htmlmixed");609  CodeMirror.registerHelper("wordChars", "soy", /[\w$]/);610  CodeMirror.registerHelper("hintWords", "soy", Object.keys(tags).concat(611      ["css", "debugger"]));612  CodeMirror.defineMIME("text/x-soy", "soy");...

Full Screen

Full Screen

project-state.js

Source:project-state.js Github

copy

Full Screen

1import keyMirror from 'keymirror';2const DONE_CREATING_COPY = 'scratch-gui/project-state/DONE_CREATING_COPY';3const DONE_CREATING_NEW = 'scratch-gui/project-state/DONE_CREATING_NEW';4const DONE_FETCHING_DEFAULT = 'scratch-gui/project-state/DONE_FETCHING_DEFAULT';5const DONE_FETCHING_WITH_ID = 'scratch-gui/project-state/DONE_FETCHING_WITH_ID';6const DONE_LOADING_VM_TO_SAVE = 'scratch-gui/project-state/DONE_LOADING_VM_TO_SAVE';7const DONE_LOADING_VM_WITH_ID = 'scratch-gui/project-state/DONE_LOADING_VM_WITH_ID';8const DONE_LOADING_VM_WITHOUT_ID = 'scratch-gui/project-state/DONE_LOADING_VM_WITHOUT_ID';9const DONE_REMIXING = 'scratch-gui/project-state/DONE_REMIXING';10const DONE_UPDATING = 'scratch-gui/project-state/DONE_UPDATING';11const DONE_UPDATING_BEFORE_COPY = 'scratch-gui/project-state/DONE_UPDATING_BEFORE_COPY';12const DONE_UPDATING_BEFORE_NEW = 'scratch-gui/project-state/DONE_UPDATING_BEFORE_NEW';13const RETURN_TO_SHOWING = 'scratch-gui/project-state/RETURN_TO_SHOWING';14const SET_PROJECT_ID = 'scratch-gui/project-state/SET_PROJECT_ID';15const START_AUTO_UPDATING = 'scratch-gui/project-state/START_AUTO_UPDATING';16const START_CREATING_NEW = 'scratch-gui/project-state/START_CREATING_NEW';17const START_ERROR = 'scratch-gui/project-state/START_ERROR';18const START_FETCHING_NEW = 'scratch-gui/project-state/START_FETCHING_NEW';19const START_LOADING_VM_FILE_UPLOAD = 'scratch-gui/project-state/START_LOADING_FILE_UPLOAD';20const START_MANUAL_UPDATING = 'scratch-gui/project-state/START_MANUAL_UPDATING';21const START_REMIXING = 'scratch-gui/project-state/START_REMIXING';22const START_UPDATING_BEFORE_CREATING_COPY = 'scratch-gui/project-state/START_UPDATING_BEFORE_CREATING_COPY';23const START_UPDATING_BEFORE_CREATING_NEW = 'scratch-gui/project-state/START_UPDATING_BEFORE_CREATING_NEW';24const defaultProjectId = '0'; // hardcoded id of default project25const LoadingState = keyMirror({26    NOT_LOADED: null,27    ERROR: null,28    AUTO_UPDATING: null,29    CREATING_COPY: null,30    CREATING_NEW: null,31    FETCHING_NEW_DEFAULT: null,32    FETCHING_WITH_ID: null,33    LOADING_VM_FILE_UPLOAD: null,34    LOADING_VM_NEW_DEFAULT: null,35    LOADING_VM_WITH_ID: null,36    MANUAL_UPDATING: null,37    REMIXING: null,38    SHOWING_WITH_ID: null,39    SHOWING_WITHOUT_ID: null,40    UPDATING_BEFORE_COPY: null,41    UPDATING_BEFORE_NEW: null42});43const LoadingStates = Object.keys(LoadingState);44const getIsFetchingWithoutId = loadingState => (45    // LOADING_VM_FILE_UPLOAD is an honorary fetch, since there is no fetching step for file uploads46    loadingState === LoadingState.LOADING_VM_FILE_UPLOAD ||47    loadingState === LoadingState.FETCHING_NEW_DEFAULT48);49const getIsFetchingWithId = loadingState => (50    loadingState === LoadingState.FETCHING_WITH_ID ||51    loadingState === LoadingState.FETCHING_NEW_DEFAULT52);53const getIsLoadingWithId = loadingState => (54    loadingState === LoadingState.LOADING_VM_WITH_ID ||55    loadingState === LoadingState.LOADING_VM_NEW_DEFAULT56);57const getIsLoading = loadingState => (58    loadingState === LoadingState.LOADING_VM_FILE_UPLOAD ||59    loadingState === LoadingState.LOADING_VM_WITH_ID ||60    loadingState === LoadingState.LOADING_VM_NEW_DEFAULT61);62const getIsLoadingUpload = loadingState => (63    loadingState === LoadingState.LOADING_VM_FILE_UPLOAD64);65const getIsCreatingNew = loadingState => (66    loadingState === LoadingState.CREATING_NEW67);68const getIsAnyCreatingNewState = loadingState => (69    loadingState === LoadingState.FETCHING_NEW_DEFAULT ||70    loadingState === LoadingState.LOADING_VM_NEW_DEFAULT ||71    loadingState === LoadingState.CREATING_NEW72);73const getIsCreatingCopy = loadingState => (74    loadingState === LoadingState.CREATING_COPY75);76const getIsManualUpdating = loadingState => (77    loadingState === LoadingState.MANUAL_UPDATING78);79const getIsRemixing = loadingState => (80    loadingState === LoadingState.REMIXING81);82const getIsUpdating = loadingState => (83    loadingState === LoadingState.AUTO_UPDATING ||84    loadingState === LoadingState.MANUAL_UPDATING ||85    loadingState === LoadingState.UPDATING_BEFORE_COPY ||86    loadingState === LoadingState.UPDATING_BEFORE_NEW87);88const getIsShowingProject = loadingState => (89    loadingState === LoadingState.SHOWING_WITH_ID ||90    loadingState === LoadingState.SHOWING_WITHOUT_ID91);92const getIsShowingWithId = loadingState => (93    loadingState === LoadingState.SHOWING_WITH_ID94);95const getIsShowingWithoutId = loadingState => (96    loadingState === LoadingState.SHOWING_WITHOUT_ID97);98const getIsError = loadingState => (99    loadingState === LoadingState.ERROR100);101const initialState = {102    error: null,103    projectData: null,104    projectId: null,105    loadingState: LoadingState.NOT_LOADED106};107const reducer = function (state, action) {108    if (typeof state === 'undefined') state = initialState;109    switch (action.type) {110    case DONE_CREATING_NEW:111        // We need to set project id since we just created new project on the server.112        // No need to load, we should have data already in vm.113        if (state.loadingState === LoadingState.CREATING_NEW) {114            return Object.assign({}, state, {115                loadingState: LoadingState.SHOWING_WITH_ID,116                projectId: action.projectId117            });118        }119        return state;120    case DONE_FETCHING_WITH_ID:121        if (state.loadingState === LoadingState.FETCHING_WITH_ID) {122            return Object.assign({}, state, {123                loadingState: LoadingState.LOADING_VM_WITH_ID,124                projectData: action.projectData125            });126        }127        return state;128    case DONE_FETCHING_DEFAULT:129        if (state.loadingState === LoadingState.FETCHING_NEW_DEFAULT) {130            return Object.assign({}, state, {131                loadingState: LoadingState.LOADING_VM_NEW_DEFAULT,132                projectData: action.projectData133            });134        }135        return state;136    case DONE_LOADING_VM_WITHOUT_ID:137        if (state.loadingState === LoadingState.LOADING_VM_FILE_UPLOAD ||138            state.loadingState === LoadingState.LOADING_VM_NEW_DEFAULT) {139            return Object.assign({}, state, {140                loadingState: LoadingState.SHOWING_WITHOUT_ID,141                projectId: defaultProjectId142            });143        }144        return state;145    case DONE_LOADING_VM_WITH_ID:146        if (state.loadingState === LoadingState.LOADING_VM_WITH_ID) {147            return Object.assign({}, state, {148                loadingState: LoadingState.SHOWING_WITH_ID149            });150        }151        return state;152    case DONE_LOADING_VM_TO_SAVE:153        if (state.loadingState === LoadingState.LOADING_VM_FILE_UPLOAD) {154            return Object.assign({}, state, {155                loadingState: LoadingState.AUTO_UPDATING156            });157        }158        return state;159    case DONE_REMIXING:160        // We need to set project id since we just created new project on the server.161        // No need to load, we should have data already in vm.162        if (state.loadingState === LoadingState.REMIXING) {163            return Object.assign({}, state, {164                loadingState: LoadingState.SHOWING_WITH_ID,165                projectId: action.projectId166            });167        }168        return state;169    case DONE_CREATING_COPY:170        // We need to set project id since we just created new project on the server.171        // No need to load, we should have data already in vm.172        if (state.loadingState === LoadingState.CREATING_COPY) {173            return Object.assign({}, state, {174                loadingState: LoadingState.SHOWING_WITH_ID,175                projectId: action.projectId176            });177        }178        return state;179    case DONE_UPDATING:180        if (state.loadingState === LoadingState.AUTO_UPDATING ||181            state.loadingState === LoadingState.MANUAL_UPDATING) {182            return Object.assign({}, state, {183                loadingState: LoadingState.SHOWING_WITH_ID184            });185        }186        return state;187    case DONE_UPDATING_BEFORE_COPY:188        if (state.loadingState === LoadingState.UPDATING_BEFORE_COPY) {189            return Object.assign({}, state, {190                loadingState: LoadingState.CREATING_COPY191            });192        }193        return state;194    case DONE_UPDATING_BEFORE_NEW:195        if (state.loadingState === LoadingState.UPDATING_BEFORE_NEW) {196            return Object.assign({}, state, {197                loadingState: LoadingState.FETCHING_NEW_DEFAULT,198                projectId: defaultProjectId199            });200        }201        return state;202    case RETURN_TO_SHOWING:203        if (state.projectId === null || state.projectId === defaultProjectId) {204            return Object.assign({}, state, {205                loadingState: LoadingState.SHOWING_WITHOUT_ID,206                projectId: defaultProjectId207            });208        }209        return Object.assign({}, state, {210            loadingState: LoadingState.SHOWING_WITH_ID211        });212    case SET_PROJECT_ID:213        // if the projectId hasn't actually changed do nothing214        if (state.projectId === action.projectId) {215            return state;216        }217        // if we were already showing a project, and a different projectId is set, only fetch that project if218        // projectId has changed. This prevents re-fetching projects unnecessarily.219        if (state.loadingState === LoadingState.SHOWING_WITH_ID) {220            // if setting the default project id, specifically fetch that project221            if (action.projectId === defaultProjectId || action.projectId === null) {222                return Object.assign({}, state, {223                    loadingState: LoadingState.FETCHING_NEW_DEFAULT,224                    projectId: defaultProjectId225                });226            }227            return Object.assign({}, state, {228                loadingState: LoadingState.FETCHING_WITH_ID,229                projectId: action.projectId230            });231        } else if (state.loadingState === LoadingState.SHOWING_WITHOUT_ID) {232            // if we were showing a project already, don't transition to default project.233            if (action.projectId !== defaultProjectId && action.projectId !== null) {234                return Object.assign({}, state, {235                    loadingState: LoadingState.FETCHING_WITH_ID,236                    projectId: action.projectId237                });238            }239        } else { // allow any other states to transition to fetching project240            // if setting the default project id, specifically fetch that project241            if (action.projectId === defaultProjectId || action.projectId === null) {242                return Object.assign({}, state, {243                    loadingState: LoadingState.FETCHING_NEW_DEFAULT,244                    projectId: defaultProjectId245                });246            }247            return Object.assign({}, state, {248                loadingState: LoadingState.FETCHING_WITH_ID,249                projectId: action.projectId250            });251        }252        return state;253    case START_AUTO_UPDATING:254        if (state.loadingState === LoadingState.SHOWING_WITH_ID) {255            return Object.assign({}, state, {256                loadingState: LoadingState.AUTO_UPDATING257            });258        }259        return state;260    case START_CREATING_NEW:261        if (state.loadingState === LoadingState.SHOWING_WITHOUT_ID) {262            return Object.assign({}, state, {263                loadingState: LoadingState.CREATING_NEW264            });265        }266        return state;267    case START_FETCHING_NEW:268        if ([269            LoadingState.SHOWING_WITH_ID,270            LoadingState.SHOWING_WITHOUT_ID271        ].includes(state.loadingState)) {272            return Object.assign({}, state, {273                loadingState: LoadingState.FETCHING_NEW_DEFAULT,274                projectId: defaultProjectId275            });276        }277        return state;278    case START_LOADING_VM_FILE_UPLOAD:279        if ([280            LoadingState.NOT_LOADED,281            LoadingState.SHOWING_WITH_ID,282            LoadingState.SHOWING_WITHOUT_ID283        ].includes(state.loadingState)) {284            return Object.assign({}, state, {285                loadingState: LoadingState.LOADING_VM_FILE_UPLOAD286            });287        }288        return state;289    case START_MANUAL_UPDATING:290        if (state.loadingState === LoadingState.SHOWING_WITH_ID) {291            return Object.assign({}, state, {292                loadingState: LoadingState.MANUAL_UPDATING293            });294        }295        return state;296    case START_REMIXING:297        if (state.loadingState === LoadingState.SHOWING_WITH_ID) {298            return Object.assign({}, state, {299                loadingState: LoadingState.REMIXING300            });301        }302        return state;303    case START_UPDATING_BEFORE_CREATING_COPY:304        if (state.loadingState === LoadingState.SHOWING_WITH_ID) {305            return Object.assign({}, state, {306                loadingState: LoadingState.UPDATING_BEFORE_COPY307            });308        }309        return state;310    case START_UPDATING_BEFORE_CREATING_NEW:311        if (state.loadingState === LoadingState.SHOWING_WITH_ID) {312            return Object.assign({}, state, {313                loadingState: LoadingState.UPDATING_BEFORE_NEW314            });315        }316        return state;317    case START_ERROR:318        // fatal errors: there's no correct editor state for us to show319        if ([320            LoadingState.FETCHING_NEW_DEFAULT,321            LoadingState.FETCHING_WITH_ID,322            LoadingState.LOADING_VM_NEW_DEFAULT,323            LoadingState.LOADING_VM_WITH_ID324        ].includes(state.loadingState)) {325            return Object.assign({}, state, {326                loadingState: LoadingState.ERROR,327                error: action.error328            });329        }330        // non-fatal errors: can keep showing editor state fine331        if ([332            LoadingState.AUTO_UPDATING,333            LoadingState.CREATING_COPY,334            LoadingState.MANUAL_UPDATING,335            LoadingState.REMIXING,336            LoadingState.UPDATING_BEFORE_COPY,337            LoadingState.UPDATING_BEFORE_NEW338        ].includes(state.loadingState)) {339            return Object.assign({}, state, {340                loadingState: LoadingState.SHOWING_WITH_ID,341                error: action.error342            });343        }344        // non-fatal error; state to show depends on whether project we're showing345        // has an id or not346        if (state.loadingState === LoadingState.CREATING_NEW) {347            if (state.projectId === defaultProjectId || state.projectId === null) {348                return Object.assign({}, state, {349                    loadingState: LoadingState.SHOWING_WITHOUT_ID,350                    error: action.error351                });352            }353            return Object.assign({}, state, {354                loadingState: LoadingState.SHOWING_WITH_ID,355                error: action.error356            });357        }358        return state;359    default:360        return state;361    }362};363const createProject = () => ({364    type: START_CREATING_NEW365});366const doneCreatingProject = (id, loadingState) => {367    switch (loadingState) {368    case LoadingState.CREATING_NEW:369        return {370            type: DONE_CREATING_NEW,371            projectId: id372        };373    case LoadingState.CREATING_COPY:374        return {375            type: DONE_CREATING_COPY,376            projectId: id377        };378    case LoadingState.REMIXING:379        return {380            type: DONE_REMIXING,381            projectId: id382        };383    default:384        break;385    }386};387const onFetchedProjectData = (projectData, loadingState) => {388    switch (loadingState) {389    case LoadingState.FETCHING_WITH_ID:390        return {391            type: DONE_FETCHING_WITH_ID,392            projectData: projectData393        };394    case LoadingState.FETCHING_NEW_DEFAULT:395        return {396            type: DONE_FETCHING_DEFAULT,397            projectData: projectData398        };399    default:400        break;401    }402};403const onLoadedProject = (loadingState, canSave, success) => {404    if (success) {405        switch (loadingState) {406        case LoadingState.LOADING_VM_WITH_ID:407            return {408                type: DONE_LOADING_VM_WITH_ID409            };410        case LoadingState.LOADING_VM_FILE_UPLOAD:411            if (canSave) {412                return {413                    type: DONE_LOADING_VM_TO_SAVE414                };415            }416            return {417                type: DONE_LOADING_VM_WITHOUT_ID418            };419        case LoadingState.LOADING_VM_NEW_DEFAULT:420            return {421                type: DONE_LOADING_VM_WITHOUT_ID422            };423        default:424            return;425        }426    }427    return {428        type: RETURN_TO_SHOWING429    };430};431const doneUpdatingProject = loadingState => {432    switch (loadingState) {433    case LoadingState.AUTO_UPDATING:434    case LoadingState.MANUAL_UPDATING:435        return {436            type: DONE_UPDATING437        };438    case LoadingState.UPDATING_BEFORE_COPY:439        return {440            type: DONE_UPDATING_BEFORE_COPY441        };442    case LoadingState.UPDATING_BEFORE_NEW:443        return {444            type: DONE_UPDATING_BEFORE_NEW445        };446    default:447        break;448    }449};450const projectError = error => ({451    type: START_ERROR,452    error: error453});454const setProjectId = id => ({455    type: SET_PROJECT_ID,456    projectId: id457});458const requestNewProject = needSave => {459    if (needSave) return {type: START_UPDATING_BEFORE_CREATING_NEW};460    return {type: START_FETCHING_NEW};461};462const requestProjectUpload = loadingState => {463    switch (loadingState) {464    case LoadingState.NOT_LOADED:465    case LoadingState.SHOWING_WITH_ID:466    case LoadingState.SHOWING_WITHOUT_ID:467        return {468            type: START_LOADING_VM_FILE_UPLOAD469        };470    default:471        break;472    }473};474const autoUpdateProject = () => ({475    type: START_AUTO_UPDATING476});477const manualUpdateProject = () => ({478    type: START_MANUAL_UPDATING479});480const saveProjectAsCopy = () => ({481    type: START_UPDATING_BEFORE_CREATING_COPY482});483const remixProject = () => ({484    type: START_REMIXING485});486export {487    reducer as default,488    initialState as projectStateInitialState,489    LoadingState,490    LoadingStates,491    autoUpdateProject,492    createProject,493    defaultProjectId,494    doneCreatingProject,495    doneUpdatingProject,496    getIsAnyCreatingNewState,497    getIsCreatingCopy,498    getIsCreatingNew,499    getIsError,500    getIsFetchingWithId,501    getIsFetchingWithoutId,502    getIsLoading,503    getIsLoadingWithId,504    getIsLoadingUpload,505    getIsManualUpdating,506    getIsRemixing,507    getIsShowingProject,508    getIsShowingWithId,509    getIsShowingWithoutId,510    getIsUpdating,511    manualUpdateProject,512    onFetchedProjectData,513    onLoadedProject,514    projectError,515    remixProject,516    requestNewProject,517    requestProjectUpload,518    saveProjectAsCopy,519    setProjectId...

Full Screen

Full Screen

slim.js

Source:slim.js Github

copy

Full Screen

1// CodeMirror, copyright (c) by Marijn Haverbeke and others2// Distributed under an MIT license: http://codemirror.net/LICENSE3// Slim Highlighting for CodeMirror copyright (c) HicknHack Software Gmbh4(function(mod) {5  if (typeof exports == "object" && typeof module == "object") // CommonJS6    mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../ruby/ruby"));7  else if (typeof define == "function" && define.amd) // AMD8    define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../ruby/ruby"], mod);9  else // Plain browser env10    mod(CodeMirror);11})(function(CodeMirror) {12"use strict";13  CodeMirror.defineMode("slim", function(config) {14    var htmlMode = CodeMirror.getMode(config, {name: "htmlmixed"});15    var rubyMode = CodeMirror.getMode(config, "ruby");16    var modes = { html: htmlMode, ruby: rubyMode };17    var embedded = {18      ruby: "ruby",19      javascript: "javascript",20      css: "text/css",21      sass: "text/x-sass",22      scss: "text/x-scss",23      less: "text/x-less",24      styl: "text/x-styl", // no highlighting so far25      coffee: "coffeescript",26      asciidoc: "text/x-asciidoc",27      markdown: "text/x-markdown",28      textile: "text/x-textile", // no highlighting so far29      creole: "text/x-creole", // no highlighting so far30      wiki: "text/x-wiki", // no highlighting so far31      mediawiki: "text/x-mediawiki", // no highlighting so far32      rdoc: "text/x-rdoc", // no highlighting so far33      builder: "text/x-builder", // no highlighting so far34      nokogiri: "text/x-nokogiri", // no highlighting so far35      erb: "application/x-erb"36    };37    var embeddedRegexp = function(map){38      var arr = [];39      for(var key in map) arr.push(key);40      return new RegExp("^("+arr.join('|')+"):");41    }(embedded);42    var styleMap = {43      "commentLine": "comment",44      "slimSwitch": "operator special",45      "slimTag": "tag",46      "slimId": "attribute def",47      "slimClass": "attribute qualifier",48      "slimAttribute": "attribute",49      "slimSubmode": "keyword special",50      "closeAttributeTag": null,51      "slimDoctype": null,52      "lineContinuation": null53    };54    var closing = {55      "{": "}",56      "[": "]",57      "(": ")"58    };59    var nameStartChar = "_a-zA-Z\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD";60    var nameChar = nameStartChar + "\\-0-9\xB7\u0300-\u036F\u203F-\u2040";61    var nameRegexp = new RegExp("^[:"+nameStartChar+"](?::["+nameChar+"]|["+nameChar+"]*)");62    var attributeNameRegexp = new RegExp("^[:"+nameStartChar+"][:\\."+nameChar+"]*(?=\\s*=)");63    var wrappedAttributeNameRegexp = new RegExp("^[:"+nameStartChar+"][:\\."+nameChar+"]*");64    var classNameRegexp = /^\.-?[_a-zA-Z]+[\w\-]*/;65    var classIdRegexp = /^#[_a-zA-Z]+[\w\-]*/;66    function backup(pos, tokenize, style) {67      var restore = function(stream, state) {68        state.tokenize = tokenize;69        if (stream.pos < pos) {70          stream.pos = pos;71          return style;72        }73        return state.tokenize(stream, state);74      };75      return function(stream, state) {76        state.tokenize = restore;77        return tokenize(stream, state);78      };79    }80    function maybeBackup(stream, state, pat, offset, style) {81      var cur = stream.current();82      var idx = cur.search(pat);83      if (idx > -1) {84        state.tokenize = backup(stream.pos, state.tokenize, style);85        stream.backUp(cur.length - idx - offset);86      }87      return style;88    }89    function continueLine(state, column) {90      state.stack = {91        parent: state.stack,92        style: "continuation",93        indented: column,94        tokenize: state.line95      };96      state.line = state.tokenize;97    }98    function finishContinue(state) {99      if (state.line == state.tokenize) {100        state.line = state.stack.tokenize;101        state.stack = state.stack.parent;102      }103    }104    function lineContinuable(column, tokenize) {105      return function(stream, state) {106        finishContinue(state);107        if (stream.match(/^\\$/)) {108          continueLine(state, column);109          return "lineContinuation";110        }111        var style = tokenize(stream, state);112        if (stream.eol() && stream.current().match(/(?:^|[^\\])(?:\\\\)*\\$/)) {113          stream.backUp(1);114        }115        return style;116      };117    }118    function commaContinuable(column, tokenize) {119      return function(stream, state) {120        finishContinue(state);121        var style = tokenize(stream, state);122        if (stream.eol() && stream.current().match(/,$/)) {123          continueLine(state, column);124        }125        return style;126      };127    }128    function rubyInQuote(endQuote, tokenize) {129      // TODO: add multi line support130      return function(stream, state) {131        var ch = stream.peek();132        if (ch == endQuote && state.rubyState.tokenize.length == 1) {133          // step out of ruby context as it seems to complete processing all the braces134          stream.next();135          state.tokenize = tokenize;136          return "closeAttributeTag";137        } else {138          return ruby(stream, state);139        }140      };141    }142    function startRubySplat(tokenize) {143      var rubyState;144      var runSplat = function(stream, state) {145        if (state.rubyState.tokenize.length == 1 && !state.rubyState.context.prev) {146          stream.backUp(1);147          if (stream.eatSpace()) {148            state.rubyState = rubyState;149            state.tokenize = tokenize;150            return tokenize(stream, state);151          }152          stream.next();153        }154        return ruby(stream, state);155      };156      return function(stream, state) {157        rubyState = state.rubyState;158        state.rubyState = rubyMode.startState();159        state.tokenize = runSplat;160        return ruby(stream, state);161      };162    }163    function ruby(stream, state) {164      return rubyMode.token(stream, state.rubyState);165    }166    function htmlLine(stream, state) {167      if (stream.match(/^\\$/)) {168        return "lineContinuation";169      }170      return html(stream, state);171    }172    function html(stream, state) {173      if (stream.match(/^#\{/)) {174        state.tokenize = rubyInQuote("}", state.tokenize);175        return null;176      }177      return maybeBackup(stream, state, /[^\\]#\{/, 1, htmlMode.token(stream, state.htmlState));178    }179    function startHtmlLine(lastTokenize) {180      return function(stream, state) {181        var style = htmlLine(stream, state);182        if (stream.eol()) state.tokenize = lastTokenize;183        return style;184      };185    }186    function startHtmlMode(stream, state, offset) {187      state.stack = {188        parent: state.stack,189        style: "html",190        indented: stream.column() + offset, // pipe + space191        tokenize: state.line192      };193      state.line = state.tokenize = html;194      return null;195    }196    function comment(stream, state) {197      stream.skipToEnd();198      return state.stack.style;199    }200    function commentMode(stream, state) {201      state.stack = {202        parent: state.stack,203        style: "comment",204        indented: state.indented + 1,205        tokenize: state.line206      };207      state.line = comment;208      return comment(stream, state);209    }210    function attributeWrapper(stream, state) {211      if (stream.eat(state.stack.endQuote)) {212        state.line = state.stack.line;213        state.tokenize = state.stack.tokenize;214        state.stack = state.stack.parent;215        return null;216      }217      if (stream.match(wrappedAttributeNameRegexp)) {218        state.tokenize = attributeWrapperAssign;219        return "slimAttribute";220      }221      stream.next();222      return null;223    }224    function attributeWrapperAssign(stream, state) {225      if (stream.match(/^==?/)) {226        state.tokenize = attributeWrapperValue;227        return null;228      }229      return attributeWrapper(stream, state);230    }231    function attributeWrapperValue(stream, state) {232      var ch = stream.peek();233      if (ch == '"' || ch == "\'") {234        state.tokenize = readQuoted(ch, "string", true, false, attributeWrapper);235        stream.next();236        return state.tokenize(stream, state);237      }238      if (ch == '[') {239        return startRubySplat(attributeWrapper)(stream, state);240      }241      if (stream.match(/^(true|false|nil)\b/)) {242        state.tokenize = attributeWrapper;243        return "keyword";244      }245      return startRubySplat(attributeWrapper)(stream, state);246    }247    function startAttributeWrapperMode(state, endQuote, tokenize) {248      state.stack = {249        parent: state.stack,250        style: "wrapper",251        indented: state.indented + 1,252        tokenize: tokenize,253        line: state.line,254        endQuote: endQuote255      };256      state.line = state.tokenize = attributeWrapper;257      return null;258    }259    function sub(stream, state) {260      if (stream.match(/^#\{/)) {261        state.tokenize = rubyInQuote("}", state.tokenize);262        return null;263      }264      var subStream = new CodeMirror.StringStream(stream.string.slice(state.stack.indented), stream.tabSize);265      subStream.pos = stream.pos - state.stack.indented;266      subStream.start = stream.start - state.stack.indented;267      subStream.lastColumnPos = stream.lastColumnPos - state.stack.indented;268      subStream.lastColumnValue = stream.lastColumnValue - state.stack.indented;269      var style = state.subMode.token(subStream, state.subState);270      stream.pos = subStream.pos + state.stack.indented;271      return style;272    }273    function firstSub(stream, state) {274      state.stack.indented = stream.column();275      state.line = state.tokenize = sub;276      return state.tokenize(stream, state);277    }278    function createMode(mode) {279      var query = embedded[mode];280      var spec = CodeMirror.mimeModes[query];281      if (spec) {282        return CodeMirror.getMode(config, spec);283      }284      var factory = CodeMirror.modes[query];285      if (factory) {286        return factory(config, {name: query});287      }288      return CodeMirror.getMode(config, "null");289    }290    function getMode(mode) {291      if (!modes.hasOwnProperty(mode)) {292        return modes[mode] = createMode(mode);293      }294      return modes[mode];295    }296    function startSubMode(mode, state) {297      var subMode = getMode(mode);298      var subState = subMode.startState && subMode.startState();299      state.subMode = subMode;300      state.subState = subState;301      state.stack = {302        parent: state.stack,303        style: "sub",304        indented: state.indented + 1,305        tokenize: state.line306      };307      state.line = state.tokenize = firstSub;308      return "slimSubmode";309    }310    function doctypeLine(stream, _state) {311      stream.skipToEnd();312      return "slimDoctype";313    }314    function startLine(stream, state) {315      var ch = stream.peek();316      if (ch == '<') {317        return (state.tokenize = startHtmlLine(state.tokenize))(stream, state);318      }319      if (stream.match(/^[|']/)) {320        return startHtmlMode(stream, state, 1);321      }322      if (stream.match(/^\/(!|\[\w+])?/)) {323        return commentMode(stream, state);324      }325      if (stream.match(/^(-|==?[<>]?)/)) {326        state.tokenize = lineContinuable(stream.column(), commaContinuable(stream.column(), ruby));327        return "slimSwitch";328      }329      if (stream.match(/^doctype\b/)) {330        state.tokenize = doctypeLine;331        return "keyword";332      }333      var m = stream.match(embeddedRegexp);334      if (m) {335        return startSubMode(m[1], state);336      }337      return slimTag(stream, state);338    }339    function slim(stream, state) {340      if (state.startOfLine) {341        return startLine(stream, state);342      }343      return slimTag(stream, state);344    }345    function slimTag(stream, state) {346      if (stream.eat('*')) {347        state.tokenize = startRubySplat(slimTagExtras);348        return null;349      }350      if (stream.match(nameRegexp)) {351        state.tokenize = slimTagExtras;352        return "slimTag";353      }354      return slimClass(stream, state);355    }356    function slimTagExtras(stream, state) {357      if (stream.match(/^(<>?|><?)/)) {358        state.tokenize = slimClass;359        return null;360      }361      return slimClass(stream, state);362    }363    function slimClass(stream, state) {364      if (stream.match(classIdRegexp)) {365        state.tokenize = slimClass;366        return "slimId";367      }368      if (stream.match(classNameRegexp)) {369        state.tokenize = slimClass;370        return "slimClass";371      }372      return slimAttribute(stream, state);373    }374    function slimAttribute(stream, state) {375      if (stream.match(/^([\[\{\(])/)) {376        return startAttributeWrapperMode(state, closing[RegExp.$1], slimAttribute);377      }378      if (stream.match(attributeNameRegexp)) {379        state.tokenize = slimAttributeAssign;380        return "slimAttribute";381      }382      if (stream.peek() == '*') {383        stream.next();384        state.tokenize = startRubySplat(slimContent);385        return null;386      }387      return slimContent(stream, state);388    }389    function slimAttributeAssign(stream, state) {390      if (stream.match(/^==?/)) {391        state.tokenize = slimAttributeValue;392        return null;393      }394      // should never happen, because of forward lookup395      return slimAttribute(stream, state);396    }397    function slimAttributeValue(stream, state) {398      var ch = stream.peek();399      if (ch == '"' || ch == "\'") {400        state.tokenize = readQuoted(ch, "string", true, false, slimAttribute);401        stream.next();402        return state.tokenize(stream, state);403      }404      if (ch == '[') {405        return startRubySplat(slimAttribute)(stream, state);406      }407      if (ch == ':') {408        return startRubySplat(slimAttributeSymbols)(stream, state);409      }410      if (stream.match(/^(true|false|nil)\b/)) {411        state.tokenize = slimAttribute;412        return "keyword";413      }414      return startRubySplat(slimAttribute)(stream, state);415    }416    function slimAttributeSymbols(stream, state) {417      stream.backUp(1);418      if (stream.match(/^[^\s],(?=:)/)) {419        state.tokenize = startRubySplat(slimAttributeSymbols);420        return null;421      }422      stream.next();423      return slimAttribute(stream, state);424    }425    function readQuoted(quote, style, embed, unescaped, nextTokenize) {426      return function(stream, state) {427        finishContinue(state);428        var fresh = stream.current().length == 0;429        if (stream.match(/^\\$/, fresh)) {430          if (!fresh) return style;431          continueLine(state, state.indented);432          return "lineContinuation";433        }434        if (stream.match(/^#\{/, fresh)) {435          if (!fresh) return style;436          state.tokenize = rubyInQuote("}", state.tokenize);437          return null;438        }439        var escaped = false, ch;440        while ((ch = stream.next()) != null) {441          if (ch == quote && (unescaped || !escaped)) {442            state.tokenize = nextTokenize;443            break;444          }445          if (embed && ch == "#" && !escaped) {446            if (stream.eat("{")) {447              stream.backUp(2);448              break;449            }450          }451          escaped = !escaped && ch == "\\";452        }453        if (stream.eol() && escaped) {454          stream.backUp(1);455        }456        return style;457      };458    }459    function slimContent(stream, state) {460      if (stream.match(/^==?/)) {461        state.tokenize = ruby;462        return "slimSwitch";463      }464      if (stream.match(/^\/$/)) { // tag close hint465        state.tokenize = slim;466        return null;467      }468      if (stream.match(/^:/)) { // inline tag469        state.tokenize = slimTag;470        return "slimSwitch";471      }472      startHtmlMode(stream, state, 0);473      return state.tokenize(stream, state);474    }475    var mode = {476      // default to html mode477      startState: function() {478        var htmlState = htmlMode.startState();479        var rubyState = rubyMode.startState();480        return {481          htmlState: htmlState,482          rubyState: rubyState,483          stack: null,484          last: null,485          tokenize: slim,486          line: slim,487          indented: 0488        };489      },490      copyState: function(state) {491        return {492          htmlState : CodeMirror.copyState(htmlMode, state.htmlState),493          rubyState: CodeMirror.copyState(rubyMode, state.rubyState),494          subMode: state.subMode,495          subState: state.subMode && CodeMirror.copyState(state.subMode, state.subState),496          stack: state.stack,497          last: state.last,498          tokenize: state.tokenize,499          line: state.line500        };501      },502      token: function(stream, state) {503        if (stream.sol()) {504          state.indented = stream.indentation();505          state.startOfLine = true;506          state.tokenize = state.line;507          while (state.stack && state.stack.indented > state.indented && state.last != "slimSubmode") {508            state.line = state.tokenize = state.stack.tokenize;509            state.stack = state.stack.parent;510            state.subMode = null;511            state.subState = null;512          }513        }514        if (stream.eatSpace()) return null;515        var style = state.tokenize(stream, state);516        state.startOfLine = false;517        if (style) state.last = style;518        return styleMap.hasOwnProperty(style) ? styleMap[style] : style;519      },520      blankLine: function(state) {521        if (state.subMode && state.subMode.blankLine) {522          return state.subMode.blankLine(state.subState);523        }524      },525      innerMode: function(state) {526        if (state.subMode) return {state: state.subState, mode: state.subMode};527        return {state: state, mode: mode};528      }529      //indent: function(state) {530      //  return state.indented;531      //}532    };533    return mode;534  }, "htmlmixed", "ruby");535  CodeMirror.defineMIME("text/x-slim", "slim");536  CodeMirror.defineMIME("application/x-slim", "slim");...

Full Screen

Full Screen

project-state-reducer.test.js

Source:project-state-reducer.test.js Github

copy

Full Screen

1/* eslint-env jest */2import projectStateReducer from '../../../src/reducers/project-state';3import {4    LoadingState,5    autoUpdateProject,6    doneCreatingProject,7    doneUpdatingProject,8    manualUpdateProject,9    onFetchedProjectData,10    onLoadedProject,11    projectError,12    remixProject,13    requestNewProject,14    requestProjectUpload,15    saveProjectAsCopy,16    setProjectId17} from '../../../src/reducers/project-state';18test('initialState', () => {19    let defaultState;20    /* projectStateReducer(state, action) */21    expect(projectStateReducer(defaultState, {type: 'anything'})).toBeDefined();22    expect(projectStateReducer(defaultState, {type: 'anything'}).error).toBe(null);23    expect(projectStateReducer(defaultState, {type: 'anything'}).projectData).toBe(null);24    expect(projectStateReducer(defaultState, {type: 'anything'}).projectId).toBe(null);25    expect(projectStateReducer(defaultState, {type: 'anything'}).loadingState).toBe(LoadingState.NOT_LOADED);26});27test('doneCreatingProject for new project with projectId type string shows project with that id', () => {28    const initialState = {29        projectId: null,30        loadingState: LoadingState.CREATING_NEW31    };32    const action = doneCreatingProject('100', initialState.loadingState);33    const resultState = projectStateReducer(initialState, action);34    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITH_ID);35    expect(resultState.projectId).toBe('100');36});37test('doneCreatingProject for new project with projectId type number shows project with id of type number', () => {38    const initialState = {39        projectId: null,40        loadingState: LoadingState.CREATING_NEW41    };42    const action = doneCreatingProject(100, initialState.loadingState);43    const resultState = projectStateReducer(initialState, action);44    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITH_ID);45    expect(resultState.projectId).toBe(100);46});47test('doneCreatingProject for remix shows project with that id', () => {48    const initialState = {49        projectId: null,50        loadingState: LoadingState.REMIXING51    };52    const action = doneCreatingProject('100', initialState.loadingState);53    const resultState = projectStateReducer(initialState, action);54    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITH_ID);55    expect(resultState.projectId).toBe('100');56});57test('doneCreatingProject for save as copy shows project with that id', () => {58    const initialState = {59        projectId: null,60        loadingState: LoadingState.CREATING_COPY61    };62    const action = doneCreatingProject('100', initialState.loadingState);63    const resultState = projectStateReducer(initialState, action);64    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITH_ID);65    expect(resultState.projectId).toBe('100');66});67test('onFetchedProjectData with id loads project data into vm', () => {68    const initialState = {69        projectData: null,70        loadingState: LoadingState.FETCHING_WITH_ID71    };72    const action = onFetchedProjectData('1010101', initialState.loadingState);73    const resultState = projectStateReducer(initialState, action);74    expect(resultState.loadingState).toBe(LoadingState.LOADING_VM_WITH_ID);75    expect(resultState.projectData).toBe('1010101');76});77test('onFetchedProjectData new loads project data into vm', () => {78    const initialState = {79        projectData: null,80        loadingState: LoadingState.FETCHING_NEW_DEFAULT81    };82    const action = onFetchedProjectData('1010101', initialState.loadingState);83    const resultState = projectStateReducer(initialState, action);84    expect(resultState.loadingState).toBe(LoadingState.LOADING_VM_NEW_DEFAULT);85    expect(resultState.projectData).toBe('1010101');86});87test('onLoadedProject upload, with canSave false, shows without id', () => {88    const initialState = {89        loadingState: LoadingState.LOADING_VM_FILE_UPLOAD90    };91    const action = onLoadedProject(initialState.loadingState, false, true);92    const resultState = projectStateReducer(initialState, action);93    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITHOUT_ID);94});95test('onLoadedProject upload, with canSave true, prepares to save', () => {96    const initialState = {97        loadingState: LoadingState.LOADING_VM_FILE_UPLOAD98    };99    const action = onLoadedProject(initialState.loadingState, true, true);100    const resultState = projectStateReducer(initialState, action);101    expect(resultState.loadingState).toBe(LoadingState.AUTO_UPDATING);102});103test('onLoadedProject with id shows with id', () => {104    const initialState = {105        loadingState: LoadingState.LOADING_VM_WITH_ID106    };107    const action = onLoadedProject(initialState.loadingState, true, true);108    const resultState = projectStateReducer(initialState, action);109    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITH_ID);110});111test('onLoadedProject new shows without id', () => {112    const initialState = {113        loadingState: LoadingState.LOADING_VM_NEW_DEFAULT114    };115    const action = onLoadedProject(initialState.loadingState, false, true);116    const resultState = projectStateReducer(initialState, action);117    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITHOUT_ID);118});119test('onLoadedProject new, to save shows without id', () => {120    const initialState = {121        loadingState: LoadingState.LOADING_VM_NEW_DEFAULT122    };123    const action = onLoadedProject(initialState.loadingState, true, true);124    const resultState = projectStateReducer(initialState, action);125    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITHOUT_ID);126});127test('onLoadedProject with success false, no project id, shows without id', () => {128    const initialState = {129        loadingState: LoadingState.LOADING_VM_WITH_ID,130        projectId: null131    };132    const action = onLoadedProject(initialState.loadingState, false, false);133    const resultState = projectStateReducer(initialState, action);134    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITHOUT_ID);135});136test('onLoadedProject with success false, valid project id, shows with id', () => {137    const initialState = {138        loadingState: LoadingState.LOADING_VM_WITH_ID,139        projectId: '12345'140    };141    const action = onLoadedProject(initialState.loadingState, false, false);142    const resultState = projectStateReducer(initialState, action);143    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITH_ID);144});145test('doneUpdatingProject with id shows with id', () => {146    const initialState = {147        loadingState: LoadingState.MANUAL_UPDATING148    };149    const action = doneUpdatingProject(initialState.loadingState);150    const resultState = projectStateReducer(initialState, action);151    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITH_ID);152});153test('doneUpdatingProject with id, before copy, creates copy', () => {154    const initialState = {155        loadingState: LoadingState.UPDATING_BEFORE_COPY156    };157    const action = doneUpdatingProject(initialState.loadingState);158    const resultState = projectStateReducer(initialState, action);159    expect(resultState.loadingState).toBe(LoadingState.CREATING_COPY);160});161test('doneUpdatingProject with id, before new, fetches default project', () => {162    const initialState = {163        loadingState: LoadingState.UPDATING_BEFORE_NEW164    };165    const action = doneUpdatingProject(initialState.loadingState);166    const resultState = projectStateReducer(initialState, action);167    expect(resultState.loadingState).toBe(LoadingState.FETCHING_NEW_DEFAULT);168});169test('setProjectId, with same id as before, should show with id, not fetch', () => {170    const initialState = {171        projectId: '100',172        loadingState: LoadingState.SHOWING_WITH_ID173    };174    const action = setProjectId('100');175    const resultState = projectStateReducer(initialState, action);176    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITH_ID);177    expect(resultState.projectId).toBe('100');178});179test('setProjectId, with different id as before, should fetch with id, not show with id', () => {180    const initialState = {181        projectId: 99,182        loadingState: LoadingState.SHOWING_WITH_ID183    };184    const action = setProjectId('100');185    const resultState = projectStateReducer(initialState, action);186    expect(resultState.loadingState).toBe(LoadingState.FETCHING_WITH_ID);187    expect(resultState.projectId).toBe('100');188});189test('setProjectId, with same id as before, but not same type, should fetch because not ===', () => {190    const initialState = {191        projectId: '100',192        loadingState: LoadingState.SHOWING_WITH_ID193    };194    const action = setProjectId(100);195    const resultState = projectStateReducer(initialState, action);196    expect(resultState.loadingState).toBe(LoadingState.FETCHING_WITH_ID);197    expect(resultState.projectId).toBe(100);198});199test('requestNewProject, when can\'t create new, should fetch default project without id', () => {200    const initialState = {201        loadingState: LoadingState.SHOWING_WITHOUT_ID202    };203    const action = requestNewProject(false);204    const resultState = projectStateReducer(initialState, action);205    expect(resultState.loadingState).toBe(LoadingState.FETCHING_NEW_DEFAULT);206});207test('requestNewProject, when can create new, should save and prepare to fetch default project', () => {208    const initialState = {209        loadingState: LoadingState.SHOWING_WITH_ID210    };211    const action = requestNewProject(true);212    const resultState = projectStateReducer(initialState, action);213    expect(resultState.loadingState).toBe(LoadingState.UPDATING_BEFORE_NEW);214});215test('requestProjectUpload when project not loaded should load', () => {216    const initialState = {217        loadingState: LoadingState.NOT_LOADED218    };219    const action = requestProjectUpload(initialState.loadingState);220    const resultState = projectStateReducer(initialState, action);221    expect(resultState.loadingState).toBe(LoadingState.LOADING_VM_FILE_UPLOAD);222});223test('requestProjectUpload when showing project with id should load', () => {224    const initialState = {225        loadingState: LoadingState.SHOWING_WITH_ID226    };227    const action = requestProjectUpload(initialState.loadingState);228    const resultState = projectStateReducer(initialState, action);229    expect(resultState.loadingState).toBe(LoadingState.LOADING_VM_FILE_UPLOAD);230});231test('requestProjectUpload when showing project without id should load', () => {232    const initialState = {233        loadingState: LoadingState.SHOWING_WITHOUT_ID234    };235    const action = requestProjectUpload(initialState.loadingState);236    const resultState = projectStateReducer(initialState, action);237    expect(resultState.loadingState).toBe(LoadingState.LOADING_VM_FILE_UPLOAD);238});239test('manualUpdateProject should prepare to update', () => {240    const initialState = {241        loadingState: LoadingState.SHOWING_WITH_ID242    };243    const action = manualUpdateProject();244    const resultState = projectStateReducer(initialState, action);245    expect(resultState.loadingState).toBe(LoadingState.MANUAL_UPDATING);246});247test('autoUpdateProject should prepare to update', () => {248    const initialState = {249        loadingState: LoadingState.SHOWING_WITH_ID250    };251    const action = autoUpdateProject();252    const resultState = projectStateReducer(initialState, action);253    expect(resultState.loadingState).toBe(LoadingState.AUTO_UPDATING);254});255test('saveProjectAsCopy should save, before preparing to save as a copy', () => {256    const initialState = {257        loadingState: LoadingState.SHOWING_WITH_ID258    };259    const action = saveProjectAsCopy();260    const resultState = projectStateReducer(initialState, action);261    expect(resultState.loadingState).toBe(LoadingState.UPDATING_BEFORE_COPY);262});263test('remixProject should prepare to remix', () => {264    const initialState = {265        loadingState: LoadingState.SHOWING_WITH_ID266    };267    const action = remixProject();268    const resultState = projectStateReducer(initialState, action);269    expect(resultState.loadingState).toBe(LoadingState.REMIXING);270});271test('projectError from various states should show error', () => {272    const startStates = [273        LoadingState.AUTO_UPDATING,274        LoadingState.CREATING_NEW,275        LoadingState.FETCHING_NEW_DEFAULT,276        LoadingState.FETCHING_WITH_ID,277        LoadingState.LOADING_VM_NEW_DEFAULT,278        LoadingState.LOADING_VM_WITH_ID,279        LoadingState.MANUAL_UPDATING,280        LoadingState.REMIXING,281        LoadingState.CREATING_COPY,282        LoadingState.UPDATING_BEFORE_NEW283    ];284    for (const startState of startStates) {285        const initialState = {286            error: null,287            loadingState: startState288        };289        const action = projectError('Error string');290        const resultState = projectStateReducer(initialState, action);291        expect(resultState.error).toEqual('Error string');292    }293});294test('fatal projectError should show error state', () => {295    const startStates = [296        LoadingState.FETCHING_NEW_DEFAULT,297        LoadingState.FETCHING_WITH_ID,298        LoadingState.LOADING_VM_NEW_DEFAULT,299        LoadingState.LOADING_VM_WITH_ID300    ];301    for (const startState of startStates) {302        const initialState = {303            error: null,304            loadingState: startState305        };306        const action = projectError('Error string');307        const resultState = projectStateReducer(initialState, action);308        expect(resultState.loadingState).toBe(LoadingState.ERROR);309    }310});311test('non-fatal projectError should show normal state', () => {312    const startStates = [313        LoadingState.AUTO_UPDATING,314        LoadingState.CREATING_COPY,315        LoadingState.MANUAL_UPDATING,316        LoadingState.REMIXING,317        LoadingState.UPDATING_BEFORE_NEW318    ];319    for (const startState of startStates) {320        const initialState = {321            error: null,322            loadingState: startState323        };324        const action = projectError('Error string');325        const resultState = projectStateReducer(initialState, action);326        expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITH_ID);327    }328});329test('projectError when creating new while viewing project with id should show project with id', () => {330    const initialState = {331        error: null,332        loadingState: LoadingState.CREATING_NEW,333        projectId: '12345'334    };335    const action = projectError('Error string');336    const resultState = projectStateReducer(initialState, action);337    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITH_ID);338});339test('projectError when creating new while logged out, looking at default project should show default project', () => {340    const initialState = {341        error: null,342        loadingState: LoadingState.CREATING_NEW,343        projectId: '0'344    };345    const action = projectError('Error string');346    const resultState = projectStateReducer(initialState, action);347    expect(resultState.loadingState).toBe(LoadingState.SHOWING_WITHOUT_ID);348});349test('projectError from showing project should show error', () => {350    const initialState = {351        error: null,352        loadingState: LoadingState.FETCHING_WITH_ID353    };354    const action = projectError('Error string');355    const resultState = projectStateReducer(initialState, action);356    expect(resultState.loadingState).toBe(LoadingState.ERROR);357    expect(resultState.error).toEqual('Error string');...

Full Screen

Full Screen

opcodes.js

Source:opcodes.js Github

copy

Full Screen

1var misc = require ( './misc.js' );2function make_opcode ( code, name, argc, stack, func ) {3  return {4    code: code,5    name: name,6    argc: argc,7    stack: stack,8    func: func,9    };10  }11var opcodes = [12  make_opcode ( 0x00, 'next', 0, 0,13  function noop ( state ) {14    // Since noop's are shifted into the bunch, or used to pad bunches, as soon15    // as a noop is encountered, the next bunch needs to be loaded.16    // It might make sense to refactor this, but this is also the must17    // efficient way to implement.18    if ( state.get_pc () === state.func.length ) {19      state.run = false;20      }21    else {22      state.check_bunch ( state.func[state.get_pc ( )] );23      state.bunch = state.func[state.get_pc ( ) ].slice ( 0 );24      state.move_pc ( 1 );25      }26    } ),27  make_opcode ( 0x01, 'dup_1', 2, 1,28    function dup1 ( state ) {29    state.push ( state.get_stack ( state.get_arg ( 1 ) ) );30    } ),31  make_opcode ( 0x02, 'li_w', 1, 1,32  function li_w ( state ) {33    state.push ( state.func[ state.get_pc ( ) ] );34    state.move_pc ( 1 );35    } ),36  make_opcode ( 0x03, 'set_1', 2, -1,37    function set ( state ) {38    state.set_stack ( state.get_arg ( 1 ), state.pop ( ) );39    } ),40  make_opcode ( 0x04, 'pop', 1, -1,41  function pop ( state ) {42    state.pop ( );43    } ),44  make_opcode ( 0x05, 'call_1', 2, 0,45  function call ( state ) {46    var arg_count = state.get_arg ( 1 );47    var func = state.get_stack ( arg_count );48    if ( func.type === 'external' ) {49      var size = state.stack.length;50      var args = state.stack.splice ( size - arg_count, size );51      var res = func.func.apply ( null, args );52      // Pop the args.53      for ( var i = 0; i < arg_count; i++ ) {54        state.pop ( );55        }56      // Pop the function.57      state.pop ( );58      // Push the result59      state.push ( res );60      }61    else if ( func.type === 'internal' ) {62      state.call_stack[state.call_stack_top++] = [state.func, state._pc, state.stack_top - ( arg_count + 1 ) ];63      state.func = func.code;64      state._pc = 0;65      }66    } ),67  make_opcode ( 0x06, 'ret', 1, 0,68  function ret ( state ) {69    if ( state.call_stack_top === 0 ) {70      state.run = false;71      }72    else {73      var info = state.call_stack[--state.call_stack_top];74      state.func = info[0];75      state._pc = info[1];76      var out = state.pop ( );77      while ( state.stack_top > info[2] ) {78        state.pop ( );79        }80      state.push ( out );81      state.clear_bunch ( );82      }83    } ),84  make_opcode ( 0x07, 'eq', 1, -1,85  function eq ( state ) {86    state.push ( state.pop ( ) === state.pop ( ) );87    } ),88  make_opcode ( 0x08, 'j_1', 2, 0,89  function j_1 ( state ) {90    state.move_pc ( state.get_arg ( 1 ) );91    } ),92  make_opcode ( 0x09, 'j_2', 3, 0,93  function j_2 ( state ) {94    state.move_pc ( state.get_arg ( 1 ) << 8 + state.get_arg ( 2 ) );95    } ),96  make_opcode ( 0x0a, 'j_3', 4, 0,97  function j_3 ( state ) {98    state.move_pc ( ( state.get_arg ( 1 ) << 8 +99                      state.get_arg ( 2 ) << 8 ) +100                      state.get_arg ( 3 ) );101    } ),102  make_opcode ( 0x0b, 'j_w', 1, 0,103  function j_w ( state ) {104    state.move_pc ( state.func[ state.get_pc ( ) ] );105    } ),106  make_opcode ( 0x0c, 'bz_1', 2, -1,107  function bz_1 ( state ) {108    if ( ! state.pop ( ) ) {109      state.move_pc ( state.get_arg ( 1 ) );110      }111    } ),112  make_opcode ( 0x0d, 'bz_2', 3, -1,113  function bz_2 ( state ) {114    if ( ! state.pop ( ) ) {115      state.move_pc ( state.get_arg ( 1 ) << 8 + state.get_arg ( 2 ) );116      }117    } ),118  make_opcode ( 0x0e, 'bz_3', 4, -1,119  function bz_3 ( state ) {120    if ( ! state.pop ( ) ) {121    state.move_pc ( ( state.get_arg ( 1 ) << 8 +122                      state.get_arg ( 2 ) << 8 ) +123                      state.get_arg ( 3 ) );124      }125    } ),126  make_opcode ( 0x0f, 'bz_w', 1, -1,127  function bz_w ( state ) {128    if ( ! state.pop ( ) ) {129      state.move_pc ( state.func[ state.get_pc ( ) ] );130      }131    } ),132  make_opcode ( 0x10, 'not', 1, 0,133  function not ( state ) {134    state.push ( ! state.pop ( ) );135    } ),136  make_opcode ( 0x11, 'fadd', 1, -1,137  function fadd ( state ) {138    var right = state.pop ( );139    var left = state.pop ( );140    state.push ( left + right );141    } ),142  make_opcode ( 0x12, 'fsub', 1, -1,143  function fsub ( state ) {144    var right = state.pop ( );145    var left = state.pop ( );146    state.push ( left - right );147    } ),148  make_opcode ( 0x13, 'fmul', 1, -1,149  function fmul ( state ) {150    var right = state.pop ( );151    var left = state.pop ( );152    state.push ( left * right );153    } ),154  make_opcode ( 0x14, 'fdiv', 1, -1,155  function fdiv ( state ) {156    var right = state.pop ( );157    var left = state.pop ( );158    state.push ( left / right );159    } ),160  make_opcode ( 0x15, 'fmod', 1, -1,161  function fmod ( state ) {162    var right = state.pop ( );163    var left = state.pop ( );164    state.push ( left % right );165    } ),166  make_opcode ( 0x16, 'iadd', 1, -1,167  function iadd ( state ) {168    var right = state.pop ( );169    var left = state.pop ( );170    state.push ( left + right );171    } ),172  make_opcode ( 0x17, 'isub', 1, -1,173  function isub ( state ) {174    var right = state.pop ( );175    var left = state.pop ( );176    state.push ( left - right );177    } ),178  make_opcode ( 0x18, 'imul', 1, -1,179  function imul ( state ) {180    var right = state.pop ( );181    var left = state.pop ( );182    state.push ( left * right );183    } ),184  make_opcode ( 0x19, 'idiv', 1, -1,185  function idiv ( state ) {186    var right = state.pop ( );187    var left = state.pop ( );188    state.push ( left / right );189    } ),190  make_opcode ( 0x1a, 'imod', 1, -1,191  function imod ( state ) {192    var right = state.pop ( );193    var left = state.pop ( );194    state.push ( left % right );195    } ),196  make_opcode ( 0x1b, 'uadd', 1, -1,197  function uadd ( state ) {198    var right = state.pop ( );199    var left = state.pop ( );200    state.push ( left + right );201    } ),202  make_opcode ( 0x1c, 'usub', 1, -1,203  function usub ( state ) {204    var right = state.pop ( );205    var left = state.pop ( );206    state.push ( left - right );207    } ),208  make_opcode ( 0x1d, 'umul', 1, -1,209  function umul ( state ) {210    var right = state.pop ( );211    var left = state.pop ( );212    state.push ( left * right );213    } ),214  make_opcode ( 0x1e, 'udiv', 1, -1,215  function udiv ( state ) {216    var right = state.pop ( );217    var left = state.pop ( );218    state.push ( left / right );219    } ),220  make_opcode ( 0x1f, 'umod', 1, -1,221  function umod ( state ) {222    var right = state.pop ( );223    var left = state.pop ( );224    state.push ( left % right );225    } ),226  make_opcode ( 0x20, 'refi', 1, 0,227  function refi ( state ) {228    // TODO(kzentner): Do we want to emulate reference counting in javascript.229    } ),230  make_opcode ( 0x21, 'refd', 1, 0,231  function refd ( state ) {232    // TODO(kzentner): Do we want to emulate reference counting in javascript.233    state.pop ( );234    } ),235  make_opcode ( 0x22, 'make_1', 2, 0,236  function make1 ( state ) {237    var field_count = state.get_arg ( 1 );238    var size = state.stack.length;239    var obj = state.stack.splice ( size - field_count - 1, size );240    // Pop the fields.241    for ( var i = 0; i < field_count; i++ ) {242      state.pop ( );243      }244    // Pop the type tag.245    state.pop ( );246    state.push ( obj );247    } ),248  make_opcode ( 0x23, 'pushfree_1', 1, 0,249  function pushfree_1 ( state ) {250    // TODO(kzentner): Do we want to emulate reference counting in javascript?251    } ),252  make_opcode ( 0x24, 'popfree_1', 1, 0,253  function popfree_1 ( state ) {254    // TODO(kzentner): Do we want to emulate reference counting in javascript?255    } ),256  make_opcode ( 0x25, 'clone', 1, 0,257  function clone ( state ) {258    function copy ( obj ) {259      if ( typeof ( obj ) !== 'object' ) {260        return obj;261        }262      out = [];263      obj.forEach ( function ( val ) {264        // TODO(kzentner): Only recurse on mutable objects.265        out.push ( copy ( val ) );266        } );267      return out;268      }269    state.push ( copy ( state.pop ( ) ) );270    } ),271  make_opcode ( 0x26, 'safe', 1, 0,272  function safe ( state ) {273    // TODO(kzentner): Implement safe point instrumentation.274    } ),275  make_opcode ( 0x27, 'read_1', 2, 0,276  function read_1 ( state ) {277    state.push ( state.pop ( )[ state.get_arg ( 1 ) - 1 ] );278    } ),279  make_opcode ( 0x28, 'write_1', 2, 0,280  function write_1 ( state ) {281    var val = state.pop ( );282    var obj = state.pop ( );283    obj[ state.get_arg ( 1 ) - 1 ] = val;284    } ),285  make_opcode ( 0x29, 'stack_1', 2, 0,286  function stack_1 ( state ) {287    state.stack_top += state.get_arg ( 1 );288    } ),289  make_opcode ( 0x2a, 'noop', 1, 0,290  function noop ( state ) {291    } ),292  make_opcode ( 0x2b, 'end', 1, 0,293  function end ( state ) {294    state.run = false;295    } ),296  make_opcode ( 0x2c, 'debug', 1, 0,297  function debug ( state ) {298    state.debug = ! state.debug;299    } ),300  make_opcode ( 0x2d, 'f2i', 1, 0,301  function f2i ( state ) {302    // TODO(kzentner): Implement integer arithmetic in the vm.303    } ),304  make_opcode ( 0x2e, 'i2f', 1, 0,305  function i2f ( state ) {306    // TODO(kzentner): Implement integer arithmetic in the vm.307    } ),308  make_opcode ( 0x2f, 'band', 1, -1,309  function band ( state ) {310    var right = state.pop ( );311    var left = state.pop ( );312    state.push ( left & right );313    } ),314  make_opcode ( 0x30, 'bor', 1, -1,315  function band ( state ) {316    var right = state.pop ( );317    var left = state.pop ( );318    state.push ( left | right );319    } ),320  make_opcode ( 0x31, 'bxor', 1, -1,321  function bxor ( state ) {322    var right = state.pop ( );323    var left = state.pop ( );324    state.push ( left ^ right );325    } ),326  make_opcode ( 0x32, 'bnot', 1, 0,327  function bnot ( state ) {328    state.push ( ~state.pop ( ) );329    } ),330  make_opcode ( 0x33, 'bsl', 1, -1,331  function bsl ( state ) {332    var right = state.pop ( );333    var left = state.pop ( );334    state.push ( left << right );335    } ),336  make_opcode ( 0x34, 'bsrl', 1, -1,337  function bsra ( state ) {338    var right = state.pop ( );339    var left = state.pop ( );340    state.push ( left >>> right );341    } ),342  make_opcode ( 0x35, 'bsra', 1, -1,343  function bsrl ( state ) {344    var right = state.pop ( );345    var left = state.pop ( );346    state.push ( left >> right );347    } ),348  ];349function make_optables ( ops ) {350  var out = {351    op: {},352    code_to_obj: [],353    code: {},354    name: [],355    argc: [],356    func: [],357    stack: [],358    };359  for ( var i in ops ) {360    out.op[ops[i].name] = ops[i];361    out.code_to_obj[ops[i].code] = ops[i];362    out.code[ops[i].name] = ops[i].code;363    out.argc[ops[i].code] = ops[i].argc;364    out.func[ops[i].code] = ops[i].func;365    out.name[ops[i].code] = ops[i].name;366    out.stack[ops[i].code] = ops[i].stack;367    }368  return out;369  }370var tables = make_optables ( opcodes );371var code = tables.code;372var argc = tables.argc;373var func = tables.func;374var name = tables.name;375var code_to_obj = tables.code_to_obj;376var op = tables.op;377var stack = tables.stack;378exports.opcodes = opcodes;379exports.op = op;380exports.code_to_obj = code_to_obj;381exports.code = code;382exports.argc = argc;383exports.func = func;384exports.name = name;385exports.tables = tables;...

Full Screen

Full Screen

Post.js

Source:Post.js Github

copy

Full Screen

1import { createReducer } from "@reduxjs/toolkit";2const initialState={};3export const likeReducer = createReducer(initialState, {4    likeRequest: (state) => {5      state.loading = true;6    },7    likeSuccess: (state, action) => {8      state.loading = false;9      state.message = action.payload;10    },11    likeFailure: (state, action) => {12      state.loading = false;13      state.error = action.payload;14    },15    16  addCommentRequest: (state) => {17    state.loading = true;18  },19  addCommentSuccess: (state, action) => {20    state.loading = false;21    state.message = action.payload;22  },23  addCommentFailure: (state, action) => {24    state.loading = false;25    state.error = action.payload;26  },27  deleteCommentRequest: (state) => {28    state.loading = true;29  },30  deleteCommentSuccess: (state, action) => {31    state.loading = false;32    state.message = action.payload;33  },34  deleteCommentFailure: (state, action) => {35    state.loading = false;36    state.error = action.payload;37  },38  newPostRequest: (state) => {39    state.loading = true;40  },41  newPostSuccess: (state, action) => {42    state.loading = false;43    state.message = action.payload;44  },45  newPostFailure: (state, action) => {46    state.loading = false;47    state.error = action.payload;48  },49  updateCaptionRequest: (state) => {50    state.loading = true;51  },52  updateCaptionSuccess: (state, action) => {53    state.loading = false;54    state.message = action.payload;55  },56  updateCaptionFailure: (state, action) => {57    state.loading = false;58    state.error = action.payload;59  },60  61  deletePostRequest: (state) => {62    state.loading = true;63  },64  deletePostSuccess: (state, action) => {65    state.loading = false;66    state.message = action.payload;67  },68  deletePostFailure: (state, action) => {69    state.loading = false;70    state.error = action.payload;71  },72  updateProfileRequest: (state) => {73    state.loading = true;74  },75  updateProfileSuccess: (state, action) => {76    state.loading = false;77    state.message = action.payload;78  },79  updateProfileFailure: (state, action) => {80    state.loading = false;81    state.error = action.payload;82  },83  updatePasswordRequest: (state) => {84    state.loading = true;85  },86  updatePasswordSuccess: (state, action) => {87    state.loading = false;88    state.message = action.payload;89  },90  updatePasswordFailure: (state, action) => {91    state.loading = false;92    state.error = action.payload;93  },94  deleteProfileRequest: (state) => {95    state.loading = true;96  },97  deleteProfileSuccess: (state, action) => {98    state.loading = false;99    state.message = action.payload;100  },101  deleteProfileFailure: (state, action) => {102    state.loading = false;103    state.error = action.payload;104  },105  forgotPasswordRequest: (state) => {106    state.loading = true;107  },108  forgotPasswordSuccess: (state, action) => {109    state.loading = false;110    state.message = action.payload;111  },112  forgotPasswordFailure: (state, action) => {113    state.loading = false;114    state.error = action.payload;115  },116  resetPasswordRequest: (state) => {117    state.loading = true;118  },119  resetPasswordSuccess: (state, action) => {120    state.loading = false;121    state.message = action.payload;122  },123  resetPasswordFailure: (state, action) => {124    state.loading = false;125    state.error = action.payload;126  },127  followUserRequest: (state) => {128    state.loading = true;129  },130  followUserSuccess: (state, action) => {131    state.loading = false;132    state.message = action.payload;133  },134  followUserFailure: (state, action) => {135    state.loading = false;136    state.error = action.payload;137  },138  clearErrors: (state) => {139    state.error = null;140  },141  clearMessage: (state) => {142    state.message = null;143  },144  145});146export const myPostsReducer = createReducer(initialState, {147  myPostsRequest: (state) => {148    state.loading = true;149  },150  myPostsSuccess: (state, action) => {151    state.loading = false;152    state.posts = action.payload;153  },154  myPostsFailure: (state, action) => {155    state.loading = false;156    state.error = action.payload;157  },158  clearErrors: (state) => {159    state.error = null;160  },161});162export const userPostsReducer = createReducer(initialState, {163  userPostsRequest: (state) => {164    state.loading = true;165  },166  userPostsSuccess: (state, action) => {167    state.loading = false;168    state.posts = action.payload;169  },170  userPostsFailure: (state, action) => {171    state.loading = false;172    state.error = action.payload;173  },174  clearErrors: (state) => {175    state.error = null;176  },...

Full Screen

Full Screen

Shape.reducer.js

Source:Shape.reducer.js Github

copy

Full Screen

1import {2  UPDATE_SHAPE,3  CHANGE_SHAPE,4  CHANGE_COLOR,5  CHANGE_PROJECT,6  UNDO_SHAPE,7  REDO_SHAPE8} from "../../redux/actions/actionTypes";9const INITIAL_STATE = {10  activeProject: "project-1",11  projectState: {},12  undoStack: {13    "project-1": [],14    "project-2": [],15    "project-3": [],16    "project-4": []17  },18  redoStack: {19    "project-1": [],20    "project-2": [],21    "project-3": [],22    "project-4": []23  }24};25const shapeReducer = (state = INITIAL_STATE, action) => {26  const { type, payload } = action;27  switch (type) {28    case UPDATE_SHAPE:29      console.log(state);30      if (state.undoStack[state.activeProject] === undefined) {31        return {32          ...state,33          projectState: {34            ...state.projectState,35            [state.activeProject]: {36              shape: payload.shape,37              color: payload.color,38              project: state.activeProject39            }40          },41          undoStack: {42            ...state.undoStack,43            [state.activeProject]: [44              {45                shape: payload.shape,46                color: payload.color,47                project: state.activeProject48              }49            ]50          }51        };52      }53      return {54        ...state,55        projectState: {56          ...state.projectState,57          [state.activeProject]: {58            shape: payload.shape,59            color: payload.color,60            project: state.activeProject61          }62        },63        undoStack: {64          ...state.undoStack,65          [state.activeProject]: state.undoStack[state.activeProject].concat({66            shape: payload.shape,67            color: payload.color,68            project: state.activeProject69          })70        }71      };72    case CHANGE_SHAPE:73      return {74        ...state,75        projectState: {76          ...state.projectState,77          [state.activeProject]: {78            ...state.projectState[state.activeProject],79            shape: payload.shape80          }81        }82      };83    case CHANGE_COLOR:84      return {85        ...state,86        projectState: {87          ...state.projectState,88          [state.activeProject]: {89            ...state.projectState[state.activeProject],90            color: payload.color91          }92        }93      };94    case CHANGE_PROJECT:95      return {96        ...state,97        activeProject: payload.project98      };99    case UNDO_SHAPE:100      if (101        state.undoStack[state.activeProject] === undefined ||102        state.undoStack[state.activeProject].length === 0103      ) {104        return { ...state };105      }106      return {107        ...state,108        redoStack: {109          ...state.redoStack,110          [state.activeProject]: state.redoStack[state.activeProject].concat(111            state.undoStack[state.activeProject][112              state.undoStack[state.activeProject].length - 1113            ]114          )115        },116        projectState: {117          ...state.projectState,118          [state.activeProject]:119            state.undoStack[state.activeProject][120              state.undoStack[state.activeProject].length - 1121            ]122        },123        undoStack: {124          ...state.undoStack,125          [state.activeProject]: state.undoStack[state.activeProject].slice(126            0,127            state.undoStack[state.activeProject].length - 1128          )129        }130      };131    case REDO_SHAPE:132      if (133        state.undoStack[state.activeProject] === undefined ||134        state.redoStack[state.activeProject].length === 0135      ) {136        return { ...state };137      }138      return {139        ...state,140        projectState: {141          ...state.projectState,142          [state.activeProject]:143            state.undoStack[state.activeProject][144              state.undoStack[state.activeProject].length - 1145            ]146        },147        undoStack: {148          ...state.undoStack,149          [state.activeProject]: state.undoStack[state.activeProject].concat(150            state.redoStack[state.activeProject][151              state.redoStack[state.activeProject].length - 1152            ]153          )154        },155        redoStack: {156          ...state.redoStack,157          [state.activeProject]: state.redoStack[state.activeProject].slice(158            0,159            state.redoStack[state.activeProject].length - 1160          )161        }162      };163    default:164      return state;165  }166};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2    it('Does not do much!', function() {3      cy.pause()4      cy.contains('type').click()5      cy.url().should('include', '/commands/actions')6      cy.get('.action-email')7        .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2    it('Visits the Kitchen Sink', function() {3        cy.pause()4        cy.contains('type').click()5        cy.url().should('include', '/commands/actions')6        cy.get('.action-email')7            .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    expect(true).to.equal(true)4  })5})6describe('My First Test', function() {7  it('Does not do much!', function() {8    expect(true).to.equal(false)9  })10})11describe('My First Test', function() {12  it('Visits the Kitchen Sink', function() {13    cy.contains('type').click()14    cy.url().should('include', '/commands/actions')15    cy.get('.action-email')16      .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2  it('Does not do much!', function() {3    expect(true).to.equal(true)4  })5})6describe('My First Test', function() {7  it('Does not do much!', function() {8    expect(true).to.equal(true)9  })10})11describe('My First Test', function() {12  it('Does not do much!', function() {13    expect(true).to.equal(true)14  })15})16describe('My First Test', function() {17  it('Does not do much!', function() {18    expect(true).to.equal(true)19  })20})21describe('My First Test', function() {22  it('Does not do much!', function() {23    expect(true).to.equal(true)24  })25})26describe('My First Test', function() {27  it('Does not do much!', function() {28    expect(true).to.equal(true)29  })30})31describe('My First Test', function() {32  it('Does not do much!', function() {33    expect(true).to.equal(true)34  })35})36describe('My First Test', function() {37  it('Does not do much!', function() {38    expect(true).to.equal(true)39  })40})41describe('My First Test', function() {42  it('Does not do much!', function() {43    expect(true).to.equal(true)44  })45})46describe('My First Test', function() {47  it('Does not do much!', function() {48    expect(true).to.equal(true)49  })50})51describe('My First Test', function() {52  it('Does not do much!', function() {53    expect(true).to.equal(true)54  })55})

Full Screen

Using AI Code Generation

copy

Full Screen

1it('should add a new todo to the list', () => {2    cy.get('.new-todo')3    .type('Clean room{enter}')4    cy.get('.todo-list li')5    .should('have.length', 1)6    .and('contain', 'Clean room')7})8it('should add a new todo to the list', () => {9    cy.get('.new-todo')10    .type('Clean room{enter}')11    cy.get('.todo-list li')12    .should('have.length', 1)13    .and('contain', 'Clean room')14    .and('have.class', 'todo')15    .find('label')16    .should('have.text', 'Clean room')17    .and('have.css', 'text-decoration-line', 'none')18    .and('have.css', 'text-decoration-style', 'solid')19    .and('have.css', 'text-decoration-color', 'rgb(0, 0, 0)')20    .invoke('text')21    .should('equal', 'Clean room')22})23it('should add a new todo to the list', () => {24    cy.get('.new-todo')25    .type('Clean room{enter}')26    cy.get('.todo-list li')27    .should('have.length', 1)28    .and('contain', 'Clean room')29    .and('have.class', 'todo')30    .find('label')31    .should('have.text', 'Clean room')32    .and('have.css', 'text-decoration-line', 'none')33    .and('have.css', 'text-decoration-style', 'solid')34    .and('have.css', 'text-decoration-color', 'rgb(0, 0, 0)')35    .invoke('text')36    .should('equal', 'Clean room')37    .invoke('split', ' ')38    .should('deep.equal', ['Clean', 'room'])39})40it('should add a new todo to the list', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', function() {2  it('Does not do much!', function() {3    cy.get('.App-header')4      .find('h2')5      .should('have.text', 'Welcome to React')6  })7})

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful