1(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 2'use strict'; 3 4var _require = require('../../lib/utils/types'), 5 ORIENTATION = _require.ORIENTATION; 6 7var entities = require('../../models/game/entities'); 8var blockColors = require('../../elements/blockly/colors'); 9 10module.exports = function () { 11 return { 12 game: { 13 tiles: [[1, 1, 1], [1, 4, 1], [1, 3, 1], [1, 3, 1], [1, 3, 1], [1, 3, 1], [1, 1, 1]], 14 15 entities: [entities.tutorialRobot({ x: 1, y: 5, id: 'ROBOT', orientation: ORIENTATION.BACK }), entities.chest({ x: 1, y: 1, orientation: 'FRONT' })] 16 }, 17 18 editor: { 19 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n<block type="start_handler" x="50" y="50" deletable="false">\n <statement name="body">\n <block type="move">\n <next>\n <block type="move"></block>\n </next>\n</block>\n</statement>\n</block>\n</xml>', 20 21 toolbox: '<xml id="toolbox" style="display: none">\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move" ></block>\n </category>\n </xml>' 22 }, 23 24 label: 'Blockly - Drag and Drop', 25 26 goals: [{ 27 type: 'moveTo', 28 params: { position: { x: 1, y: 1 }, entity: 'ROBOT' }, 29 desc: 'Move the robot to the metal tile', 30 isMandatory: true 31 }], 32 33 storyModal: { 34 text: 'Welcome to Robotopia where you can learn the basics of programming with cute little robots.', 35 hint: 'You can duplicate a block by copy and pasting it with CTRL+C and CTRL+V' 36 }, 37 38 winModal: { 39 text: 'This block allows you to rotate your robot. The direction can be changed via the dropdown menu inside the block', 40 unlockedBlock: { name: 'Rotate', img: '../../assets/img/tutorials/blocks/rotate-dropdown.png' } 41 }, 42 43 highlighters: { 44 classes: ['play-button'] 45 } 46 }; 47}; 48 49},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],2:[function(require,module,exports){ 50'use strict'; 51 52var _require = require('../../lib/utils/types'), 53 ORIENTATION = _require.ORIENTATION; 54 55var entities = require('../../models/game/entities'); 56var blockColors = require('../../elements/blockly/colors'); 57 58module.exports = function () { 59 return { 60 game: { 61 tiles: [[1, 1, 1, 1], [1, 1, 4, 1], [1, 1, 3, 1], [1, 3, 3, 1], [1, 3, 1, 1], [1, 3, 3, 1], [1, 1, 1, 1]], 62 63 entities: [entities.tutorialRobot({ x: 2, y: 5, id: 'ROBOT', orientation: ORIENTATION.LEFT })] 64 }, 65 66 editor: { 67 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n<block type="start_handler" x="50" y="50" deletable="false">\n <statement name="body">\n <block type="move" deletable="false">\n <next>\n <block type="move" deletable="false" />\n </next>\n <next>\n <block type="move" deletable="false" />\n </next>\n <next>\n <block type="move" deletable="false" />\n </next>\n <next>\n <block type="move" deletable="false" />\n </next>\n <next>\n <block type="move" deletable="false" />\n </next>\n <next>\n <block type="rotate" deletable="false" />\n </next>\n <next>\n <block type="rotate" deletable="false" />\n </next>\n <next>\n <block type="rotate" deletable="false" />\n </next>\n</block>\n</statement>\n</block>\n</xml>', 68 69 toolbox: '<xml id="toolbox" style="display: none">\n <category />\n </xml>' 70 }, 71 72 label: 'Blockly - Rearrange', 73 74 goals: [{ 75 type: 'moveTo', 76 params: { position: { x: 2, y: 1 }, entity: 'ROBOT' }, 77 desc: 'Move the robot to the metal tile', 78 isMandatory: true 79 }], 80 81 storyModal: { 82 text: 'Now that you know how to drag new blocks into the canvas, you need to master rearranging them. Stack the blocks in the right order to win this level.', 83 hint: 'You can only use the given blocks to solve this level' 84 }, 85 86 winModal: { 87 text: 'You mastered the basics of the interface, now your journey goes on with some harder puzzles.' 88 } 89 }; 90}; 91 92},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],3:[function(require,module,exports){ 93'use strict'; 94 95var _require = require('../../lib/utils/types'), 96 ORIENTATION = _require.ORIENTATION; 97 98var entities = require('../../models/game/entities'); 99var blockColors = require('../../elements/blockly/colors'); 100 101module.exports = function () { 102 return { 103 game: { 104 tiles: [[1, 1, 1, 1, 1], [1, 3, 3, 3, 1], [1, 3, 1, 3, 1], [1, 4, 1, 3, 1], [1, 1, 1, 1, 1]], 105 106 entities: [entities.tutorialRobot({ x: 3, y: 3, id: 'ROBOT', orientation: ORIENTATION.BACK })] 107 }, 108 109 editor: { 110 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n<block type="start_handler" x="50" y="50" deletable="false">\n</block>\n</xml>', 111 112 toolbox: '<xml id="toolbox" style="display: none">\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n </category>\n </xml>' 113 }, 114 115 label: 'Turn - Around', 116 117 goals: [{ 118 type: 'moveTo', 119 params: { position: { x: 1, y: 3 }, entity: 'ROBOT' }, 120 desc: 'Move the robot to the metal tile', 121 isMandatory: true 122 }], 123 124 storyModal: { 125 text: '', 126 hint: 'Next you will learn how to change the direction of the robot.' 127 }, 128 129 winModal: { 130 text: 'Good job there, making the robots spin!' 131 } 132 133 }; 134}; 135 136},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],4:[function(require,module,exports){ 137'use strict'; 138 139var _require = require('../../lib/utils/types'), 140 ORIENTATION = _require.ORIENTATION; 141 142var entities = require('../../models/game/entities'); 143var blockColors = require('../../elements/blockly/colors'); 144 145module.exports = function () { 146 return { 147 game: { 148 tiles: [[1, 1, 1, 1, 1, 1], [1, 1, 1, 3, 4, 1], [1, 1, 3, 3, 2, 1], [1, 3, 3, 2, 1, 1], [1, 3, 2, 1, 1, 1], [1, 1, 1, 1, 1, 1]], 149 150 entities: [entities.tutorialRobot({ x: 1, y: 4, id: 'ROBOT', orientation: ORIENTATION.BACK }), entities.chest({ x: 4, y: 1, orientation: 'FRONT' })] 151 }, 152 153 editor: { 154 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n<block type="start_handler" x="50" y="50" deletable="false">\n</block>\n</xml>', 155 156 toolbox: '<xml id="toolbox" style="display: none">\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n </category>\n </xml>' 157 }, 158 159 label: 'Turn - ZigZag', 160 161 goals: [{ 162 type: 'moveTo', 163 params: { position: { x: 4, y: 1 }, entity: 'ROBOT' }, 164 desc: 'Move the robot to the metal tile', 165 isMandatory: true 166 }, {
167 type: 'dontTouchTileType', 168 params: { tileID: 2, entity: 'ROBOT' }, 169 desc: 'Do not get your robot dirty', 170 isMandatory: false 171 }], 172 173 storyModal: { 174 text: 'Alright, I see you figured how to turn left. But you can also turn right. Crazy, i know.', 175 hint: '' 176 }, 177 178 winModal: { 179 text: 'Anything inside this block will be repeated as many times as defined by the number', 180 unlockedBlock: { name: 'Repeat', img: '../../assets/img/tutorials/blocks/repeat-10-block.png' } 181 } 182 183 }; 184}; 185 186},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],5:[function(require,module,exports){ 187'use strict'; 188 189var _require = require('../../lib/utils/types'), 190 ORIENTATION = _require.ORIENTATION; 191 192var entities = require('../../models/game/entities'); 193var blockColors = require('../../elements/blockly/colors'); 194 195module.exports = function () { 196 return { 197 game: { 198 tiles: [[1, 1, 1, 1], [1, 3, 4, 1], [1, 3, 1, 1], [1, 3, 1, 1], [1, 3, 1, 1], [1, 3, 1, 1], [1, 3, 1, 1], [1, 3, 1, 1], [1, 3, 1, 1], [1, 1, 1, 1]], 199 200 entities: [entities.tutorialRobot({ x: 1, y: 8, id: 'ROBOT', orientation: ORIENTATION.BACK })] 201 }, 202 203 editor: { 204 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n<block type="start_handler" x="50" y="50" deletable="false">\n <statement name="body">\n <block type="controls_repeat">\n <field name="TIMES">3</field>\n <statement name="DO">\n <block type="move"></block>\n </statement>\n</block>\n</statement>\n</block>\n</xml>', 205 206 toolbox: '<xml id="toolbox" style="display: none">\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="controls_repeat"></block>\n </category>\n </xml>' 207 }, 208 209 label: 'Loops - Getting Lazy', 210 211 goals: [{ 212 type: 'moveTo', 213 params: { position: { x: 2, y: 1 }, entity: 'ROBOT' }, 214 desc: 'Move the robot to the metal tile', 215 isMandatory: true 216 }], 217 218 storyModal: { 219 text: 'You are doing great so far! Can you also solve the next puzzle?', 220 hint: '' 221 }, 222 223 winModal: { 224 text: 'Great job!' 225 } 226 }; 227}; 228 229},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],6:[function(require,module,exports){ 230'use strict'; 231 232var _require = require('../../lib/utils/types'), 233 ORIENTATION = _require.ORIENTATION; 234 235var entities = require('../../models/game/entities'); 236var blockColors = require('../../elements/blockly/colors'); 237 238module.exports = function () { 239 return { 240 game: { 241 tiles: [[1, 1, 1, 1, 1, 1, 1], [1, 4, 3, 3, 3, 3, 1], [1, 1, 1, 1, 3, 1, 1], [1, 1, 1, 3, 3, 1, 1], [1, 1, 1, 3, 1, 1, 1], [1, 1, 3, 3, 1, 1, 1], [1, 1, 3, 1, 1, 1, 1], [1, 3, 3, 1, 1, 1, 1], [1, 3, 1, 1, 1, 1, 1], [1, 3, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1]], 242 243 entities: [entities.tutorialRobot({ x: 1, y: 9, id: 'ROBOT', orientation: ORIENTATION.BACK })] 244 }, 245 246 editor: { 247 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n<block type="start_handler" x="50" y="50" deletable="false">\n <statement name="body">\n <block type="controls_repeat">\n <field name="TIMES">3</field>\n <statement name="DO">\n <block type="move"></block>\n </statement>\n</block>\n</statement>\n</block>\n</xml>', 248 249 toolbox: '<xml id="toolbox" style="display: none">\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="controls_repeat"></block>\n </category>\n </xml>' 250 }, 251 252 label: 'Loops - The Good Parts', 253 254 goals: [{ 255 type: 'moveTo', 256 params: { position: { x: 1, y: 1 }, entity: 'ROBOT' }, 257 desc: 'Move the robot to the metal tile', 258 isMandatory: true 259 }], 260 261 storyModal: { 262 text: 'You are doing a great job. This level is going to be a little bit harder.', 263 hint: '' 264 }, 265 266 winModal: { 267 text: 'Great job!' 268 } 269 }; 270}; 271 272},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],7:[function(require,module,exports){ 273'use strict'; 274 275var _require = require('../../lib/utils/types'), 276 ORIENTATION = _require.ORIENTATION; 277 278var entities = require('../../models/game/entities'); 279var blockColors = require('../../elements/blockly/colors'); 280 281module.exports = function () { 282 return { 283 game: { 284 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 1, 1, 4, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1]], 285 286 entities: [entities.tutorialRobot({ x: 1, y: 7, id: 'ROBOT', orientation: ORIENTATION.BACK }), entities.chest({ x: 7, y: 7, orientation: 'BACK' })] 287 }, 288 289 editor: { 290 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n<block type="start_handler" x="50" y="50" deletable="false">\n <statement name="body">\n <block type="controls_repeat">\n <field name="TIMES">3</field>\n <statement name="DO">\n <block type="move"></block>\n </statement>\n</block>\n</statement>\n</block>\n</xml>', 291 292 toolbox: '<xml id="toolbox" style="display: none">\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="controls_repeat"></block>\n </category>\n </xml>' 293 }, 294 295 label: 'Loops - Nesting', 296 297 goals: [{ 298 type: 'moveTo', 299 params: { position: { x: 7, y: 7 }, entity: 'ROBOT' }, 300 desc: 'Move the robot to the metal tile', 301 isMandatory: true 302 }, {
303 type: 'maxBlocks', 304 params: { amount: 4 }, 305 desc: 'Use a maximum of four blocks', 306 isMandatory: false 307 }, { 308 type: 'useBlockWithinBlock', 309 params: { outerBlock: 'controls_repeat', innerBlock: 'controls_repeat' }, 310 desc: 'Nest a repeat block inside another repeat block', 311 isMandatory: false 312 }], 313 314 storyModal: { 315 text: 'Well done! Now here is a difficult one..', 316 hint: 'You can use a repeat inside a repeat.' 317 }, 318 319 winModal: { 320 text: 'What comes next? - Loops Hard Mode!', 321 unlockedBlock: { name: 'If-Condition Block', img: '../../assets/img/tutorials/blocks/if-condition.png' } 322 } 323 }; 324}; 325 326},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],8:[function(require,module,exports){ 327'use strict'; 328 329var _require = require('../../lib/utils/types'), 330 ORIENTATION = _require.ORIENTATION; 331 332var entities = require('../../models/game/entities'); 333var blockColors = require('../../elements/blockly/colors'); 334 335module.exports = function () { 336 return { 337 game: { 338 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 3, 3, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1], [1, 3, 1, 1, 1, 3, 1, 3, 1, 3, 1, 3, 1, 3, 1], [1, 3, 3, 3, 1, 3, 3, 3, 1, 3, 3, 3, 1, 3, 1], [1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1], [1, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1], [1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1], [1, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1], [1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1], [1, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 3, 3, 3, 3, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 339 340 entities: [entities.tutorialRobot({ x: 1, y: 9, id: 'ROBOT', orientation: ORIENTATION.BACK })] 341 }, 342 343 editor: { 344 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n<block type="start_handler" x="50" y="50" deletable="false">\n <statement name="body">\n <block type="controls_repeat">\n <field name="TIMES">3</field>\n <statement name="DO">\n <block type="move"></block>\n </statement>\n</block>\n</statement>\n</block>\n</xml>', 345 346 toolbox: '<xml id="toolbox" style="display: none">\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="controls_repeat"></block>\n </category>\n </xml>' 347 }, 348 349 label: 'Loops - Hard Mode', 350 351 goals: [{ 352 type: 'moveTo', 353 params: { position: { x: 9, y: 13 }, entity: 'ROBOT' }, 354 desc: 'Move the robot to the metal tile', 355 isMandatory: true 356 }, { 357 type: 'maxBlocks', 358 params: { amount: 17 }, 359 desc: 'Use a maximum of 17 blocks', 360 isMandatory: false 361 }], 362 363 storyModal: { 364 text: 'You\'re doing really great!', 365 hint: 'Try to look for the pattern. If you find it, things are way easier... (If it is too hard, you can always click on the logo in the upper left corner to get back to the overview.)' 366 }, 367 368 winModal: { 369 text: 'You are the Loop-King!' 370 } 371 }; 372}; 373 374},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],9:[function(require,module,exports){ 375'use strict'; 376 377var _require = require('../../lib/utils/types'), 378 ORIENTATION = _require.ORIENTATION; 379 380var entities = require('../../models/game/entities'); 381var blockColors = require('../../elements/blockly/colors'); 382 383module.exports = function () { 384 return { 385 game: { 386 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 3, 3, 3, 1, 3, 1], [1, 3, 1, 3, 1, 3, 1, 3, 1], [1, 3, 1, 3, 1, 4, 1, 3, 1], [1, 3, 1, 3, 1, 1, 1, 3, 1], [1, 3, 1, 3, 3, 3, 3, 3, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1]], 387 388 entities: [entities.tutorialRobot({ x: 1, y: 7, id: 'ROBOT', orientation: ORIENTATION.BACK })] 389 }, 390 391 editor: { 392 workspace: '\n <xml xmlns="http://www.w3.org/1999/xhtml">\n <block type="start_handler" x="50" y="50" deletable="false">\n <statement name="body">\n <block type="controls_repeat"/>\n <field name="TIMES">3</field>\n <statement name="DO">\n <block type="controls_if"/>\n </statement>\n </statement>\n </block>\n </xml>\n ', 393 394 toolbox: '\n <xml id="toolbox" style="display: none">\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="controls_repeat"></block>\n <block type="controls_if"></block>\n <block type="is_next_field"></block>\n </category>\n </xml>\n ' 395 }, 396 397 label: 'Conditions - Right Round', 398 399 goals: [{ 400 type: 'touchTile', 401 params: { tileID: 4 }, 402 desc: 'Move to the metal tile', 403 isMandatory: true 404 }, {
405 type: 'maxBlocks', 406 params: { amount: 5 }, 407 desc: 'Use a maximum of 5 blocks', 408 isMandatory: false 409 }], 410 411 storyModal: { 412 text: 'This puzzle looks quite hard, good thing you just got the condition-block. With this block, this level should be no problem at all', 413 hint: 'It might look hard, but you can simply check if the next tile is water' 414 }, 415 416 winModal: { 417 text: 'Your\'re a beast!' 418 } 419 }; 420}; 421 422},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],10:[function(require,module,exports){ 423'use strict'; 424 425var _require = require('../../lib/utils/types'), 426 ORIENTATION = _require.ORIENTATION; 427 428var entities = require('../../models/game/entities'); 429var blockColors = require('../../elements/blockly/colors'); 430 431module.exports = function () { 432 return { 433 game: { 434 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 3, 2, 1, 1, 1, 1, 1], [1, 1, 1, 1, 3, 3, 3, 3, 2, 1], [1, 1, 2, 1, 3, 1, 1, 3, 1, 1], [1, 3, 3, 3, 3, 5, 1, 3, 1, 1], [1, 1, 3, 1, 1, 1, 1, 3, 1, 1], [1, 1, 3, 1, 5, 1, 1, 3, 4, 1], [1, 2, 3, 3, 3, 3, 1, 5, 1, 1], [1, 1, 1, 1, 3, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 435 436 entities: [entities.tutorialRobot({ x: 4, y: 8, id: 'ROBOT', orientation: ORIENTATION.BACK })] 437 }, 438 439 editor: { 440 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n<block type="start_handler" x="50" y="50" deletable="false">\n <statement name="body">\n <block type="move" deletable="false"></block>\n</statement>\n</block>\n</xml>', 441 442 toolbox: '<xml id="toolbox" style="display: none">\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="rotate"></block>\n <block type="controls_repeat"></block>\n <block type="controls_if"></block>\n <block type="is_next_field"></block>\n </category>\n </xml>' 443 }, 444 445 label: 'Conditions - Follow The Signs', 446 447 goals: [{ 448 type: 'touchTile', 449 params: { tileID: 4 }, 450 desc: 'Move to the metal tile', 451 isMandatory: true 452 }], 453 454 storyModal: { 455 text: 'Now you known the power of a condition-block... This time, you have to solve the level with a single move-block', 456 hint: 'Try to see the pattern, the blocks give an indication where to go.' 457 }, 458 459 winModal: { 460 text: 'Let\'s get some resources', 461 unlockedBlock: { name: 'Collect Block', img: '../../assets/img/tutorials/blocks/collect-resource.png' } 462 } 463 }; 464}; 465 466},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],11:[function(require,module,exports){ 467'use strict'; 468 469var _require = require('../../lib/utils/types'), 470 ORIENTATION = _require.ORIENTATION; 471 472var entities = require('../../models/game/entities'); 473var blockColors = require('../../elements/blockly/colors'); 474 475module.exports = function () { 476 return { 477 game: { 478 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 2, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 3, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 3, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 3, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 3, 1, 1, 1, 3, 1], [1, 4, 1, 1, 1, 3, 3, 3, 3, 3, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 479 480 entities: [entities.tutorialRobot({ x: 1, y: 9, id: 'ROBOT', orientation: ORIENTATION.BACK, teamId: 1, discoverRange: 3, showRange: 3, resource: { hasResource: false, chunk: 0 } }), entities.tutorialBase({ x: 1, y: 9, id: 'BASE', teamId: 1 }), entities.gem({ x: 5, y: 4, value: 100, chunks: 10, color: 'BLUE' })], 481 482 teams: { 483 1: { resources: 0, points: 0 } 484 } 485 }, 486 487 editor: { 488 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n <block type="start_handler" x="50" y="50" deletable="false"></block>\n <block type="resource_event_handler" x="50" y="200" deletable="false"></block>\n</xml>', 489 490 toolbox: '<xml id="toolbox" style="display: none">\n\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="controls_repeat"></block>\n <block type="move_to_entity"></block>\n <block type="collect_resource"></block>\n </category>\n\n </xml>' 491 }, 492
493 label: 'Resource - Pick It Up', 494 495 goals: [{ 496 type: 'carryResource', 497 params: { hasResource: true }, 498 desc: 'Collect a resource', 499 isMandatory: true 500 }], 501 502 storyModal: { 503 text: 'So far it\'s all been fun and games. This is, what we\'re really after. Gems. Shiny. Valuable', 504 hint: 'Robots detect resources within 3 fields.' 505 }, 506 507 winModal: { 508 text: 'Now what? This block let\'s the robot deposit the resource when being near the base.', 509 unlockedBlock: { 510 name: 'Deposit-Resource', 511 img: '../../assets/img/tutorials/blocks/deposit-resource.png' 512 } 513 } 514 }; 515}; 516 517},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],12:[function(require,module,exports){ 518'use strict'; 519 520var _require = require('../../lib/utils/types'), 521 ORIENTATION = _require.ORIENTATION; 522 523var entities = require('../../models/game/entities'); 524var blockColors = require('../../elements/blockly/colors'); 525 526module.exports = function () { 527 return { 528 game: { 529 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 2, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 3, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 3, 1, 1, 1, 3, 1], [1, 3, 1, 1, 1, 3, 1, 1, 1, 3, 1], [1, 4, 1, 1, 1, 3, 3, 3, 3, 3, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 530 531 entities: [entities.tutorialRobot({ x: 5, y: 6, id: 'ROBOT', orientation: ORIENTATION.FRONT, teamId: 1, discoverRange: 2, resource: { hasResource: true, chunk: 10 } }), entities.tutorialBase({ x: 1, y: 9, id: 'BASE', teamId: 1 }), entities.gem({ x: 5, y: 5, value: 100, chunks: 10, color: 'BLUE' })], 532 533 teams: { 534 1: { resources: 0, points: 0 } 535 } 536 }, 537 538 editor: { 539 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n <block type="start_handler" x="50" y="50" deletable="false"></block>\n <block type="resource_event_handler" x="50" y="200" deletable="false"></block>\n</xml>', 540 541 toolbox: '<xml id="toolbox" style="display: none">\n\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="controls_repeat"></block>\n <block type="move_to_entity"></block>\n <block type="collect_resource"></block>\n <block type="deposit_resource"></block>\n </category>\n\n </xml>' 542 }, 543 544 label: 'Resource - Drop The Gem', 545 546 goals: [{ 547 type: 'collectResources', 548 params: { amount: 10 }, 549 desc: 'Bring back the resource', 550 isMandatory: true 551 }], 552 553 storyModal: { 554 text: 'Alright, you got the good stuff. Now get it home!', 555 hint: 'A good robot always knows where his base is' 556 }, 557 558 winModal: { 559 text: 'Thank you for getting my robots back to safety.', 560 unlockedBlock: { 561 name: 'Place Marker', 562 img: '../../assets/img/tutorials/blocks/place-marker.png' 563 } 564 } 565 }; 566}; 567 568},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],13:[function(require,module,exports){ 569'use strict'; 570 571var _require = require('../../lib/utils/types'), 572 ORIENTATION = _require.ORIENTATION; 573 574var entities = require('../../models/game/entities'); 575var blockColors = require('../../elements/blockly/colors'); 576 577var LOST_ROBOT_CODE = '\nrobot.onMode(\'red\', function (marker) {\n robot.moveTo(robot.getBasePosition().x, robot.getBasePosition().y)\n})\n//while (true) {\n// robot.move("FORWARD")\n// robot.rotate("LEFT")\n// }\n'; 578 579module.exports = function () { 580 return { 581 game: { 582 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 2, 3, 3, 1], [1, 3, 3, 3, 2, 2, 2, 2, 2, 2, 3, 3, 1, 1, 1, 1, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 3, 3, 2, 2, 2, 2, 3, 2, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 2, 2, 3, 3, 3, 1], [1, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1], [1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1], [1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 1, 1, 1], [1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 4, 5, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 1, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 1, 1, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 1], [1, 1, 1, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 1, 1, 1, 3, 3, 3, 3, 2, 3, 3, 3, 1, 1, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 2, 2, 2, 2, 3, 3, 1], [1, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3, 3, 3, 2, 3, 2, 3, 1], [1, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 583 584 entities: [entities.tutorialRobot({ x: 8, y: 8, id: 'ROBOT', orientation: ORIENTATION.FRONT, teamId: 1, discoverRange: 2 }), entities.tutorialRobot({ x: 21, y: 5, id: 'LOST_ROBOT01', orientation: ORIENTATION.FRONT, teamId: 1, discoverRange: 0, teamSprite: 2 }), entities.tutorialRobot({ x: 18, y: 22, id: 'LOST_ROBOT02', orientation: ORIENTATION.BACK, teamId: 1, discoverRange: 0, teamSprite: 2 }), entities.tutorialRobot({ x: 4, y: 14, id: 'LOST_ROBOT03', orientation: ORIENTATION.BACK, teamId: 1, discoverRange: 0, teamSprite: 2 }), entities.tutorialBase({ x: 12, y: 12, id: 'BASE', teamId: 1 })], 585 586 teams: { 587 1: { resources: 0, points: 0 } 588 } 589 }, 590 591 otherRobots: [{ id: 'LOST_ROBOT01', groupId: 1, overwriteCode: LOST_ROBOT_CODE }, { id: 'LOST_ROBOT02', groupId: 1, overwriteCode: LOST_ROBOT_CODE }, { id: 'LOST_ROBOT03', groupId: 1, overwriteCode: LOST_ROBOT_CODE }], 592 593 editor: { 594 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n <block type="start_handler" x="50" y="50" deletable="false"></block>\n <block type="marker_event_handler" x="50" y="400" deletable="false" editable="false">\n <field name="type">red</field>\n <data>EVENT_HANDLER</data>\n <statement name="body" editable="false">\n <block type="move_to_entity" movable="false" editable="false">\n <field name="entity">marker.position</field>\n </block>\n </statement>\n</block>\n</xml>', 595 596 toolbox: '<xml id="toolbox" style="display: none">\n\n <category name="Logic" colour="' + blockColors.LOGIC_COLOR + '">\n <block type="controls_repeat"></block>\n <block type="controls_if"></block>\n <block type="logic_compare"></block>\n </category>\n \n <sep gap="8"></sep>\n \n <category name="Numbers" colour="' + blockColors.MATH_COLOR + '">\n <block type="math_number"></block>\n <block type="random_number"></block>\n </category>\n \n <sep gap="8"></sep>
596\n \n <category name="Movement" colour="' + blockColors.MOVEMENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="move_to_entity"></block>\n </category>\n \n <sep gap="8"></sep>\n \n <category name="Actions" colour="' + blockColors.ACTION_COLOR + '">\n <block type="collect_resource"></block>\n <block type="deposit_resource"></block>\n <block type="place_marker"></block>\n </category>\n \n </xml>' 597 }, 598 599 label: 'Marker - Help Them', 600 601 goals: [{ 602 type: 'moveTo', 603 params: { position: { x: 12, y: 12 }, entity: 'LOST_ROBOT01' }, 604 desc: 'Lost robot is in time for lunch', 605 isMandatory: true 606 }, { 607 type: 'moveTo', 608 params: { position: { x: 12, y: 12 }, entity: 'LOST_ROBOT02' }, 609 desc: 'Lost robot is save', 610 isMandatory: true 611 }, { 612 type: 'moveTo', 613 params: { position: { x: 12, y: 12 }, entity: 'LOST_ROBOT03' }, 614 desc: 'Lost robot returned to home after 10 years', 615 isMandatory: true 616 }], 617 618 storyModal: { 619 text: 'Unfortunately three of the robots got lost. Luckily they will automatically move to a "red marker" as soon as one is placed.', 620 hint: 'Robots can place markers of a given color.' 621 }, 622 623 winModal: { 624 text: 'Thank you for getting my robots back to safety.', 625 unlockedBlock: { 626 name: 'Resource Discovered Event', 627 img: '../../assets/img/tutorials/blocks/resource-dicovered.png' 628 } 629 } 630 }; 631}; 632 633},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],14:[function(require,module,exports){ 634'use strict'; 635 636var _require = require('../../lib/utils/types'), 637 ORIENTATION = _require.ORIENTATION; 638 639var entities = require('../../models/game/entities'); 640var blockColors = require('../../elements/blockly/colors'); 641 642var IDLING_ROBOT_CODE = '\nrobot.onMode(\'red\', function (marker) {\n while (true) {\n robot.moveTo(marker.position.x, marker.position.y)\n robot.collectResource()\n robot.moveTo(robot.getBasePosition().x, robot.getBasePosition().y)\n robot.depositResource()\n }\n})\nwhile (true) {\n robot.move("FORWARD")\n robot.rotate("LEFT")\n}\n'; 643 644var RESOURCES_TO_WIN = 100; 645 646module.exports = function () { 647 return { 648 game: { 649 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 2, 3, 3, 1], [1, 3, 3, 3, 2, 2, 2, 2, 2, 2, 3, 3, 1, 1, 1, 1, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 3, 3, 2, 2, 2, 2, 3, 2, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 2, 2, 3, 3, 3, 1], [1, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1], [1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1], [1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 1, 1, 1], [1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 4, 5, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 1, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 1, 1, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 1], [1, 1, 1, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 1, 1, 1, 3, 3, 3, 3, 2, 3, 3, 3, 1, 1, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 2, 2, 2, 2, 3, 3, 1], [1, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3, 3, 3, 2, 3, 2, 3, 1], [1, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 650 651 entities: [entities.tutorialRobot({ x: 12, y: 12, id: 'ROBOT', orientation: ORIENTATION.BACK, teamId: 1, discoverRange: 2, resource: { hasResource: false, chunk: 0 } }), entities.tutorialRobot({ x: 21, y: 5, id: 'LOST_ROBOT01', orientation: ORIENTATION.FRONT, teamId: 1, discoverRange: 0, teamSprite: 2, resource: { hasResource: false, chunk: 0 } }), entities.tutorialRobot({ x: 18, y: 22, id: 'LOST_ROBOT02', orientation: ORIENTATION.BACK, teamId: 1, discoverRange: 0, teamSprite: 2, resource: { hasResource: false, chunk: 0 } }), entities.tutorialRobot({ x: 4, y: 14, id: 'LOST_ROBOT03', orientation: ORIENTATION.BACK, teamId: 1, discoverRange: 0, teamSprite: 2, resource: { hasResource: false, chunk: 0 } }), entities.tutorialBase({ x: 12, y: 12, id: 'BASE', teamId: 1 })], 652 653 teams: { 654 1: { resources: 0, points: 0 } 655 } 656 }, 657 658 otherRobots: [{ id: 'LOST_ROBOT01', groupId: 1, overwriteCode: IDLING_ROBOT_CODE }, { id: 'LOST_ROBOT02', groupId: 1, overwriteCode: IDLING_ROBOT_CODE }, { id: 'LOST_ROBOT03', groupId: 1, overwriteCode: IDLING_ROBOT_CODE }], 659 660 resources: { numberOfSpots: 10, value: 100, chunks: 10, color: 'BLUE' }, 661 662 editor: { 663 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n <block type="start_handler" x="50" y="50" deletable="false"></block>\n <block type="resource_event_handler" x="50" y="200" deletable="false"></block>\n <block type="marker_event_handler" x="50" y="350" deletable="false" editable="false">\n <field name="type">red</field>\n <data>EVENT_HANDLER</data>\n <statement name="body">\n <block type="move_to_entity" deletable="false" editable="false" movable="false">\n <field name="entity">marker.position</field>\n <next>\n <block type="collect_resource" deletable="false" editable="false" movable="false">\n <next>\n <block type="move_to_entity" deletable="false" editable="false" movable="false">\n <field name="entity">robot.getBasePosition()</field>\n <next>\n <block type="deposit_resource" deletable="false" editable="false" movable="false"></block>\n </next>\n </block>\n </next>\n </block>\n </next>\n </block>\n</statement>\n</block>\n</xml>', 664 665 toolbox: '<xml id="toolbox" style="display: none">\n\n <category name="Logic" colour="' + blockColors.LOGIC_COLOR + '">\n <block type="controls_repeat"></block>\n <block type="controls_if"></block>\n <block type="logic_compare"></block>\n </category>\n \n <sep gap="8"></sep>\n \n <category name="Numbers" colour="' + blockColors.MATH_COLOR + '">\n <block type="math_number"></block>\n <block type="random_number"></block>\n </category>\n \n <sep gap="8"></sep>
665\n \n <category name="Movement" colour="' + blockColors.MOVEMENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="move_to_entity"></block>\n </category>\n \n <sep gap="8"></sep>\n \n <category name="Actions" colour="' + blockColors.ACTION_COLOR + '">\n <block type="collect_resource"></block>\n <block type="deposit_resource"></block>\n <block type="place_marker"></block>\n </category>\n \n </xml>' 666 }, 667 668 label: 'Marker - Massive Collecting', 669 670 goals: [{ 671 type: 'collectResources', 672 params: { amount: RESOURCES_TO_WIN }, 673 desc: 'Collect ' + RESOURCES_TO_WIN + ' resources', 674 isMandatory: true 675 }], 676 677 storyModal: { 678 text: 'Now that we\'ve got 3 more robots, let\'s get down to business. Utilize them to gather some resources.', 679 hint: 'Place a marker next to a resource.' 680 }, 681 682 winModal: { 683 text: 'Now that\'s what I\'m talking about. ' + RESOURCES_TO_WIN + ' blue gems. So shiny!' 684 } 685 }; 686}; 687 688},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],15:[function(require,module,exports){ 689'use strict'; 690 691/* globals localStorage */ 692var _require = require('../../lib/utils/types'), 693 ORIENTATION = _require.ORIENTATION; 694 695var entities = require('../../models/game/entities'); 696var blockColors = require('../../elements/blockly/colors'); 697 698var timeLimit = 10; 699 700module.exports = function () { 701 return { 702 game: { 703 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 2, 3, 3, 1], [1, 3, 3, 3, 2, 2, 2, 2, 2, 2, 3, 3, 1, 1, 1, 1, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 3, 3, 2, 2, 2, 2, 3, 2, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 2, 2, 3, 3, 3, 1], [1, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1], [1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1], [1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 1, 1, 1], [1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 4, 5, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 1, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 1, 1, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 1, 1], [1, 1, 1, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 1, 1, 1, 3, 3, 3, 3, 2, 3, 3, 3, 1, 1, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 2, 2, 2, 2, 3, 3, 1], [1, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3, 3, 3, 2, 3, 2, 3, 1], [1, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 704 705 entities: [entities.tutorialRobot({ x: 12, y: 12, id: 'ROBOT', orientation: ORIENTATION.BACK, teamId: 1, discoverRange: 2 }), entities.tutorialBase({ x: 12, y: 12, id: 'BASE', teamId: 1 })], 706 707 teams: { 708 1: { resources: 0, points: 0 } 709 } 710 }, 711 712 resources: { numberOfSpots: 10, value: 100, chunks: 10, color: 'BLUE' }, 713 714 editor: { 715 workspace: '<xml xmlns="http://www.w3.org/1999/xhtml">\n<block type="start_handler" x="50" y="50" deletable="false">\n <statement name="body">\n <block type="controls_repeat">\n <field name="TIMES">3</field>\n <statement name="DO">\n <block type="move">\n <field name="move">FORWARD</field>\n <next>\n <block type="controls_if">\n <value name="IF0">\n <block type="logic_compare">\n <field name="OP">EQ</field>\n <value name="A">\n <block type="random_number" id="/2hWV!Bsg{eIiMHNaQm6">\n <field name="min">1</field>\n <field name="max">2</field>\n </block>\n </value>\n <value name="B">\n <block type="math_number" id="nL#iBs7tFzsRy}-I%z3a">\n <field name="NUM">1</field>\n </block>\n </value>\n </block>\n </value>\n <statement name="DO0">\n <block type="rotate">\n <field name="direction">LEFT</field>\n </block>\n </statement>\n </block>\n </next>\n </block>\n </statement>\n </block>\n </statement>\n</block>\n</xml>', 716 717 toolbox: '<xml id="toolbox" style="display: none">\n <category name="Code Blocks" colour="' + blockColors.EVENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="controls_repeat"></block>\n <block type="controls_if"></block>\n <block type="logic_compare"></block>\n <block type="math_number"></block>\n <block type="random_number"></block>\n </category>\n </xml>' 718 }, 719
720 label: 'Scout - Or... Walking Around Without Purpose', 721 722 goals: [{ 723 type: 'discoverEntityOfType', 724 params: { type: 'resource' }, 725 desc: 'Make the Robot scout the map to find something interesting', 726 isMandatory: true 727 }, { 728 type: 'gameTimeLimit', 729 params: { timeInS: timeLimit }, 730 desc: 'Find something within ' + timeLimit + ' seconds', 731 isMandatory: false 732 }], 733 734 storyModal: { 735 text: 'Scout the map. Hya!', 736 hint: 'When you start the game random diamands will appear on the map.' 737 }, 738 739 winModal: { 740 text: 'Some wise words.' 741 }, 742 743 onFinish: function onFinish(_ref) { 744 var gameState = _ref.gameState, 745 workspace = _ref.workspace; 746 747 localStorage.setItem('robot04', JSON.stringify({ 748 workspace: workspace, 749 entities: gameState && gameState.current ? JSON.stringify(gameState.current.entities) : null 750 })); 751 } 752 }; 753}; 754 755},{"../../elements/blockly/colors":19,"../../lib/utils/types":42,"../../models/game/entities":56}],16:[function(require,module,exports){ 756'use strict'; 757 758var tutorials = []; 759 760addTutorialRow('Blockly', [require('./a-blockly-01'), require('./a-blockly-02')]); 761 762addTutorialRow('Rotate', [require('./b-rotate-01'), require('./b-rotate-02')]); 763 764addTutorialRow('Loops', [require('./c-loop-01'), require('./c-loop-02'), require('./c-loop-03'), require('./c-loop-04')]); 765 766addTutorialRow('Conditions', [require('./d-conditions-01'), require('./d-conditions-02')]); 767 768addTutorialRow('Resources', [require('./e-resource-01.js'), require('./e-resource-02.js')]); 769 770addTutorialRow('Marker', [require('./f-marker-01.js'), require('./f-marker-02.js')]); 771 772addTutorialRow('Scout', [require('./g-scout-01.js')]); 773 774function addTutorialRow(categoryName, levels) { 775 var row = { 776 categoryName: categoryName, 777 levels: levels 778 }; 779 tutorials.push(row); 780} 781 782module.exports = tutorials; 783 784},{"./a-blockly-01":1,"./a-blockly-02":2,"./b-rotate-01":3,"./b-rotate-02":4,"./c-loop-01":5,"./c-loop-02":6,"./c-loop-03":7,"./c-loop-04":8,"./d-conditions-01":9,"./d-conditions-02":10,"./e-resource-01.js":11,"./e-resource-02.js":12,"./f-marker-01.js":13,"./f-marker-02.js":14,"./g-scout-01.js":15}],17:[function(require,module,exports){ 785'use strict'; 786 787function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 788 789/* globals Event */ 790var _ = require('lodash'); 791var html = {}; 792var sf = 0; 793var update = require('immutability-helper'); 794var component = require('choo-component').default; 795var classNames = require('classnames'); 796 797// PanelGroup 798// 799// creates multiple panels which are separated by dividers which can be used to resize the panels 800 801var DIVIDER_WIDTH = 10; 802 803var prefix = (require('sheetify/insert')("._98e65704 {\n display: flex;\n flex-direction: row;\n height: 100%;\n }\n\n ._98e65704.resizing {\n /* cursor: ew-resize; */\n }\n\n ._98e65704 > .panel,._98e65704 > .divider {\n height: 100%;\n flex-grow: 0;\n overflow: auto;\n }\n\n ._98e65704 > .panel {\n width: 100%;\n overflow: hidden;\n position: relative;\n }\n\n ._98e65704 > .divider {\n background: #fff;\n border: 1px solid grey;\n border-width: 0 1px;\n width: 10px;\n height: 100%;\n flex-shrink: 0;\n flex-grow: 0;\n }") || true) && "_98e65704"; 804 805module.exports = component({ 806 model: { 807 namespace: 'panelGroup', 808 809 state: { 810 selectedPanelIndex: null, 811 panelSizes: null 812 }, 813 814 reducers: { 815 initPanelSizes: function initPanelSizes(state, _ref) { 816 var panelSizes = _ref.panelSizes; 817 return update(state, { panelSizes: { $set: panelSizes } }); 818 }, 819 820 resizeGroup: function resizeGroup(state, _ref2) { 821 var width = _ref2.width; 822 var panelSizes = state.panelSizes; 823 824 var totalWidth = _.reduce(panelSizes, function (sum, width) { 825 return sum + width; 826 }, 0); 827 var newPanelSizes = _.map(panelSizes, function (panelWidth) { 828 return panelWidth / totalWidth * width; 829 }); 830 831 return update(state, { 832 panelSizes: { $set: newPanelSizes } 833 }); 834 }, 835 836 selectPanel: function selectPanel(state, _ref3) { 837 var panelIndex = _ref3.panelIndex; 838 return update(state, { 839 selectedPanelIndex: { $set: panelIndex } 840 }); 841 }, 842 843 _resizePanel: function _resizePanel(state, _ref4) { 844 var _panelSizes; 845 846 var position = _ref4.position; 847 var panelSizes = state.panelSizes, 848 selectedPanelIndex = state.selectedPanelIndex; 849 850 851 if (selectedPanelIndex === null) { 852 return; 853 } 854 855 var size = panelSizes[selectedPanelIndex]; 856 var offset = _.reduce(panelSizes.slice(0, selectedPanelIndex), function (sum, size) { 857 return sum + size; 858 }, 0); 859 var newSize = _.clamp(position - offset, 0, size + panelSizes[selectedPanelIndex + 1]); 860 var sizeChange = newSize - size; 861 862 return update(state, { 863 panelSizes: (_panelSizes = {}, _defineProperty(_panelSizes, selectedPanelIndex, { $set: newSize }), _defineProperty(_panelSizes, selectedPanelIndex + 1, { $set: panelSizes[selectedPanelIndex + 1] - sizeChange }), _panelSizes) 864 }); 865 } 866 }, 867 868 effects: { 869 resizePanel: function resizePanel(state, _ref5, send) { 870 var instanceId = _ref5.instanceId, 871 position = _ref5.position; 872 var selectedPanelIndex = state.instances[instanceId].selectedPanelIndex; 873 874 875 if (selectedPanelIndex === null) { 876 return; 877 } 878 879 // trigger resize event on window to make dynamic panels work which have javascript resize logic 880 window.dispatchEvent(new Event('resize')); 881 882 send('panelGroup:_resizePanel', { position: position }, _.noop); 883 } 884 } 885 }, 886 887 render: function render(_ref6) { 888 var panelSizes = _ref6.panelSizes, 889 selectedPanelIndex = _ref6.selectedPanelIndex, 890 panelViews = _ref6.panelViews, 891 initialPanelSizes = _ref6.initialPanelSizes, 892 initPanelSizes = _ref6.initPanelSizes, 893 resizeGroup = _ref6.resizeGroup, 894 selectPanel = _ref6.selectPanel, 895 resizePanel = _ref6.resizePanel; 896 897 var windowResizeHandler = void 0; 898 899 // add divider elements between panels 900 var panelsHtml = _(panelViews).map(function (panelHtml, index) { 901 var width = panelSizes !== null ? panelSizes[index] + 'px' : '100%'; 902 903 return [function () { 904 905 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 906 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 907 var bel0 = document.createElement("div"); 908 bel0.setAttribute("style", "flex: " + arguments[0]); 909 bel0.setAttribute("class", "panel"); 910 ac(bel0, [arguments[1]]); 911 return bel0; 912 }(initialPanelSizes[index], panelHtml), function () { 913 914 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 915 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 916 var bel0 = document.createElement("div"); 917 bel0["onmousedown"] = arguments[0]; 918 bel0.setAttribute("class", "divider"); 919 return bel0; 920 }(function () { 921 return selectPanel({ panelIndex: index }); 922 })]; 923 }
923).flatten().value().slice(0, -1); // omit divider after last panel 924 925 var className = classNames(prefix, { 926 resizing: selectedPanelIndex !== null 927 }); 928 929 // console.log('render panelSizes', panelSizes) 930 931 return function () { 932 933 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 934 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 935 var bel0 = document.createElement("div"); 936 bel0["onload"] = arguments[0]; 937 bel0["onunload"] = arguments[1]; 938 bel0["onmousemove"] = arguments[2]; 939 bel0["onmouseleave"] = arguments[3]; 940 bel0["onmouseup"] = arguments[4]; 941 bel0.setAttribute("class", arguments[5]); 942 ac(bel0, ["\n ", arguments[6], "\n "]); 943 return bel0; 944 }(init, unload, function (evt) { 945 return resizePanel({ position: evt.clientX - (selectedPanelIndex + 0.5) * DIVIDER_WIDTH }); 946 }, function () { 947 return selectPanel({ panelIndex: null }); 948 }, function () { 949 return selectPanel({ panelIndex: null }); 950 }, className, panelsHtml); 951 952 function init(panelsContainer) { 953 setTimeout(function () { 954 windowResizeHandler = function windowResizeHandler() { 955 return resizeGroup({ width: getPanelsTotalWidth(panelsContainer, panelViews.length) }); 956 }; 957 958 windowResizeHandler(); 959 960 window.addEventListener('resize', windowResizeHandler); 961 }); 962 } 963 964 function unload() { 965 window.removeEventListener('resize', windowResizeHandler); 966 } 967 } 968}); 969 970// returns width of container, subtracting the width of divider 971function getPanelsTotalWidth(panelsContainer, numberOfPanels) { 972 return panelsContainer.getBoundingClientRect().width - (numberOfPanels - 1) * DIVIDER_WIDTH; 973} 974 975},{"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"choo-component":90,"classnames":93,"immutability-helper":164,"lodash":171,"sheetify/insert":227}],18:[function(require,module,exports){ 976'use strict'; 977 978var _ = require('lodash'); 979 980var _require = require('./colors'), 981 LOGIC_COLOR = _require.LOGIC_COLOR, 982 LOOPS_COLOR = _require.LOOPS_COLOR, 983 MATH_COLOR = _require.MATH_COLOR, 984 ACTION_COLOR = _require.ACTION_COLOR, 985 EVENT_COLOR = _require.EVENT_COLOR, 986 MOVEMENT_COLOR = _require.MOVEMENT_COLOR; 987 988/* global Blockly */ 989// adds the bow on top of event blocks 990 991 992Blockly.BlockSvg.START_HAT = true; 993 994// Defines saturation and lightness 995// of the given block colors 996Blockly.HSV_SATURATION = 0.7; 997Blockly.HSV_VALUE = 0.75; 998 999function disableBlockIfNotConnected(block) { 1000 var parent = block.getParent(); 1001 1002 // ignore blocks which are inside of toolbar 1003 if (block.isInFlyout) { 1004 return; 1005 } 1006 1007 if (parent === null && block.disabled === false) { 1008 block.setDisabled(true); 1009 _.forEach(block.childBlocks_, function (child) { 1010 return child.setDisabled(true); 1011 }); 1012 return; 1013 } 1014 1015 if (parent !== null && block.disabled === true) { 1016 while (parent.getParent()) { 1017 parent = parent.getParent(); 1018 } 1019 1020 if (parent.type.endsWith('handler')) { 1021 block.setDisabled(false); 1022 return; 1023 } 1024 1025 _.forEach(block.childBlocks_, function (child) { 1026 return child.setDisabled(true); 1027 }); 1028 } 1029} 1030 1031function overrideColor(blockName, color) { 1032 var block = Blockly.Blocks[blockName]; 1033 var _init = block.init; 1034 1035 block.init = function () { 1036 _init.call(this); 1037 this.setColour(color); 1038 }; 1039} 1040 1041overrideColor('controls_if', LOGIC_COLOR); 1042overrideColor('logic_boolean', LOGIC_COLOR); 1043overrideColor('logic_negate', LOGIC_COLOR); 1044overrideColor('logic_compare', LOGIC_COLOR); 1045 1046overrideColor('controls_repeat', LOOPS_COLOR); 1047overrideColor('controls_repeat_ext', LOOPS_COLOR); 1048overrideColor('controls_whileUntil', LOOPS_COLOR); 1049 1050overrideColor('math_number', MATH_COLOR); 1051overrideColor('math_arithmetic', MATH_COLOR); 1052 1053/* add onchange handler to existing blocks */ 1054_.forEach(['logic_boolean', 'logic_negate', 'logic_compare', 'controls_if', 'controls_repeat', 'controls_repeat_ext', 'controls_whileUntil', 'math_number', 'math_arithmetic'], function (blockName) { 1055 Blockly.Blocks[blockName].onchange = function () { 1056 disableBlockIfNotConnected(this); 1057 }; 1058}); 1059 1060/* CONDITIONS */ 1061Blockly.Blocks.is_next_field = {
1062 init: function init() { 1063 this.appendDummyInput().appendField('isNextField').appendField(new Blockly.FieldDropdown([['Water', '1'], ['Dirt', '2'], ['Grass', '3'], ['Plain', '4'], ['Stone', '5']]), 'NAME'); 1064 1065 this.setOutput(true, null); 1066 this.setColour(230); 1067 this.setTooltip('Checks the next block for the given type'); 1068 }, 1069 1070 onchange: function onchange() { 1071 disableBlockIfNotConnected(this); 1072 } 1073}; 1074 1075/* MATH */ 1076 1077Blockly.Blocks.random_number_ext = { 1078 init: function init() { 1079 this.appendDummyInput().appendField('Random between'); 1080 1081 this.appendValueInput('min').setCheck('Number'); 1082 1083 this.appendValueInput('max').setCheck('Number').appendField('and'); 1084 1085 this.setInputsInline(true); 1086 this.setOutput(true, 'Number'); 1087 this.setColour(MATH_COLOR); 1088 this.setTooltip('generates a random number between min and max'); 1089 }, 1090 onchange: function onchange() { 1091 disableBlockIfNotConnected(this); 1092 } 1093}; 1094 1095Blockly.Blocks.random_number = { 1096 init: function init() { 1097 this.appendDummyInput().appendField('Random between').appendField(new Blockly.FieldNumber(1), 'min').appendField('and').appendField(new Blockly.FieldNumber(5), 'max'); 1098 1099 this.setInputsInline(true); 1100 this.setOutput(true, 'Number'); 1101 this.setColour(MATH_COLOR); 1102 this.setTooltip('generates a random number between min and max'); 1103 }, 1104 onchange: function onchange() { 1105 disableBlockIfNotConnected(this); 1106 } 1107}; 1108 1109/* MOVE */ 1110 1111Blockly.Blocks.move = { 1112 init: function init() { 1113 this.appendDummyInput().appendField('Move').appendField(new Blockly.FieldDropdown([['⧠Forward ', 'FORWARD'], ['⩠Backward', 'BACKWARD']]), 'move'); 1114 1115 this.setTooltip('move the robot in the given direction'); 1116 this.setPreviousStatement(true, null); 1117 this.setNextStatement(true, null); 1118 this.setColour(MOVEMENT_COLOR); 1119 }, 1120 onchange: function onchange() { 1121 disableBlockIfNotConnected(this); 1122 } 1123}; 1124 1125Blockly.Blocks.rotate = { 1126 init: function init() { 1127 this.appendDummyInput().appendField('Rotate').appendField(new Blockly.FieldDropdown([['⺠Left', 'LEFT'], ['⻠Right', 'RIGHT']]), 'direction'); 1128 1129 this.setTooltip('rotate the robot in the given direction'); 1130 this.setPreviousStatement(true, null); 1131 this.setNextStatement(true, null); 1132 this.setColour(MOVEMENT_COLOR); 1133 }, 1134 onchange: function onchange() { 1135 disableBlockIfNotConnected(this); 1136 } 1137}; 1138 1139Blockly.Blocks.move_to = { 1140 init: function init() { 1141 this.appendDummyInput().appendField('Move to x:').appendField(new Blockly.FieldNumber(0), 'x').appendField(' y:').appendField(new Blockly.FieldNumber(0), 'y'); 1142 1143 this.setInputsInline(true); 1144 this.setPreviousStatement(true, null); 1145 this.setNextStatement(true, null); 1146 this.setTooltip('move the robot to position x, y on the game field'); 1147 this.setColour(MOVEMENT_COLOR); 1148 }, 1149 onchange: function onchange() { 1150 disableBlockIfNotConnected(this); 1151 } 1152}; 1153 1154Blockly.Blocks.move_to_ext = { 1155 init: function init() { 1156 this.appendDummyInput().appendField('Move to'); 1157 1158 this.appendValueInput('x').setCheck(null).appendField('x:'); 1159 1160 this.appendValueInput('y').setCheck(null).appendField('y:'); 1161 1162 this.setInputsInline(true); 1163 this.setPreviousStatement(true, null); 1164 this.setNextStatement(true, null); 1165 this.setTooltip('move the robot to position x, y on the game field'); 1166 this.setColour(MOVEMENT_COLOR); 1167 }, 1168 onchange: function onchange() { 1169 disableBlockIfNotConnected(this); 1170 } 1171}; 1172 1173Blockly.Blocks.move_to_entity = { 1174 init: function init() { 1175 this.appendDummyInput().appendField('Move to').appendField(new Blockly.FieldDropdown([['marker', 'marker.position'], ['resource', 'resource.position'], ['base', 'robot.getBasePosition()']]), 'entity'); 1176 1177 this.setInputsInline(true); 1178 this.setPreviousStatement(true, null); 1179 this.setNextStatement(true, null); 1180 this.setTooltip('move the robot to position of selected entity'); 1181 this.setColour(MOVEMENT_COLOR); 1182 }, 1183 onchange: function onchange() { 1184 disableBlockIfNotConnected(this); 1185 } 1186}; 1187 1188/* ACTIONS */ 1189 1190Blockly.Blocks.collect_resource = {
1191 init: function init() { 1192 this.appendDummyInput().appendField('Collect resource'); 1193 1194 this.setTooltip('collect a resource on the the robots positions'); 1195 this.setPreviousStatement(true, null); 1196 this.setNextStatement(true, null); 1197 this.setColour(ACTION_COLOR); 1198 }, 1199 onchange: function onchange() { 1200 disableBlockIfNotConnected(this); 1201 } 1202}; 1203 1204Blockly.Blocks.deposit_resource = { 1205 init: function init() { 1206 this.appendDummyInput().appendField('Deposit resource'); 1207 1208 this.setTooltip('deposits a resource if robot is on home base'); 1209 this.setPreviousStatement(true, null); 1210 this.setNextStatement(true, null); 1211 this.setColour(ACTION_COLOR); 1212 }, 1213 onchange: function onchange() { 1214 disableBlockIfNotConnected(this); 1215 } 1216}; 1217 1218Blockly.Blocks.collected_resources = { 1219 init: function init() { 1220 this.appendDummyInput().appendField('Collected resources'); 1221 1222 this.setTooltip('number of resources which are currently available'); 1223 this.setColour(ACTION_COLOR); 1224 this.setOutput(true, 'Number'); 1225 }, 1226 onchange: function onchange() { 1227 disableBlockIfNotConnected(this); 1228 } 1229}; 1230 1231Blockly.Blocks.build_tower = { 1232 init: function init() { 1233 this.appendDummyInput().appendField('Build tower'); 1234 1235 this.setTooltip('build a tower in front of the robot'); 1236 this.setPreviousStatement(true, null); 1237 this.setNextStatement(true, null); 1238 this.setColour(ACTION_COLOR); 1239 }, 1240 onchange: function onchange() { 1241 disableBlockIfNotConnected(this); 1242 } 1243}; 1244 1245Blockly.Blocks.place_marker = { 1246 init: function init() { 1247 this.appendDummyInput().appendField('Place').appendField(new Blockly.FieldDropdown([['red', 'red'], ['green', 'green'], ['blue', 'blue'], ['yellow', 'yellow']]), 'type').appendField('marker for').appendField(new Blockly.FieldNumber(2), 'numberOfRobots').appendField('robots'); 1248 1249 this.setInputsInline(true); 1250 this.setTooltip('place a marker that triggers an event which other robots can react to'); 1251 this.setPreviousStatement(true, null); 1252 this.setNextStatement(true, null); 1253 this.setColour(ACTION_COLOR); 1254 }, 1255 onchange: function onchange() { 1256 disableBlockIfNotConnected(this); 1257 } 1258}; 1259 1260Blockly.Blocks.place_marker_ext = { 1261 init: function init() { 1262 this.appendDummyInput().appendField('Place').appendField(new Blockly.FieldDropdown([['red', 'red'], ['green', 'green'], ['blue', 'blue'], ['yellow', 'yellow']]), 'type').appendField('marker for'); 1263 1264 this.appendValueInput('numberOfRobots').setCheck('Number'); 1265 1266 this.appendDummyInput().appendField('robots'); 1267 1268 this.setInputsInline(true); 1269 this.setTooltip('place a marker that triggers an event which other robots can react to'); 1270 this.setPreviousStatement(true, null); 1271 this.setNextStatement(true, null); 1272 this.setColour(ACTION_COLOR); 1273 }, 1274 onchange: function onchange() { 1275 disableBlockIfNotConnected(this); 1276 } 1277}; 1278 1279/* EVENTS */ 1280 1281Blockly.Blocks.start_handler = { 1282 init: function init() { 1283 this.appendDummyInput().appendField('when start'); 1284 1285 this.appendStatementInput('body').setCheck(null); 1286 1287 this.setColour(EVENT_COLOR); 1288 this.setTooltip('code which is executed when programm starts'); 1289 } 1290}; 1291 1292Blockly.Blocks.marker_event_handler = { 1293 init: function init() { 1294 this.appendDummyInput().appendField('when').appendField(new Blockly.FieldDropdown([['red', 'red'], ['green', 'green'], ['blue', 'blue'], ['yellow', 'yellow']]), 'type').appendField('marker is assigned'); 1295 1296 this.appendStatementInput('body').setCheck(null); 1297 1298 this.setColour(EVENT_COLOR); 1299 this.setTooltip('code which is executed when an marker is assigned'); 1300 1301 // mark block as event handler, we use blockly data string 1302 // unfortunately only string are allowed (https://developers.google.com/blockly/guides/create-custom-blocks/define-blocks#block_data_web_only) 1303 this.data = 'EVENT_HANDLER'; 1304 } 1305}; 1306 1307Blockly.Blocks.resource_event_handler = { 1308 init: function init() { 1309 this.appendDummyInput().appendField('when resource is discovered'); 1310 1311 this.appendStatementInput('body').setCheck(null); 1312 1313 this.setColour(EVENT_COLOR); 1314 this.setTooltip('code which is executed when a new resource is discovered'); 1315 1316 // mark block as event handler 1317 this.data = 'EVENT_HANDLER'; 1318 } 1319}; 1320 1321},{"./colors":19,"lodash":171}],19:[function(require,module,exports){ 1322'use strict'; 1323 1324module.exports = { 1325 LOGIC_COLOR: '#00838F', 1326 LOOPS_COLOR: '#2E7D32', 1327 MATH_COLOR: '#4527A0', 1328 ACTION_COLOR: '#F9A825', 1329 EVENT_COLOR: '#37474F', 1330 MOVEMENT_COLOR: '#1565C0' 1331}; 1332 1333},{}],20:[function(require,module,exports){ 1334'use strict'; 1335 1336var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); }
1336 else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); 1337 1338/* global Blockly */ 1339require('./blocks'); 1340require('./javascript-commands'); 1341 1342var _ = require('lodash'); 1343var widget = require('cache-element/widget'); 1344var html = {}; 1345var sf = 0; 1346 1347var prefix = (require('sheetify/insert')("._10b514bc {\n height:100%;\n width: 100%;\n }") || true) && "_10b514bc"; 1348var DEFAULT_OPTIONS = { 1349 toolbox: '<xml id="toolbox" style="display: none"><category /></xml>', 1350 collapse: true, 1351 comments: true, 1352 disable: true, 1353 maxBlocks: Infinity, 1354 trashcan: false, 1355 scrollbars: true, 1356 sounds: true, 1357 grid: { 1358 spacing: 20, 1359 length: 1, 1360 colour: '#DDD', 1361 snap: false 1362 }, 1363 zoom: { 1364 controls: false, 1365 wheel: false 1366 } 1367}; 1368 1369function blocklyWidget() { 1370 var container = null; 1371 var prevParams = null; 1372 var onChange = _.noop; 1373 var blocklyWorkspace = null; 1374 var toolbox = void 0; 1375 1376 return widget({ 1377 onupdate: function onupdate(el, params) { 1378 onChange = params.onChange; 1379 1380 // ignore if workspace isn't initialized or params haven't changed 1381 if (blocklyWorkspace === null || prevParams.workspace === params.workspace && prevParams.toolbox === params.toolbox) { 1382 return; 1383 } 1384 1385 prevParams = params; 1386 1387 if (toolbox !== params.toolbox) { 1388 blocklyWorkspace.updateToolbox(params.toolbox); 1389 } 1390 1391 var newBlocklyWorkspace = stringToWorkspace(params.workspace); 1392 1393 if (!isWorkspaceEquivalentTo(blocklyWorkspace, newBlocklyWorkspace)) { 1394 updateWorkspace(blocklyWorkspace, params.workspace); 1395 } 1396 1397 // prevent memory leak and no don't delete this line, this call isn't here just in case to be sure. 1398 // if you remove this line bad things will happen 1399 newBlocklyWorkspace.dispose(); 1400 }, 1401 1402 onload: function onload(_container) { 1403 container = _container; 1404 blocklyWorkspace = Blockly.inject(container, DEFAULT_OPTIONS); 1405 blocklyWorkspace.addChangeListener(updateCode); 1406 1407 // remove background color 1408 container.querySelector('.blocklyMainBackground').style = ''; 1409 1410 if (prevParams === null) { 1411 return; 1412 } 1413 1414 if (prevParams.toolbox) { 1415 blocklyWorkspace.updateToolbox(prevParams.toolbox); 1416 toolbox = prevParams.toolbox; 1417 } 1418 // apply initial params 1419 if (prevParams.workspace) { 1420 updateWorkspace(blocklyWorkspace, prevParams.workspace); 1421 } 1422 }, 1423 1424 onunload: function onunload() { 1425 prevParams = null; 1426 onChange = _.noop; 1427 1428 blocklyWorkspace.removeChangeListener(updateCode); 1429 blocklyWorkspace.dispose(); 1430 }, 1431 1432 render: function render(params) { 1433 prevParams = params; 1434 1435 // setup onChange handler 1436 onChange = params.onChange; 1437 1438 return function () { 1439 1440 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 1441 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 1442 var bel0 = document.createElement("div"); 1443 bel0.setAttribute("class", arguments[0]); 1444 return bel0; 1445 }(prefix); 1446 } 1447 }); 1448 1449 function updateCode() { 1450 // don't trigger update code if block is being dragged 1451 if (container.querySelector('.blocklyDragging') !== null) { 1452 return; 1453 } 1454 1455 onChange({ 1456 workspace: workspaceToString(blocklyWorkspace), 1457 code: workspaceToOrderedCode(blocklyWorkspace) 1458 }); 1459 } 1460} 1461 1462// reinitialize workspace with xml 1463function updateWorkspace(workspace, xmlString) { 1464 var workspaceXml = Blockly.Xml.textToDom(xmlString); 1465 workspace.clear(); 1466 Blockly.Xml.domToWorkspace(workspaceXml, workspace); 1467 Blockly.svgResize(workspace); 1468} 1469 1470function stringToWorkspace(xmlString) { 1471 var workspace = new Blockly.Workspace(DEFAULT_OPTIONS); 1472 var workspaceXml = Blockly.Xml.textToDom(xmlString); 1473 Blockly.Xml.domToWorkspace(workspaceXml, workspace); 1474 return workspace; 1475} 1476 1477function workspaceToString(workspace) { 1478 var xml = Blockly.Xml.workspaceToDom(workspace); 1479 return Blockly.Xml.domToText(xml); 1480} 1481 1482// checks if workspaces generate both the same code, ignoring position of blocks 1483// you have to pass in an actual workspace not just strings
1484function isWorkspaceEquivalentTo(workspace, compareWorkspace) { 1485 var workspaceCode = workspaceToOrderedCode(workspace); 1486 var compareCode = workspaceToOrderedCode(compareWorkspace); 1487 1488 return workspaceCode === compareCode; 1489} 1490 1491// turns workspace into javascript 1492// compared to Blockly.Javascript.workspaceToCode this function guarantees that event blocks will be inserted a start 1493// of the generated JavaScript code 1494function workspaceToOrderedCode(workspace) { 1495 var blocks = workspace.getTopBlocks(); 1496 1497 var _$partition = _.partition(blocks, isBlockEventHandler), 1498 _$partition2 = _slicedToArray(_$partition, 2), 1499 eventHandlerBlocks = _$partition2[0], 1500 otherBlocks = _$partition2[1]; 1501 1502 // TODO: remove this hack 1503 // blocks that create new variables need to access the variableDB to ensure they don't override existing variables 1504 // the variableDB is provided by the workspace but since we are generating the code block wise we need to provide 1505 // our own variableDB 1506 1507 // save reference to original value 1508 1509 1510 var originalVariableDB_ = Blockly.JavaScript.variableDB_; 1511 1512 // monkey patch variableDB 1513 Blockly.JavaScript.variableDB_ = getFakeVariableDB(); 1514 1515 var codeChunks = _.map(eventHandlerBlocks.concat(otherBlocks), function (block) { 1516 return Blockly.JavaScript.blockToCode(block); 1517 }); 1518 1519 // restore variableDB 1520 Blockly.JavaScript.variableDB_ = originalVariableDB_; 1521 1522 return codeChunks.join('\n'); 1523} 1524 1525function getFakeVariableDB() { 1526 var counter = 0; 1527 1528 return { 1529 getDistinctName: function getDistinctName() { 1530 var name = 'i_' + counter; 1531 counter += 1; 1532 return name; 1533 } 1534 }; 1535} 1536 1537function isBlockEventHandler(block) { 1538 return block.data === 'EVENT_HANDLER'; 1539} 1540 1541module.exports = blocklyWidget; 1542 1543},{"./blocks":18,"./javascript-commands":21,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"cache-element/widget":87,"lodash":171,"sheetify/insert":227}],21:[function(require,module,exports){ 1544'use strict'; 1545 1546/* global Blockly */ 1547 1548/* CONDITIONS */ 1549 1550Blockly.JavaScript.is_next_field = function (block) { 1551 var tileType = block.getFieldValue('NAME'); 1552 1553 var code = 'robot.isNextTile(' + tileType + ')'; 1554 1555 return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; 1556}; 1557 1558/* MATH */ 1559 1560Blockly.JavaScript.random_number = function (block) { 1561 var min = block.getFieldValue('min'); 1562 var max = block.getFieldValue('max'); 1563 1564 var code = 'getRandomNumber(' + min + ', ' + max + ')'; 1565 return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; 1566}; 1567 1568Blockly.JavaScript.random_number_ext = function (block) { 1569 var min = Blockly.JavaScript.valueToCode(block, 'min', Blockly.JavaScript.ORDER_ATOMIC); 1570 var max = Blockly.JavaScript.valueToCode(block, 'max', Blockly.JavaScript.ORDER_ATOMIC); 1571 1572 var code = 'getRandomNumber(' + min + ', ' + max + ')'; 1573 return [code, Blockly.JavaScript.ORDER_FUNCTION_CALL]; 1574}; 1575 1576/* MOVE */ 1577 1578Blockly.JavaScript.move = function (block) { 1579 var dropdownMove = block.getFieldValue('move'); 1580 return 'robot.move(' + '"' + dropdownMove + '"' + ')\n'; 1581}; 1582 1583Blockly.JavaScript.rotate = function (block) { 1584 var dropdownDirection = block.getFieldValue('direction'); 1585 return 'robot.rotate(' + '"' + dropdownDirection + '"' + ')\n'; 1586}; 1587 1588Blockly.JavaScript.move_to = function (block) { 1589 var xPos = block.getFieldValue('x'); 1590 var yPos = block.getFieldValue('y'); 1591 1592 return 'robot.moveTo(' + xPos + ', ' + yPos + ')\n'; 1593}; 1594 1595Blockly.JavaScript.move_to_ext = function (block) { 1596 var xPos = Blockly.JavaScript.valueToCode(block, 'x', Blockly.JavaScript.ORDER_ATOMIC); 1597 var yPos = Blockly.JavaScript.valueToCode(block, 'y', Blockly.JavaScript.ORDER_ATOMIC); 1598 1599 return 'robot.moveTo(' + xPos + ', ' + yPos + ')\n'; 1600}; 1601 1602Blockly.JavaScript.move_to_entity = function (block) { 1603 var entity = block.getFieldValue('entity'); 1604 1605 return 'try {\n robot.moveTo(' + entity + '.x, ' + entity + '.y)\n\n} catch (e) { }\n'; 1606}; 1607 1608/* ACTIONS */ 1609 1610Blockly.JavaScript.collect_resource = function (block) { 1611 return 'robot.collectResource()\n'; 1612}; 1613 1614Blockly.JavaScript.deposit_resource = function (block) { 1615 return 'robot.depositResource()\n'; 1616}; 1617 1618Blockly.JavaScript.collected_resources = function (block) { 1619 return ['robot.getCollectedResources()\n', Blockly.JavaScript.ORDER_FUNCTION_CALL]; 1620}; 1621 1622Blockly.JavaScript.build_tower = function (block) { 1623 return 'robot.buildTowerNearPosition()\n'; 1624}; 1625 1626Blockly.JavaScript.place_marker = function (block) { 1627 var type = block.getFieldValue('type'); 1628 var numberOfRobots = block.getFieldValue('numberOfRobots'); 1629 1630 return 'robot.placeMarker(\'' + type + '\', ' + numberOfRobots + ')\n'; 1631}; 1632 1633Blockly.JavaScript.place_marker_ext = function (block) { 1634 var type = block.getFieldValue('type'); 1635 var numberOfRobots = Blockly.JavaScript.valueToCode(block, 'numberOfRobots', Blockly.JavaScript.ORDER_ATOMIC); 1636 1637 return 'robot.placeMarker(\'' + type + '\', ' + numberOfRobots + ')\n'; 1638}; 1639 1640/* EVENTS */ 1641 1642Blockly.JavaScript.start_handler = function (block) { 1643 // don't remove the generated comment, otherwise programs which just contain the start block won't load if the previous 1644 // workspace has been empty because the generated code is equivalent 1645 return '// Main program starts here\n' + Blockly.JavaScript.statementToCode(block, 'body') + '\n'; 1646}; 1647 1648Blockly.JavaScript.marker_event_handler = function (block) { 1649 var type = block.getFieldValue('type'); 1650 var statements = Blockly.JavaScript.statementToCode(block, 'body'); 1651 1652 return 'robot.onMode(\'' + type + '\', function (marker) {\n' + statements + '\n})\n'; 1653}; 1654 1655Blockly.JavaScript.resource_event_handler = function (block) { 1656 var statements = Blockly.JavaScript.statementToCode(block, 'body'); 1657 1658 return 'robot.onEvent(\'discover resource\', function (resource) {\n' + statements + '\n})\n'; 1659}; 1660 1661},{}],22:[function(require,module,exports){ 1662'use strict'; 1663 1664function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 1665 1666var _ = require('lodash'); 1667var html = {}; 1668var sf = 0; 1669var classNames = require('classnames'); 1670 1671var prefix = (require('sheetify/insert')("._276b82c3 {\n padding: 8px 10px;\n margin: 10px;\n border: none;\n border-radius: 3px;\n font-size: 1em;\n color: #676768;\n line-height: 100%;\n background-color: #E0E1E2;\n }\n\n ._276b82c3:hover {\n color: #2b2b2b;\n background-color: #CACBCD;\n }\n\n ._276b82c3[disabled] {\n opacity: 0.5\n }\n\n ._276b82c3.has-icon {\n padding-left: 30px;\n background-repeat: no-repeat;\n background-size: 16px;\n background-position: 10px center;\n }\n\n ._276b82c3.has-icon.has-label {\n margin-right: 5px;\n }\n\n ._276b82c3.icon-play {\n background-image: url('assets/icons/play.svg');\n }\n\n ._276b82c3.icon-pause {\n background-image: url('assets/icons/pause.svg');\n }\n\n ._276b82c3.icon-stop {\n background-image: url('assets/icons/stop.svg');\n }\n \n ._276b82c3.icon-upload {\n background-image: url('assets/icons/upload.svg');\n }") || true) && "_276b82c3"; 1672 1673function button(_ref) { 1674 var _classNames; 1675 1676 var icon = _ref.icon,
1677 label = _ref.label, 1678 _ref$disabled = _ref.disabled, 1679 disabled = _ref$disabled === undefined ? false : _ref$disabled, 1680 _ref$onClick = _ref.onClick, 1681 onClick = _ref$onClick === undefined ? _.noop : _ref$onClick, 1682 additionalClasses = _ref.additionalClasses; 1683 1684 var classes = classNames(prefix, (_classNames = {}, _defineProperty(_classNames, 'has-icon icon-' + icon, !_.isNil(icon)), _defineProperty(_classNames, 'has-label', !_.isNil(label)), _classNames)); 1685 1686 return function () { 1687 1688 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 1689 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 1690 var bel0 = document.createElement("button"); 1691 bel0["onclick"] = arguments[0]; 1692 if (arguments[1] && "disabled") bel0.setAttribute("disabled", "disabled"); 1693 bel0.setAttribute("class", arguments[2] + " "); 1694 ac(bel0, ["\n ", arguments[3], "\n "]); 1695 return bel0; 1696 }(onClick, disabled, classes + ' ' + additionalClasses, label); 1697} 1698 1699module.exports = button; 1700 1701},{"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"classnames":93,"lodash":171,"sheetify/insert":227}],23:[function(require,module,exports){ 1702'use strict'; 1703 1704var _ = require('lodash'); 1705var widget = require('cache-element/widget'); 1706var html = {}; 1707var sf = 0; 1708 1709var MIN_INITAL_VIEWPORT_SIZE = 200; // inital zoom is set so viewport will have at least this height and width 1710var MIN_SCALE = 0.1; 1711var MAX_SCALE = 1; 1712var INITIAL_TRANSFORM = { 1713 scale: 1, 1714 translate: { 1715 x: 0, y: 0 1716 } 1717}; 1718 1719var prefix = (require('sheetify/insert')("._997216c4 {\n width: 100%;\n height: 100%;\n }\n\n ._997216c4 > canvas {\n cursor: -webkit-grab;\n cursor: grab;\n }\n\n ._997216c4 > canvas.dragging {\n cursor: -webkit-grabbing;\n cursor: grabbing;\n }") || true) && "_997216c4"; 1720 1721function canvasWidget() { 1722 var ctx = null; 1723 var canvas = null; 1724 var isDragging = false; 1725 var _render = _.noop; 1726 var transform = INITIAL_TRANSFORM; 1727 var prevDragPoint = void 0; 1728 1729 return widget({ 1730 onupdate: function onupdate(el, params) { 1731 _render = params.render; 1732 1733 if (ctx !== null) { 1734 renderCanvas(); 1735 } 1736 }, 1737 1738 onload: function onload(el) { 1739 canvas = el.querySelector('canvas'); 1740 ctx = canvas.getContext('2d'); 1741 1742 canvas.addEventListener('mousedown', handleDragStart); 1743 canvas.addEventListener('mousemove', handleDragMove); 1744 canvas.addEventListener('mouseup', handleDragEnd); 1745 canvas.addEventListener('mouseleave', handleDragEnd); 1746 canvas.addEventListener('mousewheel', handleZoom); 1747 window.addEventListener('resize', resize); 1748 1749 transform.scale = Math.min(Math.min(1, canvas.width / MIN_INITAL_VIEWPORT_SIZE), canvas.height / MIN_INITAL_VIEWPORT_SIZE); 1750 1751 resize(); 1752 1753 renderCanvas(); 1754 }, 1755 1756 onunload: function onunload() { 1757 ctx = null; 1758 isDragging = false; 1759 transform = INITIAL_TRANSFORM; 1760 canvas.removeEventListener('mousedown', handleDragStart); 1761 canvas.removeEventListener('mousemove', handleDragMove); 1762 canvas.removeEventListener('mouseup', handleDragEnd); 1763 canvas.removeEventListener('mouseleave', handleDragEnd); 1764 canvas.removeEventListener('mousewheel', handleZoom); 1765 canvas = null; 1766 1767 window.removeEventListener('resize', resize); 1768 }, 1769 1770 render: function render(params) { 1771 _render = params.render; 1772 1773 return function () { 1774 1775 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 1776 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 1777 var bel1 = document.createElement("div"); 1778 bel1.setAttribute("class", arguments[0]); 1779 var bel0 = document.createElement("canvas"); 1780 ac(bel1, ["\n ", bel0, " \n "]); 1781 return bel1; 1782 }(prefix); 1783 } 1784 }); 1785 1786 function handleDragStart(evt) { 1787 isDragging = true; 1788 prevDragPoint = { x: evt.clientX, y: evt.clientY }; 1789 canvas.classList.add('dragging'); 1790 } 1791 1792 function handleDragMove(evt) { 1793 if (isDragging) { 1794 var x = evt.clientX; 1795 var y = evt.clientY; 1796 1797 transform.translate.x += (x - prevDragPoint.x) / transform.scale; 1798 transform.translate.y += (y - prevDragPoint.y) / transform.scale; 1799 1800 prevDragPoint.x = evt.clientX; 1801 prevDragPoint.y = evt.clientY; 1802 1803 renderCanvas(); 1804 } 1805 } 1806 1807 function handleDragEnd(evt) { 1808 isDragging = false;
1809 canvas.classList.remove('dragging'); 1810 } 1811 1812 function resize() { 1813 canvas.width = canvas.parentNode.offsetWidth; 1814 canvas.height = canvas.parentNode.offsetHeight; 1815 1816 renderCanvas(); 1817 } 1818 1819 function handleZoom(evt) { 1820 evt.preventDefault(); 1821 var scale = transform.scale - evt.deltaY / 2000; 1822 transform.scale = _.clamp(scale, MIN_SCALE, MAX_SCALE); 1823 1824 renderCanvas(); 1825 } 1826 1827 function renderCanvas() { 1828 var viewport = _.assign({}, { width: canvas.width, height: canvas.height }, transform); 1829 1830 ctx.clearRect(0, 0, canvas.width, canvas.height); 1831 ctx.save(); 1832 1833 _render(ctx, viewport); 1834 1835 ctx.restore(); 1836 } 1837} 1838 1839module.exports = canvasWidget; 1840 1841},{"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"cache-element/widget":87,"lodash":171,"sheetify/insert":227}],24:[function(require,module,exports){ 1842'use strict'; 1843 1844/* globals FormData */ 1845 1846var html = {}; 1847var modalView = require('./modal'); 1848var buttonView = require('./button'); 1849 1850module.exports = function (_ref) { 1851 var client = _ref.client, 1852 onSetUsername = _ref.onSetUsername, 1853 onJoinGroup = _ref.onJoinGroup, 1854 onDisconnect = _ref.onDisconnect, 1855 onDenyRecovery = _ref.onDenyRecovery; 1856 1857 if (client.connected) { 1858 return function () { 1859 1860 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 1861 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 1862 var bel0 = document.createElement("div"); 1863 return bel0; 1864 }(); 1865 } 1866 1867 if (client.connecting === true) { 1868 return waitForConnectionDialog({ onCancel: onDenyRecovery }); 1869 } 1870 1871 if (client.recoveryPossible) { 1872 return recoveryDialog({ 1873 recover: function recover() { 1874 onJoinGroup(client.groupId); 1875 }, 1876 cancel: onDenyRecovery 1877 }); 1878 } 1879 1880 if (client.username === null) { 1881 return setUsernameDialog({ onSetUsername: onSetUsername }); 1882 } 1883 1884 if (client.groupId === null) { 1885 return joinGroupDialog({ onJoinGroup: onJoinGroup }); 1886 } 1887 1888 return function () { 1889 1890 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 1891 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 1892 var bel0 = document.createElement("div"); 1893 return bel0; 1894 }(); 1895}; 1896 1897function recoveryDialog(_ref2) { 1898 var recover = _ref2.recover, 1899 cancel = _ref2.cancel; 1900 1901 var recoverButtonHtml = buttonView({ 1902 label: 'recover', 1903 onClick: function onClick(evt) { 1904 recover(); 1905 } 1906 }); 1907 var cancelButtonHtml = buttonView({ 1908 label: 'cancel', 1909 onClick: function onClick(evt) { 1910 cancel(); 1911 } 1912 }); 1913 1914 return modalView(function () { 1915 1916 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 1917 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 1918 var bel1 = document.createElement("div"); 1919 bel1.setAttribute("class", "content"); 1920 var bel0 = document.createElement("p"); 1921 ac(bel0, ["I found a previous Session on your Browser, would you like to recover?"]); 1922 ac(bel1, ["\n ", bel0, "\n ", arguments[0], "\n ", arguments[1], "\n "]); 1923 return bel1; 1924 }(recoverButtonHtml, cancelButtonHtml)); 1925} 1926 1927function setUsernameDialog(_ref3) { 1928 var onSetUsername = _ref3.onSetUsername; 1929 1930 var submitButtonHtml = buttonView({ 1931 label: 'save' 1932 }); 1933 1934 return modalView(function () { 1935 1936 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 1937 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 1938 var bel3 = document.createElement("div"); 1939 bel3.setAttribute("class", "content"); 1940 var bel0 = document.createElement("p"); 1941 ac(bel0, ["Please enter your name"]); 1942 var bel2 = document.createElement("form"); 1943 bel2["onsubmit"] = arguments[0]; 1944 var bel1 = document.createElement("input"); 1945 bel1.setAttribute("name", "username"); 1946 bel1.setAttribute("type", "text"); 1947 bel1.setAttribute("autofocus", "autofocus"); 1948 bel1.setAttribute("minlength", "2"); 1949 bel1.setAttribute("maxlength", "30"); 1950 bel1.setAttribute("value", ""); 1951 ac(bel2, ["\n ", bel1, "\n ", arguments[1], "\n "]); 1952 ac(bel3, ["\n ", bel0, "\n \n ", bel2, "\n "]); 1953 return bel3; 1954 }(handleSubmit, submitButtonHtml)); 1955 1956 function handleSubmit(evt) { 1957 var formData = new FormData(evt.target); 1958 var username = formData.get('username'); 1959 1960 evt.preventDefault(); 1961 1962 onSetUsername(username); 1963 } 1964} 1965 1966function joinGroupDialog(_ref4) { 1967 var onJoinGroup = _ref4.onJoinGroup; 1968 1969 var submitButtonHtml = buttonView({ 1970 label: 'join' 1971 }); 1972 1973 return modalView(function () { 1974 1975 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 1976 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 1977 var bel3 = document.createElement("div"); 1978 bel3.setAttribute("class", "content"); 1979 var bel0 = document.createElement("p"); 1980 ac(bel0, ["Please enter the name of the group you would like to join"]); 1981 var bel2 = document.createElement("form"); 1982 bel2["onsubmit"] = arguments[0]; 1983 var bel1 = document.createElement("input"); 1984 bel1.setAttribute("name", "groupId"); 1985 bel1.setAttribute("type", "text"); 1986 bel1.setAttribute("autofocus", "autofocus"); 1987 bel1.setAttribute("minlength", "2"); 1988 bel1.setAttribute("maxlength", "30"); 1989 bel1.setAttribute("value", ""); 1990 ac(bel2, ["\n ", bel1, "\n ", arguments[1], "\n "]); 1991 ac(bel3, ["\n ", bel0, "\n \n ", bel2, "\n "]); 1992 return bel3; 1993 }(handleSubmit, submitButtonHtml)); 1994 1995 function handleSubmit(evt) { 1996 var formData = new FormData(evt.target); 1997 var groupId = formData.get('groupId'); 1998 1999 evt.preventDefault(); 2000 2001 onJoinGroup(groupId); 2002 } 2003} 2004 2005function waitForConnectionDialog(_ref5) { 2006 var onCancel = _ref5.onCancel; 2007 2008 var cancelButtonHtml = buttonView({ 2009 label: 'cancel', 2010 onClick: onCancel 2011 }); 2012 2013 return modalView(function () { 2014 2015 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2016 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2017 var bel2 = document.createElement("div"); 2018 bel2.setAttribute("class", "content"); 2019 var bel0 = document.createElement("h1"); 2020 ac(bel0, ["Connecting..."]); 2021 var bel1 = document.createElement("img"); 2022 bel1.setAttribute("src", "../assets/img/web/load.gif"); 2023 bel1.setAttribute("alt", "loading"); 2024 bel1.setAttribute("class", "connecting"); 2025 ac(bel2, ["\n ", bel0, "\n \n ", bel1, "\n \n ", arguments[0], "\n "]); 2026 return bel2; 2027 }(cancelButtonHtml)); 2028} 2029 2030},{"./button":22,"./modal":33,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256}],25:[function(require,module,exports){ 2031'use strict'; 2032 2033var _ = require('lodash'); 2034var html = {}; 2035var sf = 0; 2036 2037var prefix = (require('sheetify/insert')("._d3ff1998 {\n min-width: 200px;\n }\n \n ._d3ff1998 li {\n font-weight: 600;\n font-size: 150%;\n }\n \n ._d3ff1998 .player {\n color: green;\n }") || true) && "_d3ff1998"; 2038 2039function clientsList(_ref) { 2040 var clients = _ref.clients, 2041 playerNumbers = _ref.playerNumbers; 2042 2043 return function () { 2044 2045 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2046 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2047 var bel2 = document.createElement("div"); 2048 bel2.setAttribute("class", arguments[1]); 2049 var bel0 = document.createElement("h1"); 2050 ac(bel0, ["Clients"]); 2051 var bel1 = document.createElement("ul"); 2052 ac(bel1, ["\n ", arguments[0], "\n "]); 2053 ac(bel2, ["\n ", bel0, "\n ", bel1, "\n "]); 2054 return bel2; 2055 }(Object.keys(clients).map(clientToLi), prefix); 2056 2057 function clientToLi(key) {
2058 var isPlayer = _.valuesIn(playerNumbers).indexOf(key) >= 0; 2059 2060 return function () { 2061 2062 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2063 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2064 var bel0 = document.createElement("li"); 2065 bel0.setAttribute("class", arguments[0]); 2066 ac(bel0, [arguments[1]]); 2067 return bel0; 2068 }(isPlayer ? 'player' : '', clients[key].username); 2069 } 2070} 2071 2072module.exports = clientsList; 2073 2074},{"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"lodash":171,"sheetify/insert":227}],26:[function(require,module,exports){ 2075'use strict'; 2076 2077var html = {}; 2078var sf = 0; 2079var gameView = require('./game'); 2080 2081var _require = require('./runtime-controls'), 2082 speedSliderView = _require.speedSliderView, 2083 playButtonView = _require.playButtonView; 2084 2085var gameStatsView = require('./game-stats'); 2086 2087var gameRunnerPrefix = (require('sheetify/insert')("._5a8deb15 {\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n }\n\n ._5a8deb15 > .controls {\n display: flex;\n flex-direction: row;\n align-items: center;\n height: 50px;\n border-bottom: 1px solid grey;\n }\n\n ._5a8deb15 > .game {\n position: relative;\n height: calc(100% - 50px);\n }") || true) && "_5a8deb15"; 2088 2089function gameRunnerView(_ref) { 2090 var game = _ref.game, 2091 clock = _ref.clock, 2092 onStart = _ref.onStart, 2093 onStop = _ref.onStop, 2094 onChangeSpeed = _ref.onChangeSpeed; 2095 2096 var gameHtml = gameView({ 2097 state: game, 2098 progress: clock.progress 2099 }); 2100 2101 var playButtonHtml = playButtonView({ 2102 isRunning: clock.isRunning, 2103 onStart: onStart, 2104 onStop: onStop 2105 }); 2106 2107 var speedSliderHtml = speedSliderView({ 2108 min: 100, 2109 max: 1000, 2110 intervalDuration: clock.intervalDuration, 2111 onChange: onChangeSpeed 2112 }); 2113 2114 var gameStatsHtml = gameStatsView({ 2115 game: game, 2116 progress: clock.progress 2117 }); 2118 2119 return function () { 2120 2121 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2122 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2123 var bel2 = document.createElement("div"); 2124 bel2.setAttribute("class", arguments[4]); 2125 var bel0 = document.createElement("div"); 2126 bel0.setAttribute("class", "controls"); 2127 ac(bel0, ["\n ", arguments[0], "\n ", arguments[1], "\n "]); 2128 var bel1 = document.createElement("div"); 2129 bel1.setAttribute("class", "game"); 2130 ac(bel1, ["\n ", arguments[2], "\n ", arguments[3], "\n "]); 2131 ac(bel2, ["\n ", bel0, "\n ", bel1, " \n "]); 2132 return bel2; 2133 }(playButtonHtml, speedSliderHtml, gameHtml, gameStatsHtml, gameRunnerPrefix); 2134} 2135 2136module.exports = gameRunnerView; 2137 2138},{"./game":28,"./game-stats":27,"./runtime-controls":37,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"sheetify/insert":227}],27:[function(require,module,exports){ 2139'use strict'; 2140 2141var _ = require('lodash'); 2142var html = {}; 2143var sf = 0; 2144 2145var _require = require('@robotopia/choo-game'), 2146 interpolate = _require.interpolate; 2147 2148var gameStatsPrefix = (require('sheetify/insert')("._1ece1d4c {\n position: absolute;\n right: 0;\n top: 0;\n background-color: rgba(221,221,221,0.85);\n color: #404040;\n padding: 10px;\n border-radius: 3px;\n margin: 20px;\n }\n \n ._1ece1d4c > h2 {\n font-size: 1.2em;\n margin: 0;\n }\n \n ._1ece1d4c > table {\n margin-top: 10px;\n border-spacing: 25px 5px;\n text-align: center;\n }\n \n ._1ece1d4c > table > th {\n text-align: center;\n }") || true) && "_1ece1d4c"; 2149 2150function gamePointsDisplay(_ref) { 2151 var game = _ref.game, 2152 progress = _ref.progress; 2153 2154 if (!game) { 2155 return null; 2156 } 2157 var teamColumnHeaderHtml = void 0; 2158 2159 var gameTeamStatsHtml = _(game.current.teams).keys().map(function (teamId) { 2160 var teamFieldHtml = void 0; 2161 var currentTeam = game.current.teams[teamId]; 2162 var prevTeam = game.prev === null ? currentTeam : game.prev.teams[teamId]; 2163 // TODO: Uncomment when points are implemented 2164 // const points = Math.round(interpolate(currentTeam.points, prevTeam.points, progress)) 2165 var resources = Math.round(interpolate(currentTeam.resources, prevTeam.resources, progress)); 2166 2167 if (_.size(game.current.teams) > 1) { 2168 teamFieldHtml = function () { 2169 2170 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2171 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2172 var bel0 = document.createElement("td"); 2173 ac(bel0, [arguments[0]]); 2174 return bel0; 2175 }(teamId); 2176 } 2177 2178 return function () { 2179 2180 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2181 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2182 var bel1 = document.createElement("tr"); 2183 var bel0 = document.createElement("td"); 2184 ac(bel0, [arguments[0]]); 2185 ac(bel1, ["\n ", arguments[1], "\n ", bel0, "\n "]); 2186 return bel1; 2187 }(resources, teamFieldHtml); 2188 }
2188).value(); 2189 2190 if (_.isEmpty(game.current.teams)) { 2191 return ''; 2192 } 2193 2194 if (_.size(game.current.teams) > 1) { 2195 teamColumnHeaderHtml = function () { 2196 2197 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2198 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2199 var bel0 = document.createElement("th"); 2200 ac(bel0, ["Team"]); 2201 return bel0; 2202 }(); 2203 } 2204 2205 return function () { 2206 2207 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2208 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2209 var bel3 = document.createElement("div"); 2210 bel3.setAttribute("class", arguments[2]); 2211 var bel2 = document.createElement("table"); 2212 var bel1 = document.createElement("tr"); 2213 var bel0 = document.createElement("th"); 2214 ac(bel0, ["Resources"]); 2215 ac(bel1, [arguments[0], bel0]); 2216 ac(bel2, ["\n ", bel1, "\n ", arguments[1], "\n "]); 2217 ac(bel3, ["\n ", bel2, "\n "]); 2218 return bel3; 2219 }(teamColumnHeaderHtml, gameTeamStatsHtml, gameStatsPrefix); 2220} 2221 2222module.exports = gamePointsDisplay; 2223 2224},{"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"@robotopia/choo-game":70,"lodash":171,"sheetify/insert":227}],28:[function(require,module,exports){ 2225'use strict'; 2226 2227var canvasWidget = require('../canvas'); 2228var renderer = require('./renderer'); 2229 2230var canvasView = canvasWidget(); 2231 2232module.exports = function (_ref) { 2233 var state = _ref.state, 2234 progress = _ref.progress; 2235 return canvasView({ 2236 render: function render(ctx, viewport) { 2237 renderer.render(ctx, viewport, state, progress); 2238 } 2239 2240 }); 2241}; 2242 2243},{"../canvas":23,"./renderer":29}],29:[function(require,module,exports){ 2244'use strict'; 2245 2246var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); 2247 2248function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 2249 2250var _ = require('lodash'); 2251var assets = require('@robotopia/assets-loader'); 2252 2253var _require = require('@robotopia/choo-game'), 2254 getAllEntities = _require.getAllEntities, 2255 getEntity = _require.getEntity, 2256 interpolate = _require.interpolate; 2257 2258var _require2 = require('../../lib/utils/types'), 2259 RENDERER = _require2.RENDERER; 2260 2261var _require3 = require('../../lib/utils/types'), 2262 ORIENTATION = _require3.ORIENTATION; 2263 2264var TILE_HEIGHT = 80; 2265var TILE_WIDTH = 100; 2266 2267// 80 / 100 = 4 / 5 => width has to be divisible by 5 2268var TILE_DIVISOR = 5; 2269 2270var RESOURCE_COLOR = { 2271 10: '#2245e3', 2272 20: '#2245e3', 2273 25: '#e4292a' 2274}; 2275 2276function render(ctx, viewport, state, progress) { 2277 var tiles = state.current.tiles; 2278 2279 2280 ctx.save(); 2281 ctx.strokeStyle = '#000'; 2282 ctx.lineWidth = 2; 2283 2284 applyViewportTransforms({ 2285 ctx: ctx, 2286 viewport: viewport, 2287 gameWidth: tiles[0].length, 2288 gameHeight: tiles.length 2289 }); 2290 2291 renderTiles(ctx, viewport, tiles); 2292 renderEntities(ctx, state.current, state.prev, progress); 2293 2294 ctx.restore(); 2295} 2296 2297function applyViewportTransforms(_ref) { 2298 var ctx = _ref.ctx, 2299 viewport = _ref.viewport, 2300 gameWidth = _ref.gameWidth, 2301 gameHeight = _ref.gameHeight; 2302 2303 // move origin to center of canvas 2304 ctx.translate(viewport.width / 2, viewport.height / 2); 2305 2306 // apply scale 2307 var scale = getEvenScale(viewport.scale); 2308 ctx.scale(scale, scale); 2309 2310 // center game field 2311 ctx.translate(-(gameWidth / 2) * TILE_WIDTH, -(gameHeight / 2) * TILE_WIDTH); 2312 2313 // apply viewport translate 2314 ctx.translate(viewport.translate.x, viewport.translate.y); 2315} 2316 2317// enforce that scale always results in integer tile dimensions (no subpixel rendering) 2318// if scale doesn't full fill this requirement find the next smaller scale that does 2319function getEvenScale(scale) { 2320 var width = Math.floor(scale * TILE_WIDTH); 2321 2322 if (width % TILE_DIVISOR === 0) { 2323 return width / TILE_WIDTH; 2324 } 2325 2326 var divisibleWidth = 0; 2327 2328 while (divisibleWidth + TILE_DIVISOR < width) { 2329 divisibleWidth += TILE_DIVISOR; 2330 } 2331 2332 return divisibleWidth / TILE_WIDTH; 2333} 2334 2335function renderTiles(ctx, viewport, tiles) { 2336 for (var y = 0; y < tiles.length; y++) { 2337 for (var x = 0; x < tiles[y].length; x++) { 2338 var image = assets.store[getTileImageType(tiles[y][x])]; 2339 ctx.drawImage(image, x * TILE_WIDTH, y * TILE_HEIGHT + 40); 2340 } 2341 } 2342} 2343 2344function getTileImageType(type) { 2345 return { 2346 1: 'WATER_TILE', 2347 2: 'DIRT_TILE', 2348 3: 'GRASS_TILE', 2349 4: 'PLAIN_TILE', 2350 5: 'STONE_TILE' 2351 }[type]; 2352} 2353 2354function renderEntities(ctx, state, prev, progress) { 2355 var entities = getAllEntities('id', state); 2356 2357 _(entities).sortBy(['position.y', 'position.x', 'zIndex']).map(function (entity) { 2358 return combineWithPrevEntityState(prev, entity); 2359 }).each(function (_ref2) { 2360 var _ref3 = _slicedToArray(_ref2, 2), 2361 entity = _ref3[0], 2362 prevEntity = _ref3[1]; 2363 2364 renderEntity(ctx, entity, prevEntity, progress); 2365 }); 2366} 2367 2368function combineWithPrevEntityState(prev, entity) { 2369 if (!prev) { 2370 return [entity, entity]; 2371 } 2372 2373 var prevEntity = getEntity(entity.id, prev); 2374 2375 if (!prevEntity) { 2376 return [entity, entity]; 2377 } 2378 2379 return [entity, prevEntity]; 2380} 2381 2382function renderEntity(ctx, entity, prevEntity, progress) { 2383 if (entity.showRange) { 2384 renderRange(ctx, entity, prevEntity, progress); 2385 } 2386 2387 if (entity.collectable) { 2388 renderCollectable(ctx, entity, prevEntity, progress); 2389 } 2390 2391 if (entity.sprite && !entity.collectable) { 2392 renderSprite(ctx, entity, prevEntity, progress); 2393 } 2394 2395 if (entity.health) { 2396 renderHealth(ctx, entity, prevEntity, progress); 2397 } 2398 2399 if (entity.collector) { 2400 renderCarriesResource(ctx, entity, prevEntity, progress); 2401 } 2402 2403 if (entity.task) { 2404 renderTask(ctx, entity, prevEntity, progress); 2405 } 2406 2407 if (entity.worker) { 2408 renderWorker(ctx, entity, prevEntity, progress); 2409 } 2410} 2411 2412function renderCollectable(ctx, entity, prevEntity, progress) { 2413 var spritePart = getCollectableSprite(entity.collectable); 2414 var sprite = entity.sprite.data.sprite; 2415 2416 var image = assets.store[sprite]; 2417 var width = image.width / 3; 2418 var height = image.height; 2419 var _entity$position = entity.position, 2420 x = _entity$position.x, 2421 y = _entity$position.y; 2422 2423 2424 ctx.drawImage(image, spritePart * width, 0, width, height, x * TILE_WIDTH, y * TILE_HEIGHT, width, height); 2425} 2426 2427function getCollectableSprite(_ref4) { 2428 var value = _ref4.value, 2429 maxValue = _ref4.maxValue; 2430 2431 var parts = maxValue / 3; 2432 2433 if (value < parts) { 2434 return 2; 2435 } 2436 if (value < parts * 2) { 2437 return 1; 2438 } 2439 return 0; 2440} 2441
2442function renderSprite(ctx, entity, prevEntity, progress) { 2443 var _entity$sprite = entity.sprite, 2444 type = _entity$sprite.type, 2445 data = _entity$sprite.data; 2446 2447 2448 switch (type) { 2449 case RENDERER.SIMPLE: 2450 simpleRenderer(ctx, data, entity); 2451 break; 2452 2453 case RENDERER.ROBOT: 2454 robotRenderer(ctx, data, entity, prevEntity, progress); 2455 break; 2456 2457 default: 2458 throw new Error('Unknown renderer type: ' + type); 2459 } 2460} 2461 2462function simpleRenderer(ctx, _ref5, _ref6) { 2463 var sprite = _ref5.sprite; 2464 var position = _ref6.position; 2465 2466 drawSprite(ctx, sprite, position.x, position.y); 2467} 2468 2469function robotRenderer(ctx, data, current, prev, progress) { 2470 var x = interpolate(current.position.x, prev.position.x, progress); 2471 var y = interpolate(current.position.y, prev.position.y, progress); 2472 var sprite = getRobotSprite(current); 2473 2474 if (sprite === undefined) { 2475 throw new Error('rotatingRenderer: no sprite defined for rotation = ' + current.position.rotation + ' '); 2476 } 2477 2478 var image = assets.store[sprite]; 2479 var width = image.width / 4; 2480 var height = image.height; 2481 2482 var frame = void 0; 2483 2484 if (current.position.x === prev.position.x && current.position.y === prev.position.y) { 2485 frame = 0; 2486 } else { 2487 frame = Math.floor(4 * progress); 2488 } 2489 2490 ctx.drawImage(image, frame * width, 0, width, height, x * TILE_WIDTH, y * TILE_HEIGHT, width, height); 2491 // drawSprite(ctx, sprite, x, y) 2492} 2493 2494function getRobotSprite(_ref7) { 2495 var _ORIENTATION$FRONT$OR; 2496 2497 var position = _ref7.position, 2498 team = _ref7.team, 2499 sprite = _ref7.sprite; 2500 2501 var positionName = (_ORIENTATION$FRONT$OR = {}, _defineProperty(_ORIENTATION$FRONT$OR, ORIENTATION.FRONT, 'ROBOT_FRONT'), _defineProperty(_ORIENTATION$FRONT$OR, ORIENTATION.BACK, 'ROBOT_BACK'), _defineProperty(_ORIENTATION$FRONT$OR, ORIENTATION.LEFT, 'ROBOT_LEFT'), _defineProperty(_ORIENTATION$FRONT$OR, ORIENTATION.RIGHT, 'ROBOT_RIGHT'), _ORIENTATION$FRONT$OR)[position.rotation]; 2502 2503 var teamId = (sprite && sprite.team) === 2 ? 2 : 1; 2504 var teamName = 'TEAM_' + teamId; 2505 2506 return positionName + '_' + teamName; 2507} 2508 2509function drawSprite(ctx, type, x, y) { 2510 ctx.drawImage(assets.store[type], x * TILE_WIDTH, y * TILE_HEIGHT); 2511} 2512 2513var HEALTH_BAR_WIDTH = 75; 2514var HEALTH_BAR_HEIGHT = 10; 2515var HEALTH_BAR_BACKGROUND = '#fff'; 2516var HEALTH_BAR_COLOR = '#00ff00'; 2517 2518function renderHealth(ctx, current, prev, progress) { 2519 ctx.fillStyle = 'red'; 2520 2521 var x = (interpolate(current.position.x, prev.position.x, progress) + 0.5) * TILE_WIDTH - HEALTH_BAR_WIDTH / 2; // align in center 2522 var y = interpolate(current.position.y, prev.position.y, progress) * TILE_HEIGHT + 20; 2523 2524 var healthPercentage = interpolate(current.health.current, prev.health.current, progress) / current.health.max; 2525 2526 // don't render health bar if entity has no damage 2527 if (healthPercentage === 1) { 2528 return; 2529 } 2530 2531 ctx.save(); 2532 2533 // draw background 2534 ctx.fillStyle = HEALTH_BAR_BACKGROUND; 2535 ctx.fillRect(x, y, HEALTH_BAR_WIDTH, HEALTH_BAR_HEIGHT); 2536 2537 // draw health percentage 2538 ctx.fillStyle = HEALTH_BAR_COLOR; 2539 ctx.fillRect(x, y, HEALTH_BAR_WIDTH * healthPercentage, HEALTH_BAR_HEIGHT); 2540 2541 // draw border 2542 ctx.strokeRect(x, y, HEALTH_BAR_WIDTH, HEALTH_BAR_HEIGHT); 2543 2544 ctx.restore(); 2545} 2546 2547function renderCarriesResource(ctx, current, prev, progress) { 2548 // maximum size of 20 2549 var HAS_RESOURCE_RADIUS = Math.min(current.collector.chunk, 25); 2550 var HAS_RESOURCE_COLOR = RESOURCE_COLOR[HAS_RESOURCE_RADIUS]; 2551 2552 // only render if robot carries resource 2553 if ((current.collector.hasResource || prev.collector.hasResource) && current.position.rotation !== ORIENTATION.BACK) { 2554 var x = 0; 2555 var y = 0; 2556 var radius = HAS_RESOURCE_RADIUS * interpolate(current.collector.hasResource, prev.collector.hasResource, progress); 2557 2558 if (current.position.rotation === ORIENTATION.FRONT) { 2559 x = (interpolate(current.position.x, prev.position.x, progress) + 0.5) * TILE_WIDTH; 2560 y = interpolate(current.position.y, prev.position.y, progress) * TILE_HEIGHT + 115; 2561 } 2562 2563 if (current.position.rotation === ORIENTATION.RIGHT) { 2564 x = (interpolate(current.position.x, prev.position.x, progress) + 0.5) * TILE_WIDTH + 25; 2565 y = interpolate(current.position.y, prev.position.y, progress) * TILE_HEIGHT + 115; 2566 } 2567 2568 if (current.position.rotation === ORIENTATION.LEFT) { 2569 x = (interpolate(current.position.x, prev.position.x, progress) + 0.5) * TILE_WIDTH - 25; 2570 y = interpolate(current.position.y, prev.position.y, progress) * TILE_HEIGHT + 115; 2571 } 2572 2573 ctx.save(); 2574 2575 ctx.fillStyle = HAS_RESOURCE_COLOR; 2576 ctx.beginPath(); 2577 ctx.arc(x, y, radius, 0, 2 * Math.PI); 2578 ctx.fill(); 2579
2580 ctx.restore(); 2581 } 2582} 2583 2584var TASK_RING_WIDTH = 15; 2585var TASK_CIRCLE_WIDTH = 25; 2586var TASK_PADDING = 10; 2587 2588function renderTask(ctx, current, prev, progress) { 2589 var assignedWorkers = interpolate(current.task.assignedWorkers, prev.task.assignedWorkers, progress); 2590 var requiredWorkers = current.task.requiredWorkers; 2591 2592 var percentage = assignedWorkers / requiredWorkers; 2593 var angle = percentage * Math.PI * 2; 2594 var x = (current.position.x + 0.5) * TILE_WIDTH; 2595 var y = (current.position.y + 1.55) * TILE_HEIGHT * 1.25; 2596 2597 ctx.save(); 2598 ctx.fillStyle = current.task.type; 2599 2600 // skew circle to make it look like a side it's viewed from the side 2601 ctx.scale(1, 0.8); 2602 2603 if (percentage > 0) { 2604 // draw ring 2605 ctx.beginPath(); 2606 ctx.arc(x, y, TASK_CIRCLE_WIDTH / 2 + TASK_RING_WIDTH + TASK_PADDING, 0, angle, false); // outer (filled) 2607 ctx.arc(x, y, TASK_CIRCLE_WIDTH / 2 + TASK_PADDING, percentage === 1 ? 0 : angle, Math.PI * 2, true); // inner (unfills it) 2608 ctx.closePath(); 2609 ctx.fill(); 2610 ctx.stroke(); 2611 } 2612 2613 // draw circle 2614 ctx.beginPath(); 2615 ctx.arc(x, y, TASK_CIRCLE_WIDTH / 2, 0, Math.PI * 2, true); 2616 ctx.fill(); 2617 ctx.stroke(); 2618 2619 ctx.restore(); 2620} 2621 2622var WORKER_ICON_SIZE = 50; 2623 2624function renderWorker(ctx, current, prev, progress) { 2625 if (current.worker.assignedTask === null) { 2626 return; 2627 } 2628 2629 var x = (interpolate(current.position.x, prev.position.x, progress) + 0.5) * TILE_WIDTH - WORKER_ICON_SIZE / 2; 2630 var y = interpolate(current.position.y, prev.position.y, progress) * TILE_HEIGHT - 35; 2631 2632 ctx.save(); 2633 2634 ctx.fillStyle = current.worker.assignedTask.type; 2635 ctx.translate(x, y); 2636 2637 // adapted from ionicions: https://raw.githubusercontent.com/driftyco/ionicons/master/src/flash.svg 2638 ctx.beginPath(); 2639 ctx.moveTo(10, 29); 2640 ctx.lineTo(24, 29); 2641 ctx.lineTo(19, 48); 2642 ctx.lineTo(42, 22); 2643 ctx.lineTo(27, 22); 2644 ctx.lineTo(32, 3); 2645 ctx.closePath(); 2646 ctx.fill(); 2647 ctx.stroke(); 2648 2649 ctx.restore(); 2650} 2651 2652var RANGE_INDICATOR_COLOR = 'rgba(255, 255, 255, 0.5)'; 2653 2654function renderRange(ctx, current, prev, progress) { 2655 var range = current.showRange; 2656 2657 var x = (interpolate(current.position.x, prev.position.x, progress) + 0.5) * TILE_WIDTH; 2658 var y = interpolate(current.position.y, prev.position.y, progress) * TILE_HEIGHT + 115; 2659 2660 ctx.save(); 2661 2662 ctx.fillStyle = RANGE_INDICATOR_COLOR; 2663 ctx.beginPath(); 2664 ctx.arc(x, y, TILE_WIDTH * (range + 0.5), 0, 2 * Math.PI); 2665 ctx.fill(); 2666 2667 ctx.restore(); 2668} 2669 2670module.exports = { 2671 render: render 2672}; 2673 2674},{"../../lib/utils/types":42,"@robotopia/assets-loader":68,"@robotopia/choo-game":70,"lodash":171}],30:[function(require,module,exports){ 2675'use strict'; 2676 2677var _ = require('lodash'); 2678 2679var _require = require('@robotopia/choo-game'), 2680 getEntity = _require.getEntity; 2681 2682var haventTouchedTile = true; 2683 2684function checkGoal(_ref) { 2685 var goal = _ref.goal, 2686 game = _ref.game, 2687 workspace = _ref.workspace; 2688 2689 switch (goal.type) { 2690 case 'moveTo': 2691 if (game === null) { 2692 return false; 2693 } 2694 2695 var entity = getEntity(goal.params.entity, game); 2696 var entityPos = { x: entity.position.x, y: entity.position.y }; 2697 2698 return _.isEqual(entityPos, goal.params.position); 2699 2700 case 'useBlock': 2701 return workspace.indexOf(goal.params.type) > -1; 2702 2703 case 'doNotUseBlock': 2704 return workspace.indexOf(goal.params.type) === -1; 2705 2706 case 'maxBlocks': 2707 var workspaceMatch = workspace.match(/<block type="\S*"/g); 2708 var matchAsString = workspaceMatch.toString(); 2709 var handlerMatch = matchAsString.match(/_handler/g); 2710 2711 if (workspaceMatch) { 2712 if (handlerMatch) { 2713 return workspaceMatch.length - handlerMatch.length <= goal.params.amount; 2714 } 2715 return workspaceMatch.length <= goal.params.amount; 2716 } 2717 return false; 2718 2719 case 'carryResource': 2720 if (game && game.entities && game.entities.ROBOT && game.entities.ROBOT.collector) { 2721 return game.entities.ROBOT.collector.hasResource === goal.params.hasResource; 2722 } 2723 return false; 2724 2725 case 'collectResources': 2726 if (game && game.teams) { 2727 return game.teams[game.entities.ROBOT.team.id].resources === goal.params.amount; 2728 } 2729 return false;
2730 2731 case 'dontTouchTileType': 2732 if (game && haventTouchedTile) { 2733 var robotPosition = game.entities.ROBOT.position; 2734 var currTile = game.tiles[robotPosition.y][robotPosition.x]; 2735 2736 haventTouchedTile = goal.params.tileID !== currTile; 2737 } 2738 2739 if (!game) { 2740 haventTouchedTile = true; 2741 } 2742 2743 return haventTouchedTile; 2744 2745 case 'touchTile': 2746 if (game) { 2747 var _robotPosition = game.entities.ROBOT.position; 2748 var _currTile = game.tiles[_robotPosition.y][_robotPosition.x]; 2749 2750 return goal.params.tileID === _currTile; 2751 } 2752 return false; 2753 2754 case 'useBlockWithinBlock': 2755 var outerBlockType = goal.params.outerBlock; 2756 var innerBlockType = goal.params.innerBlock; 2757 2758 // Regex for blocks - no need to destructure JSON 2759 return workspace.match('<block type="' + outerBlockType + '".*<statement.*<block type="' + innerBlockType + '"', 'g'); 2760 2761 case 'discoverEntityOfType': 2762 if (!game || !game.entities || game.entities.length === 0) return false; 2763 var i = void 0; 2764 for (i in game.entities) { 2765 if (game.entities[i].hasOwnProperty('discoverable')) { 2766 var discoverable = game.entities[i].discoverable; 2767 if (discoverable.type === goal.params.type && discoverable.discovererTeamIds && discoverable.discovererTeamIds['1']) return true; 2768 } 2769 } 2770 return false; 2771 2772 default: 2773 return false; 2774 } 2775} 2776 2777function checkGoals(_ref2, goals) { 2778 var game = _ref2.game, 2779 workspace = _ref2.workspace; 2780 2781 return _.every(goals, function (goal) { 2782 return checkGoal({ goal: goal, game: game, workspace: workspace }); 2783 }); 2784} 2785 2786module.exports = { 2787 checkGoal: checkGoal, 2788 checkGoals: checkGoals 2789}; 2790 2791},{"@robotopia/choo-game":70,"lodash":171}],31:[function(require,module,exports){ 2792'use strict'; 2793 2794var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); 2795 2796var _ = require('lodash'); 2797var html = {}; 2798var sf = 0; 2799var classNames = require('classnames'); 2800 2801var _require = require('./goal-evaluator'), 2802 checkGoal = _require.checkGoal; 2803 2804var goalPrefix = (require('sheetify/insert')("._b02997e0 {\n background-color: #DDDDDD;\n color: #404040;\n background-color: rgba(221,221,221,0.85);\n color: #404040;\n margin: 20px;\n padding: 25px;\n border-radius: 3px;\n }\n\n ._b02997e0 > h2 {\n font-size: 1.2em;\n margin: 0;\n }") || true) && "_b02997e0"; 2805 2806var goalListPrefix = (require('sheetify/insert')("._ed8591e2 {\n padding: 0;\n }\n \n ._ed8591e2 > .goal {\n list-style: none;\n display: flex;\n flex-direction: row;\n align-items: center;\n }\n \n ._ed8591e2 > .goal:before {\n content: '';\n width: 25px;\n height: 25px;\n background-size: 25px;\n margin-right: 7px;\n background-image: url('assets/icons/checkbox-empty.svg');\n flex-shrink: 0;\n }\n \n ._ed8591e2 > .goal.completed:before { \n background-size: 25px;\n background-image: url('assets/icons/checkbox-filled.svg');\n }") || true) && "_ed8591e2"; 2807 2808function goalProgressView(_ref) { 2809 var display = _ref.display, 2810 game = _ref.game, 2811 goals = _ref.goals, 2812 workspace = _ref.workspace; 2813 2814 if (display) { 2815 var _$partition = _.partition(goals, function (goal) { 2816 return goal.isMandatory; 2817 }), 2818 _$partition2 = _slicedToArray(_$partition, 2), 2819 mandatoryGoals = _$partition2[0], 2820 optionalGoals = _$partition2[1]; 2821 2822 return function () { 2823 2824 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2825 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2826 var bel2 = document.createElement("div"); 2827 bel2.setAttribute("class", arguments[1]); 2828 var bel0 = document.createElement("h2"); 2829 ac(bel0, ["Goals: "]); 2830 var bel1 = document.createElement("h2"); 2831 bel1.setAttribute("style", arguments[0]); 2832 ac(bel1, ["Bonus: "]); 2833 ac(bel2, ["\n ", bel0, "\n ", arguments[2], "\n \n ", bel1, "\n ", arguments[3], "\n "]); 2834 return bel2; 2835 }
2835(optionalGoals.length === 0 ? 'display: none' : '', goalPrefix, goalListView({ goals: mandatoryGoals, game: game, workspace: workspace }), goalListView({ goals: optionalGoals, game: game, workspace: workspace })); 2836 } 2837} 2838 2839function goalListView(_ref2) { 2840 var goals = _ref2.goals, 2841 game = _ref2.game, 2842 workspace = _ref2.workspace; 2843 2844 if (goals.length === 0) return; 2845 2846 var goalsHtml = _.map(goals, function (goal) { 2847 var className = classNames('goal', { 2848 'completed': checkGoal({ goal: goal, workspace: workspace, game: game }) 2849 }); 2850 2851 return function () { 2852 2853 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2854 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2855 var bel1 = document.createElement("li"); 2856 bel1.setAttribute("class", arguments[1]); 2857 var bel0 = document.createElement("span"); 2858 ac(bel0, [arguments[0]]); 2859 ac(bel1, [bel0]); 2860 return bel1; 2861 }(goal.desc, className); 2862 }); 2863 2864 return function () { 2865 2866 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2867 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2868 var bel0 = document.createElement("ul"); 2869 bel0.setAttribute("class", arguments[0]); 2870 ac(bel0, [arguments[1]]); 2871 return bel0; 2872 }(goalListPrefix, goalsHtml); 2873} 2874 2875module.exports = { 2876 goalListView: goalListView, 2877 goalProgressView: goalProgressView 2878}; 2879 2880},{"./goal-evaluator":30,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"classnames":93,"lodash":171,"sheetify/insert":227}],32:[function(require,module,exports){ 2881'use strict'; 2882 2883var html = {}; 2884var sf = 0; 2885 2886var _require = require('../elements/goal-progress'), 2887 goalProgressView = _require.goalProgressView; 2888 2889var prefix = (require('sheetify/insert')("._a6a2bf5d {\n height: 100%;\n width: 100%;\n padding: 25px;\n margin: 0;\n display: flex;\n flex-direction: column; \n align-items: center;\n }\n \n ._a6a2bf5d .story-hint {\n width: 100%;\n color: #8a6d3b;\n border: 1px solid #faebcc;\n padding: 15px;\n border-radius: 3px;\n padding-left: 50px;\n display: inline-block;\n background-color: #fcf8e3;\n background-image: url('assets/icons/info.svg');\n background-size: 32px 32px;\n background-position: 10px center;\n background-repeat: no-repeat;\n }") || true) && "_a6a2bf5d"; 2890 2891function instructionView(_ref, _ref2) { 2892 var prev = _ref.prev; 2893 var level = _ref2.level, 2894 isStoryModalOpen = _ref2.isStoryModalOpen; 2895 2896 if (level) { 2897 var story = level.storyModal; 2898 2899 var goalHtml = void 0; 2900 var hintHtml = void 0; 2901 2902 if (level !== null) { 2903 goalHtml = goalProgressView({ 2904 display: !isStoryModalOpen, 2905 game: prev, 2906 goals: level.goals, 2907 workspace: level.editor.workspace 2908 }); 2909 } 2910 2911 if (story.hint) { 2912 hintHtml = function () { 2913 2914 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2915 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2916 var bel0 = document.createElement("p"); 2917 bel0.setAttribute("class", "story-hint"); 2918 ac(bel0, ["\n ", arguments[0], "\n "]); 2919 return bel0; 2920 }(story.hint); 2921 } 2922 2923 return function () { 2924 2925 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2926 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2927 var bel2 = document.createElement("div"); 2928 bel2.setAttribute("class", arguments[2]); 2929 var bel0 = document.createElement("h1"); 2930 ac(bel0, [arguments[0]]); 2931 var bel1 = document.createElement("p"); 2932 ac(bel1, [arguments[1]]); 2933 ac(bel2, ["\n ", bel0, "\n ", bel1, "\n ", arguments[3], " \n "]); 2934 return bel2; 2935 }(level.label, hintHtml, prefix, goalHtml); 2936 } 2937} 2938 2939module.exports = { 2940 instructionView: instructionView 2941}; 2942 2943},{"../elements/goal-progress":31,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"sheetify/insert":227}],33:[function(require,module,exports){ 2944"use strict"; 2945 2946var html = {}; 2947var sf = 0; 2948 2949var prefix = (require('sheetify/insert')("._80aeacb2 {\n position: fixed;\n top: 0;\n left: 0;\n height: 100vh;\n width: 100vw;\n display: flex;\n flex-direction: row;
2949\n align-items: center;\n justify-content: center;\n background: rgba(0, 0, 0, 0.5);\n overflow: hidden;\n z-index: 500;\n }\n \n ._80aeacb2 > .inner {\n max-width: 800px;\n background: #fff;\n color: #404040;\n padding: 30px;\n border-radius: 3px;\n border: 10px solid #404040; \n overflow: scroll;\n z-index: 501;\n animation: move 1s 1 ease;\n animation-delay: 10;\n overflow: hidden;\n }\n \n ._80aeacb2 > .inner > .content {\n display: flex;\n flex-direction: column;\n justify-content: space-around;\n align-items: center;\n overflow: hidden;\n }\n \n ._80aeacb2 > .inner .img {\n max-width: 50%;\n }") || true) && "_80aeacb2"; 2950 2951function modalView(content) { 2952 return function () { 2953 2954 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2955 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2956 var bel1 = document.createElement("div"); 2957 bel1.setAttribute("class", arguments[1]); 2958 var bel0 = document.createElement("div"); 2959 bel0.setAttribute("class", "inner"); 2960 ac(bel0, [arguments[0]]); 2961 ac(bel1, ["\n ", bel0, "\n "]); 2962 return bel1; 2963 }(content, prefix); 2964} 2965 2966module.exports = modalView; 2967 2968},{"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"sheetify/insert":227}],34:[function(require,module,exports){ 2969'use strict'; 2970 2971var html = {}; 2972var sf = 0; 2973var classNames = require('classnames'); 2974 2975var prefix = (require('sheetify/insert')("._e3c405bd {\n position: absolute; \n margin: 20px;\n }\n \n ._e3c405bd.has-frame {\n background-color: rgba(221,221,221,0.85);\n color: #000;\n padding: 10px 15px;\n border-radius: 3px; \n }\n \n ._e3c405bd.top {\n top: 0\n }\n \n ._e3c405bd.left {\n left: 0\n }\n \n ._e3c405bd.right {\n right: 0\n }\n \n ._e3c405bd.bottom {\n bottom: 0\n }") || true) && "_e3c405bd"; 2976 2977function overlayView(_ref) { 2978 var content = _ref.content, 2979 position = _ref.position, 2980 _ref$hasFrame = _ref.hasFrame, 2981 hasFrame = _ref$hasFrame === undefined ? true : _ref$hasFrame; 2982 2983 var className = classNames(prefix, position, { 2984 'has-frame': hasFrame 2985 }); 2986 2987 return function () { 2988 2989 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 2990 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 2991 var bel0 = document.createElement("div"); 2992 bel0.setAttribute("class", arguments[0]); 2993 ac(bel0, ["\n ", arguments[1], "\n "]); 2994 return bel0; 2995 }(className, content); 2996} 2997 2998module.exports = overlayView; 2999 3000},{"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"classnames":93,"sheetify/insert":227}],35:[function(require,module,exports){ 3001'use strict'; 3002 3003function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } 3004 3005var _ = require('lodash'); 3006var html = {}; 3007var sf = 0; 3008var panelGroup = require('../components/panel-group'); 3009 3010var pageLayoutPrefix = (require('sheetify/insert')("._1482c51e {\n width: 100vw;\n height: 100vh;\n display: flexbox;\n }\n \n ._1482c51e > .content {\n height: calc(100% - 50px)\n }") || true) && "_1482c51e"; 3011 3012function pageLayout(_ref) { 3013 var context = _ref.context, 3014 id = _ref.id, 3015 panels = _ref.panels, 3016 menu = _ref.menu; 3017 3018 var panelSizes = _.map(panels, 'size'); 3019 var panelViews = _.map(panels, 'view'); 3020 3021 var contentHtml = panelGroup.component.apply(panelGroup, _toConsumableArray(context))(id, { 3022 props: { 3023 panelViews: panelViews, 3024 initialPanelSizes: panelSizes 3025 } 3026 }); 3027 3028 return function () { 3029 3030 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3031 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3032 var bel1 = document.createElement("div"); 3033 bel1.setAttribute("class", arguments[1]); 3034 var bel0 = document.createElement("div"); 3035 bel0.setAttribute("class", "content"); 3036 ac(bel0, ["\n ", arguments[0], "\n "]); 3037 ac(bel1, ["\n ", arguments[2], "\n ", bel0, "\n "]); 3038 return bel1; 3039 }(contentHtml, pageLayoutPrefix, getHeaderHtml(menu)); 3040} 3041 3042var headerPrefix = (require('sheetify/insert')("._c0e98046 {\n height: 50px;\n margin: 0;\n padding: 0 10px 0 20px;\n color: #fff;\n background: #03A9F4;\n display: flex;\n flex-direction: row;
3042\n align-items: center;\n justify-content: space-between;\n }\n \n ._c0e98046 > .logo {\n color: white;\n text-decoration: none;\n display: flex;\n align-items: center;\n font-size: 20px;\n font-weight: normal;\n font-family: sans-serif;\n }\n \n ._c0e98046 > .logo > img {\n height: 40px;\n margin-right: 10px;\n }") || true) && "_c0e98046"; 3043 3044function getHeaderHtml(menu) { 3045 return function () { 3046 3047 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3048 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3049 var bel3 = document.createElement("div"); 3050 bel3.setAttribute("class", arguments[1]); 3051 var bel1 = document.createElement("a"); 3052 bel1.setAttribute("href", "#"); 3053 bel1.setAttribute("class", "logo"); 3054 var bel0 = document.createElement("img"); 3055 bel0.setAttribute("src", "./assets/icons/logo.svg"); 3056 ac(bel1, ["\n ", bel0, "\n ROBOTOPIA\n "]); 3057 var bel2 = document.createElement("div"); 3058 bel2.setAttribute("class", "menu"); 3059 ac(bel2, ["\n ", arguments[0], "\n "]); 3060 ac(bel3, ["\n \n ", bel1, "\n \n ", bel2, "\n "]); 3061 return bel3; 3062 }(menu, headerPrefix); 3063} 3064 3065module.exports = pageLayout; 3066 3067},{"../components/panel-group":17,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"lodash":171,"sheetify/insert":227}],36:[function(require,module,exports){ 3068'use strict'; 3069 3070/* globals FormData */ 3071var _ = require('lodash'); 3072var html = {}; 3073var modalView = require('./modal'); 3074var buttonView = require('./button'); 3075var sf = 0; 3076 3077module.exports = function (_ref) { 3078 var presenter = _ref.presenter, 3079 currentGame = _ref.currentGame, 3080 onJoinGroup = _ref.onJoinGroup, 3081 onPlayersPicked = _ref.onPlayersPicked, 3082 onCancelPlayerPicking = _ref.onCancelPlayerPicking, 3083 _ref$onCloseWinModal = _ref.onCloseWinModal, 3084 onCloseWinModal = _ref$onCloseWinModal === undefined ? _.noop : _ref$onCloseWinModal; 3085 3086 if (!presenter.groupId) { 3087 return getCreationModal(); 3088 } 3089 3090 if (presenter.displayPlayerPickScreen) { 3091 return getPlayerPickingModal(); 3092 } 3093 3094 if (presenter.displayWinDialog) { 3095 return getWinModal(); 3096 } 3097 3098 return function () { 3099 3100 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3101 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3102 var bel0 = document.createElement("div"); 3103 return bel0; 3104 }(); 3105 3106 function getPlayerPickingModal() { 3107 var prefix = (require('sheetify/insert')("._d362117f {\n \n }\n \n ._d362117f form {\n display: inline-block;\n }\n \n ._d362117f .pick_select {\n height: 2em;\n }\n \n ._d362117f .pick_option {\n font-weight: 500;\n }\n \n ._d362117f .cancel {\n float: right\n }") || true) && "_d362117f"; 3108 3109 var startButton = buttonView({ 3110 label: 'Start' 3111 }); 3112 3113 var cancelButton = buttonView({ 3114 label: 'Cancel', 3115 onClick: onCancelPlayerPicking, 3116 additionalClasses: 'cancel' 3117 }); 3118 3119 return modalView(function () { 3120 3121 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3122 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3123 var bel2 = document.createElement("div"); 3124 bel2.setAttribute("class", arguments[4]); 3125 var bel0 = document.createElement("h1"); 3126 bel0.setAttribute("class", "pick_header"); 3127 ac(bel0, ["Chose the players to battle."]); 3128 var bel1 = document.createElement("form"); 3129 bel1["onsubmit"] = arguments[0]; 3130 ac(bel1, ["\n ", arguments[1], "\n vs\n ", arguments[2], "\n ", arguments[3], "\n "]); 3131 ac(bel2, ["\n ", bel0, "\n ", bel1, "\n ", arguments[5], "\n "]); 3132 return bel2; 3133 }(handleSubmit, clientsToOptions('1', presenter.clients, presenter.playerNumbers), clientsToOptions('2', presenter.clients, presenter.playerNumbers), startButton, prefix, cancelButton)); 3134 3135 function clientsToOptions(selectSuffix, clients, players) { 3136 return function () { 3137 3138 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3139 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3140 var bel0 = document.createElement("select"); 3141 bel0.setAttribute("name", "player" + arguments[0]); 3142 bel0.setAttribute("class", "pick_select"); 3143 ac(bel0, [" \n ", arguments[1], "\n "]); 3144 return bel0; 3145 }(selectSuffix, Object.keys(clients).map(clientToOption)); 3146 3147 function clientToOption(clientId) { 3148 var isSelected = players[selectSuffix] === clientId; 3149 return function () { 3150 3151 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3152 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3153 var bel0 = document.createElement("option"); 3154 bel0.setAttribute("value", arguments[0]); 3155 if (arguments[1] && "selected") bel0.setAttribute("selected", "selected"); 3156 bel0.setAttribute("class", "pick_option"); 3157 ac(bel0, [arguments[2]]); 3158 return bel0; 3159 }(clientId, isSelected, clients[clientId].username); 3160 } 3161 } 3162 3163 function handleSubmit(evt) { 3164 var formData = new FormData(evt.target); 3165 var player1 = formData.get('player1'); 3166 var player2 = formData.get('player2'); 3167 3168 evt.preventDefault(); 3169 3170 if (!player1 || !player2) { 3171 return; 3172 } 3173 3174 onPlayersPicked({ 3175 1: player1, 3176 2: player2 3177 }); 3178 } 3179 } 3180 3181 function getCreationModal() { 3182 var buttonHTML = buttonView({ 3183 label: 'submit' 3184 }); 3185 3186 return modalView(function () { 3187 3188 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3189 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3190 var bel3 = document.createElement("div"); 3191 var bel0 = document.createElement("p"); 3192 ac(bel0, ["Choose a group name"]); 3193 var bel2 = document.createElement("form"); 3194 bel2["onsubmit"] = arguments[1]; 3195 var bel1 = document.createElement("input"); 3196 bel1.setAttribute("type", "text"); 3197 bel1.setAttribute("name", "groupId"); 3198 bel1.setAttribute("autofocus", "autofocus"); 3199 ac(bel1, ["\n ", arguments[0], "\n "]); 3200 ac(bel2, ["\n ", bel1, "\n "]); 3201 ac(bel3, ["\n ", bel0, "\n ", bel2, "\n "]); 3202 return bel3; 3203 }(buttonHTML, handleSubmit)); 3204 3205 function handleSubmit(evt) { 3206 var formData = new FormData(evt.target); 3207 var groupId = formData.get('groupId'); 3208 3209 evt.preventDefault(); 3210 3211 onJoinGroup(groupId); 3212 } 3213 } 3214 3215 function getWinModal() { 3216 if (!currentGame || !currentGame.teams) { 3217 return function () { 3218 3219 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3220 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3221 var bel0 = document.createElement("div"); 3222 return bel0; 3223 }(); 3224 } 3225 3226 var prefix = (require('sheetify/insert')("._12ae0a68 {\n color: #404040;\n height: 100%;\n width: 30em;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n background-image: url('assets/img/celebration.png');\n background-size: cover;\n background-position: center;\n background-repeat: no-repeat;\n }\n \n ._12ae0a68 > .logo {\n width: 100%;\n height: 150px;\n background-image: url('assets/icons/robotopia.svg');\n background-size: contain;\n background-position: center;\n background-repeat: no-repeat;\n margin-bottom: 0;\n }\n \n ._12ae0a68 > .win {\n width: 100%;\n font-size: 45px;\n overflow: hidden;\n text-align: center;\n font-weight: 600;\n }\n \n ._12ae0a68 .result_container {\n width: 100%;\n overflow: hidden;\n margin-bottom: 20px;\n }\n \n ._12ae0a68 .result_table {\n width: 80%;\n margin: 0 auto;\n }\n \n ._12ae0a68 .result_table tr{\n height: 2em;\n }\n \n ._12ae0a68 .result_table td{\n text-align: center;\n vertical-align: middle;\n }") || true) && "_12ae0a68"; 3227 3228 var teams = currentGame.teams; 3229 var results = []; 3230 var i = void 0; 3231 for (i in presenter.playerNumbers) { 3232 var playerId = presenter.playerNumbers[i]; 3233 var client = presenter.clients[playerId]; 3234 var points = teams[i].points; 3235 var resources = teams[i].resources; 3236 var username = client.username; 3237 results.push({ 3238 id: playerId, 3239 name: username, 3240 points: points, 3241 resources: resources 3242 }); 3243 } 3244 3245 results.sort(function (a, b) { 3246 return a.resources < b.resources; 3247 }); 3248 3249 var buttonHTML = buttonView({ 3250 label: 'Close', 3251 onClick: onCloseWinModal 3252 }); 3253 3254 return modalView(function () { 3255 3256 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3257 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3258 var bel4 = document.createElement("div"); 3259 bel4.setAttribute("class", arguments[3]); 3260 var bel0 = document.createElement("div"); 3261 bel0.setAttribute("class", "logo"); 3262 var bel1 = document.createElement("div"); 3263 bel1.setAttribute("class", "win"); 3264 ac(bel1, [arguments[0], " won!"]); 3265 var bel2 = document.createElement("div"); 3266 bel2.setAttribute("class", "result_container"); 3267 ac(bel2, [arguments[1]]); 3268 var bel3 = document.createElement("div"); 3269 ac(bel3, [arguments[2]]); 3270 ac(bel4, ["\n ", bel0, "\n ", bel1, "\n ", bel2, "\n ", bel3, "\n "]); 3271 return bel4; 3272 }(results[0].name, getTableFromResult(results), buttonHTML, prefix)); 3273 3274 function getTableFromResult(result) { 3275 return function () { 3276 3277 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3278 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3279 var bel3 = document.createElement("table"); 3280 bel3.setAttribute("class", "result_table"); 3281 var bel2 = document.createElement("tr"); 3282 var bel0 = document.createElement("th"); 3283 ac(bel0, ["Player"]); 3284 var bel1 = document.createElement("th"); 3285 ac(bel1, ["Score"]); 3286 ac(bel2, [bel0, bel1]); 3287 ac(bel3, ["\n ", bel2, "\n ", arguments[0], "\n "]); 3288 return bel3; 3289 }(result.map(function (res) { 3290 return function () { 3291 3292 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3293 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3294 var bel2 = document.createElement("tr"); 3295 var bel0 = document.createElement("td"); 3296 ac(bel0, [arguments[0]]); 3297 var bel1 = document.createElement("td"); 3298 ac(bel1, [arguments[1]]); 3299 ac(bel2, [bel0, bel1]); 3300 return bel2; 3301 }(res.name, res.resources); 3302 })); 3303 } 3304 } 3305}; 3306 3307},{"./button":22,"./modal":33,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"lodash":171,"sheetify/insert":227}],37:[function(require,module,exports){ 3308'use strict'; 3309 3310var sf = 0; 3311var html = {}; 3312var button = require('./button'); 3313 3314var speedSliderPrefix = (require('sheetify/insert')("._490e7be8 {\n display: flex;
3314\n align-items: center;\n margin-left: 20px;\n }\n\n .label {\n display: inline-block;\n margin-right: 10px;\n color: #676768;\n }") || true) && "_490e7be8"; 3315 3316function speedSliderView(_ref) { 3317 var max = _ref.max, 3318 min = _ref.min, 3319 intervalDuration = _ref.intervalDuration, 3320 onChange = _ref.onChange; 3321 3322 // map intervalDuration to percentage, more speed => smaller interval 3323 var percentage = 1 - (intervalDuration - min) / (max - min); 3324 3325 return function () { 3326 3327 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3328 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3329 var bel2 = document.createElement("label"); 3330 bel2.setAttribute("class", arguments[2]); 3331 var bel0 = document.createElement("span"); 3332 bel0.setAttribute("class", "label"); 3333 ac(bel0, ["Speed"]); 3334 var bel1 = document.createElement("input"); 3335 bel1.setAttribute("type", "range"); 3336 bel1.setAttribute("min", "0"); 3337 bel1.setAttribute("max", "1"); 3338 bel1.setAttribute("step", "0.1"); 3339 bel1.setAttribute("value", arguments[0]); 3340 bel1["oninput"] = arguments[1]; 3341 ac(bel2, ["\n ", bel0, "\n ", bel1, "\n "]); 3342 return bel2; 3343 }(percentage, function (evt) { 3344 return onChange((1 - evt.target.value) * (max - min) + min); 3345 }, speedSliderPrefix); 3346} 3347 3348function playButtonView(_ref2) { 3349 var isRunning = _ref2.isRunning, 3350 onStart = _ref2.onStart, 3351 onStop = _ref2.onStop; 3352 3353 if (isRunning) { 3354 return button({ 3355 onClick: onStop, 3356 icon: 'stop', 3357 label: 'Reset', 3358 additionalClasses: 'play-button' 3359 }); 3360 } 3361 3362 return button({ 3363 onClick: onStart, 3364 icon: 'play', 3365 label: 'Run', 3366 additionalClasses: 'play-button' 3367 }); 3368} 3369 3370module.exports = { 3371 speedSliderView: speedSliderView, 3372 playButtonView: playButtonView 3373}; 3374 3375},{"./button":22,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"sheetify/insert":227}],38:[function(require,module,exports){ 3376"use strict"; 3377 3378var html = {}; 3379var sf = 0; 3380 3381var prefix = (require('sheetify/insert')("._863aef4e {\n background: none;\n overflow: hidden;\n display: block;\n position: relative;\n font-size: 30px;\n font-weight: 600;\n border-radius: 0.4em;\n}\n\n.timer_inner_container {\n border-style: outset;\n border-width: 4px;\n border-color: #666666;\n background-color: #666666;\n overflow: hidden;\n display: flex;\n border-radius: 0.4em;\n padding: 0.2em;\n}\n\n.timer_side {\n overflow: hidden;\n display: flex;\n}\n\n.timer_digit {\n border-style: inset;\n border-width: 0.1em;\n border-color: #888888;\n position: relative;\n overflow: hidden;\n background-color: #666666;\n padding-left: 0.2em;\n padding-right: 0.2em;\n border-radius: 0.3em;\n}\n\n.timer_divider {\n padding-right: 0.1em;\n padding-left: 0.1em;\n position: relative;\n}\n\n.timer_divider,\n.timer_digit {\n display: inline-block;\n box-sizing: border-box;\n padding-top: 0.1em;\n padding-bottom: 0.1em;\n text-decoration: none;\n color: #ffa241;\n text-shadow: 2px 2px 4px #930804;\n}") || true) && "_863aef4e"; 3382 3383function timer(_ref) { 3384 var seconds = _ref.seconds; 3385 3386 var minutes = Math.floor(seconds / 60); 3387 var secondsUntilFullMinute = seconds % 60; 3388 3389 return function () { 3390 3391 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3392 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3393 var bel8 = document.createElement("div"); 3394 bel8.setAttribute("class", arguments[4]); 3395 var bel7 = document.createElement("div"); 3396 bel7.setAttribute("class", "timer_inner_container"); 3397 var bel2 = document.createElement("div"); 3398 bel2.setAttribute("class", "timer_side"); 3399 var bel0 = document.createElement("div"); 3400 bel0.setAttribute("class", "timer_digit"); 3401 ac(bel0, [arguments[0]]); 3402 var bel1 = document.createElement("div"); 3403 bel1.setAttribute("class", "timer_digit"); 3404 ac(bel1, [arguments[1]]); 3405 ac(bel2, ["\n ", bel0, "\n ", bel1, "\n "]); 3406 var bel3 = document.createElement("div"); 3407 bel3.setAttribute("class", "timer_divider"); 3408 ac(bel3, [":"]); 3409 var bel6 = document.createElement("div"); 3410 bel6.setAttribute("class", "timer_side"); 3411 var bel4 = document.createElement("div"); 3412 bel4.setAttribute("class", "timer_digit"); 3413 ac(bel4, [arguments[2]]); 3414 var bel5 = document.createElement("div"); 3415 bel5.setAttribute("class", "timer_digit"); 3416 ac(bel5, [arguments[3]]); 3417 ac(bel6, ["\n ", bel4, "\n ", bel5, "\n "]); 3418 ac(bel7, ["\n ", bel2, "\n ", bel3, "\n ", bel6, "\n "]); 3419 ac(bel8, ["\n ", bel7, "\n "]); 3420 return bel8; 3421 }(Math.floor(minutes / 10), minutes % 10, Math.floor(secondsUntilFullMinute / 10), secondsUntilFullMinute % 10, prefix); 3422} 3423 3424module.exports = timer; 3425 3426},{"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"sheetify/insert":227}],39:[function(require,module,exports){ 3427'use strict'; 3428 3429var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); }
3429 else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); 3430 3431var _ = require('lodash'); 3432var html = {}; 3433var sf = 0; 3434 3435var _require = require('@robotopia/choo-game'), 3436 getGameState = _require.getGameState; 3437 3438var _require2 = require('../goal-progress/goal-evaluator'), 3439 checkGoals = _require2.checkGoals; 3440 3441var buttonView = require('../button'); 3442var modalView = require('../modal'); 3443 3444var _require3 = require('../goal-progress'), 3445 goalListView = _require3.goalListView; 3446 3447var prefix = (require('sheetify/insert')("._ff7f8d40 {\n min-width: 700px;\n }\n\n ._ff7f8d40 > .story-text {\n height: 80px;\n background: #dedede;\n position: relative;\n border-radius: 10px;\n padding: 15px;\n margin: 50px;\n }\n \n ._ff7f8d40 > h1 {\n color: #03a9f4;\n }\n \n ._ff7f8d40 > .unlocked {\n width: 100%;\n text-align: center;\n }\n \n ._ff7f8d40 > .unlocked > .unlockedBlock {\n border: 5px solid #DDDDDD;\n border-radius: 20px;\n max-height: 250px;\n }\n \n ._ff7f8d40 > .levelButtons {\n display: flex;\n flex-direction: row;\n justify-content: center;\n }") || true) && "_ff7f8d40"; 3448 3449var winningCondition = function winningCondition(gameState, _ref, workspace, send) { 3450 var level = _ref.level, 3451 isStoryModalOpen = _ref.isStoryModalOpen; 3452 3453 if (level) { 3454 var game = getGameState(gameState); 3455 var story = level.storyModal; 3456 3457 var _$partition = _.partition(level.goals, function (goal) { 3458 return goal.isMandatory; 3459 }), 3460 _$partition2 = _slicedToArray(_$partition, 2), 3461 mandatoryGoals = _$partition2[0], 3462 optionalGoals = _$partition2[1]; 3463 3464 if (checkGoals({ game: game, workspace: workspace }, mandatoryGoals)) { 3465 var winModal = level.winModal; 3466 3467 var repeatLevelButtonHtml = buttonView({ 3468 label: 'Restart Level', 3469 onClick: function onClick() { 3470 send('game:loadGameState', { loadState: level.game }); 3471 } 3472 }); 3473 var nextLevelButtonHtml = getNextLevelButton(send, level); 3474 var unlockedHtml = void 0; 3475 3476 if (winModal.unlockedBlock) { 3477 unlockedHtml = function () { 3478 3479 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3480 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3481 var bel2 = document.createElement("div"); 3482 bel2.setAttribute("class", "unlocked"); 3483 var bel0 = document.createElement("h3"); 3484 ac(bel0, ["You just unlocked the ", arguments[0], "-Block!"]); 3485 var bel1 = document.createElement("img"); 3486 bel1.setAttribute("src", arguments[1]); 3487 bel1.setAttribute("class", "unlockedBlock"); 3488 ac(bel2, ["\n ", bel0, "\n ", bel1, "\n "]); 3489 return bel2; 3490 }(winModal.unlockedBlock.name, winModal.unlockedBlock.img); 3491 } 3492 3493 if (level.onFinish) level.onFinish({ gameState: gameState, workspace: workspace }); 3494 3495 send('tutorial:sendEvent', { type: 'levelWon' }); 3496 3497 return modalView(function () { 3498 3499 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3500 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3501 var bel9 = document.createElement("div"); 3502 bel9.setAttribute("class", arguments[6] + " animated content"); 3503 var bel0 = document.createElement("h1"); 3504 ac(bel0, ["Congratulations, you finished the level!"]); 3505 var bel1 = document.createElement("p"); 3506 ac(bel1, [arguments[0]]); 3507 var bel6 = document.createElement("div"); 3508 bel6.setAttribute("class", "goals"); 3509 var bel3 = document.createElement("div"); 3510 var bel2 = document.createElement("h5"); 3511 ac(bel2, ["Goals: "]); 3512 ac(bel3, ["\n ", bel2, "\n ", arguments[1], "\n "]); 3513 var bel5 = document.createElement("div"); 3514 bel5.setAttribute("style", arguments[2]); 3515 var bel4 = document.createElement("h5"); 3516 ac(bel4, ["Optional: "]); 3517 ac(bel5, ["\n ", bel4, "\n ", arguments[3], "\n "]); 3518 ac(bel6, ["\n ", bel3, "\n ", bel5, "\n "]);
3519 var bel7 = document.createElement("br"); 3520 var bel8 = document.createElement("div"); 3521 bel8.setAttribute("class", "levelButtons"); 3522 ac(bel8, ["\n ", arguments[4], "\n ", arguments[5], "\n "]); 3523 ac(bel9, ["\n ", bel0, "\n ", arguments[7], "\n ", bel1, "\n ", bel6, "\n ", bel7, "\n ", bel8, "\n "]); 3524 return bel9; 3525 }(winModal.text, goalListView({ goals: mandatoryGoals, game: game, workspace: workspace }), optionalGoals.length === 0 ? 'display: none' : '', goalListView({ goals: optionalGoals, game: game, workspace: workspace }), repeatLevelButtonHtml, nextLevelButtonHtml, prefix, unlockedHtml)); 3526 } 3527 3528 if (isStoryModalOpen) { 3529 var startButton = buttonView({ 3530 label: 'Start Tutorial', 3531 onClick: function onClick() { 3532 return send('tutorial:setDisplayStoryModal', { displayStory: false }); 3533 } 3534 }); 3535 3536 return modalView(function () { 3537 3538 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 3539 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 3540 var bel7 = document.createElement("div"); 3541 bel7.setAttribute("class", arguments[5] + " content animated"); 3542 var bel0 = document.createElement("h1"); 3543 ac(bel0, [arguments[0]]); 3544 var bel1 = document.createElement("p"); 3545 bel1.setAttribute("class", "story-text"); 3546 ac(bel1, ["\n ", arguments[1], " \n "]); 3547 var bel6 = document.createElement("div"); 3548 bel6.setAttribute("class", "goals"); 3549 var bel3 = document.createElement("div"); 3550 var bel2 = document.createElement("h5"); 3551 ac(bel2, ["Goals: "]); 3552 ac(bel3, ["\n ", bel2, "\n ", arguments[2], "\n "]); 3553 var bel5 = document.createElement("div"); 3554 bel5.setAttribute("style", arguments[3]); 3555 var bel4 = document.createElement("h5"); 3556 ac(bel4, ["Optional: "]); 3557 ac(bel5, ["\n ", bel4, "\n ", arguments[4], "\n "]); 3558 ac(bel6, ["\n ", bel3, "\n ", bel5, "\n "]); 3559 ac(bel7, ["\n ", bel0, " \n \n ", bel1, "\n \n ", bel6, "\n ", arguments[6], "\n "]); 3560 return bel7; 3561 }(level.label, story.text, goalListView({ goals: mandatoryGoals, game: game, workspace: workspace }), optionalGoals.length === 0 ? 'display: none' : '', goalListView({ goals: optionalGoals, game: game, workspace: workspace }), prefix, startButton)); 3562 } 3563 } 3564}; 3565 3566function getNextLevelButton(send, level) { 3567 return buttonView({ 3568 label: 'Next', 3569 onClick: function onClick() { 3570 return send('tutorial:nextLevel', function (nextLocation) { 3571 send('location:set', nextLocation); 3572 }); 3573 } 3574 }); 3575} 3576 3577module.exports = winningCondition; 3578 3579},{"../button":22,"../goal-progress":31,"../goal-progress/goal-evaluator":30,"../modal":33,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"@robotopia/choo-game":70,"lodash":171,"sheetify/insert":227}],40:[function(require,module,exports){ 3580'use strict'; 3581 3582var P2P_CONFIG = { 3583 hubUrl: 'https://signalhub-jccqtwhdwc.now.sh' 3584 // hubUrl: 'localhost:8080' 3585}; 3586 3587var _ = require('lodash'); 3588var choo = require('choo'); 3589var assets = require('@robotopia/assets-loader'); 3590var clock = require('./models/clock')(); 3591var runtime = require('./models/runtime')(); 3592var gameModel = require('./models/game'); 3593var editorModel = require('./models/editor'); 3594var panelGroupModel = require('./components/panel-group').model; 3595var levelModel = require('./models/tutorial'); 3596var clientModel = require('./models/client')(P2P_CONFIG); 3597var presenterModel = require('./models/presenter')(P2P_CONFIG); 3598var prepfight = require('action-overlay')('prepfight'); 3599 3600var app = choo(); 3601 3602// app models 3603app.model(clock.model); 3604app.model(runtime.model); 3605app.model(gameModel); 3606app.model(editorModel); 3607app.model(levelModel); 3608app.model(clientModel); 3609app.model(presenterModel); 3610app.model(prepfight.model); 3611 3612// component models 3613app.model(panelGroupModel); 3614 3615app.use({ onStateChange: function onStateChange(state) { 3616 return runtime.setState(state.game); 3617 } }); 3618 3619clock.onTick(function (send) { 3620 send('game:beginStep', {}, _.noop); 3621 send('runtime:step', {}, _.noop); 3622 send('game:completeStep', {}, _.noop); 3623 send('tutorial:sendEvent', { type: 'clock', operation: 'tick' }, _.noop); 3624}); 3625 3626app.router({ default: '/' }, [['/', require('./pages/overview')], ['/credits', require('./pages/credits/index')], ['/editor', require('./pages/editor')], ['/tutorial/:category/:level', require('./pages/tutorial')], ['/presenter', require('./pages/presenter')]]); 3627 3628assets.load({ 3629 WATER_TILE: 'assets/img/tiles/water-tile.png', 3630 DIRT_TILE: 'assets/img/tiles/dirt-tile.png', 3631 GRASS_TILE: 'assets/img/tiles/grass-tile.png', 3632 PLAIN_TILE: 'assets/img/tiles/plain-tile.png', 3633 STONE_TILE: 'assets/img/tiles/stone-tile.png', 3634 BLUE_GEM: 'assets/img/resources/gem-blue-splitted.png', 3635 RED_GEM: 'assets/img/resources/gem-red-splitted.png', 3636 GREEN_GEM: 'assets/img/resources/gem-green-splitted.png', 3637 CHEST_FRONT: 'assets/img/chest-front.png', 3638 CHEST_BACK: 'assets/img/chest-back.png', 3639 ROBOT_FRONT_TEAM_1: 'assets/robot/robot1-front-sprite.png', 3640 ROBOT_LEFT_TEAM_1: 'assets/robot/robot1-left-sprite.png', 3641 ROBOT_BACK_TEAM_1: 'assets/robot/robot1-back-sprite.png', 3642 ROBOT_RIGHT_TEAM_1: 'assets/robot/robot1-right-sprite.png', 3643 ROBOT_FRONT_TEAM_2: 'assets/robot/robot2-front-sprite.png', 3644 ROBOT_LEFT_TEAM_2: 'assets/robot/robot2-left-sprite.png', 3645 ROBOT_BACK_TEAM_2: 'assets/robot/robot2-back-sprite.png', 3646 ROBOT_RIGHT_TEAM_2: 'assets/robot/robot2-right-sprite.png', 3647 BASE: 'assets/img/base.png', 3648 TOWER: 'assets/img/tower.png' 3649}).then(function () { 3650 document.body.appendChild(app.start({ hash: true })); 3651}); 3652 3653},{"./components/panel-group":17,"./models/client":43,"./models/clock":45,"./models/editor":46,"./models/game":57,"./models/presenter":60,"./models/runtime":63,"./models/tutorial":65,"./pages/credits/index":257,"./pages/editor":259,"./pages/overview":261,"./pages/presenter":262,"./pages/tutorial":264,"@robotopia/assets-loader":68,"action-overlay":75,"choo":92,"lodash":171}],41:[function(require,module,exports){ 3654'use strict'; 3655 3656var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); }
3656 else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); 3657 3658var _ = require('lodash'); 3659 3660var _require = require('pathfinding'), 3661 AStarFinder = _require.AStarFinder, 3662 Grid = _require.Grid; 3663 3664var _require2 = require('@robotopia/choo-game'), 3665 getAllEntities = _require2.getAllEntities; 3666 3667var finder = new AStarFinder(); 3668 3669function getGrid(game) { 3670 var tiles = game.tiles; 3671 3672 3673 var width = tiles[0].length; 3674 var height = tiles.length; 3675 var grid = new Grid(width, height); 3676 3677 for (var x = 0; x < width; x += 1) { 3678 for (var y = 0; y < height; y += 1) { 3679 if (tiles[y][x] === 1) { 3680 grid.setWalkableAt(x, y, false); 3681 } 3682 } 3683 } 3684 3685 _.forEach(getAllEntities('collides', game), function (_ref) { 3686 var position = _ref.position; 3687 return grid.setWalkableAt(position.x, position.y, false); 3688 }); 3689 3690 return grid; 3691} 3692 3693function getPath(game, startPos, endPos) { 3694 var grid = getGrid(game); 3695 var path = finder.findPath(startPos.x, startPos.y, endPos.x, endPos.y, grid); 3696 3697 return _.map(path, function (_ref2) { 3698 var _ref3 = _slicedToArray(_ref2, 2), 3699 x = _ref3[0], 3700 y = _ref3[1]; 3701 3702 return { x: x, y: y }; 3703 }); 3704} 3705 3706module.exports = { 3707 getPath: getPath 3708}; 3709 3710},{"@robotopia/choo-game":70,"lodash":171,"pathfinding":179}],42:[function(require,module,exports){ 3711'use strict'; 3712 3713module.exports = { 3714 MOVE: { 3715 FORWARD: 0, 3716 LEFT: 1, 3717 BACKWARD: 2, 3718 RIGHT: 3 3719 }, 3720 3721 ORIENTATION: { 3722 BACK: 0, 3723 LEFT: 1, 3724 FRONT: 2, 3725 RIGHT: 3 3726 }, 3727 3728 ROTATE: { 3729 LEFT: -1, 3730 RIGHT: 1 3731 }, 3732 3733 RENDERER: { 3734 SIMPLE: 'SIMPLE', 3735 ROBOT: 'ROBOT' 3736 }, 3737 3738 MARKER_TYPES: { 3739 RED: 'red', 3740 GREEN: 'green', 3741 BLUE: 'blue', 3742 YELLOW: 'yellow' 3743 } 3744}; 3745 3746},{}],43:[function(require,module,exports){ 3747'use strict'; 3748 3749/* globals localStorage */ 3750var _ = require('lodash'); 3751var cuid = require('cuid'); 3752var update = require('immutability-helper'); 3753var p2pClient = require('./p2p-client'); 3754 3755module.exports = function (_ref) { 3756 var hubUrl = _ref.hubUrl; 3757 3758 var client = p2pClient({ 3759 hubUrl: hubUrl, 3760 cid: cuid() 3761 }); 3762 3763 return { 3764 namespace: 'client', 3765 3766 state: getStateFromLocalStorage(), 3767 3768 reducers: { 3769 setUsername: function setUsername(state, _ref2) { 3770 var username = _ref2.username; 3771 3772 state.username = username; 3773 localStorage.setItem('roboSession', JSON.stringify(state)); 3774 return state; 3775 }, 3776 3777 _setGroupId: function _setGroupId(state, _ref3) { 3778 var groupId = _ref3.groupId; 3779 3780 state.groupId = groupId; 3781 localStorage.setItem('roboSession', JSON.stringify(state)); 3782 return state; 3783 }, 3784 3785 _setConnectionStatus: function _setConnectionStatus(state, _ref4) { 3786 var connected = _ref4.connected, 3787 connecting = _ref4.connecting; 3788 return update(state, { 3789 connected: { $set: connected }, 3790 connecting: { $set: connecting } 3791 }); 3792 }, 3793 3794 denyRecovery: function denyRecovery(state) { 3795 localStorage.setItem('roboSession', ''); 3796 state.username = null; 3797 state.groupId = null; 3798 state.clientId = null; 3799 state.connecting = false; 3800 state.recoveryPossible = false; 3801 return state; 3802 }, 3803 3804 _setClientId: function _setClientId(state, _ref5) { 3805 var clientId = _ref5.clientId; 3806 3807 console.log(clientId); 3808 state.clientId = clientId; 3809 localStorage.setItem('roboSession', JSON.stringify(state)); 3810 return state; 3811 } 3812 }, 3813 3814 effects: { 3815 disconnect: function disconnect(state, data, send) { 3816 client.stop(); 3817 send('client:_setGroupId', { groupId: null }, _.noop); 3818 send('client:setUsername', { username: null }, _.noop); 3819 }, 3820 3821 joinGroup: function joinGroup(state, _ref6, send) { 3822 var groupId = _ref6.groupId; 3823 3824 client.joinStar(groupId, state.clientId); 3825 send('client:_setGroupId', { groupId: groupId }, _.noop); 3826 }, 3827 3828 sendCode: function sendCode(state, _ref7) { 3829 var code = _ref7.code; 3830 3831 client.send({ 3832 type: 'COMMIT_CODE', 3833 data: { code: code } 3834 }); 3835 }, 3836 3837 sendUsername: function sendUsername(_ref8) { 3838 var username = _ref8.username; 3839 3840 client.send({ 3841 type: 'SET_USERNAME', 3842 data: { username: username } 3843 }); 3844 } 3845 }, 3846 3847 subscriptions: { 3848 p2pConnection: function p2pConnection(send) { 3849 client.onConnect(function (groupId, clientId) { 3850 send('client:_setConnectionStatus', { connected: true, connecting: false }, _.noop); 3851 send('client:_setClientId', { clientId: clientId }, _.noop); 3852 send('client:sendUsername', {}, _.noop); 3853 }); 3854 3855 client.onDisconnect(function () { 3856 send('client:_setConnectionStatus', { connected: false, connecting: true }, _.noop); 3857 }); 3858 3859 client.onConnecting(function () { 3860 send('client:_setConnectionStatus', { connected: false, connecting: true }, _.noop); 3861 }); 3862 } 3863 } 3864 }; 3865}; 3866 3867function getStateFromLocalStorage() { 3868 var localState = { 3869 username: null, 3870 groupId: null, 3871 clientId: null, 3872 connecting: false, 3873 recoveryPossible: false 3874 }; 3875 try { 3876 var session = JSON.parse(localStorage.getItem('roboSession')); 3877 if (!session || !session.username || !session.groupId || !session.clientId) { 3878 return localState; 3879 } 3880 localState.username = session.username; 3881 localState.groupId = session.groupId; 3882 localState.clientId = session.clientId; 3883 localState.recoveryPossible = true; 3884 } catch (e) { 3885 console.log('Error loading local Storage'); 3886 } 3887 return localState; 3888} 3889 3890},{"./p2p-client":44,"cuid":95,"immutability-helper":164,"lodash":171}],44:[function(require,module,exports){ 3891'use strict'; 3892 3893var _ = require('lodash'); 3894var ps = require('peer-star'); 3895 3896module.exports = function (_ref) { 3897 var hubUrl = _ref.hubUrl; 3898 3899 var star = null; 3900 var presenterPeer = null; 3901 var connectCallback = _.noop; 3902 var disconnectCallback = _.noop; 3903 var onConnectingCallback = _.noop; 3904 3905 function send(data) { 3906 if (presenterPeer === null) { 3907 return; 3908 } 3909 3910 presenterPeer.send(JSON.stringify(data)); 3911 } 3912 3913 function stop(cb) { 3914 if (star === null) { 3915 return; 3916 } 3917 3918 star.close(cb); 3919 star = null; 3920 } 3921 3922 function joinStar(gid, cid) { 3923 if (star !== null) { 3924 return stop(createNew); 3925 } 3926 3927 createNew(); 3928 3929 function createNew() { 3930 star = ps({ 3931 hubURL: hubUrl, 3932 GID: gid, 3933 CID: cid, 3934 isMain: false 3935 }); 3936 3937 onConnectingCallback(); 3938 3939 star.on('peer', function (peer, id) { 3940 if (id === 'MAIN') { 3941 presenterPeer = peer; 3942 connectCallback(gid, star.CID); 3943 } 3944 }); 3945 3946 star.on('disconnect', function (peer, id) { 3947 if (id === 'MAIN') { 3948 disconnectCallback({ gid: gid }); 3949 presenterPeer = peer; 3950 } 3951 }); 3952 } 3953 } 3954 3955 function onConnect(callback) { 3956 connectCallback = callback; 3957 } 3958 3959 function onDisconnect(callback) { 3960 disconnectCallback = callback; 3961 } 3962 3963 function onConnecting(callback) { 3964 onConnectingCallback = callback; 3965 } 3966 3967 return { 3968 send: send, 3969 joinStar: joinStar, 3970 stop: stop, 3971 onConnect: onConnect, 3972 onDisconnect: onDisconnect, 3973 onConnecting: onConnecting 3974 }; 3975}; 3976 3977},{"lodash":171,"peer-star":201}],45:[function(require,module,exports){ 3978'use strict'; 3979 3980var _ = require('lodash'); 3981var update = require('immutability-helper'); 3982var Clock = require('@robotopia/clock'); 3983 3984module.exports = function () { 3985 var tickCallback = _.noop; 3986 var _clock = new Clock(); 3987 3988 var model = { 3989 namespace: 'clock', 3990 3991 state: { 3992 progress: 0, 3993 isRunning: false, 3994 intervalDuration: _clock.intervalDuration 3995 }, 3996 3997 reducers: { 3998 _setProgress: function _setProgress(state, _ref) { 3999 var progress = _ref.progress; 4000 4001 return update(state, { 4002 progress: { $set: progress } 4003 }); 4004 }, 4005 4006 _setIsRunning: function _setIsRunning(state, _ref2) { 4007 var isRunning = _ref2.isRunning; 4008 4009 return update(state, { 4010 isRunning: { $set: isRunning } 4011 }); 4012 }, 4013 4014 _setIntervalDuration: function _setIntervalDuration(state, _ref3) { 4015 var intervalDuration = _ref3.intervalDuration; 4016 4017 return update(state, { 4018 intervalDuration: { $set: intervalDuration } 4019 }); 4020 } 4021 }, 4022 4023 effects: { 4024 start: function start(state, data, send) { 4025 _clock.start(); 4026 send('clock:_setIsRunning', { isRunning: true }, _.noop); 4027 }, 4028 stop: function stop(state, data, send) { 4029 _clock.stop(); 4030 send('clock:_setIsRunning', { isRunning: false }, _.noop); 4031 }, 4032 4033 setIntervalDuration: function setIntervalDuration(state, _ref4, send) { 4034 var intervalDuration = _ref4.intervalDuration; 4035 4036 _clock.setIntervalDuration(intervalDuration); 4037 send('clock:_setIntervalDuration', { intervalDuration: intervalDuration }, _.noop); 4038 } 4039 }, 4040 4041 subscriptions: { 4042 clock: function clock(send) { 4043 _clock.onTick(function () { 4044 send('clock:_setProgress', { progress: 0 }, _.noop); 4045 tickCallback(send); 4046 }); 4047 4048 _clock.onProgress(function (progress) { 4049 return send('clock:_setProgress', { progress: progress }, _.noop); 4050 }); 4051 } 4052 } 4053 }; 4054 4055 return { 4056 model: model, 4057 onTick: function onTick(callback) { 4058 tickCallback = callback; 4059 } 4060 }; 4061}; 4062 4063},{"@robotopia/clock":73,"immutability-helper":164,"lodash":171}],46:[function(require,module,exports){ 4064'use strict'; 4065 4066var _update = require('immutability-helper'); 4067 4068module.exports = { 4069 namespace: 'editor', 4070 4071 state: { 4072 workspace: '', 4073 code: '' 4074 }, 4075 4076 reducers: { 4077 update: function update(state, _ref) { 4078 var workspace = _ref.workspace, 4079 code = _ref.code; 4080 return _update(state, { 4081 workspace: { $set: workspace }, 4082 code: { $set: code } 4083 }); 4084 } 4085 } 4086}; 4087 4088},{"immutability-helper":164}],47:[function(require,module,exports){ 4089'use strict'; 4090 4091var _ = require('lodash'); 4092 4093module.exports = { 4094 collectable: { 4095 requires: ['position'], 4096 4097 reducers: { 4098 _setResourceValue: function _setResourceValue(state, _ref) { 4099 var value = _ref.value; 4100 4101 return { 4102 collectable: { value: { $set: value } } 4103 }; 4104 } 4105 }, 4106 4107 effects: { 4108 decreaseResource: function decreaseResource(state, _ref2, game, send) { 4109 var amount = _ref2.amount; 4110 4111 var resource = getNearResource(state.position, game.entities); 4112 4113 if (resource && resource.collectable.value > amount) { 4114 send('game:collectable._setResourceValue', { 4115 target: resource.id, 4116 data: { value: resource.collectable.value - amount } 4117 }, _.noop); 4118 } 4119 4120 if (resource && resource.collectable.value === amount) { 4121 send('game:deleteEntity', { 4122 data: { id: resource.id } 4123 }, _.noop); 4124 } 4125 } 4126 } 4127 } 4128}; 4129 4130function getNearResource(position, entitites) { 4131 var resources = _.filter(entitites, 'collectable'); 4132 4133 return _.find(resources, function (resource) { 4134 var distance = Math.abs(resource.position.x - position.x) + Math.abs(resource.position.y - position.y); 4135 return distance <= 1; 4136 }); 4137} 4138 4139},{"lodash":171}],48:[function(require,module,exports){ 4140'use strict'; 4141 4142var _ = require('lodash'); 4143 4144module.exports = { 4145 collector: { 4146 requires: ['position'], 4147 4148 reducers: { 4149 _setHasResource: function _setHasResource(state, _ref) { 4150 var hasResource = _ref.hasResource, 4151 chunk = _ref.chunk; 4152 4153 return { 4154 collector: { hasResource: { $set: hasResource }, chunk: { $set: chunk } } 4155 }; 4156 } 4157 }, 4158 4159 effects: { 4160 collectResource: function collectResource(state, data, game, send) { 4161 var hasResource = state.collector.hasResource; 4162 var nearResource = getNearResource(state, game); 4163 4164 if (!hasResource && nearResource) { 4165 var resourceChunk = nearResource.collectable.chunks; 4166 4167 send('game:collector._setHasResource', { 4168 target: state.id, 4169 data: { hasResource: true, chunk: resourceChunk } 4170 }, _.noop); 4171 send('game:collectable.decreaseResource', { 4172 target: state.id, 4173 data: { amount: resourceChunk } 4174 }, _.noop); 4175 } 4176 }, 4177 4178 depositResource: function depositResource(state, data, game, send) { 4179 var hasResource = state.collector.hasResource; 4180 var resourceChunk = state.collector.chunk; 4181 4182 if (hasResource && isOnBase(state, game)) { 4183 send('game:addResources', { teamId: state.team.id, amount: resourceChunk }, _.noop); 4184 send('game:collector._setHasResource', { 4185 target: state.id, 4186 data: { hasResource: false, chunk: resourceChunk } 4187 }, _.noop); 4188 } 4189 } 4190 } 4191 } 4192}; 4193 4194function getNearResource(_ref2, _ref3) { 4195 var position = _ref2.position; 4196 var entities = _ref3.entities; 4197 4198 var resources = _.filter(entities, 'collectable'); 4199 4200 return _.find(resources, function (resource) { 4201 var distance = Math.abs(resource.position.x - position.x) + Math.abs(resource.position.y - position.y); 4202 return distance <= 1; 4203 }); 4204} 4205 4206function isOnBase(_ref4, _ref5) { 4207 var position = _ref4.position, 4208 team = _ref4.team; 4209 var entities = _ref5.entities; 4210 4211 var teamBase = _(entities).filter('robotSpawner').find({ team: { id: team.id } }); 4212 4213 return teamBase.position.x === position.x && teamBase.position.y === position.y; 4214} 4215 4216},{"lodash":171}],49:[function(require,module,exports){ 4217'use strict'; 4218 4219function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 4220 4221var _ = require('lodash'); 4222 4223var _require = require('@robotopia/choo-game'), 4224 getAllEntities = _require.getAllEntities; 4225 4226module.exports = { 4227 discoverable: { 4228 4229 reducers: { 4230 markAsDiscoveredByTeam: function markAsDiscoveredByTeam(state, _ref) { 4231 var teamId = _ref.teamId; 4232 4233 return { 4234 discoverable: { discovererTeamIds: _defineProperty({}, teamId, { $set: true }) } 4235 }; 4236 } 4237 }, 4238 4239 effects: { 4240 update: function update(state, data, game, send) { 4241 var discoverers = getNewDiscoverersInRange(game, state); 4242 4243 _.forEach(discoverers, function (discoverer) { 4244 send('game:discoverable.markAsDiscoveredByTeam', { 4245 target: state.id, 4246 data: { 4247 teamId: discoverer.team.id 4248 } 4249 }, _.noop); 4250 4251 send('runtime:triggerEvent', { 4252 type: 'discover ' + state.discoverable.type, 4253 target: { id: discoverer.id }, 4254 args: [state] 4255 }, _.noop); 4256 }); 4257 } 4258 } 4259 } 4260 4261 // returns list of discoverers which are in range and whose teams hasn't discovered the discoverable yet 4262 // only one representative for each team is returned if multiple discoverer 'see' discoverable at the same time 4263};function getNewDiscoverersInRange(game, _ref2) { 4264 var position = _ref2.position, 4265 discoverable = _ref2.discoverable, 4266 team = _ref2.team; 4267 4268 var discoverers = getAllEntities('discoverer', game); 4269 4270 return _(discoverers).filter(function (entity) { 4271 // exclude any entitys of teams which have already discovered this 4272 if (discoverable.discovererTeamIds[entity.team.id]) { 4273 return false;
4274 } 4275 4276 // exclude any entitys of the same team as the discoverable 4277 if (team && team.id === entity.team.id) { 4278 return false; 4279 } 4280 4281 var distance = Math.sqrt(Math.pow(position.x - entity.position.x, 2) + Math.pow(position.y - entity.position.y, 2)); 4282 return entity.discoverer.range >= distance; 4283 }).uniqBy(function (_ref3) { 4284 var team = _ref3.team; 4285 return team.id; 4286 }).value(); 4287} 4288 4289},{"@robotopia/choo-game":70,"lodash":171}],50:[function(require,module,exports){ 4290'use strict'; 4291 4292var _ = require('lodash'); 4293 4294module.exports = { 4295 health: { 4296 requires: [], 4297 4298 reducers: { 4299 heal: function heal(state, _ref) { 4300 var amount = _ref.amount; 4301 4302 var newHealth = Math.min(state.health.max, state.health.current + amount); 4303 4304 return { 4305 health: { current: { $set: newHealth } } 4306 }; 4307 }, 4308 4309 _set: function _set(state, _ref2) { 4310 var health = _ref2.health; 4311 4312 return { 4313 health: { current: { $set: health } } 4314 }; 4315 } 4316 }, 4317 4318 effects: { 4319 damage: function damage(state, _ref3, game, send) { 4320 var amount = _ref3.amount; 4321 4322 var newHealth = state.health.current - amount; 4323 4324 if (newHealth > 0) { 4325 send('game:health._set', { 4326 target: state.id, 4327 data: { 4328 health: newHealth 4329 } 4330 }, _.noop); 4331 return; 4332 } 4333 4334 send('game:deleteEntity', { 4335 data: { id: state.id } 4336 }, _.noop); 4337 4338 // TODO: move this somewhere else 4339 send('runtime:destroyRobot', { 4340 id: state.id 4341 }, _.noop); 4342 } 4343 } 4344 } 4345}; 4346 4347},{"lodash":171}],51:[function(require,module,exports){ 4348'use strict'; 4349 4350var _ = require('lodash'); 4351 4352var _require = require('../../../lib/utils/types'), 4353 MOVE = _require.MOVE; 4354 4355var _require2 = require('@robotopia/choo-game'), 4356 isFieldEmpty = _require2.isFieldEmpty; 4357 4358module.exports = { 4359 movable: { 4360 requires: ['position'], 4361 4362 reducers: { 4363 move: function move(state, _ref, game) { 4364 var direction = _ref.direction; 4365 var position = state.position; 4366 var tiles = game.tiles; 4367 4368 var mapWidth = tiles[0].length; 4369 var mapHeight = tiles.length; 4370 var nextX = position.x; 4371 var nextY = position.y; 4372 var rotatedDirection = applyRotation(direction, position.rotation); 4373 4374 switch (rotatedDirection) { 4375 case MOVE.BACKWARD: 4376 nextY = position.y + 1; 4377 break; 4378 case MOVE.FORWARD: 4379 nextY = position.y - 1; 4380 break; 4381 case MOVE.LEFT: 4382 nextX = position.x - 1; 4383 break; 4384 case MOVE.RIGHT: 4385 nextX = position.x + 1; 4386 break; 4387 } 4388 4389 if (!isFieldEmpty(game, nextX, nextY)) { 4390 return {}; 4391 } 4392 4393 return { 4394 position: { 4395 x: { $set: _.clamp(nextX, 0, mapWidth - 1) }, 4396 y: { $set: _.clamp(nextY, 0, mapHeight - 1) } 4397 } 4398 }; 4399 }, 4400 4401 rotate: function rotate(state, _ref2) { 4402 var direction = _ref2.direction; 4403 var position = state.position; 4404 4405 var orientation = mod(position.rotation - direction, 4); 4406 4407 return { 4408 position: { 4409 rotation: { $set: orientation } 4410 } 4411 }; 4412 }, 4413 setRotation: function setRotation(state, _ref3) { 4414 var direction = _ref3.direction; 4415 4416 if (direction === undefined) { 4417 throw new Error('undefined rotation'); 4418 } 4419 4420 return { 4421 position: { 4422 rotation: { $set: direction } 4423 } 4424 }; 4425 } 4426 } 4427 } 4428}; 4429 4430function applyRotation(direction, rotation) { 4431 return mod(direction + rotation, 4); 4432} 4433 4434function mod(x, n) { 4435 return (x % n + n) % n; 4436} 4437 4438},{"../../../lib/utils/types":42,"@robotopia/choo-game":70,"lodash":171}],52:[function(require,module,exports){ 4439'use strict'; 4440 4441var _ = require('lodash'); 4442 4443var _require = require('@robotopia/choo-game'), 4444 getAllEntities = _require.getAllEntities; 4445 4446module.exports = { 4447 shooter: { 4448 requires: ['team'], 4449 4450 reducers: { 4451 _setTarget: function _setTarget(state, _ref) { 4452 var targetId = _ref.targetId; 4453 4454 return { 4455 shooter: { targetId: { $set: targetId } } 4456 }; 4457 } 4458 }, 4459 4460 effects: { 4461 update: function update(state, data, game, send) { 4462 var target = getWeakestEnemyInRange(game, state); 4463 var targetId = null; 4464 4465 if (target !== undefined) { 4466 targetId = target.id; 4467 4468 send('game:health.damage', { 4469 target: targetId, 4470 data: { amount: state.shooter.damage } 4471 }, _.noop); 4472 } 4473 4474 send('game:shooter._setTarget', { 4475 target: state.id, 4476 data: { targetId: targetId } 4477 }, _.noop); 4478 } 4479 } 4480 } 4481}; 4482 4483function getWeakestEnemyInRange(game, _ref2) { 4484 var shooter = _ref2.shooter, 4485 team = _ref2.team, 4486 position = _ref2.position; 4487 4488 var entities = getAllEntities('health', game); 4489 4490 return _(entities).filter(function (entity) { 4491 if (entity.team.id === team.id) { 4492 return false;
4493 } 4494 4495 var distance = Math.sqrt(Math.pow(entity.position.x - position.x, 2) + Math.pow(entity.position.y - position.y, 2)); 4496 return distance < shooter.range; 4497 }).sortBy(['health']).first(); 4498} 4499 4500},{"@robotopia/choo-game":70,"lodash":171}],53:[function(require,module,exports){ 4501'use strict'; 4502 4503var _ = require('lodash'); 4504var uid = require('uid'); 4505var entities = require('../entities'); 4506 4507var _require = require('@robotopia/choo-game'), 4508 isFieldEmpty = _require.isFieldEmpty, 4509 hasEnoughResources = _require.hasEnoughResources; 4510 4511var markerSpawner = { 4512 requires: ['position', 'team'], 4513 4514 effects: { 4515 spawn: function spawn(state, _ref, game, send) { 4516 var type = _ref.type, 4517 requiredWorkers = _ref.requiredWorkers; 4518 var position = state.position, 4519 team = state.team; 4520 4521 var marker = entities.marker({ 4522 x: position.x, 4523 y: position.y, 4524 teamId: team.id, 4525 taskType: type, 4526 requiredWorkers: requiredWorkers 4527 }); 4528 4529 send('game:createEntity', { data: marker }, _.noop); 4530 } 4531 } 4532}; 4533 4534var towerSpawner = { 4535 requires: ['position', 'team'], 4536 4537 effects: { 4538 spawn: function spawn(_ref2, data, game, send) { 4539 var position = _ref2.position, 4540 team = _ref2.team; 4541 4542 var x = position.x; 4543 var y = position.y; 4544 4545 if (isFieldEmpty(game, x, y)) { 4546 var tower = entities.tower({ x: x, y: y, teamId: team.id }); 4547 4548 // TODO: remove ! / insert real cost of tower 4549 if (!hasEnoughResources(game, team.id, 10)) { 4550 send('game:createEntity', { data: tower }, _.noop); 4551 send('game:addPoints', { teamId: team.id, amount: 100 }, _.noop); 4552 send('game:removeResources', { teamId: team.id, amount: 100 }, _.noop); 4553 } 4554 4555 // TODO: check that tower is not near base, this is checked in the buildTowerNearPosition 4556 // but could be circumvented by calling spawn direclty with custom Javascript code 4557 } 4558 } 4559 } 4560}; 4561 4562var robotSpawner = { 4563 requires: ['position', 'team'], 4564 4565 reducers: { 4566 _setStepsSinceLastSpawn: function _setStepsSinceLastSpawn(state, _ref3) { 4567 var steps = _ref3.steps; 4568 return { 4569 robotSpawner: { 4570 stepsSinceLastSpawn: { $set: steps } 4571 } 4572 }; 4573 }, 4574 4575 _incSpawnedRobots: function _incSpawnedRobots(_ref4) { 4576 var robotSpawner = _ref4.robotSpawner; 4577 return { 4578 robotSpawner: { 4579 spawnedRobots: { $set: robotSpawner.spawnedRobots + 1 } 4580 } 4581 }; 4582 } 4583 }, 4584 4585 effects: { 4586 update: function update(_ref5, data, game, send) { 4587 var id = _ref5.id, 4588 robotSpawner = _ref5.robotSpawner, 4589 position = _ref5.position, 4590 team = _ref5.team; 4591 var stepsSinceLastSpawn = robotSpawner.stepsSinceLastSpawn, 4592 maxRobots = robotSpawner.maxRobots, 4593 spawnedRobots = robotSpawner.spawnedRobots; 4594 4595 4596 if (spawnedRobots === maxRobots) { 4597 return; 4598 } 4599 4600 // spawn entity on interval 4601 if (stepsSinceLastSpawn % robotSpawner.interval === 0) { 4602 var robotId = uid(); 4603 var robot = entities.robot({ id: robotId, x: position.x, y: position.y, teamId: team.id }); 4604 4605 send('game:robotSpawner._incSpawnedRobots', { 4606 target: id, 4607 data: {} 4608 }, _.noop); 4609 send('runtime:createRobot', { id: robotId, groupId: team.id }, _.noop); 4610 send('game:createEntity', { data: robot }, _.noop); 4611 } 4612 4613 // increment stepsSinceLastSpawn 4614 send('game:robotSpawner._setStepsSinceLastSpawn', { 4615 target: id, 4616 data: { steps: stepsSinceLastSpawn + 1 } 4617 }, _.noop); 4618 } 4619 } 4620}; 4621 4622module.exports = { 4623 markerSpawner: markerSpawner, 4624 towerSpawner: towerSpawner, 4625 robotSpawner: robotSpawner 4626}; 4627 4628},{"../entities":56,"@robotopia/choo-game":70,"lodash":171,"uid":241}],54:[function(require,module,exports){ 4629'use strict'; 4630 4631var _ = require('lodash'); 4632 4633var _require = require('@robotopia/choo-game'), 4634 getAllEntities = _require.getAllEntities; 4635 4636var task = { 4637 requires: ['team'], 4638 4639 reducers: { 4640 setWorkerCompleted: function setWorkerCompleted(_ref) { 4641 var task = _ref.task; 4642 return { 4643 task: { completedWorkers: { $set: task.completedWorkers + 1 } } 4644 }; 4645 }, 4646 4647 _setAssignedWorkers: function _setAssignedWorkers(state, _ref2) { 4648 var assignedWorkers = _ref2.assignedWorkers; 4649 return { 4650 task: { assignedWorkers: { $set: assignedWorkers } } 4651 }; 4652 } 4653 }, 4654 4655 effects: { 4656 update: function update(state, data, game, send) { 4657 var id = state.id, 4658 task = state.task, 4659 team = state.team; 4660 4661 4662 if (task.completedWorkers === task.requiredWorkers) { 4663 send('game:deleteEntity', { data: { id: state.id } }, _.noop); 4664 } 4665 4666 if (task.requiredWorkers === task.assignedWorkers) { 4667 return; 4668 } 4669 4670 // get all workers required by the marker or less if there are not enough unassigned workers available 4671 var assignableWorkers = getUnassignedWorkers(team.id, game).slice(0, task.requiredWorkers - task.assignedWorkers); 4672 4673 // update number of assigned workers 4674 send('game:task._setAssignedWorkers', { 4675 target: id, 4676 data: { assignedWorkers: task.assignedWorkers + assignableWorkers.length } 4677 }, _.noop); 4678 4679 // assign each worker to marker 4680 _.forEach(assignableWorkers, function (_ref3) { 4681 var id = _ref3.id; 4682 4683 send('game:worker.assignToTask', { 4684 target: id, 4685 data: { taskEntity: state } 4686 }, _.noop); 4687 }); 4688 } 4689 } 4690}; 4691 4692function getUnassignedWorkers(teamId, game) { 4693 var workers = getAllEntities('worker', game); 4694 4695 return _.filter(workers, function (_ref4) { 4696 var team = _ref4.team, 4697 worker = _ref4.worker; 4698 return team.id === teamId && worker.assignedTask === null; 4699 }); 4700} 4701 4702var worker = { 4703 requires: ['team'], 4704 4705 reducers: { 4706 _assignTask: function _assignTask(state, _ref5) { 4707 var task = _ref5.task; 4708 return { 4709 worker: { 4710 assignedTask: { $set: task } 4711 } 4712 }; 4713 } 4714 }, 4715 4716 effects: { 4717 assignToTask: function assignToTask(_ref6, _ref7, game, send) { 4718 var id = _ref6.id; 4719 var taskEntity = _ref7.taskEntity; 4720 var task = taskEntity.task; 4721 4722 4723 send('runtime:switchMode', { 4724 type: task.type, 4725 target: { id: id }, 4726 args: [taskEntity] 4727 }, _.noop); 4728 4729 send('game:worker._assignTask', { 4730 target: id, 4731 data: { task: { id: taskEntity.id, type: taskEntity.task.type } } 4732 }, _.noop); 4733 }, 4734 4735 completeTask: function completeTask(_ref8, data, game, send) { 4736 var id = _ref8.id, 4737 worker = _ref8.worker; 4738 4739 send('game:task.setWorkerCompleted', { 4740 target: worker.assignedTask.id, 4741 data: {} 4742 }, _.noop); 4743 4744 send('game:worker._assignTask', { 4745 target: id, 4746 data: { task: null } 4747 }, _.noop); 4748 } 4749 } 4750}; 4751 4752module.exports = { task: task, worker: worker }; 4753 4754},{"@robotopia/choo-game":70,"lodash":171}],55:[function(require,module,exports){ 4755'use strict'; 4756 4757var _ = require('lodash'); 4758var entites = require('./entities'); 4759 4760var MAX_TRIES = 100; 4761 4762function initializeResourceSpots(state, _ref, send) { 4763 var numberOfSpots = _ref.numberOfSpots, 4764 value = _ref.value, 4765 chunks = _ref.chunks, 4766 color = _ref.color, 4767 _ref$requiredDistance = _ref.requiredDistance, 4768 requiredDistance = _ref$requiredDistance === undefined ? 0 : _ref$requiredDistance;
4769 var tiles = state.tiles; 4770 4771 var mapHeight = tiles.length; 4772 var mapWidth = tiles[0].length; 4773 4774 var resourceSpots = []; 4775 4776 for (var i = 0; i < numberOfSpots; i++) { 4777 var x = void 0, 4778 y = void 0, 4779 tries = 0; 4780 4781 // search for empty random dirt spot 4782 do { 4783 tries += 1; 4784 x = _.random(0, mapWidth - 1); 4785 y = _.random(0, mapHeight - 1); 4786 } while ((tiles[y][x] !== 2 || getMinDistance(x, y, resourceSpots) < requiredDistance) && tries < MAX_TRIES); 4787 4788 if (tries < MAX_TRIES) { 4789 resourceSpots.push({ x: x, y: y }); 4790 } else { 4791 i = 0; 4792 resourceSpots = []; 4793 } 4794 } 4795 4796 _.forEach(resourceSpots, function (_ref2) { 4797 var x = _ref2.x, 4798 y = _ref2.y; 4799 4800 send('game:createEntity', { data: entites.gem({ x: x, y: y, value: value, chunks: chunks, color: color }) }, _.noop); 4801 }); 4802} 4803 4804function getMinDistance(x, y, resourcePlaces) { 4805 return _.reduce(resourcePlaces, function (minDistance, resource) { 4806 var currentDistance = Math.sqrt(Math.pow(resource.x - x, 2) + Math.pow(resource.y - y, 2)); 4807 4808 if (currentDistance < minDistance) { 4809 return currentDistance; 4810 } 4811 4812 return minDistance; 4813 }, Infinity); 4814} 4815 4816module.exports = { 4817 initializeResourceSpots: initializeResourceSpots 4818}; 4819 4820},{"./entities":56,"lodash":171}],56:[function(require,module,exports){ 4821'use strict'; 4822 4823module.exports = { 4824 robot: function robot(_ref) { 4825 var id = _ref.id, 4826 x = _ref.x, 4827 y = _ref.y, 4828 teamId = _ref.teamId; 4829 return { 4830 id: id, 4831 health: { 4832 current: 5, 4833 max: 5 4834 }, 4835 team: { id: teamId }, 4836 position: { x: x, y: y, rotation: 2 }, 4837 movable: {}, 4838 discoverer: { range: 2 }, 4839 markerSpawner: {}, 4840 towerSpawner: {}, 4841 collector: { hasResource: false, chunk: 0 }, 4842 worker: { assignedTask: null }, 4843 zIndex: 1, 4844 sprite: { 4845 type: 'ROBOT', 4846 data: {}, 4847 team: teamId === 2 ? 2 : 1 4848 }, 4849 showRange: 0 4850 }; 4851 }, 4852 4853 tutorialRobot: function tutorialRobot(_ref2) { 4854 var id = _ref2.id, 4855 x = _ref2.x, 4856 y = _ref2.y, 4857 teamId = _ref2.teamId, 4858 orientation = _ref2.orientation, 4859 resource = _ref2.resource, 4860 discoverRange = _ref2.discoverRange, 4861 teamSprite = _ref2.teamSprite, 4862 showRange = _ref2.showRange; 4863 return { 4864 id: id, 4865 team: { id: teamId }, 4866 position: { x: x, y: y, rotation: orientation }, 4867 movable: {}, 4868 discoverer: { range: discoverRange | 3 }, 4869 markerSpawner: {}, 4870 towerSpawner: {}, 4871 collector: resource, 4872 worker: { assignedTask: null }, 4873 zIndex: 5, 4874 sprite: { 4875 type: 'ROBOT', 4876 data: {}, 4877 team: teamSprite === 2 ? 2 : 1 4878 }, 4879 showRange: showRange 4880 }; 4881 }, 4882 4883 gem: function gem(_ref3) { 4884 var x = _ref3.x, 4885 y = _ref3.y, 4886 value = _ref3.value, 4887 chunks = _ref3.chunks, 4888 color = _ref3.color; 4889 return { 4890 position: { x: x, y: y }, 4891 item: { type: 'gem' }, 4892 discoverable: { 4893 type: 'resource', 4894 discovererTeamIds: {} 4895 }, 4896 collides: {}, 4897 collectable: { 4898 chunks: chunks, 4899 value: value, 4900 maxValue: value 4901 }, 4902 zIndex: 1, 4903 sprite: { 4904 type: 'SIMPLE', 4905 data: { 4906 sprite: color + '_GEM' 4907 } 4908 } 4909 }; 4910 }, 4911 4912 chest: function chest(_ref4) { 4913 var x = _ref4.x, 4914 y = _ref4.y, 4915 orientation = _ref4.orientation; 4916 return { 4917 position: { x: x, y: y }, 4918 zIndex: 1, 4919 sprite: { 4920 type: 'SIMPLE', 4921 data: { 4922 sprite: 'CHEST_' + orientation 4923 } 4924 } 4925 }; 4926 }, 4927 4928 base: function base(_ref5) { 4929 var x = _ref5.x, 4930 y = _ref5.y, 4931 id = _ref5.id, 4932 teamId = _ref5.teamId; 4933 return { 4934 id: id, 4935 team: { id: teamId }, 4936 position: { x: x, y: y }, 4937 robotSpawner: { 4938 spawnedRobots: 0, 4939 maxRobots: 15, 4940 stepsSinceLastSpawn: 0, 4941 interval: 5 4942 }, 4943 zIndex: 1, 4944 sprite: { 4945 type: 'SIMPLE', 4946 data: { 4947 sprite: 'BASE' 4948 } 4949 } 4950 }; 4951 }, 4952 4953 tutorialBase: function tutorialBase(_ref6) { 4954 var x = _ref6.x, 4955 y = _ref6.y, 4956 id = _ref6.id, 4957 teamId = _ref6.teamId; 4958 return { 4959 id: id, 4960 team: { id: teamId }, 4961 position: { x: x, y: y }, 4962 robotSpawner: {}, 4963 zIndex: 1, 4964 sprite: { 4965 type: 'SIMPLE', 4966 data: { 4967 sprite: 'BASE' 4968 } 4969 } 4970 }; 4971 }, 4972 4973 tower: function tower(_ref7) { 4974 var id = _ref7.id, 4975 x = _ref7.x, 4976 y = _ref7.y, 4977 teamId = _ref7.teamId; 4978 return { 4979 id: id, 4980 team: { id: teamId }, 4981 shooter: { 4982 range: 2, 4983 damage: 1 4984 }, 4985 discoverable: { discovererTeamIds: {} },
4986 position: { x: x, y: y }, 4987 collides: {}, 4988 zIndex: 1, 4989 sprite: { 4990 type: 'SIMPLE', 4991 data: { 4992 sprite: 'TOWER' 4993 } 4994 } 4995 }; 4996 }, 4997 4998 marker: function marker(_ref8) { 4999 var x = _ref8.x, 5000 y = _ref8.y, 5001 teamId = _ref8.teamId, 5002 requiredWorkers = _ref8.requiredWorkers, 5003 taskType = _ref8.taskType; 5004 return { 5005 position: { x: x, y: y }, 5006 team: { id: teamId }, 5007 zIndex: 0, 5008 task: { 5009 type: taskType, 5010 requiredWorkers: requiredWorkers, 5011 assignedWorkers: 0, 5012 completedWorkers: 0 5013 } 5014 }; 5015 } 5016}; 5017 5018},{}],57:[function(require,module,exports){ 5019'use strict'; 5020 5021var game = require('@robotopia/choo-game'); 5022 5023var _require = require('./components/movable'), 5024 movable = _require.movable; 5025 5026var _require2 = require('./components/health'), 5027 health = _require2.health; 5028 5029var _require3 = require('./components/collector'), 5030 collector = _require3.collector; 5031 5032var _require4 = require('./components/collectable'), 5033 collectable = _require4.collectable; 5034 5035var _require5 = require('./components/spawner'), 5036 markerSpawner = _require5.markerSpawner, 5037 towerSpawner = _require5.towerSpawner, 5038 robotSpawner = _require5.robotSpawner; 5039 5040var _require6 = require('./components/shooter'), 5041 shooter = _require6.shooter; 5042 5043var _require7 = require('./components/discoverable'), 5044 discoverable = _require7.discoverable; 5045 5046var _require8 = require('./components/work'), 5047 worker = _require8.worker, 5048 task = _require8.task; 5049 5050var reducers = require('./reducers'); 5051var effects = require('./effects'); 5052 5053module.exports = game.model({ 5054 state: { 5055 tiles: [[]], 5056 entities: [], 5057 teams: {} 5058 }, 5059 components: { 5060 movable: movable, 5061 health: health, 5062 collector: collector, 5063 collectable: collectable, 5064 markerSpawner: markerSpawner, 5065 towerSpawner: towerSpawner, 5066 robotSpawner: robotSpawner, 5067 shooter: shooter, 5068 discoverable: discoverable, 5069 worker: worker, 5070 task: task 5071 }, 5072 effects: effects, 5073 reducers: reducers 5074}); 5075 5076},{"./components/collectable":47,"./components/collector":48,"./components/discoverable":49,"./components/health":50,"./components/movable":51,"./components/shooter":52,"./components/spawner":53,"./components/work":54,"./effects":55,"./reducers":58,"@robotopia/choo-game":70}],58:[function(require,module,exports){ 5077"use strict"; 5078 5079function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 5080 5081function addResources(_ref, _ref2) { 5082 var teams = _ref.teams; 5083 var teamId = _ref2.teamId, 5084 amount = _ref2.amount; 5085 5086 return { 5087 teams: _defineProperty({}, teamId, { resources: { $set: teams[teamId].resources + amount } }) 5088 }; 5089} 5090 5091function removeResources(_ref3, _ref4) { 5092 var teams = _ref3.teams; 5093 var teamId = _ref4.teamId, 5094 amount = _ref4.amount; 5095 5096 return { 5097 teams: _defineProperty({}, teamId, { resources: { $set: teams[teamId].resources + amount } }) 5098 }; 5099} 5100 5101function addPoints(_ref5, _ref6) { 5102 var teams = _ref5.teams; 5103 var teamId = _ref6.teamId, 5104 amount = _ref6.amount; 5105 5106 return { 5107 teams: _defineProperty({}, teamId, { points: { $set: teams[teamId].points + amount } }) 5108 }; 5109} 5110 5111module.exports = { 5112 addResources: addResources, 5113 removeResources: removeResources, 5114 addPoints: addPoints 5115}; 5116 5117},{}],59:[function(require,module,exports){ 5118'use strict'; 5119 5120var _ = require('lodash'); 5121var initialState = require('../../pages/presenter/initial-state'); 5122var testCode = 'robot.onEvent(\'discover resource\', function (resource) {\n robot.moveTo((resource.position.x), (resource.position.y))\n robot.placeMarker(\'green\', 2)\n\n})\n\nrobot.onMode(\'green\', function (marker) {\n robot.moveTo((marker.position.x), (marker.position.y))\n robot.collectResource()\n robot.moveTo((robot.getBasePosition().x), (robot.getBasePosition().y))\n robot.depositResource()\n\n})\n\nif (1 < getRandomNumber(1, 4)) {\n robot.rotate("LEFT")\n if (1 < getRandomNumber(1, 3)) {\n robot.rotate("LEFT")\n if (1 < getRandomNumber(1, 2)) {\n robot.rotate("LEFT")\n }\n }\n}\nwhile (true) {\n robot.move("FORWARD")\n if (10 == getRandomNumber(1, 8)) {\n robot.rotate("LEFT")\n }\n}\n'; 5123 5124module.exports = function (_ref) { 5125 var presenter = _ref.presenter, 5126 timer = _ref.timer; 5127 5128 return { 5129 disconnect: disconnect, 5130 joinGroup: joinGroup, 5131 startMatch: startMatch, 5132 stopMatch: stopMatch, 5133 _testMode: _testMode, 5134 handleMessage: handleMessage, 5135 pickPlayers: pickPlayers 5136 }; 5137 5138 function disconnect(state, data, send) { 5139 presenter.stop(); 5140 send('presenter:_setGroupId', { groupId: null }, _.noop); 5141 } 5142 5143 function joinGroup(state, _ref2, send) { 5144 var groupId = _ref2.groupId; 5145 5146 presenter.joinStar(groupId); 5147 send('presenter:_setGroupId', { groupId: groupId }, _.noop); 5148 } 5149 5150 function startMatch(_ref3, data, send, done) { 5151 var clients = _ref3.clients, 5152 playerNumbers = _ref3.playerNumbers, 5153 time = _ref3.time; 5154 5155 var playerKeys = Object.keys(playerNumbers); 5156 var showPreFight = playerKeys.length === 2 && playerKeys.indexOf('1') !== -1 && playerKeys.indexOf('2') !== -1; 5157 5158 for (var p in playerNumbers) {
5159 send('runtime:commitCode', { code: clients[playerNumbers[p]].code, groupId: p }, _.noop); 5160 } 5161 5162 send('presenter:_setPickingPlayers', { displayPlayerPickScreen: false }, _.noop); 5163 5164 if (showPreFight) { 5165 send('prepfight:setLeft', { name: clients[playerNumbers[1]].username }, _.noop); 5166 send('prepfight:setRight', { name: clients[playerNumbers[2]].username }, _.noop); 5167 send('prepfight:start', null, _.noop); 5168 } 5169 5170 send('runtime:reset', { loadState: initialState.game }, _.noop); 5171 send('game:loadGameState', { loadState: initialState.game }, _.noop); 5172 send('game:initializeResourceSpots', { numberOfSpots: 12, value: 100, chunks: 20, color: 'BLUE', requiredDistance: 5 }, _.noop); 5173 5174 setTimeout(function () { 5175 send('clock:start', null, _.noop); 5176 timer.onTick(updateTime(time, send)); 5177 timer.start(); 5178 }, showPreFight ? 4000 : 0); 5179 } 5180 5181 function stopMatch(state, data, send) { 5182 send('clock:stop', null, _.noop); 5183 timer.stop(); 5184 } 5185 5186 function _testMode(state, data, send) { 5187 send('presenter:addClient', { id: 1 }, _.noop); 5188 send('presenter:setUsername', { id: 1, username: 'Rick' }, _.noop); 5189 send('presenter:commitCode', { id: 1, code: testCode }, _.noop); 5190 send('presenter:addClient', { id: 2 }, _.noop); 5191 send('presenter:setUsername', { id: 2, username: 'Morty' }, _.noop); 5192 send('presenter:commitCode', { id: 2, code: testCode }, _.noop); 5193 } 5194 5195 function handleMessage(_ref4, _ref5, send) { 5196 var clients = _ref4.clients; 5197 var id = _ref5.id, 5198 message = _ref5.message; 5199 5200 if (!clients[id]) { 5201 return; 5202 } 5203 5204 switch (message.type) { 5205 case 'SET_USERNAME': 5206 var username = message.data.username; 5207 send('presenter:setUsername', { id: id, username: username }, _.noop); 5208 return; 5209 5210 case 'COMMIT_CODE': 5211 var code = message.data.code; 5212 send('presenter:commitCode', { id: id, code: code }, _.noop); 5213 return; 5214 5215 default: 5216 return; 5217 } 5218 } 5219 5220 function pickPlayers(state, _ref6, send) { 5221 var playerCount = _ref6.playerCount, 5222 selectionMode = _ref6.selectionMode; 5223 5224 if (!playerCount) { 5225 return send('presenter:_setPickingPlayers', { displayPlayerPickScreen: false }, _.noop); 5226 } 5227 var players = {}; 5228 if (selectionMode === 'random') { 5229 var clientIds = Object.keys(state.clients); 5230 if (clientIds.length >= playerCount) { 5231 for (var i = 1; i <= playerCount; i++) { 5232 var nextIndex = Math.random() * clientIds.length; 5233 var nextPlayer = clientIds.splice(nextIndex, 1); 5234 players[i] = nextPlayer[0]; 5235 } 5236 } 5237 send('presenter:setPlayers', players, _.noop); 5238 send('presenter:startMatch', null, _.noop); 5239 return; 5240 } 5241 send('presenter:_setPickingPlayers', { displayPlayerPickScreen: true, playerCount: playerCount }, _.noop); 5242 } 5243}; 5244 5245function updateTime(timeRemaining, send) { 5246 return function () { 5247 timeRemaining -= 1; 5248 if (timeRemaining === 0) { 5249 send('presenter:stopMatch', null, _.noop); 5250 send('presenter:showWinDialog', true, _.noop); 5251 } 5252 send('presenter:setTime', timeRemaining, _.noop); 5253 }; 5254} 5255 5256},{"../../pages/presenter/initial-state":263,"lodash":171}],60:[function(require,module,exports){ 5257'use strict'; 5258 5259var _ = require('lodash'); 5260var effects = require('./effects'); 5261var reducers = require('./reducers'); 5262var p2pPresenter = require('./p2p-presenter'); 5263var Clock = require('@robotopia/clock'); 5264 5265module.exports = function (_ref) { 5266 var hubUrl = _ref.hubUrl; 5267 5268 var presenter = p2pPresenter({ 5269 hubUrl: hubUrl 5270 }); 5271 5272 var timer = new Clock(1000); 5273 5274 return { 5275 namespace: 'presenter', 5276 5277 state: { 5278 groupId: null, 5279 clients: {}, // clients [{ id, code, username }] mapped to their id 5280 playerNumbers: {}, // maps playerNumbers to Client. eg.: 1->eflajsnf1248dsnf 5281 displayPlayerPickScreen: false, 5282 displayWinDialog: false, 5283 playerCount: 0, 5284 time: 0 5285 }, 5286 5287 reducers: reducers, 5288 5289 effects: effects({ presenter: presenter, timer: timer }), 5290 5291 subscriptions: { 5292 p2pConnection: function p2pConnection(send) { 5293 presenter.onAddClient(function (_ref2) { 5294 var id = _ref2.id; 5295 return send('presenter:addClient', { id: id }, _.noop); 5296 }); 5297 presenter.onRemoveClient(function (_ref3) { 5298 var id = _ref3.id; 5299 return send('presenter:removeClient', { id: id }, _.noop); 5300 }); 5301 presenter.onMessage(function (id, _ref4) { 5302 var type = _ref4.type, 5303 data = _ref4.data; 5304 return send('presenter:handleMessage', { id: id, message: { type: type, data: data } }, _.noop); 5305 }); 5306 } 5307 } 5308 }; 5309}; 5310 5311},{"./effects":59,"./p2p-presenter":61,"./reducers":62,"@robotopia/clock":73,"lodash":171}],61:[function(require,module,exports){ 5312'use strict'; 5313 5314var _ = require('lodash'); 5315var ps = require('peer-star'); 5316 5317module.exports = function (_ref) { 5318 var hubUrl = _ref.hubUrl; 5319 5320 var star = null; 5321 var addClientCallback = _.noop; 5322 var removeClientCallback = _.noop; 5323 var messageCallback = _.noop; 5324 5325 function joinStar(gid) { 5326 if (star !== null) { 5327 stop(); 5328 } 5329 5330 star = ps({ 5331 hubURL: hubUrl, 5332 GID: gid, 5333 isMain: true 5334 }); 5335 5336 star.on('peer', function (peer, id) { 5337 addListenersToPeer(peer, id); 5338 addClientCallback({ id: id }); 5339 }); 5340 5341 star.on('disconnect', function (peer, id) { 5342 peer.destroy(); 5343 removeClientCallback({ id: id }); 5344 }); 5345 } 5346 5347 function addListenersToPeer(peer, id) { 5348 peer.on('data', function (message) { 5349 var decodedMessage = void 0;
5350 try { 5351 decodedMessage = JSON.parse(message); 5352 } catch (err) { 5353 return; 5354 } 5355 5356 var _decodedMessage = decodedMessage, 5357 type = _decodedMessage.type, 5358 data = _decodedMessage.data; 5359 5360 5361 if (!type) { 5362 // ignore messages with type as invalid 5363 return; 5364 } 5365 5366 messageCallback(id, { type: type, data: data }); 5367 }); 5368 } 5369 5370 function stop() { 5371 if (star === null) { 5372 return; 5373 } 5374 5375 star.close(); 5376 star = null; 5377 } 5378 5379 // send message to all connected peers 5380 function broadcast(_ref2) { 5381 var type = _ref2.type, 5382 data = _ref2.data; 5383 5384 if (star === null) { 5385 return; 5386 } 5387 5388 var message = { type: type, data: data }; 5389 _.forEach(star.peers, function (peer) { 5390 return peer.send(JSON.stringify(message)); 5391 }); 5392 } 5393 5394 // send message to one specific connected peer 5395 function sendTo(recipientId, _ref3) { 5396 var type = _ref3.type, 5397 data = _ref3.data; 5398 5399 var recipient = star.contacts[recipientId]; 5400 5401 // do nothing if recipient is not connected 5402 if (!recipient || star.peers.indexOf(recipient) === -1) { 5403 return; 5404 } 5405 5406 recipient.send(JSON.stringify({ type: type, data: data })); 5407 } 5408 5409 return { 5410 joinStar: joinStar, 5411 stop: stop, 5412 broadcast: broadcast, 5413 sendTo: sendTo, 5414 onAddClient: function onAddClient(callback) { 5415 addClientCallback = callback; 5416 }, 5417 onRemoveClient: function onRemoveClient(callback) { 5418 removeClientCallback = callback; 5419 }, 5420 onMessage: function onMessage(callback) { 5421 messageCallback = callback; 5422 } 5423 }; 5424}; 5425 5426},{"lodash":171,"peer-star":201}],62:[function(require,module,exports){ 5427'use strict'; 5428 5429function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 5430 5431var _ = require('lodash'); 5432var update = require('immutability-helper'); 5433 5434function addClient(state, _ref) { 5435 var id = _ref.id; 5436 5437 var client = { 5438 id: id, 5439 username: 'unknown', 5440 code: null 5441 }; 5442 5443 return update(state, { 5444 clients: _defineProperty({}, id, { $set: client }) 5445 }); 5446} 5447 5448function removeClient(state, _ref2) { 5449 var id = _ref2.id; 5450 5451 return update(state, { 5452 clients: { $set: _.omit(state.clients, [id]) } 5453 }); 5454} 5455 5456function setUsername(state, _ref3) { 5457 var id = _ref3.id, 5458 username = _ref3.username; 5459 5460 return update(state, { 5461 clients: _defineProperty({}, id, { 5462 username: { $set: username } 5463 }) 5464 }); 5465} 5466 5467function commitCode(state, _ref4) { 5468 var id = _ref4.id, 5469 code = _ref4.code; 5470 5471 return update(state, { 5472 clients: _defineProperty({}, id, { 5473 code: { $set: code } 5474 }) 5475 }); 5476} 5477 5478function setPlayers(state, players) { 5479 return update(state, { 5480 playerNumbers: { $set: players } 5481 }); 5482} 5483 5484function _setGroupId(state, _ref5) { 5485 var groupId = _ref5.groupId; 5486 5487 return update(state, { 5488 groupId: { $set: groupId }, 5489 clients: { $set: {} } 5490 }); 5491} 5492 5493function setTime(state, newTime) { 5494 return update(state, { 5495 time: { $set: newTime } 5496 }); 5497} 5498 5499function showWinDialog(state, show) { 5500 return update(state, { 5501 displayWinDialog: { $set: show } 5502 }); 5503} 5504 5505function _setPickingPlayers(state, _ref6) { 5506 var displayPlayerPickScreen = _ref6.displayPlayerPickScreen, 5507 playerCount = _ref6.playerCount; 5508 5509 state = update(state, { 5510 displayPlayerPickScreen: { $set: displayPlayerPickScreen } 5511 }); 5512 if (!_.isNil(playerCount)) { 5513 update(state, { 5514 playerCount: { $set: playerCount } 5515 }); 5516 } 5517 return state; 5518} 5519 5520module.exports = { 5521 addClient: addClient, 5522 removeClient: removeClient, 5523 setUsername: setUsername, 5524 commitCode: commitCode, 5525 setPlayers: setPlayers, 5526 _setGroupId: _setGroupId, 5527 setTime: setTime, 5528 showWinDialog: showWinDialog, 5529 _setPickingPlayers: _setPickingPlayers 5530}; 5531 5532},{"immutability-helper":164,"lodash":171}],63:[function(require,module,exports){ 5533'use strict'; 5534 5535function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 5536 5537var _ = require('lodash'); 5538var update = require('immutability-helper'); 5539var Runtime = require('@robotopia/agent-runtime'); 5540var api = require('./robot-api'); 5541 5542module.exports = function () { 5543 var _runtime = new Runtime(); 5544 5545 var model = { 5546 namespace: 'runtime', 5547 5548 state: { 5549 code: {} 5550 }, 5551 5552 reducers: { 5553 commitCode: function commitCode(state, _ref) { 5554 var code = _ref.code, 5555 groupId = _ref.groupId; 5556 return update(state, { 5557 code: _defineProperty({}, groupId, { $set: code }) 5558 }); 5559 } 5560 }, 5561 5562 effects: { 5563 createRobot: function createRobot(_ref2, _ref3) { 5564 var code = _ref2.code; 5565 var id = _ref3.id, 5566 groupId = _ref3.groupId, 5567 overwriteCode = _ref3.overwriteCode; 5568
5569 var useCode = !_.isNil(overwriteCode) ? overwriteCode : code[groupId]; 5570 _runtime.createAgent({ 5571 id: id, 5572 api: api, 5573 code: useCode, 5574 groupId: groupId }); 5575 }, 5576 5577 destroyRobot: function destroyRobot(state, _ref4) { 5578 var id = _ref4.id; 5579 5580 _runtime.destroyAgent(id); 5581 }, 5582 5583 triggerEvent: function triggerEvent(state, _ref5) { 5584 var type = _ref5.type, 5585 args = _ref5.args, 5586 target = _ref5.target; 5587 5588 _runtime.triggerEvent(type, args, target); 5589 }, 5590 5591 switchMode: function switchMode(state, _ref6) { 5592 var type = _ref6.type, 5593 args = _ref6.args, 5594 target = _ref6.target; 5595 5596 _runtime.switchMode(type, args, target); 5597 }, 5598 5599 step: function step() { 5600 _runtime.step(); 5601 }, 5602 5603 reset: function reset() { 5604 _runtime.reset(); 5605 } 5606 }, 5607 5608 subscriptions: { 5609 runtime: function runtime(send) { 5610 _runtime.onAction(function (id, name, data) { 5611 return send(name, { target: id, data: data }, _.noop); 5612 }); 5613 _runtime.onCompleteMode(function (id) { 5614 return send('game:worker.completeTask', { target: id, data: {} }, _.noop); 5615 }); 5616 } 5617 } 5618 }; 5619 5620 return { 5621 model: model, 5622 setState: function setState(state) { 5623 return _runtime.setState(state); 5624 } 5625 }; 5626}; 5627 5628},{"./robot-api":64,"@robotopia/agent-runtime":67,"immutability-helper":164,"lodash":171}],64:[function(require,module,exports){ 5629'use strict'; 5630 5631var _ = require('lodash'); 5632 5633var _require = require('../../lib/utils/types'), 5634 MOVE = _require.MOVE, 5635 ROTATE = _require.ROTATE, 5636 ORIENTATION = _require.ORIENTATION; 5637 5638var pathfinder = require('./../../lib/pathfinder'); 5639 5640var _require2 = require('@robotopia/choo-game'), 5641 getGameState = _require2.getGameState, 5642 getEntity = _require2.getEntity, 5643 getAllEntities = _require2.getAllEntities, 5644 _isFieldEmpty = _require2.isFieldEmpty, 5645 findFieldNearPosition = _require2.findFieldNearPosition, 5646 _findEmptyFieldNearPosition = _require2.findEmptyFieldNearPosition; 5647 5648var SAVE_ZONE_SIZE = 4; // how far enemy towers have to build from base 5649 5650module.exports = { 5651 namespace: 'robot', 5652 globals: { 5653 getRandomNumber: function getRandomNumber(min, max) { 5654 return Math.floor(Math.random() * (max - min + 1) + min); 5655 } 5656 }, 5657 actionsPerRound: 1, 5658 actions: { 5659 move: function move(direction) { 5660 return { 5661 action: ['game:movable.move', { direction: MOVE[direction] }], 5662 cost: 1 5663 }; 5664 }, 5665 5666 rotate: function rotate(direction) { 5667 return { 5668 action: ['game:movable.rotate', { direction: ROTATE[direction] }], 5669 cost: 0 5670 }; 5671 }, 5672 5673 setRotation: function setRotation(direction) { 5674 return { 5675 action: ['game:movable.setRotation', { direction: ORIENTATION[direction] }], 5676 cost: 0 5677 }; 5678 }, 5679 5680 placeMarker: function placeMarker(type, requiredWorkers) { 5681 return { 5682 action: ['game:markerSpawner.spawn', { type: type, requiredWorkers: requiredWorkers }], 5683 cost: 1 5684 }; 5685 }, 5686 5687 buildTower: function buildTower() { 5688 return { 5689 action: ['game:towerSpawner.spawn'], 5690 cost: 1 5691 }; 5692 }, 5693 5694 collectResource: function collectResource() { 5695 return { 5696 action: ['game:collector.collectResource'], 5697 cost: 1 5698 }; 5699 }, 5700 5701 depositResource: function depositResource() { 5702 return { 5703 action: ['game:collector.depositResource'], 5704 cost: 1 5705 }; 5706 } 5707 }, 5708 5709 // Be careful here, the methods are converted to strings and interpreted by esper 5710 // that's because we need to execute them step by step 5711 // inside the scope of the methods only the specified actions and sensors are available 5712 // es6 is also not fully supported by esper.js yet. Don't use things like: let, const or arrow functions 5713 // 5714 // Examples: 5715 // robot.rotate(1) 5716 // robot.getPosition() 5717 5718 methods: { 5719 moveTo: function moveTo(x, y) { 5720 var comparePosition, i, path, nextPosition; 5721 var currentPosition = this.getPosition(); 5722 5723 var target = this.findEmptyFieldNearPosition(x, y); 5724 5725 if (target === null) { 5726 return; 5727 } 5728 5729 // repeat trying to find a path until target is reached 5730 while (currentPosition.x !== target.x || currentPosition.y !== target.y) { 5731 5732 // recalculate target if it is no longer empty 5733 if (!this.isFieldEmpty(target.x, target.y)) { 5734 target = this.findEmptyFieldNearPosition(x, y); 5735 break; 5736 } 5737 5738 // calculate route 5739 path = this.getPathTo(target.x, target.y); 5740 5741 // traverse route 5742 for (i = 1; i < path.length; i++) { 5743 // check if method has been interrupted by mode change or event in this case break and recalculate route 5744 comparePosition = this.getPosition(); 5745 if (currentPosition.x !== comparePosition.x || currentPosition.y !== comparePosition.y) { 5746 currentPosition = comparePosition; 5747 break; 5748 } 5749 5750 nextPosition = path[i]; 5751 5752 // recalculate route if next position isn't empty 5753 if (!this.isFieldEmpty(nextPosition.x, nextPosition.y)) { 5754 break; 5755 } 5756 5757 if (currentPosition.y < nextPosition.y) { 5758 this.setRotation('FRONT'); 5759 } else if (currentPosition.y > nextPosition.y) { 5760 this.setRotation('BACK'); 5761 } else if (currentPosition.x < nextPosition.x) { 5762 this.setRotation('RIGHT'); 5763 } else { 5764 this.setRotation('LEFT'); 5765 } 5766 5767 this.move('FORWARD'); 5768 5769 currentPosition = nextPosition; 5770 } 5771 } 5772 }, 5773 5774 isNextTile: function isNextTile(tileType) { 5775 var position = this.getPosition(); 5776 var x = position.x; 5777 var y = position.y; 5778 5779 var tiles = this.getGameTiles(); 5780 5781 var xAdd = 0; 5782 var yAdd = 0; 5783 5784 switch (position.rotation) { 5785 case 0: 5786 yAdd = -1; 5787 break; 5788 case 3: 5789 xAdd = 1; 5790 break; 5791 case 2: 5792 yAdd = 1; 5793 break; 5794 case 1:
5795 xAdd = -1; 5796 break; 5797 } 5798 5799 return tiles[y + yAdd][x + xAdd] === tileType; 5800 }, 5801 5802 buildTowerNearPosition: function buildTowerNearPosition() { 5803 // don't use arrow shorthand here because it messes with toString 5804 var botPosition = this.getPosition(); 5805 var towerPosition = this.findFieldForTowerNearPosition(botPosition.x, botPosition.y); 5806 5807 this.moveTo(towerPosition.x, towerPosition.y); 5808 this.buildTower(); 5809 }, 5810 5811 onMode: function onMode(name, handler) { 5812 if (this.__modeHandlers === undefined) { 5813 this.__modeHandlers = {}; 5814 } 5815 5816 this.__modeHandlers[name] = handler; 5817 }, 5818 5819 onEvent: function onEvent(name, handler) { 5820 if (this.__eventHandlers === undefined) { 5821 this.__eventHandlers = {}; 5822 } 5823 5824 this.__eventHandlers[name] = handler; 5825 } 5826 }, 5827 5828 sensors: { 5829 getGameTiles: function getGameTiles(state, id) { 5830 return getGameState(state).tiles; 5831 }, 5832 5833 getPosition: function getPosition(state, id) { 5834 var game = getGameState(state); 5835 var entity = getEntity(id, game); 5836 5837 return entity.position; 5838 }, 5839 5840 isFieldEmpty: function isFieldEmpty(state, id, x, y) { 5841 var game = getGameState(state); 5842 5843 return _isFieldEmpty(game, x, y); 5844 }, 5845 5846 findFieldForTowerNearPosition: function findFieldForTowerNearPosition(state, id, x, y) { 5847 var game = getGameState(state); 5848 var bot = getEntity(id, game); 5849 var bases = getEnemyBases(game, bot); 5850 5851 // find a field which is empty and not inside the save zone of another base 5852 return findFieldNearPosition(game, x, y, function (game, x, y) { 5853 if (!_isFieldEmpty(game, x, y)) { 5854 return false; 5855 } 5856 5857 return _.every(bases, function (_ref) { 5858 var position = _ref.position; 5859 5860 var distance = Math.sqrt(Math.pow(position.x - x, 2) + Math.pow(position.y - y, 2)); 5861 return distance > SAVE_ZONE_SIZE; 5862 }); 5863 }); 5864 }, 5865 5866 findEmptyFieldNearPosition: function findEmptyFieldNearPosition(state, id, x, y) { 5867 var game = getGameState(state); 5868 5869 return _findEmptyFieldNearPosition(game, x, y); 5870 }, 5871 5872 getPathTo: function getPathTo(state, id, x, y) { 5873 var game = getGameState(state); 5874 var entity = getEntity(id, game); 5875 5876 return pathfinder.getPath(game, entity.position, { x: x, y: y }); 5877 }, 5878 5879 getBasePosition: function getBasePosition(state, id, x, y) { 5880 var game = getGameState(state); 5881 var entity = getEntity(id, game); 5882 5883 return getBaseOfTeam(game, entity.team.id).position; 5884 }, 5885 5886 getCollectedResources: function getCollectedResources(state, id, x, y) { 5887 var game = getGameState(state); 5888 var entity = getEntity(id, game); 5889 5890 return game.teams[entity.team.id].resources; 5891 } 5892 } 5893}; 5894 5895function getBaseOfTeam(game, teamId) { 5896 var bases = getAllEntities('robotSpawner', game); 5897 5898 return _.find(bases, function (_ref2) { 5899 var team = _ref2.team; 5900 return team.id === teamId; 5901 }); 5902} 5903 5904function getEnemyBases(game, entity) { 5905 var bases = getAllEntities('robotSpawner', game); 5906 5907 return _.filter(bases, function (_ref3) { 5908 var team = _ref3.team; 5909 return team.id !== entity.team.id; 5910 }); 5911} 5912 5913},{"../../lib/utils/types":42,"./../../lib/pathfinder":41,"@robotopia/choo-game":70,"lodash":171}],65:[function(require,module,exports){ 5914'use strict'; 5915 5916var _ = require('lodash'); 5917var update = require('immutability-helper'); 5918var levels = require('../assets/tutorial'); 5919 5920var willStopOnNextTick = false; 5921var currentLevel = void 0; 5922 5923module.exports = { 5924 namespace: 'tutorial', 5925 5926 state: { 5927 level: null, 5928 isStoryModalOpen: true, 5929 events: {} 5930 }, 5931 5932 reducers: { 5933 _setLevel: function _setLevel(state, _ref) { 5934 var level = _ref.level; 5935 5936 return update(state, { 5937 level: { $set: level }, 5938 isStoryModalOpen: { $set: true } 5939 }); 5940 }, 5941 5942 setDisplayStoryModal: function setDisplayStoryModal(state, _ref2) { 5943 var open = _ref2.open; 5944 5945 return update(state, { 5946 isStoryModalOpen: { $set: open } 5947 }); 5948 }, 5949 5950 _updateEvents: function _updateEvents(state, events) { 5951 return update(state, { 5952 events: { $set: events } 5953 }); 5954 } 5955 }, 5956 5957 effects: { 5958 loadLevel: function loadLevel(state, _ref3, send) { 5959 var category = _ref3.category, 5960 index = _ref3.index; 5961
5962 var level = getLevelIfExistent(category, index); 5963 5964 if (level !== undefined) { 5965 currentLevel = { category: category, index: parseInt(index) }; 5966 send('tutorial:resetEvents', null, _.noop); 5967 send('tutorial:_setLevel', { level: level }, _.noop); 5968 send('game:loadGameState', { loadState: level.game }, _.noop); 5969 send('editor:update', { workspace: level.editor.workspace }, _.noop); 5970 } 5971 }, 5972 5973 nextLevel: function nextLevel(state, cb, send) { 5974 if (!currentLevel || !currentLevel.hasOwnProperty('category') || !currentLevel.hasOwnProperty('index')) { 5975 return; 5976 } 5977 var prevIndex = currentLevel.index; 5978 var prevCategory = currentLevel.category; 5979 var level = getLevelIfExistent(prevCategory, prevIndex + 1); 5980 if (level) { 5981 // send('tutorial:loadLevel', { category: prevCategory, index: prevIndex }, _.noop) 5982 console.log('loading next level of same category'); 5983 return cb('#tutorial/' + prevCategory + '/' + (prevIndex + 1)); 5984 } 5985 var oldCategoryIndex = _.findIndex(levels, { 'categoryName': currentLevel.category }); 5986 if (oldCategoryIndex === -1 || oldCategoryIndex + 1 === levels.length) { 5987 // was last category or unknown 5988 return cb('#editor'); 5989 } 5990 var nextCategory = levels[oldCategoryIndex + 1]; 5991 if (!nextCategory || !nextCategory.hasOwnProperty('categoryName')) { 5992 // jumps to tutorial overview 5993 return cb(''); 5994 } 5995 console.log('loading next level of next category'); 5996 // send('tutorial:loadLevel', { category: nextCategory.categoryName, index: 1 }, _.noop) 5997 return cb('#tutorial/' + nextCategory.categoryName + '/1'); 5998 }, 5999 6000 resetEvents: function resetEvents(state, data, send) { 6001 willStopOnNextTick = false; 6002 send('tutorial:_updateEvents', {}, _.noop); 6003 }, 6004 6005 sendEvent: function sendEvent(state, event, send) { 6006 var type = event.type; 6007 if (!type) { 6008 return state; 6009 } 6010 if (type === 'clock') { 6011 return send('tutorial:_updateEvents', handleClockEvent(state.events, event, send), _.noop); 6012 } 6013 if (type === 'levelWon') { 6014 willStopOnNextTick = true; 6015 return; 6016 } 6017 } 6018 } 6019}; 6020 6021function handleClockEvent(events, event, send) { 6022 if (!event.hasOwnProperty('operation')) { 6023 return events; 6024 } 6025 if (event.operation === 'tick') { 6026 if (willStopOnNextTick) { 6027 send('clock:stop', null, _.noop); 6028 willStopOnNextTick = false; 6029 } 6030 return update(events, { 6031 time: { $set: events.time + 1 } 6032 }); 6033 } 6034 if (event.operation === 'set' && event.hasOwnProperty('value') && !isNaN(event.value)) { 6035 return update(events, { 6036 time: { $set: event.value } 6037 }); 6038 } 6039} 6040 6041function getLevelIfExistent(category, index) { 6042 var _index = void 0; 6043 try { 6044 // subtract 1 from index to work 1 based externally and 0 based internally. 6045 _index = parseInt(index) - 1; 6046 } catch (e) { 6047 console.log('please specify the index as a number (min: 1)'); 6048 return; 6049 } 6050 if (!category || isNaN(_index)) { 6051 return; 6052 } 6053 var _category = _.find(levels, { 'categoryName': category }); 6054 if (!_category || !_category.hasOwnProperty('levels') || _category.levels.length <= _index) { 6055 return; 6056 } 6057 var level = _category.levels[_index]; 6058 if (level) { 6059 return level(); 6060 } 6061} 6062 6063},{"../assets/tutorial":16,"immutability-helper":164,"lodash":171}],66:[function(require,module,exports){ 6064'use strict'; 6065 6066var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); 6067 6068var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 6069 6070function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 6071 6072var _ = require('lodash'); 6073var esper = require('esper.js'); 6074 6075// an agent represents a entity inside an simulation which can be scripted at runtime with javascript 6076 6077var Agent = function () { 6078 function Agent(_ref) { 6079 var id = _ref.id, 6080 groupId = _ref.groupId, 6081 api = _ref.api, 6082 code = _ref.code, 6083 getState = _ref.getState, 6084 onAction = _ref.onAction, 6085 onCompleteMode = _ref.onCompleteMode; 6086 6087 _classCallCheck(this, Agent); 6088 6089 this.id = id; 6090 this.groupId = groupId; 6091 6092 // assign methods
6093 this.getState = getState; 6094 this.onActionCallback = onAction; 6095 this.onCompleteModeCallback = onCompleteMode; 6096 6097 this.initAgent(code, api); 6098 } 6099 6100 _createClass(Agent, [{ 6101 key: 'initAgent', 6102 value: function initAgent(code, api) { 6103 this.terminatedMain = false; 6104 6105 this.mainModeEngine = this.modeEngine = this.currentEngine = new esper.Engine(); 6106 this.availableActions = this.actionsPerRound = api.actionsPerRound; 6107 6108 this.addAPI(api); 6109 6110 this.mainModeEngine.load(code); 6111 } 6112 }, { 6113 key: 'addAPI', 6114 value: function addAPI(_ref2) { 6115 var _this = this; 6116 6117 var namespace = _ref2.namespace, 6118 methods = _ref2.methods, 6119 globals = _ref2.globals, 6120 actions = _ref2.actions, 6121 sensors = _ref2.sensors; 6122 6123 this.namespace = namespace; 6124 6125 _.forEach(globals, function (global, name) { 6126 _this.mainModeEngine.addGlobal(name, global); 6127 }); 6128 6129 this.mainModeEngine.addGlobal(namespace, this.getAPIObject({ actions: actions, sensors: sensors })); 6130 6131 this.registerMethods({ namespace: namespace, methods: methods }); 6132 } 6133 6134 // turns action definitions in functions which can be called by the Robot code 6135 6136 }, { 6137 key: 'getAPIObject', 6138 value: function getAPIObject(_ref3) { 6139 var actions = _ref3.actions, 6140 sensors = _ref3.sensors; 6141 6142 return _.merge({}, this.getAPIActions(actions), this.getAPISensors(sensors)); 6143 } 6144 }, { 6145 key: 'getAPIActions', 6146 value: function getAPIActions(actions) { 6147 var _this2 = this; 6148 6149 return _.reduce(actions, function (api, method, name) { 6150 api[name] = function () { 6151 for (var _len = arguments.length, params = Array(_len), _key = 0; _key < _len; _key++) { 6152 params[_key] = arguments[_key]; 6153 } 6154 6155 var _method$apply = method.apply(null, params), 6156 action = _method$apply.action, 6157 cost = _method$apply.cost; 6158 6159 var _action = _slicedToArray(action, 2), 6160 name = _action[0], 6161 data = _action[1]; 6162 6163 _this2.onActionCallback(_this2.id, name, data); 6164 6165 _this2.availableActions -= cost; 6166 }; 6167 return api; 6168 }, {}); 6169 } 6170 }, { 6171 key: 'getAPISensors', 6172 value: function getAPISensors(sensors) { 6173 var _this3 = this; 6174 6175 return _.reduce(sensors, function (api, method, name) { 6176 api[name] = function () { 6177 for (var _len2 = arguments.length, params = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { 6178 params[_key2] = arguments[_key2]; 6179 } 6180 6181 var state = _this3.getState(); 6182 return method.apply(null, [state, _this3.id].concat(params)); 6183 }; 6184 6185 return api; 6186 }, {}); 6187 } 6188 }, { 6189 key: 'registerMethods', 6190 value: function registerMethods(_ref4) { 6191 var namespace = _ref4.namespace, 6192 methods = _ref4.methods; 6193 6194 var script = _.reduce(methods, function (script, method, name) { 6195 return script + (namespace + '.' + name + '=' + method.toString() + '\n'); 6196 }, ''); 6197 6198 this.mainModeEngine.load(script); 6199 this.mainModeEngine.runSync(); 6200 } 6201 6202 // trigger event will interrupt the current executed mode handler and switch to the event handler 6203 // afterwards the execution of the handler will be continued at the position where it was interupted 6204 // if the agent already handles an event the new event will be ignored 6205 6206 }, { 6207 key: 'triggerEvent', 6208 value: function triggerEvent(name, args) { 6209 if (this.handlesEvent()) { 6210 return; 6211 } 6212 6213 var engine = this.createHandlerEngine({ type: 'event', name: name, args: args }); 6214 6215 // ignore if there is no handler defined in the code of the agent 6216 if (engine === null) { 6217 return; 6218 } 6219 6220 this.currentEngine = engine; 6221 } 6222 6223 // switch engine to execute other mode handler. Modes are intended to switch between different behaviours during the simulation 6224 // The execution of a mode handler can be interrupted by events. Once a mode handler is terminated the agent continues executing 6225 6226 }, { 6227 key: 'switchMode', 6228 value: function switchMode(name, args) { 6229 var engine = this.createHandlerEngine({ type: 'mode', name: name, args: args }); 6230 6231 // ignore if there is no handler defined in the code of the agent 6232 if (engine === null) { 6233 return; 6234 } 6235 6236 this.currentEngine = this.modeEngine = engine; 6237 } 6238 }, { 6239 key: 'createHandlerEngine', 6240 value: function createHandlerEngine(_ref5) { 6241 var type = _ref5.type, 6242 name = _ref5.name, 6243 args = _ref5.args; 6244 6245 if (!this.hasHandler({ type: type, name: name })) { 6246 return null; 6247 } 6248 6249 // create separate engine which shares all the state with the main engine 6250 // the code of the engine just calls the event handler 6251 var engine = this.mainModeEngine.fork(); 6252 6253 var source = this.namespace + '.__' + type + 'Handlers[\'' + n
6253ame + '\'].apply(' + this.namespace + ', ' + JSON.stringify(args) + ')'; 6254 6255 // load code which calls the event handler 6256 engine.load(source); 6257 6258 return engine; 6259 } 6260 }, { 6261 key: 'hasHandler', 6262 value: function hasHandler(_ref6) { 6263 var type = _ref6.type, 6264 name = _ref6.name; 6265 6266 var namespaceScope = this.currentEngine.globalScope.get(this.namespace); 6267 // this doesn't contain a regular object because we are dealing with esper.js interals here, you can just use this to test if handlers exist 6268 var handlerObject = namespaceScope.get('__' + type + 'Handlers').next().value.properties; 6269 6270 return handlerObject !== undefined && handlerObject[name] !== undefined; 6271 } 6272 }, { 6273 key: 'step', 6274 value: function step() { 6275 if (this.isInMainMode() && this.terminatedMain) { 6276 return; 6277 } 6278 6279 this.availableActions = this.actionsPerRound; 6280 var terminated = false; 6281 6282 // step until all available actions have been spent 6283 do { 6284 terminated = this.currentEngine.step(); 6285 } while (!terminated && this.availableActions > 0); 6286 6287 // only need to switch engine if current engine terminated 6288 if (terminated) { 6289 if (this.handlesEvent()) { 6290 // switch back to previous mode if event handler terminated 6291 this.currentEngine = this.modeEngine; 6292 6293 // continue execution if event handler hasn't spend all available actions 6294 if (this.availableActions > 0) { 6295 this.step(); 6296 } 6297 6298 return; 6299 } 6300 6301 if (!this.isInMainMode()) { 6302 // switch back to main if terminated other mode 6303 this.onCompleteModeCallback(this.id); 6304 this.currentEngine = this.mainModeEngine; 6305 this.modeEngine = this.mainModeEngine; 6306 return; 6307 } 6308 6309 // otherwise main mode has terminated 6310 this.terminatedMain = true; 6311 } 6312 } 6313 }, { 6314 key: 'handlesEvent', 6315 value: function handlesEvent() { 6316 return this.currentEngine !== this.modeEngine; 6317 } 6318 }, { 6319 key: 'isInMainMode', 6320 value: function isInMainMode() { 6321 return this.currentEngine === this.mainModeEngine; 6322 } 6323 }]); 6324 6325 return Agent; 6326}(); 6327 6328module.exports = Agent; 6329},{"esper.js":112,"lodash":171}],67:[function(require,module,exports){ 6330'use strict'; 6331 6332var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 6333 6334function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 6335 6336var _ = require('lodash'); 6337var Agent = require('./agent'); 6338 6339var Runtime = function () { 6340 function Runtime() { 6341 _classCallCheck(this, Runtime); 6342 6343 this.agents = {}; 6344 this._onActionCallback = _.noop; 6345 this._onCompleteModeCallback = _.noop; 6346 } 6347 6348 _createClass(Runtime, [{ 6349 key: 'onAction', 6350 value: function onAction(callback) { 6351 this._onActionCallback = callback; 6352 } 6353 }, { 6354 key: 'onCompleteMode', 6355 value: function onCompleteMode(callback) { 6356 this._onCompleteModeCallback = callback; 6357 } 6358 }, { 6359 key: 'setState', 6360 value: function setState(state) { 6361 this.state = state; 6362 } 6363 }, { 6364 key: 'createAgent', 6365 value: function createAgent(_ref) { 6366 var _this = this; 6367 6368 var id = _ref.id, 6369 groupId = _ref.groupId, 6370 api = _ref.api, 6371 code = _ref.code; 6372 6373 if (!_.isNil(this.agents[id])) { 6374 throw new Error('Agent with the id \'' + id + '\' exists already'); 6375 } 6376 6377 this.agents[id] = new Agent({ 6378 id: id, 6379 groupId: groupId, 6380 api: api, 6381 code: code, 6382 onAction: this._onActionCallback, 6383 onCompleteMode: this._onCompleteModeCallback, 6384 getState: function getState() { 6385 return _this.state; 6386 } 6387 }); 6388 } 6389 }, { 6390 key: 'destroyAgent', 6391 value: function destroyAgent(id) { 6392 delete this.agents[id]; 6393 } 6394 6395 // triggers agent event 6396 // 6397 // target can have 2 properties (most specific will apply) 6398 // id: id of the agent 6399 // groupId: groupId of the agents 6400 // 6401 6402 }, { 6403 key: 'triggerEvent', 6404 value: function triggerEvent(name, args, target) { 6405 var agents = this.getTargetedAgents(target); 6406 _.forEach(agents, function (agent) { 6407 return agent.triggerEvent(name, args); 6408 }); 6409 } 6410 6411 // switches mode handler of agent, works similar to trigger event 6412 6413 }, { 6414 key: 'switchMode', 6415 value: function switchMode(name, args, target) { 6416 var agents = this.getTargetedAgents(target); 6417 _.forEach(agents, function (agent) { 6418 return agent.switchMode(name, args); 6419 }); 6420 } 6421 }, { 6422 key: 'getTargetedAgents', 6423 value: function getTargetedAgents(target) { 6424 if (target.id !== undefined) { 6425 return [this.agents[target.id]]; 6426 } 6427 6428 if (target.groupId !== undefined) { 6429 return _.filter(this.agents, function (agent) { 6430 return agent.groupId === target.groupId; 6431 }); 6432 } 6433 6434 return this.agents; 6435 } 6436 }, { 6437 key: 'step', 6438 value: function step() { 6439 _.forEach(this.agents, function (agent, id) { 6440 return agent.step(); 6441 }); 6442 } 6443 6444 // deletes all existing agents 6445 6446 }, { 6447 key: 'reset', 6448 value: function reset() { 6449 this.agents = {}; 6450 } 6451 }]); 6452 6453 return Runtime; 6454}(); 6455 6456module.exports = Runtime; 6457},{"./agent":66,"lodash":171}],68:[function(require,module,exports){ 6458"use strict"; 6459 6460/* global Image */ 6461 6462var store = {}; 6463 6464function load(images) { 6465 var loadingImages = Object.keys(images).map(function (id) { 6466 return new Promise(function (resolve, reject) { 6467 var image = new Image(); 6468 image.src = images[id]; 6469 image.onload = function () { 6470 return resolve({ id: id, file: image }); 6471 }; 6472 image.onerror = function (error) { 6473 return reject(error); 6474 }; 6475 }); 6476 }); 6477 6478 return Promise.all(loadingImages).then(function (images) {
6479 images.forEach(function (_ref) { 6480 var id = _ref.id, 6481 file = _ref.file; 6482 6483 store[id] = file; 6484 }); 6485 }); 6486} 6487 6488module.exports = { 6489 load: load, 6490 store: store 6491}; 6492},{}],69:[function(require,module,exports){ 6493'use strict'; 6494 6495function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 6496 6497var _ = require('lodash'); 6498var update = require('immutability-helper'); 6499 6500var _require = require('./utils'), 6501 init = _require.init, 6502 _createEntity = _require.createEntity, 6503 _deleteEntity = _require.deleteEntity, 6504 updateGameState = _require.updateGameState, 6505 getGameState = _require.getGameState; 6506 6507module.exports = function (componentNames) { 6508 return { 6509 6510 reducers: { 6511 loadGameState: function loadGameState(state, _ref) { 6512 var loadState = _ref.loadState; 6513 6514 return init(loadState); 6515 }, 6516 6517 createEntity: function createEntity(state, _ref2) { 6518 var data = _ref2.data; 6519 6520 var entity = _createEntity(data); 6521 6522 return updateGameState(state, { 6523 entities: _defineProperty({}, entity.id, { $set: entity }) 6524 }); 6525 }, 6526 6527 deleteEntity: function deleteEntity(state, _ref3) { 6528 var data = _ref3.data; 6529 6530 var game = getGameState(state); 6531 6532 return updateGameState(state, { 6533 entities: { 6534 $set: _deleteEntity(data.id, game) 6535 } 6536 }); 6537 }, 6538 6539 beginStep: function beginStep(state) { 6540 return update(state, { 6541 next: { $set: state.current }, 6542 isGameStepCompleted: { $set: false } 6543 }); 6544 }, 6545 6546 _completeStep: function _completeStep(state) { 6547 if (state.isGameStepCompleted) { 6548 return state; 6549 } 6550 6551 return update(state, { 6552 prev: { $set: state.current }, 6553 current: { $set: state.next }, 6554 next: { $set: null }, 6555 isGameStepCompleted: { $set: true } 6556 }); 6557 } 6558 }, 6559 6560 effects: { 6561 completeStep: function completeStep(state, data, send) { 6562 _.forEach(componentNames, function (name) { 6563 send('game:' + name + '.update', {}, _.noop); 6564 }); 6565 6566 send('game:_completeStep', {}, _.noop); 6567 } 6568 } 6569 }; 6570}; 6571},{"./utils":72,"immutability-helper":164,"lodash":171}],70:[function(require,module,exports){ 6572'use strict'; 6573 6574var model = require('./model'); 6575 6576var _require = require('./utils'), 6577 getGameState = _require.getGameState, 6578 getEntity = _require.getEntity, 6579 getAllEntities = _require.getAllEntities, 6580 isFieldEmpty = _require.isFieldEmpty, 6581 findFieldNearPosition = _require.findFieldNearPosition, 6582 findEmptyFieldNearPosition = _require.findEmptyFieldNearPosition, 6583 getTeamResources = _require.getTeamResources, 6584 hasEnoughResources = _require.hasEnoughResources, 6585 getTeamGamePoints = _require.getTeamGamePoints, 6586 interpolate = _require.interpolate; 6587 6588module.exports = { 6589 model: model, 6590 getGameState: getGameState, 6591 getEntity: getEntity, 6592 getAllEntities: getAllEntities, 6593 isFieldEmpty: isFieldEmpty, 6594 findFieldNearPosition: findFieldNearPosition, 6595 findEmptyFieldNearPosition: findEmptyFieldNearPosition, 6596 getTeamResources: getTeamResources, 6597 hasEnoughResources: hasEnoughResources, 6598 getTeamGamePoints: getTeamGamePoints, 6599 interpolate: interpolate 6600}; 6601},{"./model":71,"./utils":72}],71:[function(require,module,exports){ 6602'use strict'; 6603 6604function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } 6605 6606var _ = require('lodash'); 6607var api = require('./api'); 6608 6609var _require = require('./utils'), 6610 init = _require.init, 6611 getGameState = _require.getGameState, 6612 updateGameState = _require.updateGameState, 6613 getEntity = _require.getEntity, 6614 getAllEntities = _require.getAllEntities; 6615 6616module.exports = function (_ref) { 6617 var state = _ref.state, 6618 components = _ref.components, 6619 reducers = _ref.reducers, 6620 effects = _ref.effects; 6621 6622 // TODO: enforce that there are no components which have effects and reducers with the same name 6623 6624 // we need to ensure that every component handles the update action which is triggered after every game step 6625 // if a component has no update handler _.noop is added as effect 6626 var componentsWithUpdateHandler = getComponentsWithUpdateHandler(components); 6627 6628 var gameAPI = api(_.keys(components)); 6629 6630 return { 6631 namespace: 'game', 6632 state: init(state), 6633 reducers: _.assign({}, getComponentsReducers(componentsWithUpdateHandler), gameAPI.reducers, getGlobalReducers(reducers)), 6634 effects: _.assign({}, getComponentsEffects(componentsWithUpdateHandler), gameAPI.effects, getGlobalEffects(effects)) 6635 }; 6636}; 6637 6638function getComponentsReducers(components) { 6639 return getComponentsActionHandlers('reducers', components, executeReducerAction); 6640} 6641 6642function getComponentsWithUpdateHandler(components) { 6643 return _.mapValues(components, function (component, name) { 6644 // add _.noop as update effect by default 6645 if (!hasUpdateHandler(component)) { 6646 if (!component.effects) { 6647 component.effects = {}; 6648 } 6649 component.effects.update = _.noop; 6650 return component; 6651 } 6652 6653 return component; 6654 }); 6655} 6656 6657function hasUpdateHandler(component) { 6658 return component.reducers && component.reducers.update || component.effects && component.effects.update; 6659} 6660 6661function getComponentsEffects(components) { 6662 return getComponentsActionHandlers('effects', components, executeEffectAction); 6663} 6664 6665/* getComponentsActionHandlers() 6666
6667 Combines all action handler of all components of one type. 6668 There are two different action types in choo: reducers and effects 6669 6670 handlers are prefixed with the name of the component so if we have two components A and B 6671 the returned handlers would look something like this 6672 6673 { 6674 'A.handler1': function(), 6675 'A.handler2': function(), 6676 'B.handler3': function() 6677 } 6678 6679 All handlers are wrapped so the action handler has only a view of the data of the entity 6680 6681 */ 6682function getComponentsActionHandlers(actionType, components, executeAction) { 6683 return _.reduce(components, function (handlers, component, componentType) { 6684 return _.reduce(component[actionType], function (handlers, actionHandler, reducerName) { 6685 handlers[componentType + '.' + reducerName] = _.partial(executeAction, componentType, actionHandler); 6686 return handlers; 6687 }, handlers); 6688 }, {}); 6689} 6690 6691function executeReducerAction(componentType, actionHandler, state, _ref2) { 6692 var target = _ref2.target, 6693 data = _ref2.data; 6694 6695 var game = getGameState(state); 6696 var entitiyChanges = void 0; 6697 6698 if (target) { 6699 entitiyChanges = getSingleEntityChanges(actionHandler, target, game, data); 6700 } else { 6701 entitiyChanges = getAllEntitiesChanges(actionHandler, componentType, game, data); 6702 } 6703 6704 return updateGameState(state, { entities: entitiyChanges }); 6705} 6706 6707function getSingleEntityChanges(actionHandler, id, state, action) { 6708 var current = getEntity(id, state); 6709 var nextChanges = actionHandler(current, action, state); 6710 6711 return _defineProperty({}, id, nextChanges); 6712} 6713 6714function getAllEntitiesChanges(actionHandler, componentType, state, action) { 6715 var game = getGameState(state); 6716 var entities = getAllEntities(componentType, game); 6717 6718 return _.reduce(entities, function (entityChanges, entity) { 6719 entityChanges[entity.id] = actionHandler(entity, action, game); 6720 6721 return entityChanges; 6722 }, {}); 6723} 6724 6725function executeEffectAction(componentType, actionHandler, state, _ref4, send, done) { 6726 var target = _ref4.target, 6727 data = _ref4.data; 6728 6729 var game = getGameState(state); 6730 6731 if (target) { 6732 var entity = getEntity(target, game); 6733 return actionHandler(entity, data, game, send, done); 6734 } 6735 6736 var entities = getAllEntities(componentType, game); 6737 _.forEach(entities, function (entity) { 6738 actionHandler(entity, data, game, send, done); 6739 }); 6740} 6741 6742function getGlobalReducers(reducers) { 6743 return _.reduce(reducers, function (handlers, handler, name) { 6744 handlers[name] = function (state, data) { 6745 var game = getGameState(state); 6746 return updateGameState(state, handler(game, data)); 6747 }; 6748 6749 return handlers; 6750 }, {}); 6751} 6752 6753function getGlobalEffects(effects) { 6754 return _.reduce(effects, function (handlers, handler, name) { 6755 handlers[name] = function (state, data, send, done) { 6756 var game = getGameState(state); 6757 handler(game, data, send, done); 6758 }; 6759 6760 return handlers; 6761 }, {}); 6762} 6763},{"./api":69,"./utils":72,"lodash":171}],72:[function(require,module,exports){ 6764'use strict'; 6765 6766var _ = require('lodash'); 6767var uid = require('uid'); 6768var update = require('immutability-helper'); 6769 6770function init(state) { 6771 var current = _.assign({}, state, { 6772 entities: _.reduce(state.entities, function (entities, entity) { 6773 var entityWithId = createEntity(entity); 6774 entities[entityWithId.id] = entityWithId; 6775 return entities; 6776 }, {}) 6777 }); 6778 6779 return { 6780 isGameStepCompleted: true, // when false, game is currently in between two steps 6781 prev: null, 6782 current: current, 6783 next: null 6784 }; 6785} 6786 6787function getGameState(state) { 6788 if (!state.isGameStepCompleted) { 6789 return state.next; 6790 } 6791 6792 return state.current; 6793} 6794 6795function updateGameState(state, changes) { 6796 if (!state.isGameStepCompleted) { 6797 return update(state, { next: changes }); 6798 } 6799 6800 return update(state, { current: changes }); 6801} 6802 6803function createEntity(entity) { 6804 if (!entity.id) { 6805 entity.id = uid(); 6806 } 6807 6808 // TODO: enforce component requirements 6809 6810 return entity; 6811} 6812 6813function getEntity(id, game) { 6814 return game.entities[id]; 6815} 6816 6817function deleteEntity(id, game) { 6818 return _.omitBy(game.entities, function (entitiy) { 6819 return entitiy.id === id; 6820 }); 6821} 6822 6823function getAllEntities(componentType, game) { 6824 return _.filter(game.entities, function (entity) { 6825 return !_.isUndefined(entity[componentType]); 6826 }); 6827} 6828 6829function isFieldEmpty(game, x, y) { 6830 if (game.tiles[y] === undefined || game.tiles[y][x] === undefined || game.tiles[y][x] === 1) { 6831 return false;
6832 } 6833 6834 return !_.some(getAllEntities('collides', game), function (_ref) { 6835 var position = _ref.position; 6836 return position.x === x && position.y === y; 6837 }); 6838} 6839 6840// searches for field which fulfills the predicate by iterating over every game field in a square spiral around the target field 6841function findFieldNearPosition(game, x, y, predicate) { 6842 var direction = 0; // which direction we're moving 6843 var length = 0; // how many steps we move, will be increased after two direction changes 6844 6845 var testX = x; // x coordinate of the field we check 6846 var testY = y; // y coordinate 6847 6848 // keep expanding until we exceeded the board size 6849 var fieldSize = Math.max(game.tiles.length, game.tiles[0].length); 6850 while (length <= fieldSize) { 6851 for (var i = 0; i <= length; i++) { 6852 // return if we found a walkable field 6853 6854 if (predicate(game, testX, testY)) { 6855 return { x: testX, y: testY }; 6856 } 6857 6858 switch (direction) { 6859 case 0: 6860 // DOWN 6861 testY += 1; 6862 break; 6863 case 1: 6864 // LEFT 6865 testX -= 1; 6866 break; 6867 case 2: 6868 // UP 6869 testY -= 1; 6870 break; 6871 case 3: 6872 // RIGHT 6873 testX += 1; 6874 break; 6875 } 6876 } 6877 6878 // increase spiral length after every 2 turns 6879 if (direction % 2 === 1) { 6880 length += 1; 6881 } 6882 6883 // turn clockwise 6884 direction = (direction + 1) % 4; 6885 } 6886 6887 // no empty field found 6888 return null; 6889} 6890 6891function findEmptyFieldNearPosition(game, x, y) { 6892 return findFieldNearPosition(game, x, y, isFieldEmpty); 6893} 6894 6895function interpolate(current, prev, progress) { 6896 return prev + (current - prev) * progress; 6897} 6898 6899module.exports = { 6900 init: init, 6901 getGameState: getGameState, 6902 updateGameState: updateGameState, 6903 createEntity: createEntity, 6904 getEntity: getEntity, 6905 deleteEntity: deleteEntity, 6906 getAllEntities: getAllEntities, 6907 isFieldEmpty: isFieldEmpty, 6908 findFieldNearPosition: findFieldNearPosition, 6909 findEmptyFieldNearPosition: findEmptyFieldNearPosition, 6910 interpolate: interpolate 6911}; 6912},{"immutability-helper":164,"lodash":171,"uid":241}],73:[function(require,module,exports){ 6913'use strict'; 6914 6915var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 6916 6917function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 6918 6919var _ = require('lodash'); 6920var raf = require('raf'); 6921var Timer = require('./timer'); 6922 6923// Clock 6924// sends ticks to drive incremental simulation 6925 6926var DEFAULT_INTERVAL = 550; 6927 6928var Clock = function () { 6929 function Clock() { 6930 var intervalDuration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_INTERVAL; 6931 6932 _classCallCheck(this, Clock); 6933 6934 this.timer = new Timer(); 6935 this.intervalDuration = intervalDuration; 6936 this.prevTickTimestamp = null; 6937 6938 this.tickCallback = _.noop; 6939 this.progressCallback = _.noop; 6940 } 6941 6942 // call to register a single tick handler 6943 6944 6945 _createClass(Clock, [{ 6946 key: 'onTick', 6947 value: function onTick(tickCallback) { 6948 this.tickCallback = tickCallback; 6949 } 6950 }, { 6951 key: 'onProgress', 6952 value: function onProgress(progressCallback) { 6953 this.progressCallback = progressCallback; 6954 } 6955 }, { 6956 key: 'triggerNextTick', 6957 value: function triggerNextTick() { 6958 var _this = this; 6959 6960 this.tickCallback(); 6961 6962 this.prevTickTimestamp = this.timer.now(); 6963 this.timeoutID = setTimeout(function () { 6964 return _this.triggerNextTick(); 6965 }, this.intervalDuration); 6966 } 6967 }, { 6968 key: 'triggerProgress', 6969 value: function triggerProgress() { 6970 var _this2 = this; 6971 6972 if (!this.timer.isRunning()) { 6973 return; 6974 } 6975 6976 raf(function () { 6977 return _this2.triggerProgress(); 6978 }); 6979 this.progressCallback(this.getProgress()); 6980 } 6981 }, { 6982 key: 'start', 6983 value: function start() { 6984 var _this3 = this; 6985 6986 if (this.timer.isRunning()) { 6987 return; 6988 } 6989 6990 this.timer.start(); 6991 6992 var timeUntilNextTick = this.getTimeUntilNextTick(); 6993 this.timeoutID = setTimeout(function () { 6994 return _this3.triggerNextTick(); 6995 }, timeUntilNextTick); 6996 6997 this.triggerProgress(); 6998 } 6999 }, { 7000 key: 'getTimeUntilNextTick', 7001 value: function getTimeUntilNextTick() { 7002 if (!this.prevTickTimestamp) { 7003 return 0; 7004 } 7005 7006 return Math.max(0, this.intervalDuration - (this.timer.now() - this.prevTickTimestamp)); 7007 } 7008 }, { 7009 key: 'stop', 7010 value: function stop() { 7011 if (this.timeoutID) { 7012 clearTimeout(this.timeoutID); 7013 } 7014 7015 this.timer.pause(); 7016 } 7017 }, { 7018 key: 'setIntervalDuration', 7019 value: function setIntervalDuration(intervalDuration) { 7020 this.intervalDuration = intervalDuration; 7021 } 7022 }, { 7023 key: 'getProgress', 7024 value: function getProgress() { 7025 if (_.isNil(this.prevTickTimestamp)) { 7026 return 0; 7027 } 7028 7029 return _.clamp((this.timer.now() - this.prevTickTimestamp) / this.intervalDuration, 0, 1); 7030 } 7031 }]); 7032 7033 return Clock; 7034}(); 7035 7036module.exports = Clock; 7037},{"./timer":74,"lodash":171,"raf":205}],74:[function(require,module,exports){ 7038"use strict"; 7039 7040var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); 7041 7042function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } 7043 7044// Timer 7045// replaces Date.now and adds the ability to pause time 7046 7047var Timer = function () { 7048 function Timer() { 7049 _classCallCheck(this, Timer); 7050 7051 this.pausedTimestamp = Date.now(); 7052 this.offset = Date.now(); 7053 } 7054 7055 _createClass(Timer, [{ 7056 key: "start", 7057 value: function start() { 7058 if (this.isRunning()) { 7059 return; 7060 } 7061 7062 this.offset += Date.now() - this.pausedTimestamp; 7063 this.pausedTimestamp = null; 7064 } 7065 }, { 7066 key: "pause", 7067 value: function pause() { 7068 if (!this.isRunning()) { 7069 return; 7070 } 7071 7072 this.pausedTimestamp = Date.now(); 7073 } 7074 }, { 7075 key: "now", 7076 value: function now() { 7077 if (!this.isRunning()) { 7078 return this.pausedTimestamp - this.offset; 7079 } 7080 7081 return Date.now() - this.offset; 7082 } 7083 }, { 7084 key: "isRunning", 7085 value: function isRunning() { 7086 return this.pausedTimestamp === null; 7087 } 7088 }]); 7089 7090 return Timer; 7091}(); 7092 7093module.exports = Timer; 7094},{}],75:[function(require,module,exports){ 7095'use strict' 7096const viewHtml = require('./view') 7097const doNothing = () => {} 7098
7099const model = (nameSpace) => { 7100 const DEF_DURATION_BUILDUP = 1500 7101 const DEF_DURATION_UPTIME = 1000 7102 const DEF_DURATION_SLIDEOUT = 1000 7103 let DURATION_BUILDUP = DEF_DURATION_BUILDUP 7104 let DURATION_SLIDEOUT = DEF_DURATION_SLIDEOUT 7105 let DURATION_UPTIME = DEF_DURATION_UPTIME 7106 let updateInterval 7107 let timeElapsed = 0 7108 const timePerUpdate = 25 7109 const startPositions = { 7110 left: -100, 7111 right: -300, 7112 vs: -800 7113 } 7114 7115 return { 7116 namespace: nameSpace, 7117 7118 state: { 7119 hidden: true, 7120 left: { 7121 img: '', 7122 name: 'Player 1', 7123 pos: 0 7124 }, 7125 right: { 7126 img: '', 7127 name: 'Player 2', 7128 pos: 0 7129 }, 7130 vs: { 7131 img: '', 7132 pos: 0, 7133 scale: 100 7134 } 7135 }, 7136 7137 reducers: { 7138 _setVisibility: (state, visible) => { 7139 state.hidden = !visible 7140 }, 7141 setLeft: (state, {img, name}) => setSide(state, 'LEFT', img, name), 7142 setRight: (state, {img, name}) => setSide(state, 'RIGHT', img, name), 7143 setVS: (state, {img}) => { 7144 state.vs.img = img 7145 return state 7146 }, 7147 updatePositions: updatePositions, 7148 updateSizes: updateSizes 7149 }, 7150 7151 effects: { 7152 start: start,
7153 dismiss: dismiss, 7154 setDurations: (state, {up, down, stay}, send, done) => { 7155 if (up > 0) DURATION_BUILDUP = up 7156 if (down > 0) DURATION_SLIDEOUT = down 7157 if (stay >= 0) DURATION_UPTIME = stay 7158 done() 7159 }, 7160 update: update 7161 } 7162 } 7163 7164 function updatePositions (state, data) { 7165 if (data.hasOwnProperty('left')) state.left.pos = data.left 7166 if (data.hasOwnProperty('right')) state.right.pos = data.right 7167 if (data.hasOwnProperty('vs')) state.vs.pos = data.vs 7168 return state 7169 } 7170 7171 function updateSizes (state, data) { 7172 if (data.hasOwnProperty('vs')) state.vs.scale = data.vs 7173 return state 7174 } 7175 7176 function update ({left, right, vs}, data, send, done) { 7177 timeElapsed += timePerUpdate 7178 let pL = left.pos 7179 let pR = right.pos 7180 let pM = vs.pos 7181 7182 if (timeElapsed < DURATION_BUILDUP) { 7183 return animIn(pL, pR, pM, send) 7184 } 7185 7186 if (timeElapsed < DURATION_BUILDUP + DURATION_UPTIME) { 7187 return 7188 } 7189 7190 if (timeElapsed < DURATION_BUILDUP + DURATION_UPTIME + DURATION_SLIDEOUT) { 7191 smallify(vs.scale, send) 7192 return slideOut(pL, pR, pM, send) 7193 } 7194 7195 send(nameSpace + ':dismiss', null, doNothing) 7196 } 7197 7198 function start (state, data, send, done) { 7199 timeElapsed = 0 7200 send(nameSpace + ':_setVisibility', true, doNothing) 7201 updateInterval = setInterval(() => { 7202 send(nameSpace + ':update', null, doNothing) 7203 }, timePerUpdate) 7204 send(nameSpace + ':updatePositions', startPositions, doNothing) 7205 send(nameSpace + ':updateSizes', {vs: 100}, doNothing) 7206 done() 7207 } 7208 7209 function dismiss (state, data, send, done) { 7210 send(nameSpace + ':_setVisibility', false, doNothing) 7211 if (updateInterval) { 7212 clearInterval(updateInterval) 7213 } 7214 done() 7215 } 7216 7217 function setSide (state, side, img, name) { 7218 if (side === 'LEFT') { 7219 if (img) state.left.img = img 7220 if (name) state.left.name = name 7221 } 7222 if (side === 'RIGHT') { 7223 if (img) state.right.img = img 7224 if (name) state.right.name = name 7225 } 7226 } 7227 7228 function animIn (pL, pR, pM, send) { 7229 const speed = (timePerUpdate / 25) * (DEF_DURATION_BUILDUP / DURATION_BUILDUP) 7230 pL += speed * 15 7231 pR += speed * 15 7232 pM += speed * 20 7233 if (pL > 0) pL = 0 7234 if (pR > 0) pR = 0 7235 if (pM > 0) pM = 0 7236 send(nameSpace + ':updatePositions', {left: pL, right: pR, vs: pM}, doNothing) 7237 } 7238 7239 function slideOut (pL, pR, pM, send) { 7240 const speed = (timePerUpdate / 25) * (DEF_DURATION_SLIDEOUT / DURATION_SLIDEOUT) 7241 pL -= speed * 2 7242 pR -= speed * 2 7243 send(nameSpace + ':updatePositions', {left: pL, right: pR}, doNothing) 7244 } 7245 7246 function smallify (vsScale, send) { 7247 const speed = (timePerUpdate / 25) * (DEF_DURATION_SLIDEOUT / DURATION_SLIDEOUT) 7248 vsScale -= speed * 5 7249 if (vsScale < 0) vsScale = 0 7250 send(nameSpace + ':updateSizes', {vs: vsScale}, doNothing) 7251 } 7252} 7253 7254module.exports = (nameSpace) => { 7255 return { 7256 model: model(nameSpace), 7257 view: viewHtml(nameSpace) 7258 } 7259} 7260 7261 7262},{"./view":77}],76:[function(require,module,exports){ 7263module.exports = require('yo-yo') 7264 7265},{"yo-yo":253}],77:[function(require,module,exports){ 7266'use strict' 7267const html = require('choo/html') 7268const sf = 0 7269const css = ((require('insert-css')("/* Layer, covering the whole parent element */\n._66929eac .actionO_overlay {\n width: inherit;\n height: inherit;\n position: absolute;\n top: 0;\n left: 0;\n overflow: hidden;\n z-index: 100;\n}\n\n/* Playernames */\n._66929eac .actionO_Name {\n font-size: 200px;\n font-weight: 500;\n position: relative;\n z-index: 104;\n margin: 0 auto;\n color: white;\n overflow: hidden;\n max-width: 100%;\n display: block;\n text-align: center;\n}\n\n/* Left Area sliding in having an intransparent slightly red background*/\n._66929eac #actionO_left {\n background-color: rgba(255,150,150,1);\n left: 0;\n}\n\n\n/* The Line at the very right of the left area, contains a red gradient by default */\n._66929eac #actionO_left > .actionO_Line {\n background: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(255,0,0,1), rgba(0,0,0,0)); /*Safari 5.1-6*/\n background: -o-linear-gradient(left, rgba(0,0,0,0), rgba(255,0,0,1), rgba(0,0,0,0)); /*Opera 11.1-12*/\n background: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(255,0,0,1), rgba(0,0,0,0)); /*Fx 3.6-15*/\n background: linear-gradient(to left, rgba(0,0,0,0), rgba(255,0,0,1), rgba(0,0,0,0)); /*Standard*/\n width: 50%;\n right: -15%;\n}
7269\n\n/* works vice versa to the left side */\n._66929eac #actionO_right {\n background-color: rgba(150,150,255,1);\n right: 0;\n}\n\n/* works vice versa to the left side */\n._66929eac #actionO_right > .actionO_Line {\n background: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,255,1), rgba(0,0,0,0)); /*Safari 5.1-6*/\n background: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,255,1), rgba(0,0,0,0)); /*Opera 11.1-12*/\n background: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,255,1), rgba(0,0,0,0)); /*Fx 3.6-15*/\n background: linear-gradient(to left, rgba(0,0,0,0), rgba(0,0,255,1), rgba(0,0,0,0)); /*Standard*/\n width: 50%;\n left: -15%;\n}\n\n/* internal CSS. You can overwrite it, but no one knows what might happen. */\n\n._66929eac #actionO_left > .actionO_Image > img {\n float: left;\n}\n\n._66929eac #actionO_right > .actionO_Image > img {\n float: right;\n}\n\n._66929eac .actionO_VS {\n height: 100%;\n width: 100%;\n position: absolute;\n top: 0;\n z-index: 103;\n overflow: hidden;\n}\n\n._66929eac .actionO_VS > div > div {\n display: table-cell;\n position: relative;\n width: 100%;\n vertical-align: middle;\n text-align: center;\n}\n\n._66929eac .actionO_VS > div > div > div {\n width: 100%;\n background-repeat: no-repeat;\n background-size: contain;\n}\n\n._66929eac .actionO_VS > div{\n display: table;\n width: 25%;\n height: 100%;\n margin: 0 auto;\n position: relative;\n}\n\n._66929eac .actionO_Image {\n position: absolute;\n background-repeat: no-repeat;\n background-size: contain;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n z-index: 102;\n}\n\n._66929eac .actionO_Image > img {\n width: 100%;\n}\n\n._66929eac .actionO_Line {\n height: 100%;\n overflow: hidden;\n top: 0;\n position: absolute;\n width: 10px;\n background-color: black;\n background-repeat: no-repeat;\n background-size: cover;\n z-index: 101;\n}\n\n._66929eac #actionO_left,\n._66929eac #actionO_right {\n width: 50%;\n height: 100%;\n position: absolute;\n top: 0;\n overflow: hidden;\n}") || true) && "_66929eac") 7270 7271module.exports = (nameSpace) => { 7272 return (state, prev, send) => { 7273 return html` 7274 <div class="${css} actionO_overlay" style="visibility: ${state[nameSpace].hidden ? 'hidden' : 'visible'}"> 7275 <div id="actionO_left" style="left: ${state[nameSpace].left.pos + '%'}"> 7276 <div class="actionO_Image"><img src="${state[nameSpace].left.img}"/></div> 7277 <div class="actionO_Line"></div> 7278 <div class="actionO_Name">${state[nameSpace].left.name}</div> 7279 </div> 7280 7281 <div class="actionO_VS" style="top: ${state[nameSpace].vs.pos + '%'}"> 7282 <div> 7283 <div> 7284 <img src=${state[nameSpace].vs.img} width="${state[nameSpace].vs.scale}%" alt="VS"/> 7285 </div> 7286 </div> 7287 </div> 7288 7289 <div id="actionO_right" style="right: ${state[nameSpace].right.pos + '%'}""> 7290 <div class="actionO_Image"><img src="${state[nameSpace].right.img}"/></div> 7291 <div class="actionO_Line"></div> 7292 <div class="actionO_Name">${state[nameSpace].right.name}</div> 7293 </div> 7294 </div> 7295 ` 7296 } 7297} 7298 7299},{"choo/html":76,"insert-css":166}],78:[function(require,module,exports){ 7300(function (global){ 7301'use strict'; 7302 7303// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js 7304// original notice: 7305 7306/*! 7307 * The buffer module from node.js, for the browser. 7308 * 7309 * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> 7310 * @license MIT 7311 */ 7312function compare(a, b) { 7313 if (a === b) { 7314 return 0; 7315 } 7316 7317 var x = a.length; 7318 var y = b.length; 7319 7320 for (var i = 0, len = Math.min(x, y); i < len; ++i) { 7321 if (a[i] !== b[i]) { 7322 x = a[i]; 7323 y = b[i]; 7324 break; 7325 } 7326 } 7327 7328 if (x < y) { 7329 return -1; 7330 } 7331 if (y < x) { 7332 return 1; 7333 } 7334 return 0; 7335} 7336function isBuffer(b) { 7337 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { 7338 return global.Buffer.isBuffer(b); 7339 } 7340 return !!(b != null && b._isBuffer); 7341} 7342 7343// based on node assert, original notice:
vendor: 14,432 bytes, lines 7343-7783
7343 7344 7345// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 7346// 7347// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! 7348// 7349// Originally from narwhal.js (http://narwhaljs.org) 7350// Copyright (c) 2009 Thomas Robinson <280north.com> 7351// 7352// Permission is hereby granted, free of charge, to any person obtaining a copy 7353// of this software and associated documentation files (the 'Software'), to 7354// deal in the Software without restriction, including without limitation the 7355// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 7356// sell copies of the Software, and to permit persons to whom the Software is 7357// furnished to do so, subject to the following conditions: 7358// 7359// The above copyright notice and this permission notice shall be included in 7360// all copies or substantial portions of the Software. 7361// 7362// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 7363// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 7364// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 7365// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN 7366// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 7367// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 7368 7369var util = require('util/'); 7370var hasOwn = Object.prototype.hasOwnProperty; 7371var pSlice = Array.prototype.slice; 7372var functionsHaveNames = (function () { 7373 return function foo() {}.name === 'foo'; 7374}()); 7375function pToString (obj) { 7376 return Object.prototype.toString.call(obj); 7377} 7378function isView(arrbuf) { 7379 if (isBuffer(arrbuf)) { 7380 return false; 7381 } 7382 if (typeof global.ArrayBuffer !== 'function') { 7383 return false; 7384 } 7385 if (typeof ArrayBuffer.isView === 'function') { 7386 return ArrayBuffer.isView(arrbuf); 7387 } 7388 if (!arrbuf) { 7389 return false; 7390 } 7391 if (arrbuf instanceof DataView) { 7392 return true; 7393 } 7394 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { 7395 return true; 7396 } 7397 return false; 7398} 7399// 1. The assert module provides functions that throw 7400// AssertionError's when particular conditions are not met. The 7401// assert module must conform to the following interface. 7402 7403var assert = module.exports = ok; 7404 7405// 2. The AssertionError is defined in assert. 7406// new assert.AssertionError({ message: message, 7407// actual: actual, 7408// expected: expected }) 7409 7410var regex = /\s*function\s+([^\(\s]*)\s*/; 7411// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js 7412function getName(func) { 7413 if (!util.isFunction(func)) { 7414 return; 7415 } 7416 if (functionsHaveNames) { 7417 return func.name; 7418 } 7419 var str = func.toString(); 7420 var match = str.match(regex); 7421 return match && match[1]; 7422} 7423assert.AssertionError = function AssertionError(options) { 7424 this.name = 'AssertionError'; 7425 this.actual = options.actual; 7426 this.expected = options.expected; 7427 this.operator = options.operator; 7428 if (options.message) { 7429 this.message = options.message; 7430 this.generatedMessage = false; 7431 } else { 7432 this.message = getMessage(this); 7433 this.generatedMessage = true; 7434 } 7435 var stackStartFunction = options.stackStartFunction || fail; 7436 if (Error.captureStackTrace) { 7437 Error.captureStackTrace(this, stackStartFunction); 7438 } else { 7439 // non v8 browsers so we can have a stacktrace 7440 var err = new Error(); 7441 if (err.stack) { 7442 var out = err.stack; 7443 7444 // try to strip useless frames 7445 var fn_name = getName(stackStartFunction); 7446 var idx = out.indexOf('\n' + fn_name); 7447 if (idx >= 0) { 7448 // once we have located the function frame 7449 // we need to strip out everything before it (and its line) 7450 var next_line = out.indexOf('\n', idx + 1); 7451 out = out.substring(next_line + 1); 7452 } 7453 7454 this.stack = out; 7455 } 7456 } 7457}; 7458 7459// assert.AssertionError instanceof Error 7460util.inherits(assert.AssertionError, Error); 7461 7462function truncate(s, n) { 7463 if (typeof s === 'string') { 7464 return s.length < n ? s : s.slice(0, n); 7465 } else { 7466 return s; 7467 } 7468} 7469function inspect(something) { 7470 if (functionsHaveNames || !util.isFunction(something)) { 7471 return util.inspect(something); 7472 } 7473 var rawname = getName(something); 7474 var name = rawname ? ': ' + rawname : ''; 7475 return '[Function' + name + ']'; 7476} 7477function getMessage(self) { 7478 return truncate(inspect(self.actual), 128) + ' ' + 7479 self.operator + ' ' + 7480 truncate(inspect(self.expected), 128); 7481} 7482 7483// At present only the three keys mentioned above are used and 7484// understood by the spec. Implementations or sub modules can pass 7485// other keys to the AssertionError's constructor - they will be 7486// ignored. 7487 7488// 3. All of the following functions must throw an AssertionError 7489// when a corresponding condition is not met, with a message that 7490// may be undefined if not provided. All assertion methods provide 7491// both the actual and expected values to the assertion error for 7492// display purposes. 7493 7494function fail(actual, expected, message, operator, stackStartFunction) { 7495 throw new assert.AssertionError({ 7496 message: message, 7497 actual: actual, 7498 expected: expected, 7499 operator: operator, 7500 stackStartFunction: stackStartFunction 7501 }); 7502} 7503 7504// EXTENSION! allows for well behaved errors defined elsewhere. 7505assert.fail = fail; 7506 7507// 4. Pure assertion tests whether a value is truthy, as determined 7508// by !!guard. 7509// assert.ok(guard, message_opt); 7510// This statement is equivalent to assert.equal(true, !!guard, 7511// message_opt);. To test strictly for the value true, use 7512// assert.strictEqual(true, guard, message_opt);. 7513 7514function ok(value, message) { 7515 if (!value) fail(value, true, message, '==', assert.ok); 7516} 7517assert.ok = ok; 7518 7519// 5. The equality assertion tests shallow, coercive equality with 7520// ==. 7521// assert.equal(actual, expected, message_opt); 7522 7523assert.equal = function equal(actual, expected, message) { 7524 if (actual != expected) fail(actual, expected, message, '==', assert.equal); 7525}; 7526 7527// 6. The non-equality assertion tests for whether two objects are not equal 7528// with != assert.notEqual(actual, expected, message_opt); 7529 7530assert.notEqual = function notEqual(actual, expected, message) { 7531 if (actual == expected) { 7532 fail(actual, expected, message, '!=', assert.notEqual); 7533 } 7534}; 7535 7536// 7. The equivalence assertion tests a deep equality relation. 7537// assert.deepEqual(actual, expected, message_opt); 7538 7539assert.deepEqual = function deepEqual(actual, expected, message) { 7540 if (!_deepEqual(actual, expected, false)) { 7541 fail(actual, expected, message, 'deepEqual', assert.deepEqual); 7542 } 7543}; 7544 7545assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { 7546 if (!_deepEqual(actual, expected, true)) { 7547 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); 7548 } 7549}; 7550 7551function _deepEqual(actual, expected, strict, memos) { 7552 // 7.1. All identical values are equivalent, as determined by ===. 7553 if (actual === expected) { 7554 return true; 7555 } else if (isBuffer(actual) && isBuffer(expected)) { 7556 return compare(actual, expected) === 0; 7557 7558 // 7.2. If the expected value is a Date object, the actual value is 7559 // equivalent if it is also a Date object that refers to the same time. 7560 } else if (util.isDate(actual) && util.isDate(expected)) { 7561 return actual.getTime() === expected.getTime(); 7562 7563 // 7.3 If the expected value is a RegExp object, the actual value is 7564 // equivalent if it is also a RegExp object with the same source and 7565 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). 7566 } else if (util.isRegExp(actual) && util.isRegExp(expected)) { 7567 return actual.source === expected.source && 7568 actual.global === expected.global && 7569 actual.multiline === expected.multiline && 7570 actual.lastIndex === expected.lastIndex && 7571 actual.ignoreCase === expected.ignoreCase; 7572 7573 // 7.4. Other pairs that do not both pass typeof value == 'object', 7574 // equivalence is determined by ==. 7575 } else if ((actual === null || typeof actual !== 'object') && 7576 (expected === null || typeof expected !== 'object')) { 7577 return strict ? actual === expected : actual == expected; 7578 7579 // If both values are instances of typed arrays, wrap their underlying 7580 // ArrayBuffers in a Buffer each to increase performance 7581 // This optimization requires the arrays to have the same type as checked by 7582 // Object.prototype.toString (aka pToString). Never perform binary 7583 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their 7584 // bit patterns are not identical. 7585 } else if (isView(actual) && isView(expected) && 7586 pToString(actual) === pToString(expected) && 7587 !(actual instanceof Float32Array || 7588 actual instanceof Float64Array)) { 7589 return compare(new Uint8Array(actual.buffer), 7590 new Uint8Array(expected.buffer)) === 0; 7591 7592 // 7.5 For all other Object pairs, including Array objects, equivalence is 7593 // determined by having the same number of owned properties (as verified 7594 // with Object.prototype.hasOwnProperty.call), the same set of keys 7595 // (although not necessarily the same order), equivalent values for every 7596 // corresponding key, and an identical 'prototype' property. Note: this 7597 // accounts for both named and indexed properties on Arrays. 7598 } else if (isBuffer(actual) !== isBuffer(expected)) { 7599 return false; 7600 } else { 7601 memos = memos || {actual: [], expected: []}; 7602 7603 var actualIndex = memos.actual.indexOf(actual); 7604 if (actualIndex !== -1) { 7605 if (actualIndex === memos.expected.indexOf(expected)) { 7606 return true; 7607 } 7608 } 7609 7610 memos.actual.push(actual); 7611 memos.expected.push(expected); 7612 7613 return objEquiv(actual, expected, strict, memos); 7614 } 7615} 7616 7617function isArguments(object) { 7618 return Object.prototype.toString.call(object) == '[object Arguments]'; 7619} 7620 7621function objEquiv(a, b, strict, actualVisitedObjects) { 7622 if (a === null || a === undefined || b === null || b === undefined) 7623 return false; 7624 // if one is a primitive, the other must be same 7625 if (util.isPrimitive(a) || util.isPrimitive(b)) 7626 return a === b; 7627 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) 7628 return false; 7629 var aIsArgs = isArguments(a); 7630 var bIsArgs = isArguments(b); 7631 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) 7632 return false; 7633 if (aIsArgs) { 7634 a = pSlice.call(a); 7635 b = pSlice.call(b); 7636 return _deepEqual(a, b, strict); 7637 } 7638 var ka = objectKeys(a); 7639 var kb = objectKeys(b); 7640 var key, i; 7641 // having the same number of owned properties (keys incorporates 7642 // hasOwnProperty) 7643 if (ka.length !== kb.length) 7644 return false; 7645 //the same set of keys (although not necessarily the same order), 7646 ka.sort(); 7647 kb.sort(); 7648 //~~~cheap key test 7649 for (i = ka.length - 1; i >= 0; i--) { 7650 if (ka[i] !== kb[i]) 7651 return false; 7652 } 7653 //equivalent values for every corresponding key, and 7654 //~~~possibly expensive deep test 7655 for (i = ka.length - 1; i >= 0; i--) { 7656 key = ka[i]; 7657 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) 7658 return false; 7659 } 7660 return true; 7661} 7662 7663// 8. The non-equivalence assertion tests for any deep inequality. 7664// assert.notDeepEqual(actual, expected, message_opt); 7665 7666assert.notDeepEqual = function notDeepEqual(actual, expected, message) { 7667 if (_deepEqual(actual, expected, false)) { 7668 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); 7669 } 7670}; 7671 7672assert.notDeepStrictEqual = notDeepStrictEqual; 7673function notDeepStrictEqual(actual, expected, message) { 7674 if (_deepEqual(actual, expected, true)) { 7675 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); 7676 } 7677} 7678 7679 7680// 9. The strict equality assertion tests strict equality, as determined by ===. 7681// assert.strictEqual(actual, expected, message_opt); 7682 7683assert.strictEqual = function strictEqual(actual, expected, message) { 7684 if (actual !== expected) { 7685 fail(actual, expected, message, '===', assert.strictEqual); 7686 } 7687}; 7688 7689// 10. The strict non-equality assertion tests for strict inequality, as 7690// determined by !==. assert.notStrictEqual(actual, expected, message_opt); 7691 7692assert.notStrictEqual = function notStrictEqual(actual, expected, message) { 7693 if (actual === expected) { 7694 fail(actual, expected, message, '!==', assert.notStrictEqual); 7695 } 7696}; 7697 7698function expectedException(actual, expected) { 7699 if (!actual || !expected) { 7700 return false; 7701 } 7702 7703 if (Object.prototype.toString.call(expected) == '[object RegExp]') { 7704 return expected.test(actual); 7705 } 7706 7707 try { 7708 if (actual instanceof expected) { 7709 return true; 7710 } 7711 } catch (e) { 7712 // Ignore. The instanceof check doesn't work for arrow functions. 7713 } 7714 7715 if (Error.isPrototypeOf(expected)) { 7716 return false; 7717 } 7718 7719 return expected.call({}, actual) === true; 7720} 7721 7722function _tryBlock(block) { 7723 var error; 7724 try { 7725 block(); 7726 } catch (e) { 7727 error = e; 7728 } 7729 return error; 7730} 7731 7732function _throws(shouldThrow, block, expected, message) { 7733 var actual; 7734 7735 if (typeof block !== 'function') { 7736 throw new TypeError('"block" argument must be a function'); 7737 } 7738 7739 if (typeof expected === 'string') { 7740 message = expected; 7741 expected = null; 7742 } 7743 7744 actual = _tryBlock(block); 7745 7746 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + 7747 (message ? ' ' + message : '.'); 7748 7749 if (shouldThrow && !actual) { 7750 fail(actual, expected, 'Missing expected exception' + message); 7751 } 7752 7753 var userProvidedMessage = typeof message === 'string'; 7754 var isUnwantedException = !shouldThrow && util.isError(actual); 7755 var isUnexpectedException = !shouldThrow && actual && !expected; 7756 7757 if ((isUnwantedException && 7758 userProvidedMessage && 7759 expectedException(actual, expected)) || 7760 isUnexpectedException) { 7761 fail(actual, expected, 'Got unwanted exception' + message); 7762 } 7763 7764 if ((shouldThrow && actual && expected && 7765 !expectedException(actual, expected)) || (!shouldThrow && actual)) { 7766 throw actual; 7767 } 7768} 7769 7770// 11. Expected to throw an error: 7771// assert.throws(block, Error_opt, message_opt); 7772 7773assert.throws = function(block, /*optional*/error, /*optional*/message) { 7774 _throws(true, block, error, message); 7775}; 7776 7777// EXTENSION! This is annoying to write outside this module. 7778assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { 7779 _throws(false, block, error, message); 7780}; 7781 7782assert.ifError = function(err) { if (err) throw err; }; 7783
7784var objectKeys = Object.keys || function (obj) { 7785 var keys = []; 7786 for (var key in obj) { 7787 if (hasOwn.call(obj, key)) keys.push(key); 7788 } 7789 return keys; 7790}; 7791 7792}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 7793},{"util/":245}],79:[function(require,module,exports){ 7794module.exports = applyHook 7795 7796// apply arguments onto an array of functions, useful for hooks 7797// (arr, any?, any?, any?, any?, any?) -> null 7798function applyHook (arr, arg1, arg2, arg3, arg4, arg5) { 7799 arr.forEach(function (fn) { 7800 fn(arg1, arg2, arg3, arg4, arg5) 7801 }) 7802} 7803 7804},{}],80:[function(require,module,exports){ 7805var mutate = require('xtend/mutable') 7806var nanotick = require('nanotick') 7807var assert = require('assert') 7808var xtend = require('xtend') 7809 7810var applyHook = require('./apply-hook') 7811 7812module.exports = dispatcher 7813 7814// initialize a new barracks instance 7815// obj -> obj 7816function dispatcher (hooks) { 7817 hooks = hooks || {} 7818 assert.equal(typeof hooks, 'object', 'barracks: hooks should be undefined or an object') 7819 7820 var onStateChangeHooks = [] 7821 var onActionHooks = [] 7822 var onErrorHooks = [] 7823 7824 var subscriptionWraps = [] 7825 var initialStateWraps = [] 7826 var reducerWraps = [] 7827 var effectWraps = [] 7828 7829 use(hooks) 7830 7831 var reducersCalled = false 7832 var effectsCalled = false 7833 var stateCalled = false 7834 var subsCalled = false 7835 var stopped = false 7836 7837 var subscriptions = start._subscriptions = {} 7838 var reducers = start._reducers = {} 7839 var effects = start._effects = {} 7840 var models = start._models = [] 7841 var _state = {} 7842 7843 var tick = nanotick() 7844 7845 start.model = setModel 7846 start.state = getState 7847 start.start = start 7848 start.stop = stop 7849 start.use = use 7850 7851 return start 7852 7853 // push an object of hooks onto an array 7854 // obj -> null 7855 function use (hooks) { 7856 assert.equal(typeof hooks, 'object', 'barracks.use: hooks should be an object') 7857 assert.ok(!hooks.onError || typeof hooks.onError === 'function', 'barracks.use: onError should be undefined or a function') 7858 assert.ok(!hooks.onAction || typeof hooks.onAction === 'function', 'barracks.use: onAction should be undefined or a function') 7859 assert.ok(!hooks.onStateChange || typeof hooks.onStateChange === 'function', 'barracks.use: onStateChange should be undefined or a function') 7860 7861 if (hooks.onStateChange) onStateChangeHooks.push(hooks.onStateChange) 7862 if (hooks.onError) onErrorHooks.push(wrapOnError(hooks.onError)) 7863 if (hooks.onAction) onActionHooks.push(hooks.onAction) 7864 if (hooks.wrapSubscriptions) subscriptionWraps.push(hooks.wrapSubscriptions) 7865 if (hooks.wrapInitialState) initialStateWraps.push(hooks.wrapInitialState) 7866 if (hooks.wrapReducers) reducerWraps.push(hooks.wrapReducers) 7867 if (hooks.wrapEffects) effectWraps.push(hooks.wrapEffects) 7868 if (hooks.models) hooks.models.forEach(setModel) 7869 } 7870 7871 // push a model to be initiated 7872 // obj -> null 7873 function setModel (model) { 7874 assert.equal(typeof model, 'object', 'barracks.store.model: model should be an object') 7875 models.push(model) 7876 } 7877 7878 // get the current state from the store 7879 // obj? -> obj 7880 function getState (opts) { 7881 opts = opts || {} 7882 assert.equal(typeof opts, 'object', 'barracks.store.state: opts should be an object') 7883 7884 var state = opts.state 7885 if (!opts.state && opts.freeze === false) return xtend(_state) 7886 else if (!opts.state) return Object.freeze(xtend(_state)) 7887 assert.equal(typeof state, 'object', 'barracks.store.state: state should be an object') 7888 7889 var namespaces = [] 7890 var newState = {} 7891 7892 // apply all fields from the model, and namespaced fields from the passed 7893 // in state 7894 models.forEach(function (model) { 7895 var ns = model.namespace 7896 namespaces.push(ns) 7897 var modelState = model.state || {} 7898 if (ns) { 7899 newState[ns] = newState[ns] || {} 7900 apply(ns, modelState, newState) 7901 newState[ns] = xtend(newState[ns], state[ns]) 7902 } else { 7903 mutate(newState, modelState) 7904 } 7905 }) 7906 7907 // now apply all fields that weren't namespaced from the passed in state 7908 Object.keys(state).forEach(function (key) { 7909 if (namespaces.indexOf(key) !== -1) return 7910 newState[key] = state[key] 7911 }) 7912 7913 var tmpState = xtend(_state, xtend(state, newState)) 7914 var wrappedState = wrapHook(tmpState, initialStateWraps) 7915 7916 return (opts.freeze === false) 7917 ? wrappedState 7918 : Object.freeze(wrappedState) 7919 } 7920 7921 // initialize the store hooks, get the send() function 7922 // obj? -> fn 7923 function start (opts) { 7924 opts = opts || {} 7925 assert.equal(typeof opts, 'object', 'barracks.store.start: opts should be undefined or an object') 7926 7927 // register values from the models
7928 models.forEach(function (model) { 7929 var ns = model.namespace 7930 if (!stateCalled && model.state && opts.state !== false) { 7931 var modelState = model.state || {} 7932 if (ns) { 7933 _state[ns] = _state[ns] || {} 7934 apply(ns, modelState, _state) 7935 } else { 7936 mutate(_state, modelState) 7937 } 7938 } 7939 if (!reducersCalled && model.reducers && opts.reducers !== false) { 7940 apply(ns, model.reducers, reducers, function (cb) { 7941 return wrapHook(cb, reducerWraps) 7942 }) 7943 } 7944 if (!effectsCalled && model.effects && opts.effects !== false) { 7945 apply(ns, model.effects, effects, function (cb) { 7946 return wrapHook(cb, effectWraps) 7947 }) 7948 } 7949 if (!subsCalled && model.subscriptions && opts.subscriptions !== false) { 7950 apply(ns, model.subscriptions, subscriptions, function (cb, key) { 7951 var send = createSend('subscription: ' + (ns ? ns + ':' + key : key)) 7952 cb = wrapHook(cb, subscriptionWraps) 7953 cb(send, function (err) { 7954 applyHook(onErrorHooks, err, _state, createSend) 7955 }) 7956 return cb 7957 }) 7958 } 7959 }) 7960 7961 // the state wrap is special because we want to operate on the full 7962 // state rather than indvidual chunks, so we apply it outside the loop 7963 if (!stateCalled && opts.state !== false) { 7964 _state = wrapHook(_state, initialStateWraps) 7965 } 7966 7967 if (!opts.noSubscriptions) subsCalled = true 7968 if (!opts.noReducers) reducersCalled = true 7969 if (!opts.noEffects) effectsCalled = true 7970 if (!opts.noState) stateCalled = true 7971 7972 if (!onErrorHooks.length) onErrorHooks.push(wrapOnError(defaultOnError)) 7973 7974 return createSend 7975 7976 // call an action from a view 7977 // (str, bool?) -> (str, any?, fn?) -> null 7978 function createSend (selfName, callOnError) { 7979 assert.equal(typeof selfName, 'string', 'barracks.store.start.createSend: selfName should be a string') 7980 assert.ok(!callOnError || typeof callOnError === 'boolean', 'barracks.store.start.send: callOnError should be undefined or a boolean') 7981 7982 return function send (name, data, cb) { 7983 if (!cb && !callOnError) { 7984 cb = data 7985 data = null 7986 } 7987 data = (typeof data === 'undefined' ? null : data) 7988 7989 assert.equal(typeof name, 'string', 'barracks.store.start.send: name should be a string') 7990 assert.ok(!cb || typeof cb === 'function', 'barracks.store.start.send: cb should be a function') 7991 7992 var done = callOnError ? onErrorCallback : cb 7993 _send(name, data, selfName, done) 7994 7995 function onErrorCallback (err) { 7996 err = err || null 7997 if (err) { 7998 applyHook(onErrorHooks, err, _state, function createSend (selfName) { 7999 return function send (name, data) { 8000 assert.equal(typeof name, 'string', 'barracks.store.start.send: name should be a string') 8001 data = (typeof data === 'undefined' ? null : data) 8002 _send(name, data, selfName, done) 8003 } 8004 }) 8005 } 8006 } 8007 } 8008 } 8009 8010 // call an action 8011 // (str, str, any, fn) -> null 8012 function _send (name, data, caller, cb) { 8013 if (stopped) return 8014 8015 assert.equal(typeof name, 'string', 'barracks._send: name should be a string') 8016 assert.equal(typeof caller, 'string', 'barracks._send: caller should be a string') 8017 assert.equal(typeof cb, 'function', 'barracks._send: cb should be a function') 8018 8019 ;(tick(function () { 8020 var reducersCalled = false 8021 var effectsCalled = false 8022 var newState = xtend(_state) 8023 8024 if (onActionHooks.length) { 8025 applyHook(onActionHooks, _state, data, name, caller, createSend) 8026 } 8027 8028 // validate if a namespace exists. Namespaces are delimited by ':'. 8029 var actionName = name 8030 if (/:/.test(name)) { 8031 var arr = name.split(':') 8032 var ns = arr.shift() 8033 actionName = arr.join(':') 8034 } 8035 8036 var _reducers = ns ? reducers[ns] : reducers 8037 if (_reducers && _reducers[actionName]) { 8038 if (ns) { 8039 var reducedState = _reducers[actionName](_state[ns], data) 8040 newState[ns] = xtend(_state[ns], reducedState) 8041 } else { 8042 mutate(newState, reducers[actionName](_state, data)) 8043 } 8044 reducersCalled = true 8045 if (onStateChangeHooks.length) { 8046 applyHook(onStateChangeHooks, newState, data, _state, actionName, createSend) 8047 } 8048 _state = newState 8049 cb(null, newState) 8050 } 8051 8052 var _effects = ns ? effects[ns] : effects 8053 if (!reducersCalled && _effects && _effects[actionName]) { 8054 var send = createSend('effect: ' + name) 8055 if (ns) _effects[actionName](_state[ns], data, send, cb) 8056 else _effects[actionName](_state, data, send, cb) 8057 effectsCalled = true 8058 } 8059 8060 if (!reducersCalled && !effectsCalled) { 8061 throw new Error('Could not find action ' + actionName) 8062 } 8063 }))() 8064 } 8065 } 8066 8067 // stop an app, essentially turns 8068 // all send() calls into no-ops. 8069 // () -> null 8070 function stop () { 8071 stopped = true 8072 } 8073} 8074
8075// compose an object conditionally 8076// optionally contains a namespace 8077// which is used to nest properties. 8078// (str, obj, obj, fn?) -> null 8079function apply (ns, source, target, wrap) { 8080 if (ns && !target[ns]) target[ns] = {} 8081 Object.keys(source).forEach(function (key) { 8082 var cb = wrap ? wrap(source[key], key) : source[key] 8083 if (ns) target[ns][key] = cb 8084 else target[key] = cb 8085 }) 8086} 8087 8088// handle errors all the way at the top of the trace 8089// err? -> null 8090function defaultOnError (err) { 8091 throw err 8092} 8093 8094function wrapOnError (onError) { 8095 return function onErrorWrap (err, state, createSend) { 8096 if (err) onError(err, state, createSend) 8097 } 8098} 8099 8100// take a apply an array of transforms onto a value. The new value 8101// must be returned synchronously from the transform 8102// (any, [fn]) -> any 8103function wrapHook (value, transforms) { 8104 transforms.forEach(function (transform) { 8105 value = transform(value) 8106 }) 8107 return value 8108} 8109 8110},{"./apply-hook":79,"assert":78,"nanotick":174,"xtend":251,"xtend/mutable":252}],81:[function(require,module,exports){ 8111'use strict' 8112 8113exports.byteLength = byteLength 8114exports.toByteArray = toByteArray 8115exports.fromByteArray = fromByteArray 8116 8117var lookup = [] 8118var revLookup = [] 8119var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array 8120 8121var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' 8122for (var i = 0, len = code.length; i < len; ++i) { 8123 lookup[i] = code[i] 8124 revLookup[code.charCodeAt(i)] = i 8125} 8126 8127revLookup['-'.charCodeAt(0)] = 62 8128revLookup['_'.charCodeAt(0)] = 63 8129 8130function placeHoldersCount (b64) { 8131 var len = b64.length 8132 if (len % 4 > 0) { 8133 throw new Error('Invalid string. Length must be a multiple of 4') 8134 } 8135 8136 // the number of equal signs (place holders) 8137 // if there are two placeholders, than the two characters before it 8138 // represent one byte 8139 // if there is only one, then the three characters before it represent 2 bytes 8140 // this is just a cheap hack to not do indexOf twice 8141 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 8142} 8143 8144function byteLength (b64) { 8145 // base64 is 4/3 + up to two characters of the original data 8146 return (b64.length * 3 / 4) - placeHoldersCount(b64) 8147} 8148 8149function toByteArray (b64) { 8150 var i, l, tmp, placeHolders, arr 8151 var len = b64.length 8152 placeHolders = placeHoldersCount(b64) 8153 8154 arr = new Arr((len * 3 / 4) - placeHolders) 8155 8156 // if there are placeholders, only get up to the last complete 4 chars 8157 l = placeHolders > 0 ? len - 4 : len 8158 8159 var L = 0 8160 8161 for (i = 0; i < l; i += 4) { 8162 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] 8163 arr[L++] = (tmp >> 16) & 0xFF 8164 arr[L++] = (tmp >> 8) & 0xFF 8165 arr[L++] = tmp & 0xFF 8166 } 8167 8168 if (placeHolders === 2) { 8169 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) 8170 arr[L++] = tmp & 0xFF 8171 } else if (placeHolders === 1) { 8172 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) 8173 arr[L++] = (tmp >> 8) & 0xFF 8174 arr[L++] = tmp & 0xFF 8175 } 8176 8177 return arr 8178} 8179 8180function tripletToBase64 (num) { 8181 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] 8182} 8183 8184function encodeChunk (uint8, start, end) { 8185 var tmp 8186 var output = [] 8187 for (var i = start; i < end; i += 3) { 8188 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) 8189 output.push(tripletToBase64(tmp)) 8190 } 8191 return output.join('') 8192} 8193 8194function fromByteArray (uint8) { 8195 var tmp 8196 var len = uint8.length 8197 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes 8198 var output = '' 8199 var parts = [] 8200 var maxChunkLength = 16383 // must be multiple of 3 8201 8202 // go through the array every three bytes, we'll deal with trailing stuff later 8203 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { 8204 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) 8205 } 8206 8207 // pad the end with zeros, but make sure to not forget the extra bytes 8208 if (extraBytes === 1) { 8209 tmp = uint8[len - 1] 8210 output += lookup[tmp >> 2] 8211 output += lookup[(tmp << 4) & 0x3F] 8212 output += '==' 8213 } else if (extraBytes === 2) { 8214 tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) 8215 output += lookup[tmp >> 10] 8216 output += lookup[(tmp >> 4) & 0x3F] 8217 output += lookup[(tmp << 2) & 0x3F] 8218 output += '=' 8219 } 8220 8221 parts.push(output) 8222 8223 return parts.join('') 8224} 8225 8226},{}],82:[function(require,module,exports){ 8227var document = require('global/document') 8228var hyperx = require('hyperx') 8229var onload = require('on-load') 8230 8231var SVGNS = 'http://www.w3.org/2000/svg' 8232var XLINKNS = 'http://www.w3.org/1999/xlink' 8233 8234var BOOL_PROPS = { 8235 autofocus: 1, 8236 checked: 1, 8237 defaultchecked: 1, 8238 disabled: 1, 8239 formnovalidate: 1, 8240 indeterminate: 1, 8241 readonly: 1, 8242 required: 1, 8243 selected: 1, 8244 willvalidate: 1 8245} 8246var SVG_TAGS = [ 8247 'svg', 8248 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor', 8249 'animateMotion', 'animateTransform', 'circle', 'clipPath', 'color-profile', 8250 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix', 8251 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 8252 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 8253 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 8254 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 8255 'feSpotLight', 'feTile', 'feTurbulence', 'filter', 'font', 'font-face', 8256 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 8257 'foreignObject', 'g', 'glyph', 'glyphRef', 'hkern', 'image', 'line', 8258 'linearGradient', 'marker', 'mask', 'metadata', 'missing-glyph', 'mpath', 8259 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 8260 'set', 'stop', 'switch', 'symbol', 'text', 'textPath', 'title', 'tref', 8261 'tspan', 'use', 'view', 'vkern' 8262] 8263 8264function belCreateElement (tag, props, children) { 8265 var el 8266 8267 // If an svg tag, it needs a namespace 8268 if (SVG_TAGS.indexOf(tag) !== -1) { 8269 props.namespace = SVGNS 8270 } 8271 8272 // If we are using a namespace 8273 var ns = false 8274 if (props.namespace) { 8275 ns = props.namespace 8276 delete props.namespace 8277 } 8278 8279 // Create the element 8280 if (ns) { 8281 el = document.createElementNS(ns, tag) 8282 } else { 8283 el = document.createElement(tag) 8284 } 8285 8286 // If adding onload events 8287 if (props.onload || props.onunload) { 8288 var load = props.onload || function () {} 8289 var unload = props.onunload || function () {} 8290 onload(el, function belOnload () { 8291 load(el) 8292 }, function belOnunload () { 8293 unload(el) 8294 }, 8295 // We have to use non-standard `caller` to find who invokes `belCreateElement` 8296 belCreateElement.caller.caller.caller) 8297 delete props.onload 8298 delete props.onunload 8299 } 8300 8301 // Create the properties 8302 for (var p in props) { 8303 if (props.hasOwnProperty(p)) { 8304 var key = p.toLowerCase() 8305 var val = props[p] 8306 // Normalize className 8307 if (key === 'classname') { 8308 key = 'class' 8309 p = 'class' 8310 } 8311 // The for attribute gets transformed to htmlFor, but we just set as for 8312 if (p === 'htmlFor') { 8313 p = 'for' 8314 } 8315 // If a property is boolean, set itself to the key 8316 if (BOOL_PROPS[key]) { 8317 if (val === 'true') val = key 8318 else if (val === 'false') continue 8319 } 8320 // If a property prefers being set directly vs setAttribute 8321 if (key.slice(0, 2) === 'on') { 8322 el[p] = val 8323 } else { 8324 if (ns) { 8325 if (p === 'xlink:href') { 8326 el.setAttributeNS(XLINKNS, p, val) 8327 } else if (/^xmlns($|:)/i.test(p)) { 8328 // skip xmlns definitions 8329 } else { 8330 el.setAttributeNS(null, p, val) 8331 } 8332 } else { 8333 el.setAttribute(p, val) 8334 } 8335 } 8336 } 8337 } 8338 8339 function appendChild (childs) { 8340 if (!Array.isArray(childs)) return 8341 for (var i = 0; i < childs.length; i++) { 8342 var node = childs[i] 8343 if (Array.isArray(node)) { 8344 appendChild(node) 8345 continue 8346 } 8347 8348 if (typeof node === 'number' || 8349 typeof node === 'boolean' || 8350 node instanceof Date || 8351 node instanceof RegExp) { 8352 node = node.toString() 8353 } 8354 8355 if (typeof node === 'string') { 8356 if (el.lastChild && el.lastChild.nodeName === '#text') { 8357 el.lastChild.nodeValue += node 8358 continue 8359 } 8360 node = document.createTextNode(node) 8361 } 8362 8363 if (node && node.nodeType) { 8364 el.appendChild(node) 8365 } 8366 } 8367 } 8368 appendChild(children) 8369 8370 return el 8371} 8372 8373module.exports = hyperx(belCreateElement) 8374module.exports.default = module.exports 8375module.exports.createElement = belCreateElement 8376 8377},{"global/document":157,"hyperx":162,"on-load":176}],83:[function(require,module,exports){ 8378 8379},{}],84
vendor: 5,461 bytes, lines 8379-8565
8379:[function(require,module,exports){ 8380// shim for using process in browser 8381var process = module.exports = {}; 8382 8383// cached from whatever global is present so that test runners that stub it 8384// don't break things. But we need to wrap it in a try catch in case it is 8385// wrapped in strict mode code which doesn't define any globals. It's inside a 8386// function because try/catches deoptimize in certain engines. 8387 8388var cachedSetTimeout; 8389var cachedClearTimeout; 8390 8391function defaultSetTimout() { 8392 throw new Error('setTimeout has not been defined'); 8393} 8394function defaultClearTimeout () { 8395 throw new Error('clearTimeout has not been defined'); 8396} 8397(function () { 8398 try { 8399 if (typeof setTimeout === 'function') { 8400 cachedSetTimeout = setTimeout; 8401 } else { 8402 cachedSetTimeout = defaultSetTimout; 8403 } 8404 } catch (e) { 8405 cachedSetTimeout = defaultSetTimout; 8406 } 8407 try { 8408 if (typeof clearTimeout === 'function') { 8409 cachedClearTimeout = clearTimeout; 8410 } else { 8411 cachedClearTimeout = defaultClearTimeout; 8412 } 8413 } catch (e) { 8414 cachedClearTimeout = defaultClearTimeout; 8415 } 8416} ()) 8417function runTimeout(fun) { 8418 if (cachedSetTimeout === setTimeout) { 8419 //normal enviroments in sane situations 8420 return setTimeout(fun, 0); 8421 } 8422 // if setTimeout wasn't available but was latter defined 8423 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { 8424 cachedSetTimeout = setTimeout; 8425 return setTimeout(fun, 0); 8426 } 8427 try { 8428 // when when somebody has screwed with setTimeout but no I.E. maddness 8429 return cachedSetTimeout(fun, 0); 8430 } catch(e){ 8431 try { 8432 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally 8433 return cachedSetTimeout.call(null, fun, 0); 8434 } catch(e){ 8435 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error 8436 return cachedSetTimeout.call(this, fun, 0); 8437 } 8438 } 8439 8440 8441} 8442function runClearTimeout(marker) { 8443 if (cachedClearTimeout === clearTimeout) { 8444 //normal enviroments in sane situations 8445 return clearTimeout(marker); 8446 } 8447 // if clearTimeout wasn't available but was latter defined 8448 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { 8449 cachedClearTimeout = clearTimeout; 8450 return clearTimeout(marker); 8451 } 8452 try { 8453 // when when somebody has screwed with setTimeout but no I.E. maddness 8454 return cachedClearTimeout(marker); 8455 } catch (e){ 8456 try { 8457 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally 8458 return cachedClearTimeout.call(null, marker); 8459 } catch (e){ 8460 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. 8461 // Some versions of I.E. have different rules for clearTimeout vs setTimeout 8462 return cachedClearTimeout.call(this, marker); 8463 } 8464 } 8465 8466 8467 8468} 8469var queue = []; 8470var draining = false; 8471var currentQueue; 8472var queueIndex = -1; 8473 8474function cleanUpNextTick() { 8475 if (!draining || !currentQueue) { 8476 return; 8477 } 8478 draining = false; 8479 if (currentQueue.length) { 8480 queue = currentQueue.concat(queue); 8481 } else { 8482 queueIndex = -1; 8483 } 8484 if (queue.length) { 8485 drainQueue(); 8486 } 8487} 8488 8489function drainQueue() { 8490 if (draining) { 8491 return; 8492 } 8493 var timeout = runTimeout(cleanUpNextTick); 8494 draining = true; 8495 8496 var len = queue.length; 8497 while(len) { 8498 currentQueue = queue; 8499 queue = []; 8500 while (++queueIndex < len) { 8501 if (currentQueue) { 8502 currentQueue[queueIndex].run(); 8503 } 8504 } 8505 queueIndex = -1; 8506 len = queue.length; 8507 } 8508 currentQueue = null; 8509 draining = false; 8510 runClearTimeout(timeout); 8511} 8512 8513process.nextTick = function (fun) { 8514 var args = new Array(arguments.length - 1); 8515 if (arguments.length > 1) { 8516 for (var i = 1; i < arguments.length; i++) { 8517 args[i - 1] = arguments[i]; 8518 } 8519 } 8520 queue.push(new Item(fun, args)); 8521 if (queue.length === 1 && !draining) { 8522 runTimeout(drainQueue); 8523 } 8524}; 8525 8526// v8 likes predictible objects 8527function Item(fun, array) { 8528 this.fun = fun; 8529 this.array = array; 8530} 8531Item.prototype.run = function () { 8532 this.fun.apply(null, this.array); 8533}; 8534process.title = 'browser'; 8535process.browser = true; 8536process.env = {}; 8537process.argv = []; 8538process.version = ''; // empty string to avoid regexp issues 8539process.versions = {}; 8540 8541function noop() {} 8542 8543process.on = noop; 8544process.addListener = noop; 8545process.once = noop; 8546process.off = noop; 8547process.removeListener = noop; 8548process.removeAllListeners = noop; 8549process.emit = noop; 8550process.prependListener = noop; 8551process.prependOnceListener = noop; 8552 8553process.listeners = function (name) { return [] } 8554 8555process.binding = function (name) { 8556 throw new Error('process.binding is not supported'); 8557}; 8558 8559process.cwd = function () { return '/' }; 8560process.chdir = function (dir) { 8561 throw new Error('process.chdir is not supported'); 8562}; 8563process.umask = function() { return 0; }; 8564 8565},{}],
vendor: 3,291 bytes, lines 8565-8676
856585:[function(require,module,exports){ 8566(function (global){ 8567'use strict'; 8568 8569var buffer = require('buffer'); 8570var Buffer = buffer.Buffer; 8571var SlowBuffer = buffer.SlowBuffer; 8572var MAX_LEN = buffer.kMaxLength || 2147483647; 8573exports.alloc = function alloc(size, fill, encoding) { 8574 if (typeof Buffer.alloc === 'function') { 8575 return Buffer.alloc(size, fill, encoding); 8576 } 8577 if (typeof encoding === 'number') { 8578 throw new TypeError('encoding must not be number'); 8579 } 8580 if (typeof size !== 'number') { 8581 throw new TypeError('size must be a number'); 8582 } 8583 if (size > MAX_LEN) { 8584 throw new RangeError('size is too large'); 8585 } 8586 var enc = encoding; 8587 var _fill = fill; 8588 if (_fill === undefined) { 8589 enc = undefined; 8590 _fill = 0; 8591 } 8592 var buf = new Buffer(size); 8593 if (typeof _fill === 'string') { 8594 var fillBuf = new Buffer(_fill, enc); 8595 var flen = fillBuf.length; 8596 var i = -1; 8597 while (++i < size) { 8598 buf[i] = fillBuf[i % flen]; 8599 } 8600 } else { 8601 buf.fill(_fill); 8602 } 8603 return buf; 8604} 8605exports.allocUnsafe = function allocUnsafe(size) { 8606 if (typeof Buffer.allocUnsafe === 'function') { 8607 return Buffer.allocUnsafe(size); 8608 } 8609 if (typeof size !== 'number') { 8610 throw new TypeError('size must be a number'); 8611 } 8612 if (size > MAX_LEN) { 8613 throw new RangeError('size is too large'); 8614 } 8615 return new Buffer(size); 8616} 8617exports.from = function from(value, encodingOrOffset, length) { 8618 if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { 8619 return Buffer.from(value, encodingOrOffset, length); 8620 } 8621 if (typeof value === 'number') { 8622 throw new TypeError('"value" argument must not be a number'); 8623 } 8624 if (typeof value === 'string') { 8625 return new Buffer(value, encodingOrOffset); 8626 } 8627 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { 8628 var offset = encodingOrOffset; 8629 if (arguments.length === 1) { 8630 return new Buffer(value); 8631 } 8632 if (typeof offset === 'undefined') { 8633 offset = 0; 8634 } 8635 var len = length; 8636 if (typeof len === 'undefined') { 8637 len = value.byteLength - offset; 8638 } 8639 if (offset >= value.byteLength) { 8640 throw new RangeError('\'offset\' is out of bounds'); 8641 } 8642 if (len > value.byteLength - offset) { 8643 throw new RangeError('\'length\' is out of bounds'); 8644 } 8645 return new Buffer(value.slice(offset, offset + len)); 8646 } 8647 if (Buffer.isBuffer(value)) { 8648 var out = new Buffer(value.length); 8649 value.copy(out, 0, 0, value.length); 8650 return out; 8651 } 8652 if (value) { 8653 if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { 8654 return new Buffer(value); 8655 } 8656 if (value.type === 'Buffer' && Array.isArray(value.data)) { 8657 return new Buffer(value.data); 8658 } 8659 } 8660 8661 throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); 8662} 8663exports.allocUnsafeSlow = function allocUnsafeSlow(size) { 8664 if (typeof Buffer.allocUnsafeSlow === 'function') { 8665 return Buffer.allocUnsafeSlow(size); 8666 } 8667 if (typeof size !== 'number') { 8668 throw new TypeError('size must be a number'); 8669 } 8670 if (size >= MAX_LEN) { 8671 throw new RangeError('size is too large'); 8672 } 8673 return new SlowBuffer(size); 8674} 8675 8676}
8676).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 8677},{"buffer":86}],86:[function(require,module,exports){ 8678/*! 8679 * The buffer module from node.js, for the browser. 8680 * 8681 * @author Feross Aboukhadijeh <https://feross.org> 8682 * @license MIT 8683 */ 8684/* eslint-disable no-proto */ 8685 8686'use strict' 8687 8688var base64 = require('base64-js') 8689var ieee754 = require('ieee754') 8690 8691exports.Buffer = Buffer 8692exports.SlowBuffer = SlowBuffer 8693exports.INSPECT_MAX_BYTES = 50 8694 8695var K_MAX_LENGTH = 0x7fffffff 8696exports.kMaxLength = K_MAX_LENGTH 8697 8698/** 8699 * If `Buffer.TYPED_ARRAY_SUPPORT`: 8700 * === true Use Uint8Array implementation (fastest) 8701 * === false Print warning and recommend using `buffer` v4.x which has an Object 8702 * implementation (most compatible, even IE6) 8703 * 8704 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, 8705 * Opera 11.6+, iOS 4.2+. 8706 * 8707 * We report that the browser does not support typed arrays if the are not subclassable 8708 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` 8709 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support 8710 * for __proto__ and has a buggy typed array implementation. 8711 */ 8712Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() 8713 8714if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && 8715 typeof console.error === 'function') { 8716 console.error( 8717 'This browser lacks typed array (Uint8Array) support which is required by ' + 8718 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' 8719 ) 8720} 8721 8722function typedArraySupport () { 8723 // Can typed array instances can be augmented? 8724 try { 8725 var arr = new Uint8Array(1) 8726 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} 8727 return arr.foo() === 42 8728 } catch (e) { 8729 return false 8730 } 8731} 8732 8733function createBuffer (length) { 8734 if (length > K_MAX_LENGTH) { 8735 throw new RangeError('Invalid typed array length') 8736 } 8737 // Return an augmented `Uint8Array` instance 8738 var buf = new Uint8Array(length) 8739 buf.__proto__ = Buffer.prototype 8740 return buf 8741} 8742 8743/** 8744 * The Buffer constructor returns instances of `Uint8Array` that have their 8745 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of 8746 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods 8747 * and the `Uint8Array` methods. Square bracket notation works as expected -- it 8748 * returns a single octet. 8749 * 8750 * The `Uint8Array` prototype remains unmodified. 8751 */ 8752 8753function Buffer (arg, encodingOrOffset, length) { 8754 // Common case. 8755 if (typeof arg === 'number') { 8756 if (typeof encodingOrOffset === 'string') { 8757 throw new Error( 8758 'If encoding is specified then the first argument must be a string' 8759 ) 8760 } 8761 return allocUnsafe(arg) 8762 } 8763 return from(arg, encodingOrOffset, length) 8764} 8765 8766// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 8767if (typeof Symbol !== 'undefined' && Symbol.species && 8768 Buffer[Symbol.species] === Buffer) { 8769 Object.defineProperty(Buffer, Symbol.species, { 8770 value: null, 8771 configurable: true, 8772 enumerable: false, 8773 writable: false 8774 }) 8775} 8776 8777Buffer.poolSize = 8192 // not used by this implementation 8778 8779function from (value, encodingOrOffset, length) { 8780 if (typeof value === 'number') { 8781 throw new TypeError('"value" argument must not be a number') 8782 } 8783 8784 if (isArrayBuffer(value)) { 8785 return fromArrayBuffer(value, encodingOrOffset, length) 8786 } 8787 8788 if (typeof value === 'string') { 8789 return fromString(value, encodingOrOffset) 8790 } 8791 8792 return fromObject(value) 8793} 8794 8795/** 8796 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError 8797 * if value is a number. 8798 * Buffer.from(str[, encoding]) 8799 * Buffer.from(array) 8800 * Buffer.from(buffer) 8801 * Buffer.from(arrayBuffer[, byteOffset[, length]]) 8802 **/ 8803Buffer.from = function (value, encodingOrOffset, length) { 8804 return from(value, encodingOrOffset, length) 8805} 8806 8807// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: 8808// https://github.com/feross/buffer/pull/148 8809Buffer.prototype.__proto__ = Uint8Array.prototype 8810Buffer.__proto__ = Uint8Array 8811 8812function assertSize (size) { 8813 if (typeof size !== 'number') { 8814 throw new TypeError('"size" argument must be a number') 8815 } else if (size < 0) { 8816 throw new RangeError('"size" argument must not be negative') 8817 } 8818} 8819 8820function alloc (size, fill, encoding) { 8821 assertSize(size) 8822 if (size <= 0) { 8823 return createBuffer(size) 8824 } 8825 if (fill !== undefined) { 8826 // Only pay attention to encoding if it's a string. This 8827 // prevents accidentally sending in a number that would 8828 // be interpretted as a start offset. 8829 return typeof encoding === 'string' 8830 ? createBuffer(size).fill(fill, encoding) 8831 : createBuffer(size).fill(fill) 8832 } 8833 return createBuffer(size) 8834} 8835 8836/** 8837 * Creates a new filled Buffer instance. 8838 * alloc(size[, fill[, encoding]]) 8839 **/ 8840Buffer.alloc = function (size, fill, encoding) { 8841 return alloc(size, fill, encoding) 8842} 8843 8844function allocUnsafe (size) { 8845 assertSize(size) 8846 return createBuffer(size < 0 ? 0 : checked(size) | 0) 8847} 8848 8849/** 8850 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. 8851 * */ 8852Buffer.allocUnsafe = function (size) { 8853 return allocUnsafe(size) 8854} 8855/** 8856 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. 8857 */ 8858Buffer.allocUnsafeSlow = function (size) { 8859 return allocUnsafe(size) 8860} 8861 8862function fromString (string, encoding) { 8863 if (typeof encoding !== 'string' || encoding === '') { 8864 encoding = 'utf8' 8865 } 8866 8867 if (!Buffer.isEncoding(encoding)) { 8868 throw new TypeError('"encoding" must be a valid string encoding') 8869 } 8870 8871 var length = byteLength(string, encoding) | 0 8872 var buf = createBuffer(length) 8873 8874 var actual = buf.write(string, encoding) 8875 8876 if (actual !== length) {
8877 // Writing a hex string, for example, that contains invalid characters will 8878 // cause everything after the first invalid character to be ignored. (e.g. 8879 // 'abxxcd' will be treated as 'ab') 8880 buf = buf.slice(0, actual) 8881 } 8882 8883 return buf 8884} 8885 8886function fromArrayLike (array) { 8887 var length = array.length < 0 ? 0 : checked(array.length) | 0 8888 var buf = createBuffer(length) 8889 for (var i = 0; i < length; i += 1) { 8890 buf[i] = array[i] & 255 8891 } 8892 return buf 8893} 8894 8895function fromArrayBuffer (array, byteOffset, length) { 8896 if (byteOffset < 0 || array.byteLength < byteOffset) { 8897 throw new RangeError('\'offset\' is out of bounds') 8898 } 8899 8900 if (array.byteLength < byteOffset + (length || 0)) { 8901 throw new RangeError('\'length\' is out of bounds') 8902 } 8903 8904 var buf 8905 if (byteOffset === undefined && length === undefined) { 8906 buf = new Uint8Array(array) 8907 } else if (length === undefined) { 8908 buf = new Uint8Array(array, byteOffset) 8909 } else { 8910 buf = new Uint8Array(array, byteOffset, length) 8911 } 8912 8913 // Return an augmented `Uint8Array` instance 8914 buf.__proto__ = Buffer.prototype 8915 return buf 8916} 8917 8918function fromObject (obj) { 8919 if (Buffer.isBuffer(obj)) { 8920 var len = checked(obj.length) | 0 8921 var buf = createBuffer(len) 8922 8923 if (buf.length === 0) { 8924 return buf 8925 } 8926 8927 obj.copy(buf, 0, 0, len) 8928 return buf 8929 } 8930 8931 if (obj) { 8932 if (isArrayBufferView(obj) || 'length' in obj) { 8933 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { 8934 return createBuffer(0) 8935 } 8936 return fromArrayLike(obj) 8937 } 8938 8939 if (obj.type === 'Buffer' && Array.isArray(obj.data)) { 8940 return fromArrayLike(obj.data) 8941 } 8942 } 8943 8944 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') 8945} 8946 8947function checked (length) { 8948 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when 8949 // length is NaN (which is otherwise coerced to zero.) 8950 if (length >= K_MAX_LENGTH) { 8951 throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 8952 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') 8953 } 8954 return length | 0 8955} 8956 8957function SlowBuffer (length) { 8958 if (+length != length) { // eslint-disable-line eqeqeq 8959 length = 0 8960 } 8961 return Buffer.alloc(+length) 8962} 8963 8964Buffer.isBuffer = function isBuffer (b) { 8965 return b != null && b._isBuffer === true 8966} 8967 8968Buffer.compare = function compare (a, b) { 8969 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { 8970 throw new TypeError('Arguments must be Buffers') 8971 } 8972 8973 if (a === b) return 0 8974 8975 var x = a.length 8976 var y = b.length 8977 8978 for (var i = 0, len = Math.min(x, y); i < len; ++i) { 8979 if (a[i] !== b[i]) { 8980 x = a[i] 8981 y = b[i] 8982 break 8983 } 8984 } 8985 8986 if (x < y) return -1 8987 if (y < x) return 1 8988 return 0 8989} 8990 8991Buffer.isEncoding = function isEncoding (encoding) { 8992 switch (String(encoding).toLowerCase()) { 8993 case 'hex': 8994 case 'utf8': 8995 case 'utf-8': 8996 case 'ascii': 8997 case 'latin1': 8998 case 'binary': 8999 case 'base64': 9000 case 'ucs2': 9001 case 'ucs-2': 9002 case 'utf16le': 9003 case 'utf-16le': 9004 return true 9005 default: 9006 return false 9007 } 9008} 9009 9010Buffer.concat = function concat (list, length) { 9011 if (!Array.isArray(list)) { 9012 throw new TypeError('"list" argument must be an Array of Buffers') 9013 } 9014 9015 if (list.length === 0) { 9016 return Buffer.alloc(0) 9017 } 9018 9019 var i 9020 if (length === undefined) { 9021 length = 0 9022 for (i = 0; i < list.length; ++i) { 9023 length += list[i].length 9024 } 9025 } 9026 9027 var buffer = Buffer.allocUnsafe(length) 9028 var pos = 0 9029 for (i = 0; i < list.length; ++i) { 9030 var buf = list[i] 9031 if (!Buffer.isBuffer(buf)) { 9032 throw new TypeError('"list" argument must be an Array of Buffers') 9033 } 9034 buf.copy(buffer, pos) 9035 pos += buf.length 9036 } 9037 return buffer 9038} 9039 9040function byteLength (string, encoding) { 9041 if (Buffer.isBuffer(string)) { 9042 return string.length 9043 } 9044 if (isArrayBufferView(string) || isArrayBuffer(string)) { 9045 return string.byteLength 9046 } 9047 if (typeof string !== 'string') { 9048 string = '' + string 9049 } 9050 9051 var len = string.length 9052 if (len === 0) return 0 9053 9054 // Use a for loop to avoid recursion 9055 var loweredCase = false 9056 for (;;) { 9057 switch (encoding) { 9058 case 'ascii': 9059 case 'latin1': 9060 case 'binary': 9061 return len 9062 case 'utf8': 9063 case 'utf-8': 9064 case undefined: 9065 return utf8ToBytes(string).length 9066 case 'ucs2': 9067 case 'ucs-2': 9068 case 'utf16le': 9069 case 'utf-16le': 9070 return len * 2 9071 case 'hex': 9072 return len >>> 1 9073 case 'base64': 9074 return base64ToBytes(string).length 9075 default: 9076 if (loweredCase) return utf8ToBytes(string).length // assume utf8 9077 encoding = ('' + encoding).toLowerCase() 9078 loweredCase = true 9079 } 9080 } 9081} 9082Buffer.byteLength = byteLength 9083 9084function slowToString (encoding, start, end) { 9085 var loweredCase = false 9086 9087 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only 9088 // property of a typed array.
vendor: 6,395 bytes, lines 9089-9332
9089 9090 // This behaves neither like String nor Uint8Array in that we set start/end 9091 // to their upper/lower bounds if the value passed is out of range. 9092 // undefined is handled specially as per ECMA-262 6th Edition, 9093 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. 9094 if (start === undefined || start < 0) { 9095 start = 0 9096 } 9097 // Return early if start > this.length. Done here to prevent potential uint32 9098 // coercion fail below. 9099 if (start > this.length) { 9100 return '' 9101 } 9102 9103 if (end === undefined || end > this.length) { 9104 end = this.length 9105 } 9106 9107 if (end <= 0) { 9108 return '' 9109 } 9110 9111 // Force coersion to uint32. This will also coerce falsey/NaN values to 0. 9112 end >>>= 0 9113 start >>>= 0 9114 9115 if (end <= start) { 9116 return '' 9117 } 9118 9119 if (!encoding) encoding = 'utf8' 9120 9121 while (true) { 9122 switch (encoding) { 9123 case 'hex': 9124 return hexSlice(this, start, end) 9125 9126 case 'utf8': 9127 case 'utf-8': 9128 return utf8Slice(this, start, end) 9129 9130 case 'ascii': 9131 return asciiSlice(this, start, end) 9132 9133 case 'latin1': 9134 case 'binary': 9135 return latin1Slice(this, start, end) 9136 9137 case 'base64': 9138 return base64Slice(this, start, end) 9139 9140 case 'ucs2': 9141 case 'ucs-2': 9142 case 'utf16le': 9143 case 'utf-16le': 9144 return utf16leSlice(this, start, end) 9145 9146 default: 9147 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) 9148 encoding = (encoding + '').toLowerCase() 9149 loweredCase = true 9150 } 9151 } 9152} 9153 9154// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) 9155// to detect a Buffer instance. It's not possible to use `instanceof Buffer` 9156// reliably in a browserify context because there could be multiple different 9157// copies of the 'buffer' package in use. This method works even for Buffer 9158// instances that were created from another copy of the `buffer` package. 9159// See: https://github.com/feross/buffer/issues/154 9160Buffer.prototype._isBuffer = true 9161 9162function swap (b, n, m) { 9163 var i = b[n] 9164 b[n] = b[m] 9165 b[m] = i 9166} 9167 9168Buffer.prototype.swap16 = function swap16 () { 9169 var len = this.length 9170 if (len % 2 !== 0) { 9171 throw new RangeError('Buffer size must be a multiple of 16-bits') 9172 } 9173 for (var i = 0; i < len; i += 2) { 9174 swap(this, i, i + 1) 9175 } 9176 return this 9177} 9178 9179Buffer.prototype.swap32 = function swap32 () { 9180 var len = this.length 9181 if (len % 4 !== 0) { 9182 throw new RangeError('Buffer size must be a multiple of 32-bits') 9183 } 9184 for (var i = 0; i < len; i += 4) { 9185 swap(this, i, i + 3) 9186 swap(this, i + 1, i + 2) 9187 } 9188 return this 9189} 9190 9191Buffer.prototype.swap64 = function swap64 () { 9192 var len = this.length 9193 if (len % 8 !== 0) { 9194 throw new RangeError('Buffer size must be a multiple of 64-bits') 9195 } 9196 for (var i = 0; i < len; i += 8) { 9197 swap(this, i, i + 7) 9198 swap(this, i + 1, i + 6) 9199 swap(this, i + 2, i + 5) 9200 swap(this, i + 3, i + 4) 9201 } 9202 return this 9203} 9204 9205Buffer.prototype.toString = function toString () { 9206 var length = this.length 9207 if (length === 0) return '' 9208 if (arguments.length === 0) return utf8Slice(this, 0, length) 9209 return slowToString.apply(this, arguments) 9210} 9211 9212Buffer.prototype.equals = function equals (b) { 9213 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') 9214 if (this === b) return true 9215 return Buffer.compare(this, b) === 0 9216} 9217 9218Buffer.prototype.inspect = function inspect () { 9219 var str = '' 9220 var max = exports.INSPECT_MAX_BYTES 9221 if (this.length > 0) { 9222 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') 9223 if (this.length > max) str += ' ... ' 9224 } 9225 return '<Buffer ' + str + '>' 9226} 9227 9228Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { 9229 if (!Buffer.isBuffer(target)) { 9230 throw new TypeError('Argument must be a Buffer') 9231 } 9232 9233 if (start === undefined) { 9234 start = 0 9235 } 9236 if (end === undefined) { 9237 end = target ? target.length : 0 9238 } 9239 if (thisStart === undefined) { 9240 thisStart = 0 9241 } 9242 if (thisEnd === undefined) { 9243 thisEnd = this.length 9244 } 9245 9246 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { 9247 throw new RangeError('out of range index') 9248 } 9249 9250 if (thisStart >= thisEnd && start >= end) { 9251 return 0 9252 } 9253 if (thisStart >= thisEnd) { 9254 return -1 9255 } 9256 if (start >= end) { 9257 return 1 9258 } 9259 9260 start >>>= 0 9261 end >>>= 0 9262 thisStart >>>= 0 9263 thisEnd >>>= 0 9264 9265 if (this === target) return 0 9266 9267 var x = thisEnd - thisStart 9268 var y = end - start 9269 var len = Math.min(x, y) 9270 9271 var thisCopy = this.slice(thisStart, thisEnd) 9272 var targetCopy = target.slice(start, end) 9273 9274 for (var i = 0; i < len; ++i) { 9275 if (thisCopy[i] !== targetCopy[i]) { 9276 x = thisCopy[i] 9277 y = targetCopy[i] 9278 break 9279 } 9280 } 9281 9282 if (x < y) return -1 9283 if (y < x) return 1 9284 return 0 9285} 9286 9287// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, 9288// OR the last index of `val` in `buffer` at offset <= `byteOffset`. 9289// 9290// Arguments: 9291// - buffer - a Buffer to search 9292// - val - a string, Buffer, or number 9293// - byteOffset - an index into `buffer`; will be clamped to an int32 9294// - encoding - an optional encoding, relevant is val is a string 9295// - dir - true for indexOf, false for lastIndexOf 9296function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { 9297 // Empty buffer means no match 9298 if (buffer.length === 0) return -1 9299 9300 // Normalize byteOffset 9301 if (typeof byteOffset === 'string') { 9302 encoding = byteOffset 9303 byteOffset = 0 9304 } else if (byteOffset > 0x7fffffff) { 9305 byteOffset = 0x7fffffff 9306 } else if (byteOffset < -0x80000000) { 9307 byteOffset = -0x80000000 9308 } 9309 byteOffset = +byteOffset // Coerce to Number. 9310 if (numberIsNaN(byteOffset)) { 9311 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer 9312 byteOffset = dir ? 0 : (buffer.length - 1) 9313 } 9314 9315 // Normalize byteOffset: negative offsets start from the end of the buffer 9316 if (byteOffset < 0) byteOffset = buffer.length + byteOffset 9317 if (byteOffset >= buffer.length) { 9318 if (dir) return -1 9319 else byteOffset = buffer.length - 1 9320 } else if (byteOffset < 0) { 9321 if (dir) byteOffset = 0 9322 else return -1 9323 } 9324 9325 // Normalize val 9326 if (typeof val === 'string') { 9327 val = Buffer.from(val, encoding) 9328 } 9329 9330 // Finally, search either indexOf (if dir is true) or lastIndexOf 9331 if (Buffer.isBuffer(val)) { 9332 // Special case: looking for empty string/buffer always fail
vendor: 6,275 bytes, lines 9332-9563
9332s 9333 if (val.length === 0) { 9334 return -1 9335 } 9336 return arrayIndexOf(buffer, val, byteOffset, encoding, dir) 9337 } else if (typeof val === 'number') { 9338 val = val & 0xFF // Search for a byte value [0-255] 9339 if (typeof Uint8Array.prototype.indexOf === 'function') { 9340 if (dir) { 9341 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) 9342 } else { 9343 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) 9344 } 9345 } 9346 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) 9347 } 9348 9349 throw new TypeError('val must be string, number or Buffer') 9350} 9351 9352function arrayIndexOf (arr, val, byteOffset, encoding, dir) { 9353 var indexSize = 1 9354 var arrLength = arr.length 9355 var valLength = val.length 9356 9357 if (encoding !== undefined) { 9358 encoding = String(encoding).toLowerCase() 9359 if (encoding === 'ucs2' || encoding === 'ucs-2' || 9360 encoding === 'utf16le' || encoding === 'utf-16le') { 9361 if (arr.length < 2 || val.length < 2) { 9362 return -1 9363 } 9364 indexSize = 2 9365 arrLength /= 2 9366 valLength /= 2 9367 byteOffset /= 2 9368 } 9369 } 9370 9371 function read (buf, i) { 9372 if (indexSize === 1) { 9373 return buf[i] 9374 } else { 9375 return buf.readUInt16BE(i * indexSize) 9376 } 9377 } 9378 9379 var i 9380 if (dir) { 9381 var foundIndex = -1 9382 for (i = byteOffset; i < arrLength; i++) { 9383 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { 9384 if (foundIndex === -1) foundIndex = i 9385 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize 9386 } else { 9387 if (foundIndex !== -1) i -= i - foundIndex 9388 foundIndex = -1 9389 } 9390 } 9391 } else { 9392 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength 9393 for (i = byteOffset; i >= 0; i--) { 9394 var found = true 9395 for (var j = 0; j < valLength; j++) { 9396 if (read(arr, i + j) !== read(val, j)) { 9397 found = false 9398 break 9399 } 9400 } 9401 if (found) return i 9402 } 9403 } 9404 9405 return -1 9406} 9407 9408Buffer.prototype.includes = function includes (val, byteOffset, encoding) { 9409 return this.indexOf(val, byteOffset, encoding) !== -1 9410} 9411 9412Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { 9413 return bidirectionalIndexOf(this, val, byteOffset, encoding, true) 9414} 9415 9416Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { 9417 return bidirectionalIndexOf(this, val, byteOffset, encoding, false) 9418} 9419 9420function hexWrite (buf, string, offset, length) { 9421 offset = Number(offset) || 0 9422 var remaining = buf.length - offset 9423 if (!length) { 9424 length = remaining 9425 } else { 9426 length = Number(length) 9427 if (length > remaining) { 9428 length = remaining 9429 } 9430 } 9431 9432 // must be an even number of digits 9433 var strLen = string.length 9434 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') 9435 9436 if (length > strLen / 2) { 9437 length = strLen / 2 9438 } 9439 for (var i = 0; i < length; ++i) { 9440 var parsed = parseInt(string.substr(i * 2, 2), 16) 9441 if (numberIsNaN(parsed)) return i 9442 buf[offset + i] = parsed 9443 } 9444 return i 9445} 9446 9447function utf8Write (buf, string, offset, length) { 9448 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) 9449} 9450 9451function asciiWrite (buf, string, offset, length) { 9452 return blitBuffer(asciiToBytes(string), buf, offset, length) 9453} 9454 9455function latin1Write (buf, string, offset, length) { 9456 return asciiWrite(buf, string, offset, length) 9457} 9458 9459function base64Write (buf, string, offset, length) { 9460 return blitBuffer(base64ToBytes(string), buf, offset, length) 9461} 9462 9463function ucs2Write (buf, string, offset, length) { 9464 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) 9465} 9466 9467Buffer.prototype.write = function write (string, offset, length, encoding) { 9468 // Buffer#write(string) 9469 if (offset === undefined) { 9470 encoding = 'utf8' 9471 length = this.length 9472 offset = 0 9473 // Buffer#write(string, encoding) 9474 } else if (length === undefined && typeof offset === 'string') { 9475 encoding = offset 9476 length = this.length 9477 offset = 0 9478 // Buffer#write(string, offset[, length][, encoding]) 9479 } else if (isFinite(offset)) { 9480 offset = offset >>> 0 9481 if (isFinite(length)) { 9482 length = length >>> 0 9483 if (encoding === undefined) encoding = 'utf8' 9484 } else { 9485 encoding = length 9486 length = undefined 9487 } 9488 } else { 9489 throw new Error( 9490 'Buffer.write(string, encoding, offset[, length]) is no longer supported' 9491 ) 9492 } 9493 9494 var remaining = this.length - offset 9495 if (length === undefined || length > remaining) length = remaining 9496 9497 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { 9498 throw new RangeError('Attempt to write outside buffer bounds') 9499 } 9500 9501 if (!encoding) encoding = 'utf8' 9502 9503 var loweredCase = false 9504 for (;;) { 9505 switch (encoding) { 9506 case 'hex': 9507 return hexWrite(this, string, offset, length) 9508 9509 case 'utf8': 9510 case 'utf-8': 9511 return utf8Write(this, string, offset, length) 9512 9513 case 'ascii': 9514 return asciiWrite(this, string, offset, length) 9515 9516 case 'latin1': 9517 case 'binary': 9518 return latin1Write(this, string, offset, length) 9519 9520 case 'base64': 9521 // Warning: maxLength not taken into account in base64Write 9522 return base64Write(this, string, offset, length) 9523 9524 case 'ucs2': 9525 case 'ucs-2': 9526 case 'utf16le': 9527 case 'utf-16le': 9528 return ucs2Write(this, string, offset, length) 9529 9530 default: 9531 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) 9532 encoding = ('' + encoding).toLowerCase() 9533 loweredCase = true 9534 } 9535 } 9536} 9537 9538Buffer.prototype.toJSON = function toJSON () { 9539 return { 9540 type: 'Buffer', 9541 data: Array.prototype.slice.call(this._arr || this, 0) 9542 } 9543} 9544 9545function base64Slice (buf, start, end) { 9546 if (start === 0 && end === buf.length) { 9547 return base64.fromByteArray(buf) 9548 } else { 9549 return base64.fromByteArray(buf.slice(start, end)) 9550 } 9551} 9552 9553function utf8Slice (buf, start, end) { 9554 end = Math.min(buf.length, end) 9555 var res = [] 9556 9557 var i = start 9558 while (i < end) { 9559 var firstByte = buf[i] 9560 var codePoint = null 9561 var bytesPerSequence = (firstByte > 0xEF) ? 4 9562 : (firstByte > 0xDF) ? 3 9563 : (firstByte > 0xBF) ? 2
vendor: 16,210 bytes, lines 9564-10127
9564 : 1 9565 9566 if (i + bytesPerSequence <= end) { 9567 var secondByte, thirdByte, fourthByte, tempCodePoint 9568 9569 switch (bytesPerSequence) { 9570 case 1: 9571 if (firstByte < 0x80) { 9572 codePoint = firstByte 9573 } 9574 break 9575 case 2: 9576 secondByte = buf[i + 1] 9577 if ((secondByte & 0xC0) === 0x80) { 9578 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) 9579 if (tempCodePoint > 0x7F) { 9580 codePoint = tempCodePoint 9581 } 9582 } 9583 break 9584 case 3: 9585 secondByte = buf[i + 1] 9586 thirdByte = buf[i + 2] 9587 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { 9588 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) 9589 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { 9590 codePoint = tempCodePoint 9591 } 9592 } 9593 break 9594 case 4: 9595 secondByte = buf[i + 1] 9596 thirdByte = buf[i + 2] 9597 fourthByte = buf[i + 3] 9598 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { 9599 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) 9600 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { 9601 codePoint = tempCodePoint 9602 } 9603 } 9604 } 9605 } 9606 9607 if (codePoint === null) { 9608 // we did not generate a valid codePoint so insert a 9609 // replacement char (U+FFFD) and advance only 1 byte 9610 codePoint = 0xFFFD 9611 bytesPerSequence = 1 9612 } else if (codePoint > 0xFFFF) { 9613 // encode to utf16 (surrogate pair dance) 9614 codePoint -= 0x10000 9615 res.push(codePoint >>> 10 & 0x3FF | 0xD800) 9616 codePoint = 0xDC00 | codePoint & 0x3FF 9617 } 9618 9619 res.push(codePoint) 9620 i += bytesPerSequence 9621 } 9622 9623 return decodeCodePointsArray(res) 9624} 9625 9626// Based on http://stackoverflow.com/a/22747272/680742, the browser with 9627// the lowest limit is Chrome, with 0x10000 args. 9628// We go 1 magnitude less, for safety 9629var MAX_ARGUMENTS_LENGTH = 0x1000 9630 9631function decodeCodePointsArray (codePoints) { 9632 var len = codePoints.length 9633 if (len <= MAX_ARGUMENTS_LENGTH) { 9634 return String.fromCharCode.apply(String, codePoints) // avoid extra slice() 9635 } 9636 9637 // Decode in chunks to avoid "call stack size exceeded". 9638 var res = '' 9639 var i = 0 9640 while (i < len) { 9641 res += String.fromCharCode.apply( 9642 String, 9643 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) 9644 ) 9645 } 9646 return res 9647} 9648 9649function asciiSlice (buf, start, end) { 9650 var ret = '' 9651 end = Math.min(buf.length, end) 9652 9653 for (var i = start; i < end; ++i) { 9654 ret += String.fromCharCode(buf[i] & 0x7F) 9655 } 9656 return ret 9657} 9658 9659function latin1Slice (buf, start, end) { 9660 var ret = '' 9661 end = Math.min(buf.length, end) 9662 9663 for (var i = start; i < end; ++i) { 9664 ret += String.fromCharCode(buf[i]) 9665 } 9666 return ret 9667} 9668 9669function hexSlice (buf, start, end) { 9670 var len = buf.length 9671 9672 if (!start || start < 0) start = 0 9673 if (!end || end < 0 || end > len) end = len 9674 9675 var out = '' 9676 for (var i = start; i < end; ++i) { 9677 out += toHex(buf[i]) 9678 } 9679 return out 9680} 9681 9682function utf16leSlice (buf, start, end) { 9683 var bytes = buf.slice(start, end) 9684 var res = '' 9685 for (var i = 0; i < bytes.length; i += 2) { 9686 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) 9687 } 9688 return res 9689} 9690 9691Buffer.prototype.slice = function slice (start, end) { 9692 var len = this.length 9693 start = ~~start 9694 end = end === undefined ? len : ~~end 9695 9696 if (start < 0) { 9697 start += len 9698 if (start < 0) start = 0 9699 } else if (start > len) { 9700 start = len 9701 } 9702 9703 if (end < 0) { 9704 end += len 9705 if (end < 0) end = 0 9706 } else if (end > len) { 9707 end = len 9708 } 9709 9710 if (end < start) end = start 9711 9712 var newBuf = this.subarray(start, end) 9713 // Return an augmented `Uint8Array` instance 9714 newBuf.__proto__ = Buffer.prototype 9715 return newBuf 9716} 9717 9718/* 9719 * Need to make sure that buffer isn't trying to write out of bounds. 9720 */ 9721function checkOffset (offset, ext, length) { 9722 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') 9723 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') 9724} 9725 9726Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { 9727 offset = offset >>> 0 9728 byteLength = byteLength >>> 0 9729 if (!noAssert) checkOffset(offset, byteLength, this.length) 9730 9731 var val = this[offset] 9732 var mul = 1 9733 var i = 0 9734 while (++i < byteLength && (mul *= 0x100)) { 9735 val += this[offset + i] * mul 9736 } 9737 9738 return val 9739} 9740 9741Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { 9742 offset = offset >>> 0 9743 byteLength = byteLength >>> 0 9744 if (!noAssert) { 9745 checkOffset(offset, byteLength, this.length) 9746 } 9747 9748 var val = this[offset + --byteLength] 9749 var mul = 1 9750 while (byteLength > 0 && (mul *= 0x100)) { 9751 val += this[offset + --byteLength] * mul 9752 } 9753 9754 return val 9755} 9756 9757Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { 9758 offset = offset >>> 0 9759 if (!noAssert) checkOffset(offset, 1, this.length) 9760 return this[offset] 9761} 9762 9763Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { 9764 offset = offset >>> 0 9765 if (!noAssert) checkOffset(offset, 2, this.length) 9766 return this[offset] | (this[offset + 1] << 8) 9767} 9768 9769Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { 9770 offset = offset >>> 0 9771 if (!noAssert) checkOffset(offset, 2, this.length) 9772 return (this[offset] << 8) | this[offset + 1] 9773} 9774 9775Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { 9776 offset = offset >>> 0 9777 if (!noAssert) checkOffset(offset, 4, this.length) 9778 9779 return ((this[offset]) | 9780 (this[offset + 1] << 8) | 9781 (this[offset + 2] << 16)) + 9782 (this[offset + 3] * 0x1000000) 9783} 9784 9785Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { 9786 offset = offset >>> 0 9787 if (!noAssert) checkOffset(offset, 4, this.length) 9788 9789 return (this[offset] * 0x1000000) + 9790 ((this[offset + 1] << 16) | 9791 (this[offset + 2] << 8) | 9792 this[offset + 3]) 9793} 9794 9795Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { 9796 offset = offset >>> 0 9797 byteLength = byteLength >>> 0 9798 if (!noAssert) checkOffset(offset, byteLength, this.length) 9799 9800 var val = this[offset] 9801 var mul = 1 9802 var i = 0 9803 while (++i < byteLength && (mul *= 0x100)) { 9804 val += this[offset + i] * mul 9805 } 9806 mul *= 0x80 9807 9808 if (val >= mul) val -= Math.pow(2, 8 * byteLength) 9809 9810 return val 9811} 9812 9813Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { 9814 offset = offset >>> 0 9815 byteLength = byteLength >>> 0 9816 if (!noAssert) checkOffset(offset, byteLength, this.length) 9817 9818 var i = byteLength 9819 var mul = 1 9820 var val = this[offset + --i] 9821 while (i > 0 && (mul *= 0x100)) { 9822 val += this[offset + --i] * mul 9823 } 9824 mul *= 0x80 9825 9826 if (val >= mul) val -= Math.pow(2, 8 * byteLength) 9827 9828 return val 9829} 9830 9831Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { 9832 offset = offset >>> 0 9833 if (!noAssert) checkOffset(offset, 1, this.length) 9834 if (!(this[offset] & 0x80)) return (this[offset]) 9835 return ((0xff - this[offset] + 1) * -1) 9836} 9837 9838Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { 9839 offset = offset >>> 0 9840 if (!noAssert) checkOffset(offset, 2, this.length) 9841 var val = this[offset] | (this[offset + 1] << 8) 9842 return (val & 0x8000) ? val | 0xFFFF0000 : val 9843} 9844 9845Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { 9846 offset = offset >>> 0 9847 if (!noAssert) checkOffset(offset, 2, this.length) 9848 var val = this[offset + 1] | (this[offset] << 8) 9849 return (val & 0x8000) ? val | 0xFFFF0000 : val 9850} 9851 9852Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { 9853 offset = offset >>> 0 9854 if (!noAssert) checkOffset(offset, 4, this.length) 9855 9856 return (this[offset]) | 9857 (this[offset + 1] << 8) | 9858 (this[offset + 2] << 16) | 9859 (this[offset + 3] << 24) 9860} 9861 9862Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { 9863 offset = offset >>> 0 9864 if (!noAssert) checkOffset(offset, 4, this.length) 9865 9866 return (this[offset] << 24) | 9867 (this[offset + 1] << 16) | 9868 (this[offset + 2] << 8) | 9869 (this[offset + 3]) 9870} 9871 9872Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { 9873 offset = offset >>> 0 9874 if (!noAssert) checkOffset(offset, 4, this.length) 9875 return ieee754.read(this, offset, true, 23, 4) 9876} 9877 9878Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { 9879 offset = offset >>> 0 9880 if (!noAssert) checkOffset(offset, 4, this.length) 9881 return ieee754.read(this, offset, false, 23, 4) 9882} 9883 9884Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { 9885 offset = offset >>> 0 9886 if (!noAssert) checkOffset(offset, 8, this.length) 9887 return ieee754.read(this, offset, true, 52, 8) 9888} 9889 9890Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { 9891 offset = offset >>> 0 9892 if (!noAssert) checkOffset(offset, 8, this.length) 9893 return ieee754.read(this, offset, false, 52, 8) 9894} 9895 9896function checkInt (buf, value, offset, ext, max, min) { 9897 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') 9898 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') 9899 if (offset + ext > buf.length) throw new RangeError('Index out of range') 9900} 9901 9902Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { 9903 value = +value 9904 offset = offset >>> 0 9905 byteLength = byteLength >>> 0 9906 if (!noAssert) { 9907 var maxBytes = Math.pow(2, 8 * byteLength) - 1 9908 checkInt(this, value, offset, byteLength, maxBytes, 0) 9909 } 9910 9911 var mul = 1 9912 var i = 0 9913 this[offset] = value & 0xFF 9914 while (++i < byteLength && (mul *= 0x100)) { 9915 this[offset + i] = (value / mul) & 0xFF 9916 } 9917 9918 return offset + byteLength 9919} 9920 9921Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { 9922 value = +value 9923 offset = offset >>> 0 9924 byteLength = byteLength >>> 0 9925 if (!noAssert) { 9926 var maxBytes = Math.pow(2, 8 * byteLength) - 1 9927 checkInt(this, value, offset, byteLength, maxBytes, 0) 9928 } 9929 9930 var i = byteLength - 1 9931 var mul = 1 9932 this[offset + i] = value & 0xFF 9933 while (--i >= 0 && (mul *= 0x100)) { 9934 this[offset + i] = (value / mul) & 0xFF 9935 } 9936 9937 return offset + byteLength 9938} 9939 9940Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { 9941 value = +value 9942 offset = offset >>> 0 9943 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) 9944 this[offset] = (value & 0xff) 9945 return offset + 1 9946} 9947 9948Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { 9949 value = +value 9950 offset = offset >>> 0 9951 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) 9952 this[offset] = (value & 0xff) 9953 this[offset + 1] = (value >>> 8) 9954 return offset + 2 9955} 9956 9957Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { 9958 value = +value 9959 offset = offset >>> 0 9960 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) 9961 this[offset] = (value >>> 8) 9962 this[offset + 1] = (value & 0xff) 9963 return offset + 2 9964} 9965 9966Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { 9967 value = +value 9968 offset = offset >>> 0 9969 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) 9970 this[offset + 3] = (value >>> 24) 9971 this[offset + 2] = (value >>> 16) 9972 this[offset + 1] = (value >>> 8) 9973 this[offset] = (value & 0xff) 9974 return offset + 4 9975} 9976 9977Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { 9978 value = +value 9979 offset = offset >>> 0 9980 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) 9981 this[offset] = (value >>> 24) 9982 this[offset + 1] = (value >>> 16) 9983 this[offset + 2] = (value >>> 8) 9984 this[offset + 3] = (value & 0xff) 9985 return offset + 4 9986} 9987 9988Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { 9989 value = +value 9990 offset = offset >>> 0 9991 if (!noAssert) { 9992 var limit = Math.pow(2, (8 * byteLength) - 1) 9993 9994 checkInt(this, value, offset, byteLength, limit - 1, -limit) 9995 } 9996 9997 var i = 0 9998 var mul = 1 9999 var sub = 0 10000 this[offset] = value & 0xFF 10001 while (++i < byteLength && (mul *= 0x100)) { 10002 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { 10003 sub = 1 10004 } 10005 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF 10006 } 10007 10008 return offset + byteLength 10009} 10010 10011Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { 10012 value = +value 10013 offset = offset >>> 0 10014 if (!noAssert) { 10015 var limit = Math.pow(2, (8 * byteLength) - 1) 10016 10017 checkInt(this, value, offset, byteLength, limit - 1, -limit) 10018 } 10019 10020 var i = byteLength - 1 10021 var mul = 1 10022 var sub = 0 10023 this[offset + i] = value & 0xFF 10024 while (--i >= 0 && (mul *= 0x100)) { 10025 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { 10026 sub = 1 10027 } 10028 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF 10029 } 10030 10031 return offset + byteLength 10032} 10033 10034Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { 10035 value = +value 10036 offset = offset >>> 0 10037 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) 10038 if (value < 0) value = 0xff + value + 1 10039 this[offset] = (value & 0xff) 10040 return offset + 1 10041} 10042 10043Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { 10044 value = +value 10045 offset = offset >>> 0 10046 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) 10047 this[offset] = (value & 0xff) 10048 this[offset + 1] = (value >>> 8) 10049 return offset + 2 10050} 10051 10052Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { 10053 value = +value 10054 offset = offset >>> 0 10055 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) 10056 this[offset] = (value >>> 8) 10057 this[offset + 1] = (value & 0xff) 10058 return offset + 2 10059} 10060 10061Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { 10062 value = +value 10063 offset = offset >>> 0 10064 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) 10065 this[offset] = (value & 0xff) 10066 this[offset + 1] = (value >>> 8) 10067 this[offset + 2] = (value >>> 16) 10068 this[offset + 3] = (value >>> 24) 10069 return offset + 4 10070} 10071 10072Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { 10073 value = +value 10074 offset = offset >>> 0 10075 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) 10076 if (value < 0) value = 0xffffffff + value + 1 10077 this[offset] = (value >>> 24) 10078 this[offset + 1] = (value >>> 16) 10079 this[offset + 2] = (value >>> 8) 10080 this[offset + 3] = (value & 0xff) 10081 return offset + 4 10082} 10083 10084function checkIEEE754 (buf, value, offset, ext, max, min) { 10085 if (offset + ext > buf.length) throw new RangeError('Index out of range') 10086 if (offset < 0) throw new RangeError('Index out of range') 10087} 10088 10089function writeFloat (buf, value, offset, littleEndian, noAssert) { 10090 value = +value 10091 offset = offset >>> 0 10092 if (!noAssert) { 10093 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) 10094 } 10095 ieee754.write(buf, value, offset, littleEndian, 23, 4) 10096 return offset + 4 10097} 10098 10099Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { 10100 return writeFloat(this, value, offset, true, noAssert) 10101} 10102 10103Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { 10104 return writeFloat(this, value, offset, false, noAssert) 10105} 10106 10107function writeDouble (buf, value, offset, littleEndian, noAssert) { 10108 value = +value 10109 offset = offset >>> 0 10110 if (!noAssert) { 10111 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) 10112 } 10113 ieee754.write(buf, value, offset, littleEndian, 52, 8) 10114 return offset + 8 10115} 10116 10117Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { 10118 return writeDouble(this, value, offset, true, noAssert) 10119} 10120 10121Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { 10122 return writeDouble(this, value, offset, false, noAssert) 10123} 10124 10125// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) 10126Buffer.prototype.copy = function copy (target, targetStart, start, end) { 10127 if (!
vendor: 4,905 bytes, lines 10127-10313
10127start) start = 0 10128 if (!end && end !== 0) end = this.length 10129 if (targetStart >= target.length) targetStart = target.length 10130 if (!targetStart) targetStart = 0 10131 if (end > 0 && end < start) end = start 10132 10133 // Copy 0 bytes; we're done 10134 if (end === start) return 0 10135 if (target.length === 0 || this.length === 0) return 0 10136 10137 // Fatal error conditions 10138 if (targetStart < 0) { 10139 throw new RangeError('targetStart out of bounds') 10140 } 10141 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') 10142 if (end < 0) throw new RangeError('sourceEnd out of bounds') 10143 10144 // Are we oob? 10145 if (end > this.length) end = this.length 10146 if (target.length - targetStart < end - start) { 10147 end = target.length - targetStart + start 10148 } 10149 10150 var len = end - start 10151 var i 10152 10153 if (this === target && start < targetStart && targetStart < end) { 10154 // descending copy from end 10155 for (i = len - 1; i >= 0; --i) { 10156 target[i + targetStart] = this[i + start] 10157 } 10158 } else if (len < 1000) { 10159 // ascending copy from start 10160 for (i = 0; i < len; ++i) { 10161 target[i + targetStart] = this[i + start] 10162 } 10163 } else { 10164 Uint8Array.prototype.set.call( 10165 target, 10166 this.subarray(start, start + len), 10167 targetStart 10168 ) 10169 } 10170 10171 return len 10172} 10173 10174// Usage: 10175// buffer.fill(number[, offset[, end]]) 10176// buffer.fill(buffer[, offset[, end]]) 10177// buffer.fill(string[, offset[, end]][, encoding]) 10178Buffer.prototype.fill = function fill (val, start, end, encoding) { 10179 // Handle string cases: 10180 if (typeof val === 'string') { 10181 if (typeof start === 'string') { 10182 encoding = start 10183 start = 0 10184 end = this.length 10185 } else if (typeof end === 'string') { 10186 encoding = end 10187 end = this.length 10188 } 10189 if (val.length === 1) { 10190 var code = val.charCodeAt(0) 10191 if (code < 256) { 10192 val = code 10193 } 10194 } 10195 if (encoding !== undefined && typeof encoding !== 'string') { 10196 throw new TypeError('encoding must be a string') 10197 } 10198 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { 10199 throw new TypeError('Unknown encoding: ' + encoding) 10200 } 10201 } else if (typeof val === 'number') { 10202 val = val & 255 10203 } 10204 10205 // Invalid ranges are not set to a default, so can range check early. 10206 if (start < 0 || this.length < start || this.length < end) { 10207 throw new RangeError('Out of range index') 10208 } 10209 10210 if (end <= start) { 10211 return this 10212 } 10213 10214 start = start >>> 0 10215 end = end === undefined ? this.length : end >>> 0 10216 10217 if (!val) val = 0 10218 10219 var i 10220 if (typeof val === 'number') { 10221 for (i = start; i < end; ++i) { 10222 this[i] = val 10223 } 10224 } else { 10225 var bytes = Buffer.isBuffer(val) 10226 ? val 10227 : new Buffer(val, encoding) 10228 var len = bytes.length 10229 for (i = 0; i < end - start; ++i) { 10230 this[i + start] = bytes[i % len] 10231 } 10232 } 10233 10234 return this 10235} 10236 10237// HELPER FUNCTIONS 10238// ================ 10239 10240var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g 10241 10242function base64clean (str) { 10243 // Node strips out invalid characters like \n and \t from the string, base64-js does not 10244 str = str.trim().replace(INVALID_BASE64_RE, '') 10245 // Node converts strings with length < 2 to '' 10246 if (str.length < 2) return '' 10247 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not 10248 while (str.length % 4 !== 0) { 10249 str = str + '=' 10250 } 10251 return str 10252} 10253 10254function toHex (n) { 10255 if (n < 16) return '0' + n.toString(16) 10256 return n.toString(16) 10257} 10258 10259function utf8ToBytes (string, units) { 10260 units = units || Infinity 10261 var codePoint 10262 var length = string.length 10263 var leadSurrogate = null 10264 var bytes = [] 10265 10266 for (var i = 0; i < length; ++i) { 10267 codePoint = string.charCodeAt(i) 10268 10269 // is surrogate component 10270 if (codePoint > 0xD7FF && codePoint < 0xE000) { 10271 // last char was a lead 10272 if (!leadSurrogate) { 10273 // no lead yet 10274 if (codePoint > 0xDBFF) { 10275 // unexpected trail 10276 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) 10277 continue 10278 } else if (i + 1 === length) { 10279 // unpaired lead 10280 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) 10281 continue 10282 } 10283 10284 // valid lead 10285 leadSurrogate = codePoint 10286 10287 continue 10288 } 10289 10290 // 2 leads in a row 10291 if (codePoint < 0xDC00) { 10292 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) 10293 leadSurrogate = codePoint 10294 continue 10295 } 10296 10297 // valid surrogate pair 10298 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 10299 } else if (leadSurrogate) { 10300 // valid bmp char, but last char was a lead 10301 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) 10302 } 10303 10304 leadSurrogate = null 10305 10306 // encode utf8 10307 if (codePoint < 0x80) { 10308 if ((units -= 1) < 0) break 10309 bytes.push(codePoint) 10310 } else if (codePoint < 0x800) { 10311 if ((units -= 2) < 0) break 10312 bytes.push( 10313 codePoint >> 0x6 | 0xC0,
10314 codePoint & 0x3F | 0x80 10315 ) 10316 } else if (codePoint < 0x10000) { 10317 if ((units -= 3) < 0) break 10318 bytes.push( 10319 codePoint >> 0xC | 0xE0, 10320 codePoint >> 0x6 & 0x3F | 0x80, 10321 codePoint & 0x3F | 0x80 10322 ) 10323 } else if (codePoint < 0x110000) { 10324 if ((units -= 4) < 0) break 10325 bytes.push( 10326 codePoint >> 0x12 | 0xF0, 10327 codePoint >> 0xC & 0x3F | 0x80, 10328 codePoint >> 0x6 & 0x3F | 0x80, 10329 codePoint & 0x3F | 0x80 10330 ) 10331 } else { 10332 throw new Error('Invalid code point') 10333 } 10334 } 10335 10336 return bytes 10337} 10338 10339function asciiToBytes (str) { 10340 var byteArray = [] 10341 for (var i = 0; i < str.length; ++i) { 10342 // Node's code seems to be doing this and not & 0x7F.. 10343 byteArray.push(str.charCodeAt(i) & 0xFF) 10344 } 10345 return byteArray 10346} 10347 10348function utf16leToBytes (str, units) { 10349 var c, hi, lo 10350 var byteArray = [] 10351 for (var i = 0; i < str.length; ++i) { 10352 if ((units -= 2) < 0) break 10353 10354 c = str.charCodeAt(i) 10355 hi = c >> 8 10356 lo = c % 256 10357 byteArray.push(lo) 10358 byteArray.push(hi) 10359 } 10360 10361 return byteArray 10362} 10363 10364function base64ToBytes (str) { 10365 return base64.toByteArray(base64clean(str)) 10366} 10367 10368function blitBuffer (src, dst, offset, length) { 10369 for (var i = 0; i < length; ++i) { 10370 if ((i + offset >= dst.length) || (i >= src.length)) break 10371 dst[i + offset] = src[i] 10372 } 10373 return i 10374} 10375 10376// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check 10377// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 10378function isArrayBuffer (obj) { 10379 return obj instanceof ArrayBuffer || 10380 (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && 10381 typeof obj.byteLength === 'number') 10382} 10383 10384// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` 10385function isArrayBufferView (obj) { 10386 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) 10387} 10388 10389function numberIsNaN (obj) { 10390 return obj !== obj // eslint-disable-line no-self-compare 10391} 10392 10393},{"base64-js":81,"ieee754":163}],87:[function(require,module,exports){ 10394var document = require('global/document') 10395var onload = require('on-load') 10396var assert = require('assert') 10397 10398var elType = 'div' 10399 10400module.exports = widgetify 10401 10402// turn an element into a widget 10403// (obj, fn?) -> fn(any) -> DOMElement 10404function widgetify (methods, compare) { 10405 compare = compare || defaultCompare 10406 10407 assert.equal(typeof methods, 'object', 'cache-element/widget: methods should be an object') 10408 assert.equal(typeof methods.render, 'function', 'cache-element/widget: methods.render should be a function') 10409 assert.equal(typeof compare, 'function', 'cache-element/widget: compare should be a function') 10410 10411 var _onupdate = methods.onupdate || noop 10412 var _onunload = methods.onunload || noop 10413 var _onload = methods.onload || noop 10414 var _render = methods.render 10415 10416 var _isProxied = false 10417 var _element = null 10418 var _proxy = null 10419 var _args = null 10420 10421 return function () { 10422 var args = new Array(arguments.length) 10423 for (var i = 0; i < args.length; i++) { 10424 args[i] = arguments[i] 10425 } 10426 if (!_args) _args = args 10427 10428 if (!_element) { 10429 _element = _render.apply(null, args) 10430 10431 // apply lifecycle hooks 10432 // TODO: also call _element's onunload function 10433 onload(_element, _onload, function (el) { 10434 _isProxied = false 10435 _element = null 10436 _proxy = null 10437 10438 _onunload(el) 10439 }) 10440 10441 return _element 10442 } else { 10443 if (!_isProxied) { 10444 _proxy = document.createElement(elType) 10445 _proxy.isSameNode = function (el) { 10446 return (el === _element) 10447 } 10448 } 10449 if (_onupdate && !compare(_args, args)) { 10450 var copy = args.slice(0) 10451 copy.unshift(_element) // add element as first arg 10452 _onupdate.apply(null, copy) 10453 _args = args 10454 } 10455 return _proxy 10456 } 10457 } 10458} 10459 10460function noop () {} 10461 10462function defaultCompare (args1, args2) { 10463 var length = args1.length 10464 if (length !== args2.length) return false 10465 for (var i = 0; i < length; i++) { 10466 if (args1[i] !== args2[i]) return false 10467 } 10468 return true 10469} 10470 10471},{"assert":78,"global/document":157,"on-load":176}],88:[function(require,module,exports){ 10472var __assign = (this && this.__assign) || Object.assign || function(t) { 10473 for (var s, i = 1, n = arguments.length; i < n; i++) { 10474 s = arguments[i]; 10475 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) 10476 t[p] = s[p]; 10477 } 10478 return t; 10479}; 10480function default_1(reducers, effects, send, instanceId, namespace) { 10481 return Object.keys(reducers) 10482 .concat(Object.keys(effects)) 10483 .reduce(function (curr, key) { 10484 return __assign({}, curr, (_a = {}, _a[key] = function (payload) { 10485 if (payload === void 0) { payload = {}; } 10486 send(namespace + ":" + key, __assign({ instanceId: instanceId }, payload)); 10487 }, _a)); 10488 var _a; 10489 }, {}); 10490} 10491Object.defineProperty(exports, "__esModule", { value: true }); 10492exports.default = default_1; 10493 10494},{}],89:[function(require,module,exports){ 10495var __assign = (this && this.__assign) || Object.assign || function(t) { 10496 for (var s, i = 1, n = arguments.length; i < n; i++) { 10497 s = arguments[i]; 10498 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) 10499 t[p] = s[p]; 10500 } 10501 return t; 10502}; 10503function default_1(effects) { 10504 return Object.keys(effects).reduce(function (curr, key) { 10505 return __assign({}, curr, (_a = {}, _a[key] = function (state, payload, send, done) { 10506 return effects[key](state, payload, function (name, effectPayload) { 10507 return send(name, __assign({}, effectPayload, { instanceId: payload.instanceId }), done); 10508 }, done); 10509 }, _a)); 10510 var _a; 10511 }, {}); 10512} 10513Object.defineProperty(exports, "__esModule", { value: true }); 10514exports.default = default_1; 10515 10516},{}],90:[function(require,module,exports){ 10517var __assign = (this && this.__assign) || Object.assign || function(t) { 10518 for (var s, i = 1, n = arguments.length; i < n; i++) { 10519 s = arguments[i]; 10520 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) 10521 t[p] = s[p]; 10522 } 10523 return t; 10524}; 10525var reducers_1 = require("./reducers"); 10526var effects_1 = require("./effects"); 10527var behaviour_1 = require("./behaviour"); 10528function getCurrentInstanceState(state, model, instanceId) { 10529 if (state[model.namespace].instances[instanceId]) { 10530 return state[model.namespace].instances[instanceId]; 10531 } 10532 return model.state || {}; 10533} 10534function default_1(opts) { 10535 var reducers = reducers_1.default(opts.model.reducers ? opts.model.reducers : {}); 10536 var effects = effects_1.default(opts.model.effects ? opts.model.effects : {}); 10537 return { 10538 model: { 10539 namespace: opts.model.namespace, 10540 state: { instances: {} }, 10541 reducers: reducers, 10542 effects: effects, 10543 }, 10544 component: function (state, prev, send) { 10545 return function (instanceId, params) { 10546 if (!state[opts.model.namespace].instances[instanceId]) { 10547 send(opts.model.namespace + ":setup", { 10548 instanceId: instanceId, 10549 initialState: params.initialState || opts.model.state, 10550 }); 10551 } 10552 return opts.render(__assign({}, behaviour_1.default(reducers, effects, send, instanceId, opts.model.namespace), getCurrentInstanceState(state, opts.model, instanceId), params.props)); 10553 }; 10554 }, 10555 }; 10556} 10557Object.defineProperty(exports, "__esModule", { value: true }); 10558exports.default = default_1; 10559 10560},{"./behaviour":88,"./effects":89,"./reducers":91}],91:[function(require,module,exports){ 10561var __assign = (this && this.__assign) || Object.assign || function(t) { 10562 for (var s, i = 1, n = arguments.length; i < n; i++) { 10563 s = arguments[i]; 10564 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) 10565 t[p] = s[p]; 10566 } 10567 return t; 10568}; 10569// Create onload and onunload reducers to initiate and 10570// garbage collect an instance of a component when 10571// onload and onunload lifecycle methods are called 10572// setup sets the default state in the component 10573// and teardown removes an instance from the state 10574function defaultReducers() { 10575 return { 10576 setup: function (state, payload) { 10577 return { 10578 instances: __assign({}, state.instances, (_a = {}, _a[payload.instanceId] = payload.initialState, _a)), 10579 }; 10580 var _a; 10581 }, 10582 teardown: function (state, payload) { 10583 var instances = Object.keys(state.instances) 10584 .filter(function (key) { return key !== payload.instanceId; }) 10585 .reduce(function (prev, curr) { 10586 return __assign({}
10586, prev, (_a = {}, _a[curr] = state.instances[curr], _a)); 10587 var _a; 10588 }, {}); 10589 return { 10590 instances: instances, 10591 }; 10592 }, 10593 }; 10594} 10595exports.defaultReducers = defaultReducers; 10596// Wrap reducers so that functions in the component 10597// receive instance state rather than global state 10598// note that for this to work, reducers need to be 10599// send object payloads. Reducers then only need 10600// to return an updated instance state and do not 10601// need to worry about other instances 10602function decorateReducers(reducers) { 10603 return Object.keys(reducers).reduce(function (accumulator, reducerName) { 10604 return __assign({}, accumulator, (_a = {}, _a[reducerName] = function (state, payload) { 10605 return { 10606 instances: __assign({}, state.instances, (_a = {}, _a[payload.instanceId] = __assign({}, state.instances[payload.instanceId], reducers[reducerName](state.instances[payload.instanceId], payload)), _a)), 10607 }; 10608 var _a; 10609 }, _a)); 10610 var _a; 10611 }, {}); 10612} 10613exports.decorateReducers = decorateReducers; 10614function default_1(reducers) { 10615 return __assign({}, decorateReducers(reducers), defaultReducers()); 10616} 10617Object.defineProperty(exports, "__esModule", { value: true }); 10618exports.default = default_1; 10619 10620},{}],92:[function(require,module,exports){ 10621const createLocation = require('sheet-router/create-location') 10622const onHistoryChange = require('sheet-router/history') 10623const sheetRouter = require('sheet-router') 10624const onHref = require('sheet-router/href') 10625const walk = require('sheet-router/walk') 10626const mutate = require('xtend/mutable') 10627const barracks = require('barracks') 10628const nanoraf = require('nanoraf') 10629const assert = require('assert') 10630const xtend = require('xtend') 10631const yo = require('yo-yo') 10632 10633module.exports = choo 10634 10635// framework for creating sturdy web applications 10636// null -> fn 10637function choo (opts) { 10638 opts = opts || {} 10639 10640 const _store = start._store = barracks() 10641 var _router = start._router = null 10642 var _routerOpts = null 10643 var _rootNode = null 10644 var _routes = null 10645 var _frame = null 10646 10647 if (typeof window !== 'undefined') { 10648 _store.use({ onStateChange: render }) 10649 } 10650 _store.use(opts) 10651 10652 start.toString = toString 10653 start.router = router 10654 start.model = model 10655 start.start = start 10656 start.stop = _store.stop 10657 start.use = use 10658 10659 return start 10660 10661 // render the application to a string 10662 // (str, obj) -> str 10663 function toString (route, serverState) { 10664 serverState = serverState || {} 10665 assert.equal(typeof route, 'string', 'choo.app.toString: route must be a string') 10666 assert.equal(typeof serverState, 'object', 'choo.app.toString: serverState must be an object') 10667 _store.start({ subscriptions: false, reducers: false, effects: false }) 10668 10669 const state = _store.state({ state: serverState }) 10670 const router = createRouter(_routerOpts, _routes, createSend) 10671 const tree = router(route, state) 10672 return tree.outerHTML || tree.toString() 10673 10674 function createSend () { 10675 return function send () { 10676 assert.ok(false, 'choo: send() cannot be called from Node') 10677 } 10678 } 10679 } 10680 10681 // start the application 10682 // (str?, obj?) -> DOMNode 10683 function start () { 10684 _store.model(createLocationModel(opts)) 10685 const createSend = _store.start(opts) 10686 _router = start._router = createRouter(_routerOpts, _routes, createSend) 10687 const state = _store.state({state: {}}) 10688 10689 const tree = _router(state.location.href, state) 10690 assert.ok(tree, 'choo.start: the router should always return a valid DOM node') 10691 assert.equal(typeof tree, 'object', 'choo.start: the router should always return a valid DOM node') 10692 _rootNode = tree 10693 tree.done = done 10694 10695 return tree 10696 10697 // allow a 'mount' function to return the new node 10698 // html -> null 10699 function done (newNode) { 10700 _rootNode = newNode 10701 } 10702 } 10703 10704 // update the DOM after every state mutation 10705 // (obj, obj, obj, str, fn) -> null 10706 function render (state, data, prev, name, createSend) { 10707 if (!_frame) { 10708 _frame = nanoraf(function (state, prev) { 10709 const newTree = _router(state.location.href, state, prev) 10710 _rootNode = yo.update(_rootNode, newTree) 10711 }) 10712 } 10713 _frame(state, prev) 10714 } 10715 10716 // register all routes on the router 10717 // (str?, [fn|[fn]]) -> obj 10718 function router (defaultRoute, routes) { 10719 _routerOpts = defaultRoute 10720 _routes = routes 10721 } 10722 10723 // create a new model 10724 // (str?, obj) -> null 10725 function model (model) { 10726 _store.model(model) 10727 } 10728 10729 // register a plugin 10730 // (obj) -> null 10731 function use (hooks) { 10732 assert.equal(typeof hooks, 'object', 'choo.use: hooks should be an object') 10733 _store.use(hooks) 10734 } 10735 10736 // create a new router with a custom `createRoute()` function 10737 // (str?, obj) -> null 10738 function createRouter (routerOpts, routes, createSend) { 10739 var prev = null 10740 if (!routes) { 10741 routes = routerOpts 10742 routerOpts = {} 10743 }
10744 routerOpts = mutate({ thunk: 'match' }, routerOpts) 10745 const router = sheetRouter(routerOpts, routes) 10746 walk(router, wrap) 10747 10748 return router 10749 10750 function wrap (route, handler) { 10751 const send = createSend('view: ' + route, true) 10752 return function chooWrap (params) { 10753 return function (state) { 10754 // TODO(yw): find a way to wrap handlers so params shows up in state 10755 const nwState = xtend(state) 10756 nwState.location = xtend(nwState.location, { params: params }) 10757 10758 const nwPrev = prev 10759 prev = nwState // save for next time 10760 10761 if (opts.freeze !== false) Object.freeze(nwState) 10762 return handler(nwState, nwPrev, send) 10763 } 10764 } 10765 } 10766 } 10767} 10768 10769// application location model 10770// obj -> obj 10771function createLocationModel (opts) { 10772 return { 10773 namespace: 'location', 10774 state: mutate(createLocation(), { params: {} }), 10775 subscriptions: createSubscriptions(opts), 10776 effects: { set: setLocation, touch: touchLocation }, 10777 reducers: { update: updateLocation } 10778 } 10779 10780 // update the location on the state 10781 // try and jump to an anchor on the page if it exists 10782 // (obj, obj) -> obj 10783 function updateLocation (state, data) { 10784 if (opts.history !== false && data.hash && data.hash !== state.hash) { 10785 try { 10786 const el = document.querySelector(data.hash) 10787 if (el) el.scrollIntoView(true) 10788 } catch (e) { 10789 return data 10790 } 10791 } 10792 return data 10793 } 10794 10795 // update internal location only 10796 // (str, obj, fn, fn) -> null 10797 function touchLocation (state, data, send, done) { 10798 const newLocation = createLocation(state, data) 10799 send('location:update', newLocation, done) 10800 } 10801 10802 // set a new location e.g. "/foo/bar#baz?beep=boop" 10803 // (str, obj, fn, fn) -> null 10804 function setLocation (state, data, send, done) { 10805 const newLocation = createLocation(state, data) 10806 10807 // update url bar if it changed 10808 if (opts.history !== false && newLocation.href !== state.href) { 10809 window.history.pushState({}, null, newLocation.href) 10810 } 10811 10812 send('location:update', newLocation, done) 10813 } 10814 10815 function createSubscriptions (opts) { 10816 const subs = {} 10817 10818 if (opts.history !== false) { 10819 subs.handleHistory = function (send, done) { 10820 onHistoryChange(function navigate (href) { 10821 send('location:touch', href, done) 10822 }) 10823 } 10824 } 10825 10826 if (opts.href !== false) { 10827 subs.handleHref = function (send, done) { 10828 onHref(function navigate (location) { 10829 send('location:set', location, done) 10830 }) 10831 } 10832 } 10833 10834 return subs 10835 } 10836} 10837 10838},{"assert":78,"barracks":80,"nanoraf":173,"sheet-router":224,"sheet-router/create-location":221,"sheet-router/history":222,"sheet-router/href":223,"sheet-router/walk":226,"xtend":251,"xtend/mutable":252,"yo-yo":253}],93:[function(require,module,exports){ 10839/*! 10840 Copyright (c) 2016 Jed Watson. 10841 Licensed under the MIT License (MIT), see 10842 http://jedwatson.github.io/classnames 10843*/ 10844/* global define */ 10845 10846(function () { 10847 'use strict'; 10848 10849 var hasOwn = {}.hasOwnProperty; 10850 10851 function classNames () { 10852 var classes = []; 10853 10854 for (var i = 0; i < arguments.length; i++) { 10855 var arg = arguments[i]; 10856 if (!arg) continue; 10857 10858 var argType = typeof arg; 10859 10860 if (argType === 'string' || argType === 'number') { 10861 classes.push(arg); 10862 } else if (Array.isArray(arg)) { 10863 classes.push(classNames.apply(null, arg)); 10864 } else if (argType === 'object') { 10865 for (var key in arg) { 10866 if (hasOwn.call(arg, key) && arg[key]) { 10867 classes.push(key); 10868 } 10869 } 10870 } 10871 } 10872 10873 return classes.join(' '); 10874 } 10875 10876 if (typeof module !== 'undefined' && module.exports) { 10877 module.exports = classNames; 10878 } else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { 10879 // register as 'classnames', consistent with npm package name 10880 define('classnames', [], function () { 10881 return classNames; 10882 }); 10883 } else { 10884 window.classNames = classNames; 10885 } 10886}()); 10887 10888},{}],94:[function(require,module,exports){ 10889(function (Buffer){ 10890// Copyright Joyent, Inc. and other Node contributors. 10891// 10892// Permission is hereby granted, free of charge, to any person obtaining a 10893// copy of this software and associated documentation files (the 10894// "Software"), to deal in the Software without restriction, including 10895// without limitation the rights to use, copy, modify, merge, publish, 10896// distribute, sublicense, and/or sell copies of the Software, and to permit 10897// persons to whom the Software is furnished to do so, subject to the 10898// following conditions: 10899// 10900// The above copyright notice and this permission notice shall be included 10901// in all copies or substantial portions of the Software. 10902// 10903// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 10904// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 10905// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 10906// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 10907// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 10908// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 10909// USE OR OTHER DEALINGS IN THE SOFTWARE. 10910 10911// NOTE: These type checking functions intentionally don't use `instanceof` 10912// because it is fragile and can be easily faked with `Object.create()`. 10913 10914function isArray(arg) { 10915 if (Array.isArray) { 10916 return Array.isArray(arg); 10917 } 10918 return objectToString(arg) === '[object Array]'; 10919} 10920exports.isArray = isArray; 10921 10922function isBoolean(arg) { 10923 return typeof arg === 'boolean'; 10924} 10925exports.isBoolean = isBoolean; 10926 10927function isNull(arg) { 10928 return arg === null; 10929} 10930exports.isNull = isNull; 10931 10932function isNullOrUndefined(arg) { 10933 return arg == null; 10934} 10935exports.isNullOrUndefined = isNullOrUndefined; 10936 10937function isNumber(arg) { 10938 return typeof arg === 'number'; 10939} 10940exports.isNumber = isNumber; 10941 10942function isString(arg) { 10943 return typeof arg === 'string'; 10944} 10945exports.isString = isString; 10946 10947function isSymbol(arg) { 10948 return typeof arg === 'symbol'; 10949} 10950exports.isSymbol = isSymbol; 10951 10952function isUndefined(arg) { 10953 return arg === void 0; 10954} 10955exports.isUndefined = isUndefined; 10956 10957function isRegExp(re) { 10958 return objectToString(re) === '[object RegExp]'; 10959} 10960exports.isRegExp = isRegExp; 10961 10962function isObject(arg) { 10963 return typeof arg === 'object' && arg !== null; 10964} 10965exports.isObject = isObject; 10966 10967function isDate(d) { 10968 return objectToString(d) === '[object Date]'; 10969} 10970exports.isDate = isDate; 10971 10972function isError(e) { 10973 return (objectToString(e) === '[object Error]' || e instanceof Error); 10974} 10975exports.isError = isError; 10976 10977function isFunction(arg) { 10978 return typeof arg === 'function'; 10979} 10980exports.isFunction = isFunction; 10981 10982function isPrimitive(arg) { 10983 return arg === null || 10984 typeof arg === 'boolean' || 10985 typeof arg === 'number' || 10986 typeof arg === 'string' || 10987 typeof arg === 'symbol' || // ES6 symbol 10988 typeof arg === 'undefined'; 10989} 10990exports.isPrimitive = isPrimitive; 10991 10992exports.isBuffer = Buffer.isBuffer; 10993 10994function objectToString(o) { 10995 return Object.prototype.toString.call(o); 10996} 10997 10998}
10998).call(this,{"isBuffer":require("../../is-buffer/index.js")}) 10999},{"../../is-buffer/index.js":168}],95:[function(require,module,exports){ 11000/** 11001 * cuid.js 11002 * Collision-resistant UID generator for browsers and node. 11003 * Sequential for fast db lookups and recency sorting. 11004 * Safe for element IDs and server-side lookups. 11005 * 11006 * Extracted from CLCTR 11007 * 11008 * Copyright (c) Eric Elliott 2012 11009 * MIT License 11010 */ 11011 11012/*global window, navigator, document, require, process, module */ 11013(function (app) { 11014 'use strict'; 11015 var namespace = 'cuid', 11016 c = 0, 11017 blockSize = 4, 11018 base = 36, 11019 discreteValues = Math.pow(base, blockSize), 11020 11021 pad = function pad(num, size) { 11022 var s = "000000000" + num; 11023 return s.substr(s.length-size); 11024 }, 11025 11026 randomBlock = function randomBlock() { 11027 return pad((Math.random() * 11028 discreteValues << 0) 11029 .toString(base), blockSize); 11030 }, 11031 11032 safeCounter = function () { 11033 c = (c < discreteValues) ? c : 0; 11034 c++; // this is not subliminal 11035 return c - 1; 11036 }, 11037 11038 api = function cuid() { 11039 // Starting with a lowercase letter makes 11040 // it HTML element ID friendly. 11041 var letter = 'c', // hard-coded allows for sequential access 11042 11043 // timestamp 11044 // warning: this exposes the exact date and time 11045 // that the uid was created. 11046 timestamp = (new Date().getTime()).toString(base), 11047 11048 // Prevent same-machine collisions. 11049 counter, 11050 11051 // A few chars to generate distinct ids for different 11052 // clients (so different computers are far less 11053 // likely to generate the same id) 11054 fingerprint = api.fingerprint(), 11055 11056 // Grab some more chars from Math.random() 11057 random = randomBlock() + randomBlock(); 11058 11059 counter = pad(safeCounter().toString(base), blockSize); 11060 11061 return (letter + timestamp + counter + fingerprint + random); 11062 }; 11063 11064 api.slug = function slug() { 11065 var date = new Date().getTime().toString(36), 11066 counter, 11067 print = api.fingerprint().slice(0,1) + 11068 api.fingerprint().slice(-1), 11069 random = randomBlock().slice(-2); 11070 11071 counter = safeCounter().toString(36).slice(-4); 11072 11073 return date.slice(-2) + 11074 counter + print + random; 11075 }; 11076 11077 api.globalCount = function globalCount() { 11078 // We want to cache the results of this 11079 var cache = (function calc() { 11080 var i, 11081 count = 0; 11082 11083 for (i in window) { 11084 count++; 11085 } 11086 11087 return count; 11088 }()); 11089 11090 api.globalCount = function () { return cache; }; 11091 return cache; 11092 }; 11093 11094 api.fingerprint = function browserPrint() { 11095 return pad((navigator.mimeTypes.length + 11096 navigator.userAgent.length).toString(36) + 11097 api.globalCount().toString(36), 4); 11098 }; 11099 11100 // don't change anything from here down. 11101 if (app.register) { 11102 app.register(namespace, api); 11103 } else if (typeof module !== 'undefined') { 11104 module.exports = api; 11105 } else { 11106 app[namespace] = api; 11107 } 11108 11109}(this.applitude || this)); 11110 11111},{}],96:[function(require,module,exports){ 11112/** 11113 * Helpers. 11114 */ 11115 11116var s = 1000; 11117var m = s * 60; 11118var h = m * 60; 11119var d = h * 24; 11120var y = d * 365.25; 11121 11122/** 11123 * Parse or format the given `val`. 11124 * 11125 * Options: 11126 * 11127 * - `long` verbose formatting [false] 11128 * 11129 * @param {String|Number} val 11130 * @param {Object} [options] 11131 * @throws {Error} throw an error if val is not a non-empty string or a number 11132 * @return {String|Number} 11133 * @api public 11134 */ 11135 11136module.exports = function(val, options) { 11137 options = options || {}; 11138 var type = typeof val; 11139 if (type === 'string' && val.length > 0) { 11140 return parse(val); 11141 } else if (type === 'number' && isNaN(val) === false) { 11142 return options.long ? fmtLong(val) : fmtShort(val); 11143 } 11144 throw new Error( 11145 'val is not a non-empty string or a valid number. val=' + 11146 JSON.stringify(val) 11147 ); 11148}; 11149 11150/** 11151 * Parse the given `str` and return milliseconds. 11152 * 11153 * @param {String} str 11154 * @return {Number} 11155 * @api private 11156 */ 11157 11158function parse(str) { 11159 str = String(str); 11160 if (str.length > 100) { 11161 return; 11162 } 11163 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( 11164 str 11165 ); 11166 if (!match) { 11167 return; 11168 } 11169 var n = parseFloat(match[1]); 11170 var type = (match[2] || 'ms').toLowerCase(); 11171 switch (type) { 11172 case 'years': 11173 case 'year': 11174 case 'yrs': 11175 case 'yr': 11176 case 'y': 11177 return n * y; 11178 case 'days': 11179 case 'day': 11180 case 'd': 11181 return n * d; 11182 case 'hours': 11183 case 'hour': 11184 case 'hrs': 11185 case 'hr': 11186 case 'h': 11187 return n * h; 11188 case 'minutes': 11189 case 'minute': 11190 case 'mins': 11191 case 'min': 11192 case 'm': 11193 return n * m; 11194 case 'seconds': 11195 case 'second': 11196 case 'secs': 11197 case 'sec': 11198 case 's': 11199 return n * s; 11200 case 'milliseconds': 11201 case 'millisecond': 11202 case 'msecs': 11203 case 'msec': 11204 case 'ms': 11205 return n; 11206 default: 11207 return undefined; 11208 } 11209} 11210 11211/** 11212 * Short format for `ms`. 11213 * 11214 * @param {Number} ms 11215 * @return {String} 11216 * @api private 11217 */ 11218 11219function fmtShort(ms) { 11220 if (ms >= d) { 11221 return Math.round(ms / d) + 'd'; 11222 } 11223 if (ms >= h) { 11224 return Math.round(ms / h) + 'h'; 11225 } 11226 if (ms >= m) { 11227 return Math.round(ms / m) + 'm'; 11228 } 11229 if (ms >= s) { 11230 return Math.round(ms / s) + 's'; 11231 } 11232 return ms + 'ms'; 11233} 11234
vendor: 5,748 bytes, lines 11235-11468
11235/** 11236 * Long format for `ms`. 11237 * 11238 * @param {Number} ms 11239 * @return {String} 11240 * @api private 11241 */ 11242 11243function fmtLong(ms) { 11244 return plural(ms, d, 'day') || 11245 plural(ms, h, 'hour') || 11246 plural(ms, m, 'minute') || 11247 plural(ms, s, 'second') || 11248 ms + ' ms'; 11249} 11250 11251/** 11252 * Pluralization helper. 11253 */ 11254 11255function plural(ms, n, name) { 11256 if (ms < n) { 11257 return; 11258 } 11259 if (ms < n * 1.5) { 11260 return Math.floor(ms / n) + ' ' + name; 11261 } 11262 return Math.ceil(ms / n) + ' ' + name + 's'; 11263} 11264 11265},{}],97:[function(require,module,exports){ 11266(function (process){ 11267/** 11268 * This is the web browser implementation of `debug()`. 11269 * 11270 * Expose `debug()` as the module. 11271 */ 11272 11273exports = module.exports = require('./debug'); 11274exports.log = log; 11275exports.formatArgs = formatArgs; 11276exports.save = save; 11277exports.load = load; 11278exports.useColors = useColors; 11279exports.storage = 'undefined' != typeof chrome 11280 && 'undefined' != typeof chrome.storage 11281 ? chrome.storage.local 11282 : localstorage(); 11283 11284/** 11285 * Colors. 11286 */ 11287 11288exports.colors = [ 11289 'lightseagreen', 11290 'forestgreen', 11291 'goldenrod', 11292 'dodgerblue', 11293 'darkorchid', 11294 'crimson' 11295]; 11296 11297/** 11298 * Currently only WebKit-based Web Inspectors, Firefox >= v31, 11299 * and the Firebug extension (any Firefox version) are known 11300 * to support "%c" CSS customizations. 11301 * 11302 * TODO: add a `localStorage` variable to explicitly enable/disable colors 11303 */ 11304 11305function useColors() { 11306 // NB: In an Electron preload script, document will be defined but not fully 11307 // initialized. Since we know we're in Chrome, we'll just detect this case 11308 // explicitly 11309 if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { 11310 return true; 11311 } 11312 11313 // is webkit? http://stackoverflow.com/a/16459606/376773 11314 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 11315 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || 11316 // is firebug? http://stackoverflow.com/a/398120/376773 11317 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || 11318 // is firefox >= v31? 11319 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages 11320 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || 11321 // double check webkit in userAgent just in case we are in a worker 11322 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); 11323} 11324 11325/** 11326 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. 11327 */ 11328 11329exports.formatters.j = function(v) { 11330 try { 11331 return JSON.stringify(v); 11332 } catch (err) { 11333 return '[UnexpectedJSONParseError]: ' + err.message; 11334 } 11335}; 11336 11337 11338/** 11339 * Colorize log arguments if enabled. 11340 * 11341 * @api public 11342 */ 11343 11344function formatArgs(args) { 11345 var useColors = this.useColors; 11346 11347 args[0] = (useColors ? '%c' : '') 11348 + this.namespace 11349 + (useColors ? ' %c' : ' ') 11350 + args[0] 11351 + (useColors ? '%c ' : ' ') 11352 + '+' + exports.humanize(this.diff); 11353 11354 if (!useColors) return; 11355 11356 var c = 'color: ' + this.color; 11357 args.splice(1, 0, c, 'color: inherit') 11358 11359 // the final "%c" is somewhat tricky, because there could be other 11360 // arguments passed either before or after the %c, so we need to 11361 // figure out the correct index to insert the CSS into 11362 var index = 0; 11363 var lastC = 0; 11364 args[0].replace(/%[a-zA-Z%]/g, function(match) { 11365 if ('%%' === match) return; 11366 index++; 11367 if ('%c' === match) { 11368 // we only are interested in the *last* %c 11369 // (the user may have provided their own) 11370 lastC = index; 11371 } 11372 }); 11373 11374 args.splice(lastC, 0, c); 11375} 11376 11377/** 11378 * Invokes `console.log()` when available. 11379 * No-op when `console.log` is not a "function". 11380 * 11381 * @api public 11382 */ 11383 11384function log() { 11385 // this hackery is required for IE8/9, where 11386 // the `console.log` function doesn't have 'apply' 11387 return 'object' === typeof console 11388 && console.log 11389 && Function.prototype.apply.call(console.log, console, arguments); 11390} 11391 11392/** 11393 * Save `namespaces`. 11394 * 11395 * @param {String} namespaces 11396 * @api private 11397 */ 11398 11399function save(namespaces) { 11400 try { 11401 if (null == namespaces) { 11402 exports.storage.removeItem('debug'); 11403 } else { 11404 exports.storage.debug = namespaces; 11405 } 11406 } catch(e) {} 11407} 11408 11409/** 11410 * Load `namespaces`. 11411 * 11412 * @return {String} returns the previously persisted debug modes 11413 * @api private 11414 */ 11415 11416function load() { 11417 var r; 11418 try { 11419 r = exports.storage.debug; 11420 } catch(e) {} 11421 11422 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG 11423 if (!r && typeof process !== 'undefined' && 'env' in process) { 11424 r = process.env.DEBUG; 11425 } 11426 11427 return r; 11428} 11429 11430/** 11431 * Enable namespaces listed in `localStorage.debug` initially. 11432 */ 11433 11434exports.enable(load()); 11435 11436/** 11437 * Localstorage attempts to return the localstorage. 11438 * 11439 * This is necessary because safari throws 11440 * when a user disables cookies/localstorage 11441 * and you attempt to access it. 11442 * 11443 * @return {LocalStorage} 11444 * @api private 11445 */ 11446 11447function localstorage() { 11448 try { 11449 return window.localStorage; 11450 } catch (e) {} 11451} 11452 11453}).call(this,require('_process')) 11454},{"./debug":98,"_process":84}],98:[function(require,module,exports){ 11455 11456/** 11457 * This is the common logic for both the Node.js and web browser 11458 * implementations of `debug()`. 11459 * 11460 * Expose `debug()` as the module. 11461 */ 11462 11463exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; 11464exports.coerce = coerce; 11465exports.disable = disable; 11466exports.enable = enable; 11467exports.enabled = enabled; 11468exports.humanize = require('ms'
vendor: 4,029 bytes, lines 11468-11657
11468); 11469 11470/** 11471 * The currently active debug mode names, and names to skip. 11472 */ 11473 11474exports.names = []; 11475exports.skips = []; 11476 11477/** 11478 * Map of special "%n" handling functions, for the debug "format" argument. 11479 * 11480 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". 11481 */ 11482 11483exports.formatters = {}; 11484 11485/** 11486 * Previous log timestamp. 11487 */ 11488 11489var prevTime; 11490 11491/** 11492 * Select a color. 11493 * @param {String} namespace 11494 * @return {Number} 11495 * @api private 11496 */ 11497 11498function selectColor(namespace) { 11499 var hash = 0, i; 11500 11501 for (i in namespace) { 11502 hash = ((hash << 5) - hash) + namespace.charCodeAt(i); 11503 hash |= 0; // Convert to 32bit integer 11504 } 11505 11506 return exports.colors[Math.abs(hash) % exports.colors.length]; 11507} 11508 11509/** 11510 * Create a debugger with the given `namespace`. 11511 * 11512 * @param {String} namespace 11513 * @return {Function} 11514 * @api public 11515 */ 11516 11517function createDebug(namespace) { 11518 11519 function debug() { 11520 // disabled? 11521 if (!debug.enabled) return; 11522 11523 var self = debug; 11524 11525 // set `diff` timestamp 11526 var curr = +new Date(); 11527 var ms = curr - (prevTime || curr); 11528 self.diff = ms; 11529 self.prev = prevTime; 11530 self.curr = curr; 11531 prevTime = curr; 11532 11533 // turn the `arguments` into a proper Array 11534 var args = new Array(arguments.length); 11535 for (var i = 0; i < args.length; i++) { 11536 args[i] = arguments[i]; 11537 } 11538 11539 args[0] = exports.coerce(args[0]); 11540 11541 if ('string' !== typeof args[0]) { 11542 // anything else let's inspect with %O 11543 args.unshift('%O'); 11544 } 11545 11546 // apply any `formatters` transformations 11547 var index = 0; 11548 args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { 11549 // if we encounter an escaped % then don't increase the array index 11550 if (match === '%%') return match; 11551 index++; 11552 var formatter = exports.formatters[format]; 11553 if ('function' === typeof formatter) { 11554 var val = args[index]; 11555 match = formatter.call(self, val); 11556 11557 // now we need to remove `args[index]` since it's inlined in the `format` 11558 args.splice(index, 1); 11559 index--; 11560 } 11561 return match; 11562 }); 11563 11564 // apply env-specific formatting (colors, etc.) 11565 exports.formatArgs.call(self, args); 11566 11567 var logFn = debug.log || exports.log || console.log.bind(console); 11568 logFn.apply(self, args); 11569 } 11570 11571 debug.namespace = namespace; 11572 debug.enabled = exports.enabled(namespace); 11573 debug.useColors = exports.useColors(); 11574 debug.color = selectColor(namespace); 11575 11576 // env-specific initialization logic for debug instances 11577 if ('function' === typeof exports.init) { 11578 exports.init(debug); 11579 } 11580 11581 return debug; 11582} 11583 11584/** 11585 * Enables a debug mode by namespaces. This can include modes 11586 * separated by a colon and wildcards. 11587 * 11588 * @param {String} namespaces 11589 * @api public 11590 */ 11591 11592function enable(namespaces) { 11593 exports.save(namespaces); 11594 11595 exports.names = []; 11596 exports.skips = []; 11597 11598 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); 11599 var len = split.length; 11600 11601 for (var i = 0; i < len; i++) { 11602 if (!split[i]) continue; // ignore empty strings 11603 namespaces = split[i].replace(/\*/g, '.*?'); 11604 if (namespaces[0] === '-') { 11605 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); 11606 } else { 11607 exports.names.push(new RegExp('^' + namespaces + '$')); 11608 } 11609 } 11610} 11611 11612/** 11613 * Disable debug output. 11614 * 11615 * @api public 11616 */ 11617 11618function disable() { 11619 exports.enable(''); 11620} 11621 11622/** 11623 * Returns true if the given mode name is enabled, false otherwise. 11624 * 11625 * @param {String} name 11626 * @return {Boolean} 11627 * @api public 11628 */ 11629 11630function enabled(name) { 11631 var i, len; 11632 for (i = 0, len = exports.skips.length; i < len; i++) { 11633 if (exports.skips[i].test(name)) { 11634 return false; 11635 } 11636 } 11637 for (i = 0, len = exports.names.length; i < len; i++) { 11638 if (exports.names[i].test(name)) { 11639 return true; 11640 } 11641 } 11642 return false; 11643} 11644 11645/** 11646 * Coerce `val`. 11647 * 11648 * @param {Mixed} val 11649 * @return {Mixed} 11650 * @api private 11651 */ 11652 11653function coerce(val) { 11654 if (val instanceof Error) return val.stack || val.message; 11655 return val; 11656} 11657
11658},{"ms":96}],99:[function(require,module,exports){ 11659var once = require('once'); 11660 11661var noop = function() {}; 11662 11663var isRequest = function(stream) { 11664 return stream.setHeader && typeof stream.abort === 'function'; 11665}; 11666 11667var isChildProcess = function(stream) { 11668 return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 11669}; 11670 11671var eos = function(stream, opts, callback) { 11672 if (typeof opts === 'function') return eos(stream, null, opts); 11673 if (!opts) opts = {}; 11674 11675 callback = once(callback || noop); 11676 11677 var ws = stream._writableState; 11678 var rs = stream._readableState; 11679 var readable = opts.readable || (opts.readable !== false && stream.readable); 11680 var writable = opts.writable || (opts.writable !== false && stream.writable); 11681 11682 var onlegacyfinish = function() { 11683 if (!stream.writable) onfinish(); 11684 }; 11685 11686 var onfinish = function() { 11687 writable = false; 11688 if (!readable) callback.call(stream); 11689 }; 11690 11691 var onend = function() { 11692 readable = false; 11693 if (!writable) callback.call(stream); 11694 }; 11695 11696 var onexit = function(exitCode) { 11697 callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); 11698 }; 11699 11700 var onclose = function() { 11701 if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); 11702 if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); 11703 }; 11704 11705 var onrequest = function() { 11706 stream.req.on('finish', onfinish); 11707 }; 11708 11709 if (isRequest(stream)) { 11710 stream.on('complete', onfinish); 11711 stream.on('abort', onclose); 11712 if (stream.req) onrequest(); 11713 else stream.on('request', onrequest); 11714 } else if (writable && !ws) { // legacy streams 11715 stream.on('end', onlegacyfinish); 11716 stream.on('close', onlegacyfinish); 11717 } 11718 11719 if (isChildProcess(stream)) stream.on('exit', onexit); 11720 11721 stream.on('end', onend); 11722 stream.on('finish', onfinish); 11723 if (opts.error !== false) stream.on('error', callback); 11724 stream.on('close', onclose); 11725 11726 return function() { 11727 stream.removeListener('complete', onfinish); 11728 stream.removeListener('abort', onclose); 11729 stream.removeListener('request', onrequest); 11730 if (stream.req) stream.req.removeListener('finish', onfinish); 11731 stream.removeListener('end', onlegacyfinish); 11732 stream.removeListener('close', onlegacyfinish); 11733 stream.removeListener('finish', onfinish); 11734 stream.removeListener('exit', onexit); 11735 stream.removeListener('end', onend); 11736 stream.removeListener('error', callback); 11737 stream.removeListener('close', onclose); 11738 }; 11739}; 11740 11741module.exports = eos; 11742 11743},{"once":100}],100:[function(require,module,exports){ 11744var wrappy = require('wrappy') 11745module.exports = wrappy(once) 11746module.exports.strict = wrappy(onceStrict) 11747 11748once.proto = once(function () { 11749 Object.defineProperty(Function.prototype, 'once', { 11750 value: function () { 11751 return once(this) 11752 }, 11753 configurable: true 11754 }) 11755 11756 Object.defineProperty(Function.prototype, 'onceStrict', { 11757 value: function () { 11758 return onceStrict(this) 11759 }, 11760 configurable: true 11761 }) 11762}) 11763 11764function once (fn) { 11765 var f = function () { 11766 if (f.called) return f.value 11767 f.called = true 11768 return f.value = fn.apply(this, arguments) 11769 } 11770 f.called = false 11771 return f 11772} 11773 11774function onceStrict (fn) { 11775 var f = function () { 11776 if (f.called) 11777 throw new Error(f.onceError) 11778 f.called = true 11779 return f.value = fn.apply(this, arguments) 11780 } 11781 var name = fn.name || 'Function wrapped with `once`' 11782 f.onceError = name + " shouldn't be called more than once" 11783 f.called = false 11784 return f 11785} 11786 11787},{"wrappy":249}],101:[function(require,module,exports){ 11788module.exports={ 11789 "_args": [ 11790 [ 11791 { 11792 "raw": "esper.js@^0.1.7", 11793 "scope": null, 11794 "escapedName": "esper.js", 11795 "name": "esper.js", 11796 "rawSpec": "^0.1.7", 11797 "spec": ">=0.1.7 <0.2.0", 11798 "type": "range" 11799 }, 11800 "/Users/paul/repos/robotopia/node_modules/@robotopia/agent-runtime" 11801 ] 11802 ], 11803 "_from": "esper.js@>=0.1.7 <0.2.0", 11804 "_id": "[email protected]", 11805 "_inCache": true, 11806 "_location": "/esper.js", 11807 "_nodeVersion": "4.2.1", 11808 "_npmOperationalInternal": { 11809 "host": "packages-12-west.internal.npmjs.com", 11810 "tmp": "tmp/esper.js-0.1.7.tgz_1471988795990_0.5655501254368573" 11811 }, 11812 "_npmUser": { 11813 "name": "basicer", 11814 "email": "[email protected]" 11815 }, 11816 "_npmVersion": "2.14.8", 11817 "_phantomChildren": {}, 11818 "_requested": { 11819 "raw": "esper.js@^0.1.7", 11820 "scope": null, 11821 "escapedName": "esper.js", 11822 "name": "esper.js", 11823 "rawSpec": "^0.1.7", 11824 "spec": ">=0.1.7 <0.2.0", 11825 "type": "range" 11826 }, 11827 "_requiredBy": [ 11828 "/@robotopia/agent-runtime" 11829 ], 11830 "_resolved": "https://registry.npmjs.org/esper.js/-/esper.js-0.1.7.tgz", 11831 "_shasum": "acae781a61ad3f3abc01a2a933053690aa45a5e1", 11832 "_shrinkwrap": null, 11833 "_spec": "esper.js@^0.1.7", 11834 "_where": "/Users/paul/repos/robotopia/node_modules/@robotopia/agent-runtime", 11835 "author": { 11836 "name": "Rob Blanckaert" 11837 }, 11838 "bin": { 11839 "esper": "./contrib/cli.js" 11840 }, 11841 "bugs": { 11842 "url": "https://github.com/codecombat/esper.js/issues" 11843 },
11844 "dependencies": { 11845 "commander": "^2.9.0", 11846 "escodegen": "^1.8.0", 11847 "esprima": "^2.7.1" 11848 }, 11849 "description": "Esper javascript interperter.", 11850 "devDependencies": { 11851 "babel-core": "^6.4.0", 11852 "babel-loader": "^6.2.1", 11853 "babel-plugin-check-es2015-constants": "^6.3.13", 11854 "babel-plugin-transform-es2015-arrow-functions": "^6.3.13", 11855 "babel-plugin-transform-es2015-block-scoped-functions": "^6.3.13", 11856 "babel-plugin-transform-es2015-block-scoping": "^6.3.13", 11857 "babel-plugin-transform-es2015-classes": "^6.3.13", 11858 "babel-plugin-transform-es2015-computed-properties": "^6.3.13", 11859 "babel-plugin-transform-es2015-destructuring": "^6.3.13", 11860 "babel-plugin-transform-es2015-for-of": "^6.3.13", 11861 "babel-plugin-transform-es2015-function-name": "^6.3.13", 11862 "babel-plugin-transform-es2015-literals": "^6.3.13", 11863 "babel-plugin-transform-es2015-modules-commonjs": "^6.4.0", 11864 "babel-plugin-transform-es2015-object-super": "^6.3.13", 11865 "babel-plugin-transform-es2015-parameters": "^6.3.13", 11866 "babel-plugin-transform-es2015-shorthand-properties": "^6.3.13", 11867 "babel-plugin-transform-es2015-spread": "^6.3.13", 11868 "babel-plugin-transform-es2015-sticky-regex": "^6.3.13", 11869 "babel-plugin-transform-es2015-template-literals": "^6.3.13", 11870 "babel-plugin-transform-es2015-typeof-symbol": "^6.3.13", 11871 "babel-plugin-transform-es2015-unicode-regex": "^6.3.13", 11872 "babel-plugin-transform-regenerator": "^6.3.13", 11873 "babel-plugin-transform-runtime": "^6.6.0", 11874 "babel-polyfill": "^6.3.14", 11875 "babel-regenerator-runtime": "^6.5.0", 11876 "babel-register": "^6.3.13", 11877 "babel-runtime": "^6.6.1", 11878 "chai": "^3.4.1", 11879 "core-js": "^2.1.0", 11880 "esdoc": "^0.4.3", 11881 "istanbul": "^1.0.0-alpha.2", 11882 "json-loader": "^0.5.4", 11883 "lodash": "^4.11.2", 11884 "lua2js": "0.0.11", 11885 "mocha": "^2.4.5", 11886 "mocha-loader": "^0.7.1", 11887 "raw-loader": "^0.5.1", 11888 "v8-profiler": "^5.6.5", 11889 "webpack": "^1.12.11", 11890 "webpack-dev-server": "^1.14.1" 11891 }, 11892 "directories": {}, 11893 "dist": { 11894 "shasum": "acae781a61ad3f3abc01a2a933053690aa45a5e1", 11895 "tarball": "https://registry.npmjs.org/esper.js/-/esper.js-0.1.7.tgz" 11896 }, 11897 "gitHead": "c8b6aae03622414f1d79e0c7853ef0e9b2662aa8", 11898 "homepage": "https://github.com/codecombat/esper.js#readme", 11899 "keywords": [ 11900 "esper", 11901 "javascript", 11902 "interperter", 11903 "ast", 11904 "eval" 11905 ], 11906 "license": "MIT", 11907 "main": "src/index.js", 11908 "maintainers": [ 11909 { 11910 "name": "basicer", 11911 "email": "[email protected]" 11912 } 11913 ], 11914 "name": "esper.js", 11915 "optionalDependencies": {}, 11916 "readme": "ERROR: No README data found!", 11917 "repository": { 11918 "type": "git", 11919 "url": "git+ssh://[email protected]/codecombat/esper.js.git" 11920 }, 11921 "scripts": { 11922 "cover": "./node_modules/istanbul/lib/cli.js cover node_modules/.bin/_mocha -- --reporter dot", 11923 "demo": "esdoc -c esdoc.json && node contrib/examine-corpus.js && webpack && webpack --test && webpack --test --profile=modern && node contrib/ui.js", 11924 "dev-server": "webpack-dev-server src/index.js --content-base contrib/ui", 11925 "doc": "esdoc -c esdoc.json", 11926 "lint": "jshint src --show-non-errors", 11927 "prepublish": "node contrib/build.js", 11928 "repl": "node contrib/cli.js -i", 11929 "style": "jscs src", 11930 "test": "mocha", 11931 "webpack": "webpack" 11932 }, 11933 "version": "0.1.7" 11934} 11935 11936},{}],102:[function(require,module,exports){ 11937(function (process){ 11938'use strict'; 11939 11940function invokeCB(o, name) { 11941 if ( !(name in o ) ) return; 11942 var args = Array.prototype.slice.call(arguments, 2); 11943 o[name].apply(o, args); 11944} 11945 11946function detectStrict(body) { 11947 if ( !body || body.length < 1 ) return; 11948 let first = body[0]; 11949 if ( first.type === 'ExpressionStatement' ) { 11950 let exp = first.expression; 11951 if ( exp.type === 'Literal' && exp.value === 'use strict' ) { 11952 return true; 11953 } 11954 } 11955} 11956 11957 11958class ASTNode { 11959 constructor(o) { 11960 if ( typeof o === 'object' ) { 11961 for ( var k in o ) this[k] = o[k]; 11962 } 11963 } 11964 11965 addHiddenProperty(name, value) { 11966 Object.defineProperty(this, name, { 11967 value: value, 11968 configurable: true 11969 }); 11970 } 11971 11972 source() { 11973 if ( !this._source ) return; 11974 if ( !this.range ) return; 11975 return this._source.substring(this.range[0], this.range[1]); 11976 } 11977 11978 toString() { 11979 let extra = Object.keys(this).map((k) => { 11980 let v = this[k]; 11981 if ( v === null || typeof v === 'function' ) return; 11982 if ( k == 'range' || k == 'loc' || k == 'nodeID') return; 11983 if ( v instanceof ASTNode ) return `${k}: [ASTNode: ${v.type}]`; 11984 if ( Array.isArray(v) ) return '[...]'; 11985 else return `${k}: ${JSON.stringify(v)}`; 11986 }).filter((v) => !!v).join(', '); 11987 return `[ASTNode: ${this.type} ${extra}]`; 11988 } 11989 11990} 11991 11992class ASTPreprocessor { 11993 11994 static process(ast, extra) { 11995 if ( typeof ast !== 'object' ) throw new TypeError('Provided AST is invali
11995d (type is ' + typeof ast + ')'); 11996 let nast = JSON.parse(JSON.stringify(ast), function(n, o) { 11997 if ( o === null ) return null; 11998 if ( typeof o !== 'object' ) return o; 11999 if ( o.type ) { 12000 let z = new ASTNode(o); 12001 if ( extra && extra.source ) z.addHiddenProperty('_source', extra.source); 12002 return z; 12003 } 12004 return o; 12005 }); 12006 new ASTPreprocessor(nast, extra).start(); 12007 return nast; 12008 } 12009 12010 static *walker(ast, cbs, parent) { 12011 var me = (a) => ASTPreprocessor.walker(a, cbs, ast); 12012 invokeCB(cbs, 'enter', ast); 12013 invokeCB(cbs, 'enter' + ast.type, ast); 12014 if ( parent && ast instanceof ASTNode ) ast.addHiddenProperty('parent', parent); 12015 switch ( ast.type ) { 12016 case 'Program': 12017 for ( let e of ast.body ) yield * me(e); 12018 break; 12019 case 'BlockStatement': 12020 for ( let e of ast.body ) yield * me(e); 12021 break; 12022 case 'NewExpression': 12023 case 'CallExpression': 12024 for ( let e of ast.arguments ) yield * me(e); 12025 yield * me(ast.callee); 12026 break; 12027 case 'WhileStatement': 12028 case 'DoWhileStatement': 12029 if ( ast.test ) yield * me(ast.test); 12030 yield * me(ast.body); 12031 break; 12032 case 'VariableDeclaration': 12033 for ( let e of ast.declarations ) yield * me(e); 12034 break; 12035 case 'VariableDeclarator': 12036 invokeCB(cbs, 'decl', ast); 12037 if ( ast.init ) yield * me(ast.init); 12038 break; 12039 case 'FunctionDeclaration': 12040 invokeCB(cbs, 'decl', ast); 12041 invokeCB(cbs, 'enterFunction', ast); 12042 yield * me(ast.body); 12043 invokeCB(cbs, 'exitFunction', ast); 12044 break; 12045 12046 case 'ArrowFunctionExpression': 12047 case 'FunctionExpression': 12048 invokeCB(cbs, 'enterFunction', ast); 12049 yield * me(ast.body); 12050 invokeCB(cbs, 'exitFunction', ast); 12051 break; 12052 case 'Identifier': 12053 break; 12054 case 'ArrayExpression': 12055 if ( ast.elements ) { 12056 for ( let e of ast.elements ) { 12057 if ( e ) yield * me(e); 12058 } 12059 } 12060 break; 12061 case 'ObjectExpression': 12062 if ( ast.properties ) { 12063 for ( let e of ast.properties ) { 12064 if ( e ) yield * me(e); 12065 } 12066 } 12067 break; 12068 case 'Property': 12069 yield * me(ast.key); 12070 yield * me(ast.value); 12071 break; 12072 default: 12073 for (var p in ast) { 12074 let n = ast[p]; 12075 if ( p === 'parent' ) continue; 12076 if ( p === 'loc' ) continue; 12077 if ( p === 'type' ) continue; 12078 if ( p === 'nodeID' ) continue; 12079 if ( p === 'parentFunction' ) continue; 12080 if ( p === 'funcs' ) continue; 12081 if ( n === null ) continue; 12082 if ( typeof n.type !== 'string' ) { 12083 continue; 12084 } 12085 yield * me(n); 12086 } 12087 } 12088 12089 12090 invokeCB(cbs, 'exit' + ast.type, ast); 12091 invokeCB(cbs, 'exit', ast); 12092 } 12093 12094 12095 constructor(ast, options) { 12096 this.options = options || {}; 12097 this.ast = ast; 12098 this.gen = ASTPreprocessor.walker(ast, this); 12099 } 12100 12101 start() { 12102 this.counter = 0; 12103 this.depth = 0; 12104 12105 let globalScope = Object.create(null); 12106 let globalVars = Object.create(null); 12107 let globalFuncs = Object.create(null); 12108 12109 this.scopeStack = [globalScope]; 12110 this.varStack = [globalVars]; 12111 this.funcStack = [globalFuncs]; 12112 for ( var x of this.gen ) { 12113 12114 } 12115 } 12116 12117 log() { 12118 let str = Array.prototype.join.call(arguments, ', '); 12119 let indent = new Array(this.depth).join(' '); 12120 //console.log(indent + str); 12121 } 12122 12123 enter(a) { 12124 ++this.depth; 12125 a.nodeID = this.counter++; 12126 this.log('Entering', a.type); 12127 } 12128 12129 enterIdentifier(a) { 12130 let fn = this.funcStack[0]; 12131 fn.refs[a.name] = true; 12132 } 12133 12134 decl(a) { 12135 if ( a.parent.type == 'VariableDeclaration' && a.parent.kind != 'var' ) return; 12136 let stack = this.varStack[0]; 12137 stack[a.id.name] = a; 12138 } 12139 12140 enterProgram(a) { 12141 let scope = Object.create(null); 12142 12143 a.addHiddenProperty('refs', Object.create(null)); 12144 a.addHiddenProperty('vars', Object.create(null)); 12145 a.addHiddenProperty('funcs', Object.create(null)); 12146 12147 this.funcStack.unshift(a); 12148 this.scopeStack.unshift(scope); 12149 this.varStack.unshift(a.vars); 12150 12151 this.mangleBody(a); 12152 12153 let strict = detectStrict(a.body); 12154 if ( strict !== undefined ) a.strict = strict; 12155 } 12156 12157 enterThisExpression(a) { 12158 a.srcName = 'this'; 12159 } 12160 12161 enterLabeledStatement(a) { 12162 a.body.label = a.label.name; 12163 } 12164 12165 exitArrayExpression(a) { 12166 a.srcName = '[' + a.elements.map((e) => e ? e.srcName : '').join() + ']'; 12167 } 12168 12169 mangleBody(a) { 12170 function prehoist(s) { 12171 if ( s.type === 'VariableDeclaration' && s.kind == 'var' ) { 12172 for ( var decl of s.declarations ) { 12173 a.vars[decl.id.name] = decl; 12174 } 12175 12176 } else if ( s.type === 'FunctionDeclaration' ) { 12177 a.vars[s.id.name] = s; 12178 } 12179 } 12180 12181 if ( a.body.type === 'BlockStatement' ) { 12182 for ( let stmt of a.body.body ) prehoist(stmt); 12183 } else if ( Array.isArray(a.body) ) { 12184 for ( let stmt of a.body ) prehoist(stmt); 12185 } else { 12186 prehoist(a.body); 12187 } 12188 12189 } 12190 12191 enterFunction(a) { 12192 this.funcStack.unshift(a); 12193 let scope = Object.create(this.scopeStack[0]); 12194 this.scopeStack.unshift(scope); 12195 12196 a.addHiddenProperty('refs', Object.create(null)); 12197 a.addHiddenProperty('vars', Object.create(null)); 12198 a.addHiddenProperty('funcs', Object.create(null)); 12199 12200 if ( this.options.nonUserCode ) { 12201 a.addHiddenProperty('nonUserCode', true); 12202 } 12203 12204 for ( let o of a.params ) { 12205 a.vars[o.name] = a; 12206 } 12207 12208 this.mangleBody(a); 12209 12210 let strict = detectStrict(a.body.body); 12211 if ( strict !== undefined ) a.strict = strict; 12212 12213 this.varStack.unshift(a.vars); 12214 } 12215 12216 enterFunctionDeclaration(a) { 12217 let parent = this.funcStack[0]; 12218 //a.parentFunction = parent.nodeID; 12219 a.srcName = 'function ' + a.id.name + ' {'; 12220 parent.funcs[a.id.name] = a; 12221 } 12222 12223 exitIdentifier(a) { 12224 a.srcName = a.name; 12225 } 12226 12227 exitLiteral(a) { 12228 if ( a.regex ) { 12229 a.srcName = '/' + a.regex.pattern + '/' + a.regex.flags; 12230 } else if ( typeof a.value === 'string' ) { 12231 a.srcName = a.raw; 12232 } else if ( typeof a.value === 'undefined' ) { 12233 a.srcName = 'undefiend'; 12234 } else { 12235 a.srcName = a.raw; 12236 } 12237 } 12238 12239 12240 exitBinaryExpression(a) { 12241 a.srcName = a.left.srcName + ' ' + a.operator + ' ' + a.right.srcName; 12242 } 12243 12244 exitMemberExpression(a) { 12245 let left = a.object.srcName || '??';
12246 let right = a.property.srcName || '(intermediate value)'; 12247 if (!a.computed) a.srcName = left + '.' + right; 12248 else a.srcName = a.srcName = left + '[' + right + ']'; 12249 } 12250 12251 exitCallExpression(a) { 12252 a.srcName = a.callee.srcName + '(...)'; 12253 } 12254 12255 12256 exitFunction(a) { 12257 var vars = this.varStack.shift(); 12258 var free = {}; 12259 var upvars = {}; 12260 for ( var r in a.refs ) { 12261 if ( r in vars ) { 12262 //Local refrence 12263 } else if ( r in this.varStack[0] ) { 12264 upvars[r] = true; 12265 } else { 12266 free[r] = true; 12267 } 12268 } 12269 a.upvars = upvars; 12270 a.freevars = free; 12271 12272 this.scopeStack.shift(); 12273 this.funcStack.shift(); 12274 delete a.refs; 12275 //this.log("VARS:", Object.getOwnPropertyNames(a.vars).join(', ')); 12276 } 12277 12278 exitProgram(a) { 12279 this.scopeStack.shift(); 12280 var vars = this.varStack.shift(); 12281 //this.log("VARS:", Object.getOwnPropertyNames(a.vars).join(', ')); 12282 } 12283 12284 exit(a) { 12285 this.log('Exiting', a.type); 12286 --this.depth; 12287 } 12288 12289} 12290 12291module.exports = ASTPreprocessor; 12292 12293}).call(this,require('_process')) 12294},{"_process":84}],103:[function(require,module,exports){ 12295'use strict'; 12296 12297let Value = require('./Value'); 12298 12299class CompletionRecord { 12300 constructor(type, value, target) { 12301 if ( value === undefined ) { 12302 value = type; 12303 type = CompletionRecord.NORMAL; 12304 } 12305 12306 this.type = type; 12307 this.value = value; 12308 this.target = target; 12309 } 12310 12311 get abrupt() { return this.type !== CompletionRecord.NORMAL; } 12312 12313 static makeTypeError(realm, msg) { 12314 let err; 12315 if ( msg instanceof Error ) err = realm.TypeError.makeFrom(msg); 12316 else err = realm.TypeError.make(msg); 12317 return new CompletionRecord(CompletionRecord.THROW, err); 12318 } 12319 12320 static makeReferenceError(realm, msg) { 12321 let err; 12322 if ( msg instanceof Error ) err = realm.ReferenceError.makeFrom(msg); 12323 else err = realm.ReferenceError.make(msg); 12324 return new CompletionRecord(CompletionRecord.THROW, err); 12325 } 12326 12327 static makeSyntaxError(realm, msg) { 12328 let err; 12329 if ( msg instanceof Error ) err = realm.SyntaxError.makeFrom(msg); 12330 else err = realm.SyntaxError.make(msg); 12331 return new CompletionRecord(CompletionRecord.THROW, err); 12332 } 12333 12334 static makeRangeError(realm, msg) { 12335 let err; 12336 if ( msg instanceof Error ) err = realm.RangeError.makeFrom(msg); 12337 else err = realm.RangeError.make(msg); 12338 return new CompletionRecord(CompletionRecord.THROW, err); 12339 } 12340 12341 /** 12342 * Easy access to value.addExtra. 12343 * Note: Returns a generator. 12344 * @param {Object} obj - Extra properties 12345 */ 12346 addExtra(obj) { 12347 return this.value.addExtra(obj); 12348 } 12349 12350} 12351module.exports = CompletionRecord; 12352 12353 12354 12355CompletionRecord.NORMAL = 0; 12356CompletionRecord.BREAK = 1; 12357CompletionRecord.CONTINUE = 2; 12358CompletionRecord.RETURN = 3; 12359CompletionRecord.THROW = 4; 12360 12361 12362 12363},{"./Value":111}],104:[function(require,module,exports){ 12364'use strict'; 12365 12366const Evaluator = require('./Evaluator'); 12367const Realm = require('./Realm'); 12368const Scope = require('./Scope'); 12369const Value = require('./Value'); 12370const BridgeValue = require('./values/BridgeValue'); 12371const ASTPreprocessor = require('./ASTPreprocessor'); 12372const FutureValue = require('./values/FutureValue'); 12373const EasyNativeFunction = require('./values/EasyNativeFunction'); 12374const ClosureValue = require('./values/ClosureValue'); 12375 12376let defaultOptions = { 12377 strict: false, 12378 foreignObjectMode: 'link', 12379 addInternalStack: false, 12380 executionLimit: Infinity, 12381 exposeEsperGlobal: true, 12382 extraErrorInfo: false, 12383 addExtraErrorInfoToStacks: false, 12384 bookmarkInvocationMode: 'error', 12385 yieldPower: 5, 12386 debug: false 12387}; 12388 12389/** 12390 * Container class for all of esper. 12391 */ 12392class Engine { 12393 12394 constructor(options) { 12395 options = options || {}; 12396 this.options = {}; 12397 for ( var k in defaultOptions ) { 12398 if ( k in options ) this.options[k] = options[k]; 12399 else this.options[k] = defaultOptions[k]; 12400 } 12401 this.realm = new Realm(this.options); 12402 this.evaluator = new Evaluator(this.realm, null, this.globalScope); 12403 if ( this.options.debug ) { 12404 this.evaluator.debug = true; 12405 } 12406 12407 this.evaluator.defaultYieldPower = this.options.yieldPower; 12408 this.evaluator.yieldPower = this.options.yieldPower; 12409 } 12410 12411 /** 12412 * Evalute `code` and return a promise for the result. 12413 * 12414 * @access public 12415 * @param {string} code - String of code to evaulate 12416 * @return {Promise<Value>} - The result of execution, as a promise. 12417 */ 12418 eval(code) { 12419 let ast = this.realm.parser(code); 12420 return this.evalAST(ast, {source: code}); 12421 } 12422 12423 /** 12424 * Evalute `code` and return a the result. 12425 * 12426 * @access public 12427 * @param {string} code - String of code to evaulate 12428 * @return {Value} - The result of execution 12429 */ 12430 evalSync(code) { 12431 let ast = this.realm.parser(code); 12432 return this.evalASTSync(ast, {source: code}); 12433 } 12434 12435 /** 12436 * Evalute `ast` and return a promise for the result. 12437 * 12438 * @access public 12439 * @param {Node} ast - ESTree AST representing the code to run. 12440 * @param {string} codeRef - The code that was used to generate the AST. 12441 * @return {Value} - The result of execution, as a promise. 12442 */ 12443 evalAST(ast, opts) { 12444 //console.log(escodegen.generate(ast)); 12445 this.loadAST(ast, opts); 12446 let p = this.run(); 12447 p.then(() => delete this.generator); 12448 return p; 12449 } 12450 12451 evalASTSync(ast, opts) { 12452 this.loadAST(ast, opts); 12453 let value = this.runSync(); 12454 delete this.generator; 12455 return value; 12456 } 12457 12458 loadAST(ast, opts) { 12459 let past = ASTPreprocessor.process(ast, opts); 12460 this.evaluator.frames = []; 12461 this.evaluator.pushAST(past, this.globalScope); 12462 this.evaluator.ast = past; 12463 this.generator = this.evaluator.generator(); 12464 } 12465 12466 load(code) { 12467 let ast = this.realm.parser(code); 12468 this.loadAST(ast, code); 12469 } 12470 12471 step() { 12472 if ( !this.generator ) throw new Error('No code loaded to step'); 12473 let value = this.generator.next(); 12474 return value.done; 12475 } 12476 12477 run() { 12478 let that = this; 12479 let steps = 0; 12480 function handler(value) { 12481 while ( !value.done ) { 12482 value = that.generator.next(); 12483 if ( value.value && value.value.then ) { 12484 return value.value.then((v) => { 12485 return {done: false, value: v}; 12486 }); 12487 } 12488 if ( ++steps > that.options.executionLimit ) throw new Error('Execution Limit Reached'); 12489 } 12490 return value; 12491 } 12492 return new Promise(function(resolve, reject) { 12493 try { 12494 let value = that.generator.next(); 12495 resolve(value); 12496 } catch ( e ) { 12497 reject(e); 12498 } 12499 }).then(handler).then((v) => v.value); 12500 } 12501 12502 runSync() { 12503 let steps = 0; 12504 let value = this.generator.next(); 12505 while ( !value.done ) { 12506 value = this.generator.next(); 12507 if ( value.value && value.value.then ) throw new Error('Can\'t deal with futures when running in sync mode'); 12508 if ( ++steps > this.options.executionLimit ) throw new Error('Execution Limit Reached'); 12509 } 12510 return value.value; 12511 } 12512 12513 12514 12515 /** 12516 * Refrence to the global scope. 12517 * @return {Scope} 12518 */ 12519 get globalScope() { 12520 return this.realm.globalScope; 12521 } 12522 12523 addGlobal(name, what, opts) { 12524 opts = opts || {};
12525 if ( !(what instanceof Value) ) what = this.realm.makeForForeignObject(what); 12526 if ( !opts.const ) this.globalScope.add(name, what); 12527 else this.globalScope.addConst(name, what); 12528 } 12529 12530 addGlobalFx(name, what, opts) { 12531 var x = EasyNativeFunction.makeForNative(this.realm, what); 12532 this.addGlobal(name, x, opts); 12533 } 12534 12535 addGlobalValue(name, what, opts) { 12536 this.addGlobal(name, Value.fromNative(what, this.realm), opts); 12537 } 12538 12539 addGlobalBridge(name, what, opts) { 12540 this.addGlobal(name, new BridgeValue(what, this.realm), opts); 12541 } 12542 12543 fetchFunctionSync(name, shouldYield) { 12544 var genfx = this.fetchFunction(name, shouldYield); 12545 return function() { 12546 let gen = genfx.apply(this, arguments); 12547 let val = gen.next(); 12548 //TODO: Make sure we dont await as it will loop FOREVER. 12549 while (!val.done) val = gen.next(); 12550 return val.value; 12551 }; 12552 } 12553 12554 fetchFunction(name, shouldYield) { 12555 var val = this.globalScope.get(name); 12556 return this.makeFunctionFromClosure(val, shouldYield); 12557 } 12558 12559 functionFromSource(source, shouldYield) { 12560 let code = source; 12561 let ast = this.realm.parser(code, {inFunctionBody: true}); 12562 return this.functionFromAST(ast, shouldYield); 12563 } 12564 12565 functionFromAST(ast, shouldYield, source) { 12566 let past = { 12567 type: 'FunctionExpression', 12568 body: {type: 'BlockStatement', body: ast.body}, 12569 params: [], 12570 }; 12571 past = ASTPreprocessor.process(past, {source: source}); 12572 let fx = new ClosureValue(past, this.globalScope); 12573 return this.makeFunctionFromClosure(fx, shouldYield, this.evaluator); 12574 } 12575 12576 functionFromSourceSync(source, shouldYield) { 12577 let genfx = this.functionFromSource(source, shouldYield); 12578 return function() { 12579 let gen = genfx.apply(this, arguments); 12580 let val = gen.next(); 12581 //TODO: Make sure we dont await as it will loop FOREVER. 12582 while (!val.done) val = gen.next(); 12583 return val.value; 12584 }; 12585 } 12586 12587 functionFromASTSync(ast, shouldYield, source) { 12588 let genfx = this.functionFromAST(ast, shouldYield, source); 12589 return function() { 12590 let gen = genfx.apply(this, arguments); 12591 let val = gen.next(); 12592 //TODO: Make sure we dont await as it will loop FOREVER. 12593 while (!val.done) val = gen.next(); 12594 return val.value; 12595 }; 12596 } 12597 12598 makeFunctionFromClosure(val, shouldYield, evalu) { 12599 12600 var realm = this.realm; 12601 var scope = this.globalScope; 12602 var that = this; 12603 let evaluator = evalu || this.evaluator; 12604 if ( !evaluator ) throw new Error("Evaluator is falsey"); 12605 if ( !val ) return; 12606 12607 return function*() { 12608 var realThis = realm.makeForForeignObject(this); 12609 var realArgs = new Array(arguments.length); 12610 for ( let i = 0; i < arguments.length; ++i ) { 12611 realArgs[i] = realm.makeForForeignObject(arguments[i]); 12612 } 12613 12614 12615 let c = val.call(realThis, realArgs, scope); 12616 evaluator.pushFrame({type: 'program', generator: c, scope: scope}); 12617 let gen = evaluator.generator(); 12618 12619 let last = yield * that.filterGenerator(gen, shouldYield, evaluator); 12620 if ( last ) return last.toNative(); 12621 }; 12622 } 12623 12624 /** 12625 * Returns a new engine that executes in the same Realm. Useful 12626 * for creating threads / coroutines 12627 * @return {Engine} 12628 */ 12629 fork() { 12630 let engine = new Engine(this.options); 12631 var scope = this.globalScope; 12632 12633 engine.realm = this.realm; 12634 12635 engine.evaluator = this.makeEvaluatorClone(); 12636 return engine; 12637 } 12638 12639 makeEvaluatorClone() { 12640 let evaluator = new Evaluator(this.realm, this.evaluator.ast, this.globalScope); 12641 evaluator.frames = []; 12642 if ( this.evaluator.insturment ) { 12643 evaluator.insturment = this.evaluator.insturment; 12644 } 12645 if ( this.evaluator.debug ) { 12646 evaluator.debug = true; 12647 } 12648 return evaluator; 12649 } 12650 12651 *filterGenerator(gen, shouldYield, evaluator) { 12652 let value = gen.next(); 12653 let steps = 0; 12654 if ( !evaluator ) throw new Error("Evaluator is falsey"); 12655 while ( !value.done ) { 12656 if ( !shouldYield ) yield; 12657 else if ( evaluator.topFrame.type == 'await' ) { 12658 if ( !value.value.resolved ) yield; 12659 } else { 12660 var yieldValue = shouldYield(this, evaluator, value.value); 12661 if ( yieldValue !== false ) yield yieldValue; 12662 } 12663 value = gen.next(value.value); 12664 if ( ++steps > this.options.executionLimit ) throw new Error('Execution Limit Reached'); 12665 } 12666 return value.value; 12667 } 12668} 12669 12670module.exports = Engine; 12671 12672},{"./ASTPreprocessor":102,"./Evaluator":105,"./Realm":109,"./Scope":110,"./Value":111,"./values/BridgeValue":135,"./values/ClosureValue":136,"./values/EasyNativeFunction":137,"./values/FutureValue":141}],105:[function(require,module,exports){ 12673'use strict'; 12674 12675const Value = require('./Value'); 12676const CompletionRecord = require('./CompletionRecord'); 12677const ClosureValue = require('./values/ClosureValue'); 12678const ObjectValue = require('./values/ObjectValue'); 12679const FutureValue = require('./values/FutureValue'); 12680const RegExpValue = require('./values/RegExpValue'); 12681const PropertyDescriptor = require('./values/PropertyDescriptor'); 12682const ErrorValue = require('./values/ErrorValue'); 12683const ArrayValue = require('./values/ArrayValue'); 12684const EvaluatorInstruction = require('./EvaluatorInstruction'); 12685 12686class Frame { 12687 constructor(type, o) { 12688 this.type = type; 12689 for ( var k in o ) this[k] = o[k]; 12690 } 12691} 12692 12693class Evaluator { 12694 constructor(realm, n, s) { 12695 this.realm = realm; 12696 let that = this; 12697 this.lastValue = null; 12698 this.ast = n; 12699 this.defaultYieldPower = 5; 12700 this.yieldPower = this.defaultYieldPower; 12701 this.debug = false;
12702 this.profile = false; 12703 this.lastASTNodeProcessed = null; 12704 /** 12705 * @type {Object[]} 12706 * @property {Generator} generator 12707 * @property {string} type 12708 * @property {ast} ast 12709 */ 12710 this.frames = []; 12711 if ( n ) this.pushAST(n, s); 12712 } 12713 12714 pushAST(n, s) { 12715 let that = this; 12716 let gen = n ? this.branch(n,s) : (function*() { 12717 return yield EvaluatorInstruction.stepMinor; 12718 })(); 12719 this.pushFrame({generator: gen, type: 'program', scope: s, ast: n}); 12720 } 12721 processLostFrames(frames) { 12722 for ( let f of frames ) { 12723 if ( f.profileName ) { 12724 this.incrCtr('fxTime', f.profileName, Date.now() - f.entered); 12725 } 12726 } 12727 } 12728 unwindStack(target, canCrossFxBounds, label) { 12729 let finallyFrames = []; 12730 for ( let i = 0; i < this.frames.length; ++i ) { 12731 let t = this.frames[i].type; 12732 let match = t == target || (target == 'return' && t == 'function' ); 12733 if ( match && label ) { 12734 match = label == this.frames[i].label; 12735 } 12736 12737 if ( match ) { 12738 let j = i + 1; 12739 for (; j < this.frames.length; ++j ) if ( this.frames[j].type != 'finally' ) break; 12740 let fr = this.frames[j]; 12741 this.processLostFrames(this.frames.splice(0,i + 1)); 12742 this.saveFrameShortcuts(); 12743 Array.prototype.unshift.apply(this.frames, finallyFrames); 12744 return fr; 12745 } else if ( target == 'return' && this.frames[i].retValue ) { 12746 let fr = this.frames[i]; 12747 this.processLostFrames(this.frames.splice(0, i)); 12748 this.saveFrameShortcuts(); 12749 Array.prototype.unshift.apply(this.frames, finallyFrames); 12750 return fr; 12751 } else if ( !canCrossFxBounds && this.frames[i].type == 'function' ) { 12752 break; 12753 } else if ( t == 'finally' ) { 12754 finallyFrames.push(this.frames[i]); 12755 } 12756 } 12757 return false; 12758 } 12759 12760 next(lastValueOveride) { 12761 let frames = this.frames; 12762 12763 //Implement proper tailcalls by hand. 12764 do { 12765 let top = frames[0]; 12766 let result; 12767 //console.log(top.type, top.ast && top.ast.type); 12768 12769 if ( top.exception ) { 12770 this.lastValue = top.exception; 12771 delete top.exception; 12772 } else if ( top.retValue ) { 12773 this.lastValue = top.retValue; 12774 delete top.retValue; 12775 } 12776 12777 result = top.generator.next(lastValueOveride || this.lastValue); 12778 lastValueOveride = undefined; 12779 let val = result.value; 12780 12781 if ( val instanceof EvaluatorInstruction ) { 12782 switch ( val.type ) { 12783 case 'branch': 12784 this.branchFrame(val.kind, val.ast, val.scope, val.extra); 12785 continue; 12786 case 'getEvaluator': 12787 //lastValueOveride = this; 12788 //continue; 12789 return this.next(this); 12790 case 'waitForFramePop': 12791 continue; 12792 case 'framePushed': 12793 continue; 12794 case 'event': 12795 case 'step': 12796 if ( this.instrument ) this.instrument(this, val); 12797 return {done: false, value: val}; 12798 } 12799 } 12800 12801 if ( val instanceof CompletionRecord ) { 12802 this.processCompletionValueMeaning(val); 12803 this.lastValue = val.value; 12804 continue; 12805 } 12806 //if ( !val ) console.log("Bad val somewhere around", this.topFrame.type); 12807 if ( this.instrument ) this.instrument(this, val); 12808 12809 if ( val && val.then ) { 12810 if ( top && top.type !== 'await' ) { 12811 this.pushFrame({generator: (function *(f) { 12812 while ( !f.resolved ) yield f; 12813 if ( f.successful ) { 12814 return f.value; 12815 } else { 12816 return new CompletionRecord(CompletionRecord.THROW, f.value); 12817 } 12818 })(val), type: 'await'}); 12819 } 12820 return {done: false, value: val}; 12821 } 12822 12823 this.lastValue = val; 12824 if ( result.done ) { 12825 let lastFrame = this.popFrame(); 12826 12827 if ( lastFrame.profileName ) { 12828 this.processLostFrames([lastFrame]); 12829 } 12830 12831 // Latient values can't cross function calls. 12832 // Dont do this, and you get coffeescript mode. 12833 if ( lastFrame.type === 'function' && !lastFrame.returnLastValue ) { 12834 this.lastValue = Value.undef; 12835 } 12836 12837 if ( frames.length === 0 ) { 12838 if ( this.debug ) { 12839 this.dumpProfilingInformation(); 12840 } 12841 return {done: true, value: result.value}; 12842 } else continue; 12843 } 12844 } while ( false ); 12845 12846 return {done: false, value: this.lastValue}; 12847 } 12848 12849 processCompletionValueMeaning(val) { 12850 if ( !(val.value instanceof Value) ) { 12851 if ( val.value instanceof Error ) { 12852 throw new Error('Value was an error: ' + val.value.stack); 12853 } 12854 throw new Error('Value isnt of type Value, its' + val.value.toString()); 12855 } 12856 12857 switch ( val.type ) { 12858 case CompletionRecord.CONTINUE: 12859 if ( this.unwindStack('continue', false, val.target) ) return true; 12860 throw new Error('Cant find matching loop frame for continue'); 12861 case CompletionRecord.BREAK: 12862 if ( this.unwindStack('loop', false, val.target) ) return true; 12863 throw new Error('Cant find matching loop frame for break'); 12864 case CompletionRecord.RETURN: 12865 let rfr = this.unwindStack('return', false); 12866 if ( !rfr ) throw new Error('Cant find function bounds.'); 12867 rfr.retValue = val.value; 12868 return true; 12869 case CompletionRecord.THROW: 12870 //TODO: Fix this nonsense: 12871 let e = val.value.toNative(); 12872 //val.value.native = e; 12873 12874 let smallStack; 12875 if ( e && e.stack ) smallStack = e.stack.split(/\n/).slice(0,4).join('\n'); 12876 let stk = this.buildStacktrace(e).join('\n '); 12877 let bestFrame; 12878 for ( let i = 0; i < this.frames.length; ++i ) { 12879 if ( this.frames[i].ast ) { 12880 bestFrame = this.frames[i]; 12881 break; 12882 } 12883 } 12884 12885 if ( val.value instanceof ErrorValue ) { 12886 if ( this.realm.options.addExtraErrorInfoToStacks && val.value.extra ) { 12887 stk += '\n-------------'; 12888 for ( let key in val.value.extra ) { 12889 let vv = val.value.extra[key]; 12890 if ( vv instanceof Value ) stk += `\n${key} => ${vv.debugString}`; 12891 else stk += `\n${key} => ${vv}`; 12892 } 12893 } 12894 } 12895 12896 if ( e instanceof Error ) { 12897 e.stack = stk; 12898 if ( smallStack && this.realm.options.addInternalStack ) e.stack += '\n-------------\n' + smallStack; 12899 if ( bestFrame ) { 12900 e.range = bestFrame.ast.range; 12901 e.loc = bestFrame.ast.loc; 12902 } 12903 } 12904 12905 if ( val.value instanceof ErrorValue ) { 12906 if ( !val.value.has('stack') ) {
12907 val.value.setImmediate('stack', Value.fromNative(stk)); 12908 val.value.properties['stack'].enumerable = false; 12909 } 12910 } 12911 12912 let tfr = this.unwindStack('catch', true); 12913 if ( tfr ) { 12914 tfr.exception = val; 12915 this.lastValue = val; 12916 return true; 12917 } 12918 let line = -1; 12919 if ( this.topFrame.ast && this.topFrame.ast.attr) { 12920 line = this.topFrame.ast.attr.pos.start_line; 12921 } 12922 //console.log(this.buildStacktrace(val.value.toNative())); 12923 throw val.value.toNative(); 12924 case CompletionRecord.NORMAL: 12925 return false; 12926 } 12927 } 12928 12929 buildStacktrace(e) { 12930 let lines = e ? [e.toString()] : []; 12931 for ( var f of this.frames ) { 12932 //if ( f.type !== 'function' ) continue; 12933 if ( f.ast ) { 12934 let line = 'at ' + (f.ast.srcName || f.ast.type) + ' '; 12935 if ( f.ast.loc ) line += '(<src>:' + f.ast.loc.start.line + ':' + f.ast.loc.start.column + ')'; 12936 lines.push(line); 12937 } 12938 } 12939 return lines; 12940 } 12941 pushFrame(frame) { 12942 frame.srcAst = frame.ast; 12943 if ( frame.yieldPower === undefined ) frame.yieldPower = this.defaultYieldPower; 12944 this.frames.unshift(new Frame(frame.type, frame)); 12945 this.saveFrameShortcuts(); 12946 } 12947 12948 popFrame() { 12949 let frame = this.frames.shift(); 12950 this.saveFrameShortcuts(); 12951 return frame; 12952 } 12953 12954 saveFrameShortcuts() { 12955 let prev = this.yieldPower; 12956 if ( this.frames.length == 0 ) { 12957 this.topFrame = undefined; 12958 this.yieldPower = this.defaultYieldPower; 12959 } else { 12960 this.topFrame = this.frames[0]; 12961 this.yieldPower = this.topFrame.yieldPower; 12962 } 12963 } 12964 12965 fromNative(native) { 12966 return this.realm.valueFromNative(native); 12967 } 12968 12969 generator() { 12970 return {next: this.next.bind(this), throw: (e) => { throw e; }}; 12971 } 12972 12973 breakFrames() { 12974 12975 } 12976 12977 12978 *resolveRef(n, s, create) { 12979 let oldAST = this.topFrame.ast; 12980 this.topFrame.ast = n; 12981 switch (n.type) { 12982 case 'Identifier': 12983 let iref = s.ref(n.name, s.realm); 12984 if ( !iref ) { 12985 iref = { 12986 getValue: function*() { 12987 let err = CompletionRecord.makeReferenceError(s.realm, `${n.name} is not defined`); 12988 yield * err.addExtra({code: 'UndefinedVariable', when: 'read', ident: n.name, strict: s.strict}); 12989 return yield err; 12990 }, 12991 del: function() { 12992 return true; 12993 } 12994 }; 12995 if ( !create || s.strict ) { 12996 iref.setValue = function *() { 12997 let err = CompletionRecord.makeReferenceError(s.realm, `${n.name} is not defined`); 12998 yield * err.addExtra({code: 'UndefinedVariable', when: 'write', ident: n.name, strict: s.strict}); 12999 return yield err; 13000 }; 13001 } else { 13002 iref.setValue = function *(value) { 13003 s.global.set(n.name, value, s); 13004 let aref = s.global.ref(n.name, s.realm); 13005 this.setValue = aref.setValue; 13006 this.getValue = aref.getValue; 13007 this.del = aref.delete; 13008 }; 13009 } 13010 } 13011 this.topFrame.ast = oldAST; 13012 return iref;
13013 case 'MemberExpression': 13014 let idx; 13015 let ref = yield * this.branch(n.object, s); 13016 if ( n.computed ) { 13017 idx = (yield * this.branch(n.property, s)).toNative(); 13018 } else { 13019 idx = n.property.name; 13020 } 13021 13022 if ( !ref ) { 13023 return yield CompletionRecord.makeTypeError(s.realm, `Can't write property of undefined: ${idx}`); 13024 } 13025 13026 if ( !ref.ref ) { 13027 return yield CompletionRecord.makeTypeError(s.realm, `Can't write property of non-object type: ${idx}`); 13028 } 13029 13030 this.topFrame.ast = oldAST; 13031 return ref.ref(idx, s.realm); 13032 13033 default: 13034 return yield CompletionRecord.makeTypeError(s.realm, `Couldnt resolve ref component: ${n.type}`); 13035 } 13036 } 13037 13038 *partialMemberExpression(left, n, s) { 13039 if ( n.computed ) { 13040 let right = yield * this.branch(n.property,s); 13041 return yield * left.get(right.toNative(), s.realm); 13042 } else if ( n.property.type == 'Identifier') { 13043 if ( !left ) throw `Cant index ${n.property.name} of undefined`; 13044 return yield * left.get(n.property.name, s.realm); 13045 } else { 13046 if ( !left ) throw `Cant index ${n.property.value.toString()} of undefined`; 13047 return yield * left.get(n.property.value.toString(), s.realm); 13048 } 13049 } 13050 13051 //NOTE: Returns generator, fast return yield *; 13052 doBinaryEvaluation(operator, left, right, realm) { 13053 switch ( operator ) { 13054 case '==': return left.doubleEquals(right, realm); 13055 case '!=': return left.notEquals(right, realm); 13056 case '===': return left.tripleEquals(right, realm); 13057 case '!==': return left.doubleNotEquals(right, realm); 13058 case '+': return left.add(right, realm); 13059 case '-': return left.subtract(right, realm); 13060 case '*': return left.multiply(right, realm); 13061 case '/': return left.divide(right, realm); 13062 case '%': return left.mod(right, realm); 13063 case '|': return left.bitOr(right, realm); 13064 case '^': return left.bitXor(right, realm); 13065 case '&': return left.bitAnd(right, realm); 13066 case 'in': return right.inOperator(left, realm); 13067 case 'instanceof': return left.instanceOf(right, realm); 13068 case '>': return left.gt(right, realm); 13069 case '<': return left.lt(right, realm); 13070 case '>=': return left.gte(right, realm); 13071 case '<=': return left.lte(right, realm); 13072 case '<<': return left.shiftLeft(right, realm); 13073 case '>>': return left.shiftRight(right, realm); 13074 case '>>>': return left.shiftRightZF(right, realm); 13075 default: 13076 throw new Error('Unknown binary operator: ' + operator); 13077 } 13078 } 13079 13080 branchFrame(type, n, s, extra) { 13081 let frame = {generator: this.branch(n,s), type: type, scope: s, ast: n}; 13082 13083 if ( extra ) { 13084 for ( var k in extra ) { 13085 frame[k] = extra[k]; 13086 } 13087 if ( extra.profileName ) { 13088 frame.entered = Date.now(); 13089 } 13090 } 13091 this.pushFrame(frame); 13092 return EvaluatorInstruction.framePushed; 13093 } 13094 13095 beforeNode(n) { 13096 let tf = this.topFrame; 13097 let state = {top: tf, ast: tf.ast, node: n}; 13098 this.lastASTNodeProcessed = n; 13099 if ( this.debug ) this.incrCtr('astInvocationCount', n.type); 13100 tf.ast = n; 13101 return state; 13102 } 13103 13104 afterNode(state, r) { 13105 let tf = this.topFrame; 13106 tf.value = r; 13107 tf.ast = state.ast; 13108 } 13109 13110 /** 13111 * @private 13112 * @param {object} n - AST Node to dispatch 13113 * @param {Scope} s - Current evaluation scope 13114 */ 13115 branch(n, s) { 13116 if ( !n.dispatch ) { 13117 let nextStep = this.findNextStep(n.type); 13118 13119 n.dispatch = function*(that, n, s) { 13120 let state = that.beforeNode(n); 13121 13122 let result = yield * nextStep(that, n,s); 13123 if ( result instanceof CompletionRecord ) result = yield result; 13124 if ( result && result.then ) result = yield result; 13125 13126 that.afterNode(state, result); 13127 13128 return result; 13129 }; 13130 } 13131 return n.dispatch(this, n, s); 13132 } 13133 13134 incrCtr(n, c, v) { 13135 if ( v === undefined ) v = 1; 13136 if ( !this.profile ) this.profile = {}; 13137 let o = this.profile[n]; 13138 if ( !o ) { 13139 o = {}; 13140 this.profile[n] = o; 13141 } 13142 c = c || '???'; 13143 if ( c in o ) o[c] += v 13144 else o[c] = v; 13145 } 13146 13147 13148 dumpProfilingInformation() { 13149 function lpad(s, l) { return s + new Array(Math.max(l - s.length,1)).join(' '); } 13150 13151 if ( !this.profile ) { 13152 console.log("===== Profile: None collected ====="); 13153 return; 13154 } 13155 13156 console.log('===== Profile ====='); 13157 for ( let sec in this.profile ) { 13158 console.log(sec + ' Stats:'); 13159 let o = this.profile[sec]; 13160 let okeys = Object.keys(o).sort((a,b) => o[b] - o[a]); 13161 for ( let name of okeys ) { 13162 console.log(` ${lpad(name, 20)}: ${o[name]}`); 13163 } 13164 } 13165 console.log('================='); 13166 } 13167 13168 get insterment() { return this.instrument; } 13169 set insterment(v) { this.instrument = v; } 13170} 13171 13172Evaluator.prototype.findNextStep = require('./EvaluatorHandlers'); 13173 13174module.exports = Evaluator; 13175 13176},{"./CompletionRecord":103,"./EvaluatorHandlers":106,"./EvaluatorInstruction":107,"./Value":111,"./values/ArrayValue":134,"./values/ClosureValue":136,"./values/ErrorValue":140,"./values/FutureValue":141,"./values/ObjectValue":145,"./values/PropertyDescriptor":147,"./values/RegExpValue":148}],106:[function(require,module,exports){ 13177'use strict'; 13178 13179const Value = require('./Value'); 13180const CompletionRecord = require('./CompletionRecord'); 13181const ClosureValue = require('./values/ClosureValue'); 13182const ObjectValue = require('./values/ObjectValue'); 13183const FutureValue = require('./values/FutureValue'); 13184const RegExpValue = require('./values/RegExpValue'); 13185const PropertyDescriptor = require('./values/PropertyDescriptor'); 13186const ErrorValue = require('./values/ErrorValue'); 13187const ArrayValue = require('./values/ArrayValue'); 13188const EvaluatorInstruction = require('./EvaluatorInstruction'); 13189 13190 13191 13192function *evaluateArrayExpression(e, n, s) { 13193 //let result = new ObjectValue(); 13194 let result = new Array(n.elements.length); 13195 for ( let i = 0; i < n.elements.length; ++i ) { 13196 if ( n.elements[i] ) { 13197 result[i] = yield * e.branch(n.elements[i],s); 13198 } 13199 } 13200 if ( e.yieldPower >= 3 ) yield EvaluatorInstruction.stepMinor; 13201 return ArrayValue.make(result, e.realm); 13202} 13203 13204function *evaluateAssignmentExpression(e, n, s) { 13205 //TODO: Account for not-strict mode 13206 var realm = s.realm; 13207 let ref = yield * e.resolveRef(n.left, s, n.operator === '='); 13208 13209 if ( !ref && s.strict ) { 13210 return CompletionRecord.makeReferenceError(s.realm, `Invalid refrence in assignment.`); 13211 } 13212
13213 let argument = yield * e.branch(n.right, s); 13214 let value; 13215 let cur; 13216 if ( e.yieldPower >= 3 ) yield EvaluatorInstruction.stepMinor; 13217 switch ( n.operator ) { 13218 case '=': 13219 value = argument; 13220 break; 13221 case '+=': 13222 cur = yield * ref.getValue(); 13223 value = yield * cur.add(argument, realm); 13224 break; 13225 case '-=': 13226 cur = yield * ref.getValue(); 13227 value = yield * cur.subtract(argument, realm); 13228 break; 13229 case '*=': 13230 cur = yield * ref.getValue(); 13231 value = yield * cur.multiply(argument, realm); 13232 break; 13233 case '/=': 13234 cur = yield * ref.getValue(); 13235 value = yield * cur.divide(argument, realm); 13236 break; 13237 case '%=': 13238 cur = yield * ref.getValue(); 13239 value = yield * cur.mod(argument, realm); 13240 break; 13241 case '<<=': 13242 cur = yield * ref.getValue(); 13243 value = yield * cur.shiftLeft(argument, realm); 13244 break; 13245 case '>>=': 13246 cur = yield * ref.getValue(); 13247 value = yield * cur.shiftRight(argument, realm); 13248 break; 13249 case '>>>=': 13250 cur = yield * ref.getValue(); 13251 value = yield * cur.shiftRightZF(argument, realm); 13252 break; 13253 case '|=': 13254 cur = yield * ref.getValue(); 13255 value = yield * cur.bitOr(argument, realm); 13256 break; 13257 case '&=': 13258 cur = yield * ref.getValue(); 13259 value = yield * cur.bitAnd(argument, realm); 13260 break; 13261 case '^=': 13262 cur = yield * ref.getValue(); 13263 value = yield * cur.bitXor(argument, realm); 13264 break; 13265 default: 13266 throw new Error('Unknown assignment operator: ' + n.operator); 13267 } 13268 13269 if ( ref ) { 13270 yield * ref.setValue(value, s); 13271 } else { 13272 yield * s.put(n.left.name, value, s); 13273 } 13274 13275 return value; 13276} 13277 13278function *evaulateBinaryExpression(e, n, s) { 13279 let left = yield * e.branch(n.left,s); 13280 let right = yield * e.branch(n.right,s); 13281 if ( e.yieldPower >= 4 ) yield EvaluatorInstruction.stepMinor; 13282 return yield * e.doBinaryEvaluation(n.operator, left, right, s); 13283} 13284 13285function *evaluateBlockStatement(e, n, s) { 13286 let result = Value.undef; 13287 for ( let statement of n.body ) { 13288 result = yield * e.branch(statement,s); 13289 } 13290 return result; 13291} 13292 13293 13294function *evaluateBreakStatement(e, n, s) { 13295 let label = n.label ? n.label.name : undefined; 13296 if ( e.yieldPower >= 1 ) yield EvaluatorInstruction.stepMinor; 13297 return new CompletionRecord(CompletionRecord.BREAK, Value.undef, label); 13298} 13299 13300 13301function *evaluateCallExpression(e, n, s) { 13302 let thiz = Value.undef; 13303 13304 let callee, base; 13305 13306 if ( n.callee.type === 'MemberExpression' ) { 13307 thiz = base = yield * e.branch(n.callee.object, s); 13308 callee = yield * e.partialMemberExpression(thiz, n.callee, s); 13309 if ( callee instanceof CompletionRecord ) { 13310 if ( callee.type == CompletionRecord.THROW ) return callee; 13311 callee = callee.value; 13312 } 13313 } else { 13314 callee = yield * e.branch(n.callee, s); 13315 } 13316 13317 if ( n.type === 'NewExpression' ) { 13318 thiz = yield * callee.makeThisForNew(s.realm); 13319 if ( thiz instanceof CompletionRecord ) { 13320 if ( thiz.type == CompletionRecord.THROW ) return thiz; 13321 thiz = thiz.value; 13322 } 13323 } 13324 13325 if ( typeof callee.rawCall === 'function' ) { 13326 return yield * callee.rawCall(n, e, s); 13327 } 13328 13329 //console.log("Calling", callee, callee.call); 13330 13331 let args = new Array(n.arguments.length); 13332 for ( let i = 0; i < n.arguments.length; ++i ) { 13333 args[i] = yield * e.branch(n.arguments[i],s); 13334 } 13335 13336 let name = n.callee.srcName || callee.jsTypeName; 13337 13338 if ( e.yieldPower >= 1 ) yield EvaluatorInstruction.stepMajor; 13339 13340 if ( !callee.isCallable ) { 13341 let err = CompletionRecord.makeTypeError(e.realm, '' + name + ' is not a function'); 13342 yield * err.addExtra({ 13343 code: 'CallNonFunction', 13344 target: callee, 13345 targetAst: n.callee, 13346 targetName: name, 13347 base: base 13348 }); 13349 return err; 13350 } 13351 13352 if ( e.debug ) { 13353 e.incrCtr('fxInvocationCount', n.callee.srcName); 13354 } 13355 13356 let callResult = callee.call(thiz, args, s, { 13357 asConstructor: n.type === 'NewExpression', 13358 callNode: n, 13359 evaluator: e 13360 }); 13361 13362 if ( callResult instanceof CompletionRecord ) return callResult; 13363 13364 if ( typeof callResult.next !== 'function' ) { 13365 console.log('Generator Failure', callResult); 13366 return CompletionRecord.makeTypeError(e.realm, '' + name + ' didnt make a generator'); 13367 } 13368 13369 let result = yield * callResult; 13370 if ( n.type === 'NewExpression' ) { 13371 //TODO: If a constructor returns, you actually use that value 13372 if ( result instanceof Value ) { 13373 if ( result.specTypeName === 'undefined' ) return thiz; 13374 return result; 13375 } 13376 return thiz; 13377 } else { 13378 return result; 13379 } 13380} 13381 13382function *evaluateClassExpression(e, n, s) { 13383 let clazz = new ObjectValue(e.realm); 13384 clazz.call = function*() { return Value.undef; }; 13385 13386 let proto = new ObjectValue(e.realm); 13387 yield * clazz.set('prototype', proto); 13388 yield * proto.set('constructor', clazz); 13389 13390 if ( e.yieldPower >= 3 ) yield EvaluatorInstruction.stepMinor; 13391 for ( let m of n.body.body ) { 13392 let fx = yield * e.branch(m.value, s); 13393
13394 //TODO: Support getters and setters 13395 if ( m.kind == 'constructor' ) { 13396 clazz.call = function*(thiz, args, s) { return yield * fx.call(thiz,args,s); }; 13397 13398 } else { 13399 let ks; 13400 if ( m.computed ) { 13401 let k = yield * e.branch(m.key, s); 13402 ks = yield * k.toStringNative(e.realm); 13403 } else { 13404 ks = m.key.name; 13405 } 13406 13407 if ( m.static ) clazz.setImmediate(ks, fx); 13408 else proto.setImmediate(ks, fx); 13409 } 13410 } 13411 return clazz; 13412} 13413 13414function *evaluateClassDeclaration(e, n, s) { 13415 let clazz = yield * evaluateClassExpression(e, n, s); 13416 yield * s.put(n.id.name, clazz); 13417 return clazz; 13418} 13419 13420function *evaluateConditionalExpression(e, n, s) { 13421 let test = yield * e.branch(n.test, s); 13422 if ( e.yieldPower >= 4 ) yield EvaluatorInstruction.stepMinor; 13423 if ( test.truthy ) { 13424 return yield * e.branch(n.consequent, s); 13425 } else { 13426 if ( n.alternate ) { 13427 return yield * e.branch(n.alternate, s); 13428 } 13429 } 13430 return Value.undef; 13431} 13432 13433 13434function *evaluateContinueStatement(e, n, s) { 13435 let label = n.label ? n.label.name : undefined; 13436 let val = new CompletionRecord(CompletionRecord.CONTINUE, Value.undef, label); 13437 if ( e.yieldPower >= 1 ) yield EvaluatorInstruction.stepMinor; 13438 return val; 13439} 13440 13441function *evaluateDoWhileStatement(e, n, s) { 13442 let last = Value.undef; 13443 let that = e; 13444 var gen = function*() { 13445 do { 13446 last = yield that.branchFrame('continue', n.body, s, {label: n.label}); 13447 } while ( (yield * that.branch(n.test,s)).truthy ); 13448 }; 13449 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.stepMinor; 13450 e.pushFrame({generator: gen(), type: 'loop', label: n.label, ast: n}); 13451 13452 13453 let finished = yield EvaluatorInstruction.waitForFramePop; 13454 return Value.undef; 13455} 13456 13457function *evaluateEmptyStatement(e, n, s) { 13458 if ( e.yieldPower >= 5 ) yield EvaluatorInstruction.stepMinor; 13459 return Value.undef; 13460} 13461 13462function *evaluateExpressionStatement(e, n, s) { 13463 if ( e.yieldPower > 4 ) yield EvaluatorInstruction.stepMinor; 13464 return yield * e.branch(n.expression,s); 13465} 13466 13467function *evaluateIdentifier(e, n, s) { 13468 if ( e.yieldPower >= 4 ) yield EvaluatorInstruction.stepMinor; 13469 if ( n.name === 'undefined' ) return Value.undef; 13470 if ( !s.has(n.name) ) { 13471 // Allow undeclared varibles to be null? 13472 if ( false ) return Value.undef; 13473 let err = CompletionRecord.makeReferenceError(e.realm, `${n.name} is not defined`); 13474 yield * err.addExtra({code: 'UndefinedVariable', when: 'read', ident: n.name, strict: s.strict}); 13475 return yield err; 13476 } 13477 return s.get(n.name); 13478} 13479 13480function *evaluateIfStatement(e, n, s) { 13481 if ( e.yieldPower >= 2 ) yield EvaluatorInstruction.stepStatement; 13482 let test = yield * e.branch(n.test, s); 13483 if ( test.truthy ) { 13484 return yield * e.branch(n.consequent, s); 13485 } else { 13486 if ( n.alternate ) { 13487 return yield * e.branch(n.alternate, s); 13488 } 13489 } 13490 return Value.undef; 13491} 13492 13493function* genForLoop(e, n, s) { 13494 let test = Value.true; 13495 if ( n.test ) test = yield * e.branch(n.test,s); 13496 let last = Value.undef; 13497 while ( test.truthy ) { 13498 e.topFrame.ast = n; 13499 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.eventLoopBodyStart; 13500 last = yield e.branchFrame('continue', n.body, s, {label: n.label}); 13501 if ( n.update ) yield * e.branch(n.update,s); 13502 if ( n.test ) test = yield * e.branch(n.test,s); 13503 } 13504}; 13505 13506function *evaluateForStatement(e, n, s) { 13507 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.stepStatement; 13508 if ( n.init ) yield * e.branch(n.init,s); 13509 13510 e.pushFrame({generator: genForLoop(e, n, s), type: 'loop', label: n.label, ast: n}); 13511 13512 13513 let finished = yield EvaluatorInstruction.waitForFramePop; 13514 return Value.undef; 13515} 13516 13517function *evaluateForInStatement(e, n, s) { 13518 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.stepStatement; 13519 let last = Value.undef; 13520 let object = yield * e.branch(n.right,s); 13521 let names = object.observableProperties(s.realm); 13522 let that = e; 13523 let ref; 13524 13525 if ( n.left.type === 'VariableDeclaration' ) { 13526 s.add(n.left.declarations[0].id.name, Value.undef); 13527 ref = s.ref(n.left.declarations[0].id.name, s.realm); 13528 } else { 13529 ref = s.ref(n.left.name, s.realm); 13530 } 13531 13532 var gen = function*() { 13533 for ( let name of names ) { 13534 yield * ref.setValue(name); 13535 last = yield that.branchFrame('continue', n.body, s, {label: n.label}); 13536 } 13537 }; 13538 e.pushFrame({generator: gen(), type: 'loop', label: n.label, ast: n}); 13539 13540 13541 let finished = yield EvaluatorInstruction.waitForFramePop; 13542 return Value.undef; 13543} 13544 13545//TODO: For of does more crazy Symbol iterator stuff
13546function *evaluateForOfStatement(e, n, s) { 13547 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.stepStatement; 13548 let last = Value.undef; 13549 let object = yield * e.branch(n.right,s); 13550 let names = object.observableProperties(s.realm); 13551 let that = e; 13552 let ref; 13553 13554 if ( n.left.type === 'VariableDeclaration' ) { 13555 yield * s.put(n.left.declarations[0].id.name, Value.undef); 13556 ref = s.ref(n.left.declarations[0].id.name, s.realm); 13557 } else { 13558 ref = s.ref(n.left.name, s.realm); 13559 } 13560 13561 var gen = function*() { 13562 for ( let name of names ) { 13563 yield * ref.setValue(yield * object.get(yield * name.toStringNative())); 13564 last = yield that.branchFrame('continue', n.body, s, {label: n.label}); 13565 } 13566 }; 13567 e.pushFrame({generator: gen(), type: 'loop', label: n.label}); 13568 13569 13570 let finished = yield EvaluatorInstruction.waitForFramePop; 13571 return Value.undef; 13572} 13573 13574function *evaluateFunctionDeclaration(e, n, s) { 13575 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.stepMajor; 13576 let closure = new ClosureValue(n, s); 13577 s.add(n.id.name, closure); 13578 return Value.undef; 13579} 13580 13581function *evaluateFunctionExpression(e, n, s) { 13582 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.stepMajor; 13583 let value = new ClosureValue(n, s); 13584 if ( n.type === 'ArrowFunctionExpression' ) { 13585 value.thiz = s.thiz; 13586 if ( n.expression ) value.returnLastValue = true; 13587 } 13588 return value; 13589} 13590 13591function *evaluateLabeledStatement(e, n, s) { 13592 if ( e.yieldPower >= 5 ) yield EvaluatorInstruction.stepMinor; 13593 return yield * e.branch(n.body, s); 13594} 13595 13596function *evaulateLiteral(e, n, s) { 13597 if ( e.yieldPower >= 5 ) yield EvaluatorInstruction.stepMinor; 13598 if ( n.regex ) { 13599 return RegExpValue.make(new RegExp(n.regex.pattern, n.regex.flags), s.realm); 13600 } else if ( n.value === null ) { 13601 if ( e.raw === 'null' ) return Value.null; 13602 13603 //Work around Esprima turning Infinity into null. =\ 13604 let tryFloat = parseFloat(n.raw); 13605 if ( !isNaN(tryFloat) ) return e.fromNative(tryFloat); 13606 return e.fromNative(null); 13607 } else { 13608 return e.fromNative(n.value); 13609 } 13610} 13611 13612function *evaluateLogicalExpression(e, n, s) { 13613 let left = yield * e.branch(n.left,s); 13614 if ( e.yieldPower >= 4 ) yield EvaluatorInstruction.stepMajor; 13615 switch ( n.operator ) { 13616 case '&&': 13617 if ( left.truthy ) return yield * e.branch(n.right,s); 13618 return left; 13619 case '||': 13620 if ( left.truthy ) return left; 13621 return yield * e.branch(n.right,s); 13622 default: 13623 throw new Error('Unknown logical operator: ' + n.operator); 13624 } 13625 13626} 13627 13628function *evaluateMemberExpression(e, n, s) { 13629 if ( e.yieldPower >= 4 ) yield EvaluatorInstruction.stepMinor; 13630 let left = yield * e.branch(n.object,s); 13631 return yield * e.partialMemberExpression(left, n, s); 13632} 13633 13634function *evaluateObjectExpression(e, n, s) { 13635 //TODO: Need to wire up native prototype 13636 var nat = new ObjectValue(s.realm); 13637 for ( let i = 0; i < n.properties.length; ++i ) { 13638 let prop = n.properties[i]; 13639 let key; 13640 if ( n.computed ) { 13641 key = (yield * e.branch(prop.key, s)).toNative().toString(); 13642 } else if ( prop.key.type == 'Identifier') { 13643 key = prop.key.name; 13644 } else if ( prop.key.type == 'Literal' ) { 13645 key = prop.key.value.toString(); 13646 } 13647 13648 let value = yield * e.branch(prop.value, s); 13649 let pd; 13650 13651 if ( Object.prototype.hasOwnProperty.call(nat.properties, key) ) { 13652 pd = nat.properties[key]; 13653 } else { 13654 pd = new PropertyDescriptor(Value.undef); 13655 nat.rawSetProperty(key, pd); 13656 } 13657 13658 switch ( prop.kind ) { 13659 case 'init': 13660 default: 13661 pd.value = value; 13662 break; 13663 case 'get': 13664 pd.getter = value; 13665 break; 13666 case 'set': 13667 pd.setter = value; 13668 break; 13669 } 13670 13671 } 13672 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.stepMajor; 13673 return nat; 13674} 13675 13676function *evaluateProgram(e, n, s) { 13677 let result = Value.undef; 13678 if ( n.vars ) 13679 for ( var v in n.vars ) { 13680 s.add(v, Value.undef); 13681 } 13682 if ( n.strict === true ) s.strict = true; 13683 if ( e.yieldPower >= 4 ) yield EvaluatorInstruction.stepMajor; 13684 for ( let statement of n.body ) { 13685 result = yield * e.branch(statement, s); 13686 } 13687 return result; 13688} 13689
13690function *evaluateReturnStatement(e, n, s) { 13691 let retVal = Value.undef; 13692 if ( n.argument ) retVal = yield * e.branch(n.argument,s); 13693 if ( e.yieldPower >= 2 ) yield EvaluatorInstruction.stepMajor; 13694 return new CompletionRecord(CompletionRecord.RETURN, retVal); 13695} 13696 13697function *evaluateSequenceExpression(e, n, s) { 13698 let last = Value.undef; 13699 if ( e.yieldPower >= 4 ) yield EvaluatorInstruction.stepMajor; 13700 for ( let expr of n.expressions ) { 13701 last = yield * e.branch(expr,s); 13702 } 13703 return last; 13704} 13705 13706function *evaluateSwitchStatement(e, n, s) { 13707 if ( e.yieldPower >= 2 ) yield EvaluatorInstruction.stepMajor; 13708 let discriminant = yield * e.branch(n.discriminant, s); 13709 let last = Value.undef; 13710 let matches = 0; 13711 let matchVals = new Array(n.cases.length); 13712 let matched = false; 13713 13714 for ( let i = 0; i < n.cases.length; ++i ) { 13715 let cas = n.cases[i]; 13716 if ( cas.test ) { 13717 let testval = yield * e.branch(cas.test, s); 13718 let equality = yield * testval.tripleEquals(discriminant); 13719 if ( equality.truthy ) ++matches; 13720 matchVals[i] = equality.truthy; 13721 } 13722 } 13723 13724 13725 let genSwitch = function*(e, n) { 13726 13727 for ( let i = 0; i < n.cases.length; ++i ) { 13728 let cas = n.cases[i]; 13729 if ( !matched ) { 13730 if ( cas.test ) { 13731 if ( !matchVals[i] ) continue; 13732 } else { 13733 if ( matches !== 0 ) continue; 13734 } 13735 matched = true; 13736 } 13737 for ( let statement of cas.consequent ) { 13738 last = yield * e.branch(statement, s); 13739 } 13740 } 13741 }; 13742 13743 e.pushFrame({generator: genSwitch(e, n), type: 'loop', label: n.label}); 13744 let finished = yield EvaluatorInstruction.waitForFramePop; 13745 13746 return last; 13747} 13748 13749function *evaluateThisExpression(e, n, s) { 13750 if ( e.yieldPower >= 4 ) yield EvaluatorInstruction.stepMajor; 13751 if ( s.thiz ) return s.thiz; 13752 else return Value.undef; 13753} 13754 13755function *evaluateThrowStatement(e, n, s) { 13756 let value = yield * e.branch(n.argument, s); 13757 if ( e.yieldPower >= 2 ) yield EvaluatorInstruction.stepMajor; 13758 return new CompletionRecord(CompletionRecord.THROW, value); 13759} 13760 13761function *evaluateTryStatement(e, n, s) { 13762 if ( e.yieldPower >= 2 ) yield EvaluatorInstruction.stepMajor; 13763 if ( n.finalizer ) e.pushFrame({generator: e.branch(n.finalizer,s), type: 'finally', scope: s}); 13764 let result = yield e.branchFrame('catch', n.block, s); 13765 if ( result instanceof CompletionRecord && result.type == CompletionRecord.THROW ) { 13766 if ( !n.handler ) { 13767 //console.log("No catch..., throwing", result.obj); 13768 return result; 13769 } 13770 let handlerScope = s.createChild(); 13771 handlerScope.add(n.handler.param.name, result.value); 13772 return yield * e.branch(n.handler.body, handlerScope); 13773 } 13774 return result; 13775} 13776 13777function *evaluateUpdateExpression(e, n, s) { 13778 //TODO: Need to support something like ++x[1]; 13779 let nue; 13780 if ( e.yieldPower >= 3 ) yield EvaluatorInstruction.stepMajor; 13781 let ref = yield * e.resolveRef(n.argument, s, true); 13782 let old = Value.nan; 13783 13784 if ( ref ) old = yield * ref.getValue(); 13785 if ( old === undefined ) old = Value.nan; 13786 switch (n.operator) { 13787 case '++': nue = yield * old.add(e.fromNative(1)); break; 13788 case '--': nue = yield * old.subtract(e.fromNative(1)); break; 13789 default: throw new Error('Unknown update expression type: ' + n.operator); 13790 } 13791 if ( ref ) yield * ref.setValue(nue, s); 13792 13793 if ( n.prefix ) return nue; 13794 return old; 13795} 13796 13797function *evaulateUnaryExpression(e, n, s) { 13798 if ( e.yieldPower >= 4 ) yield EvaluatorInstruction.stepMajor; 13799 if ( n.operator === 'delete' ) { 13800 if ( n.argument.type !== 'MemberExpression' && n.argument.type !== 'Identifier' ) { 13801 //e isnt something you can delete? 13802 return Value.true; 13803 } 13804 13805 let ref = yield * e.resolveRef(n.argument, s); 13806 if ( !ref ) return Value.false; 13807 if ( ref.isVariable ) { return Value.false; } 13808 let worked = ref.del(s); 13809 if ( worked instanceof CompletionRecord ) return yield worked; 13810 return Value.fromNative(worked); 13811 } 13812 13813 if ( n.operator === 'typeof' ) { 13814 if ( n.argument.type == 'Identifier' ) { 13815 if ( !s.has(n.argument.name) ) return yield * Value.undef.typeOf(); 13816 } 13817 } 13818 13819 let left = yield * e.branch(n.argument,s); 13820 switch ( n.operator ) { 13821 case '-': return yield * left.unaryMinus(); 13822 case '+': return yield * left.unaryPlus(); 13823 case '!': return yield * left.not(); 13824 case '~': return yield * left.bitNot(); 13825 case 'typeof': return yield * left.typeOf(); 13826 case 'void': return Value.undef; 13827 default: 13828 throw new Error('Unknown binary operator: ' + n.operator); 13829 } 13830} 13831 13832function *evaluateVariableDeclaration(e, n, s) { 13833 let kind = n.kind; 13834 if ( e.yieldPower >= 3 ) yield EvaluatorInstruction.stepMajor; 13835 for ( let decl of n.declarations ) { 13836 let value = Value.undef; 13837 if ( decl.init ) value = yield * e.branch(decl.init,s); 13838 else if ( s.has(decl.id.name) ) continue; 13839 13840 if ( kind === 'const' ) { 13841 s.addConst(decl.id.name, value); 13842 } else { 13843 s.add(decl.id.name, value); 13844 } 13845 } 13846 return Value.undef; 13847} 13848 13849function* genWhileLoop(e, n, s) { 13850 let last = Value.undef; 13851 while ( (yield * e.branch(n.test,s)).truthy ) { 13852 e.topFrame.ast = n; 13853 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.eventLoopBodyStart; 13854 last = yield e.branchFrame('continue', n.body, s); 13855 } 13856} 13857
13858function *evaluateWhileStatement(e, n, s) { 13859 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.stepMajor; 13860 e.pushFrame({generator: genWhileLoop(e, n, s), type: 'loop', label: n.label, ast: n}); 13861 let finished = yield EvaluatorInstruction.waitForFramePop; 13862 return Value.undef; 13863} 13864 13865function *evaluateWithStatement(e, n, s) { 13866 if ( e.yieldPower > 0 ) yield EvaluatorInstruction.stepMajor; 13867 if ( s.strict ) return CompletionRecord.makeSyntaxError(e.realm, 'Strict mode code may not include a with statement'); 13868 return CompletionRecord.makeSyntaxError(e.realm, 'With statement not supported by esper'); 13869} 13870 13871function findNextStep(type) { 13872 switch ( type ) { 13873 case 'ArrayExpression': return evaluateArrayExpression; 13874 case 'ArrowFunctionExpression': return evaluateFunctionExpression; 13875 case 'AssignmentExpression': return evaluateAssignmentExpression; 13876 case 'BinaryExpression': return evaulateBinaryExpression; 13877 case 'BreakStatement': return evaluateBreakStatement; 13878 case 'BlockStatement': return evaluateBlockStatement; 13879 case 'CallExpression': return evaluateCallExpression; 13880 case 'ClassDeclaration': return evaluateClassDeclaration; 13881 case 'ClassExpression': return evaluateClassExpression; 13882 case 'ConditionalExpression': return evaluateConditionalExpression; 13883 case 'DebuggerStatement': return evaluateEmptyStatement; 13884 case 'DoWhileStatement': return evaluateDoWhileStatement; 13885 case 'ContinueStatement': return evaluateContinueStatement; 13886 case 'EmptyStatement': return evaluateEmptyStatement; 13887 case 'ExpressionStatement': return evaluateExpressionStatement; 13888 case 'ForStatement': return evaluateForStatement; 13889 case 'ForInStatement': return evaluateForInStatement; 13890 case 'ForOfStatement': return evaluateForOfStatement; 13891 case 'FunctionDeclaration': return evaluateFunctionDeclaration; 13892 case 'FunctionExpression': return evaluateFunctionExpression; 13893 case 'Identifier': return evaluateIdentifier; 13894 case 'IfStatement': return evaluateIfStatement; 13895 case 'LabeledStatement': return evaluateLabeledStatement; 13896 case 'Literal': return evaulateLiteral; 13897 case 'LogicalExpression': return evaluateLogicalExpression;
13898 case 'MemberExpression': return evaluateMemberExpression; 13899 case 'NewExpression': return evaluateCallExpression; 13900 case 'ObjectExpression': return evaluateObjectExpression; 13901 case 'Program': return evaluateProgram; 13902 case 'ReturnStatement': return evaluateReturnStatement; 13903 case 'SequenceExpression': return evaluateSequenceExpression; 13904 case 'SwitchStatement': return evaluateSwitchStatement; 13905 case 'ThisExpression': return evaluateThisExpression; 13906 case 'ThrowStatement': return evaluateThrowStatement; 13907 case 'TryStatement': return evaluateTryStatement; 13908 case 'UnaryExpression': return evaulateUnaryExpression; 13909 case 'UpdateExpression': return evaluateUpdateExpression; 13910 case 'VariableDeclaration': return evaluateVariableDeclaration; 13911 case 'WhileStatement': return evaluateWhileStatement; 13912 case 'WithStatement': return evaluateWithStatement; 13913 default: 13914 throw new Error('Unknown AST Node Type: ' + type); 13915 } 13916} 13917 13918module.exports = findNextStep; 13919 13920 13921},{"./CompletionRecord":103,"./EvaluatorInstruction":107,"./Value":111,"./values/ArrayValue":134,"./values/ClosureValue":136,"./values/ErrorValue":140,"./values/FutureValue":141,"./values/ObjectValue":145,"./values/PropertyDescriptor":147,"./values/RegExpValue":148}],107:[function(require,module,exports){ 13922'use strict'; 13923 13924 13925class EvaluatorInstruction { 13926 static branch(kind, ast, scope, extra) { 13927 let ei = new EvaluatorInstruction('branch'); 13928 ei.kind = kind; 13929 ei.ast = ast; 13930 ei.scope = scope; 13931 ei.extra = extra; 13932 return ei; 13933 } 13934 13935 static getEvaluator() { 13936 return new EvaluatorInstruction('getEvaluator'); 13937 } 13938 13939 constructor(type) { 13940 this.type = type; 13941 } 13942 13943 mark(o) { 13944 for ( let k in o ) this[k] = o[k]; 13945 return this; 13946 } 13947} 13948 13949EvaluatorInstruction.stepMinor = new EvaluatorInstruction('step'); 13950EvaluatorInstruction.stepMajor = new EvaluatorInstruction('step'); 13951EvaluatorInstruction.stepStatement = new EvaluatorInstruction('step'); 13952EvaluatorInstruction.waitForFramePop = new EvaluatorInstruction('waitForFramePop'); 13953EvaluatorInstruction.framePushed = new EvaluatorInstruction('framePushed'); 13954 13955EvaluatorInstruction.eventLoopBodyStart = new EvaluatorInstruction('event').mark({event: 'loopBodyStart'}); 13956module.exports = EvaluatorInstruction; 13957 13958},{}],108:[function(require,module,exports){ 13959'use strict'; 13960 13961function *sortValArray(arr, comp) { 13962 if ( arr.length < 2 ) return arr; 13963 let mid = Math.floor(arr.length / 2); 13964 let left = yield * sortValArray(arr.slice(0,mid), comp); 13965 let right = yield * sortValArray(arr.slice(mid, arr.length), comp); 13966 return yield * mergeValArray(left, right, comp); 13967} 13968 13969function *mergeValArray(l, r, comp) { 13970 var result = []; 13971 while ( l.length && r.length ) { 13972 if ( yield * comp(l[0], r[0]) ) result.push(l.shift()); 13973 else result.push(r.shift()); 13974 } 13975 13976 while (l.length) result.push(l.shift()); 13977 while (r.length) result.push(r.shift()); 13978 return result; 13979} 13980 13981class GenDash { 13982 static *identify(value) { 13983 return value; 13984 } 13985 13986 13987 static *map(what, fx) { 13988 fx = fx || GenDash.identify; 13989 var out = new Array(what.length); 13990 for ( let i = 0; i < what.length; ++i ) { 13991 out[i] = yield * fx(what[i], i, what); 13992 } 13993 return out; 13994 } 13995 13996 static *each(what, fx) { 13997 if ( what == null ) return what; 13998 for ( let i = 0; i < what.length; ++i ) { 13999 if ( false === (yield * fx(what[i], i, what)) ) break; 14000 } 14001 return what; 14002 } 14003 14004 static *noop() { } 14005 14006 static *sort(what, comp) { 14007 comp = comp || function *(left, right) { return left < right; }; 14008 return yield * sortValArray(what, comp); 14009 } 14010 14011 static *values(what) { 14012 var out = []; 14013 for ( let o in what ) { 14014 if ( !Object.hasOwnProperty(o) ) continue; 14015 out.push(what[o]); 14016 } 14017 return out; 14018 } 14019 14020 static *keys(what) { 14021 var out = []; 14022 for ( let o in what ) { 14023 if ( !Object.hasOwnProperty(o) ) continue; 14024 out.push(o); 14025 } 14026 return out; 14027 } 14028 14029 static *identity(value) { 14030 return value; 14031 } 14032 14033 static syncGenHelper(gen) { 14034 var val = gen.next(); 14035 if ( !val.done ) { 14036 console.log('This code path uses a helper, but the actual method yielded...'); 14037 throw new Error('This code path uses a helper, but the actual method yielded...'); 14038 } 14039 return val.value; 14040 } 14041} 14042 14043module.exports = GenDash; 14044 14045},{}],109:[function(require,module,exports){ 14046'use strict'; 14047 14048const Scope = require('./Scope'); 14049const Value = require('./Value'); 14050const esprima = require('esprima'); 14051const CompletionRecord = require('./CompletionRecord'); 14052const ObjectValue = require('./values/ObjectValue'); 14053const PrimitiveValue = require('./values/PrimitiveValue.js'); 14054const StringValue = require('./values/StringValue'); 14055const LinkValue = require('./values/LinkValue'); 14056const SmartLinkValue = require('./values/SmartLinkValue'); 14057const BridgeValue = require('./values/BridgeValue'); 14058const ASTPreprocessor = require('./ASTPreprocessor'); 14059const EasyNativeFunction = require('./values/EasyNativeFunction'); 14060const PropertyDescriptor = require('./values/PropertyDescriptor'); 14061const EvaluatorInstruction = require('./EvaluatorInstruction'); 14062 14063const ObjectPrototype = require('./stdlib/ObjectPrototype'); 14064const FunctionPrototype = require('./stdlib/FunctionPrototype'); 14065const ObjectClass = require('./stdlib/Object'); 14066const FunctionClass = require('./stdlib/Function'); 14067const NumberPrototype = require('./stdlib/NumberPrototype'); 14068 14069const StringPrototype = require('./stdlib/StringPrototype'); 14070 14071const ArrayPrototype = require('./stdlib/ArrayPrototype'); 14072const ArrayClass = require('./stdlib/Array'); 14073const StringClass = require('./stdlib/String'); 14074const NumberClass = require('./stdlib/Number'); 14075 14076 14077const BooleanPrototype = require('./stdlib/BooleanPrototype'); 14078const BooleanClass = require('./stdlib/Boolean'); 14079const RegExpPrototype = require('./stdlib/RegExpPrototype'); 14080const RegExpClass = require('./stdlib/RegExp'); 14081const EsperClass = require('./stdlib/Esper'); 14082const ErrorPrototype = require('./stdlib/ErrorPrototype'); 14083const ErrorClass = require('./stdlib/Error'); 14084 14085const AssertClass = require('./stdlib/Assert'); 14086const MathClass = require('./stdlib/Math.js'); 14087const ConsoleClass = require('./stdlib/Console'); 14088const JSONClass = require('./stdlib/JSON'); 14089 14090class EvalFunction extends ObjectValue { 14091 14092 constructor(realm) { 14093 super(realm); 14094 this.setPrototype(realm.FunctionPrototype); 14095 } 14096 14097 *call(thiz, args, scope) { 14098 let cv = Value.undef; 14099 if ( args.length > 0 ) cv = args[0]; 14100 if ( !(cv instanceof StringValue) ) return cv; 14101 let code = yield * cv.toStringNative(); 14102 let ast; 14103 try { 14104 let oast = scope.realm.parser(code, {loc: true}); 14105 ast = ASTPreprocessor.process(oast); 14106 } catch ( e ) { 14107 var eo; 14108 14109 if ( e.description == 'Invalid left-hand side in assignment' ) eo = new ReferenceError(e.description, e.fileName, e.lineNumber); 14110 else eo = new SyntaxError(e.description, e.fileName, e.lineNumber); 14111 14112 if ( e.stack ) eo.stack = e.stack; 14113 return new CompletionRecord(CompletionRecord.THROW, Value.fromNative(eo, scope.realm)); 14114 } 14115 14116 //TODO: Dont run in the parent scope if we are called indirectly 14117 let bak = yield EvaluatorInstruction.branch('eval', ast, scope.parent ? scope.parent : scope); 14118 //console.log("EVALED: ", bak); 14119 return bak; 14120 } 14121} 14122 14123 14124/** 14125 * Represents a javascript execution environment including 14126 * it's scopes and standard libraries. 14127 */ 14128class Realm { 14129 print() { 14130 console.log.apply(console, arguments); 14131 } 14132 14133 parser(code, options) { 14134 options = options || {}; 14135 let opts = {loc: true, range: true}; 14136 if ( options.inFunctionBody ) { 14137 opts.tolerant = true; 14138 opts.allowReturnOutsideFunction = true; 14139 } 14140 14141 let ast = esprima.parse(code, opts); 14142 let errors = []; 14143 if ( ast.errors ) { 14144 errors = ast.errors.filter((x) => { 14145 if ( options.inFunctionBody && x.message === 'Illegal return statement' ) return false;
14146 }); 14147 } 14148 delete ast.errors; 14149 if ( errors.length > 0 ) throw errors[0]; 14150 return ast; 14151 } 14152 14153 constructor(options) { 14154 this.options = options || {}; 14155 /** @type {Value} */ 14156 this.ObjectPrototype = new ObjectPrototype(this); 14157 this.FunctionPrototype = new FunctionPrototype(this); 14158 this.Object = new ObjectClass(this); 14159 this.ObjectPrototype._init(this); 14160 this.FunctionPrototype._init(this); 14161 this.Object.setPrototype(this.ObjectPrototype); 14162 this.FunctionPrototype.setPrototype(this.ObjectPrototype); 14163 14164 //TODO: Do this when we can make the property non enumerable. 14165 this.ObjectPrototype.rawSetProperty('constructor', new PropertyDescriptor(this.Object, false)); 14166 14167 this.Function = new FunctionClass(this); 14168 14169 /** @type {Math} */ 14170 this.Math = new MathClass(this); 14171 14172 /** @type {NumberPrototype} */ 14173 this.NumberPrototype = new NumberPrototype(this); 14174 14175 /** @type {StringPrototype} */ 14176 this.StringPrototype = new StringPrototype(this); 14177 14178 this.ArrayPrototype = new ArrayPrototype(this); 14179 this.Array = new ArrayClass(this); 14180 this.String = new StringClass(this); 14181 this.Number = new NumberClass(this); 14182 14183 14184 this.BooleanPrototype = new BooleanPrototype(this); 14185 this.Boolean = new BooleanClass(this); 14186 14187 this.RegExpPrototype = new RegExpPrototype(this); 14188 this.RegExp = new RegExpClass(this); 14189 14190 this.Esper = new EsperClass(this); 14191 this.ErrorPrototype = new ErrorPrototype(this); 14192 this.Error = new ErrorClass(this); 14193 this.ErrorPrototype.rawSetProperty('constructor', new PropertyDescriptor(this.Error, false)); 14194 14195 /** @type {Value} */ 14196 this.console = new ConsoleClass(this); 14197 14198 let scope = new Scope(this); 14199 scope.object.clazz = 'global'; 14200 scope.strict = options.strict || false; 14201 let that = this; 14202 var printer = EasyNativeFunction.makeForNative(this, function() { 14203 that.print.apply(that, arguments); 14204 }); 14205 scope.set('print', printer); 14206 scope.set('log', printer); 14207 14208 scope.addConst('NaN', this.fromNative(NaN)); 14209 scope.addConst('Infinity', this.fromNative(Infinity)); 14210 14211 scope.set('console', this.console); 14212 scope.set('JSON', new JSONClass(this)); 14213 14214 if ( options.exposeEsperGlobal ) { 14215 scope.set('Esper', this.Esper); 14216 } 14217 14218 scope.set('Math', this.Math); 14219 14220 scope.set('Number', this.Number); 14221 scope.set('Boolean', this.Boolean); 14222 scope.set('Object', this.Object); 14223 scope.set('Function', this.Function); 14224 scope.set('Array', this.Array); 14225 scope.set('String', this.String); 14226 scope.set('RegExp', this.RegExp); 14227 14228 scope.set('Error', this.Error); 14229 scope.set('TypeError', this.TypeError = this.Error.makeErrorType(TypeError)); 14230 scope.set('SyntaxError', this.SyntaxError = this.Error.makeErrorType(SyntaxError)); 14231 scope.set('ReferenceError', this.ReferenceError = this.Error.makeErrorType(ReferenceError)); 14232 scope.set('RangeError', this.RangeError = this.Error.makeErrorType(RangeError)); 14233 scope.set('EvalError', this.EvalError = this.Error.makeErrorType(EvalError)); 14234 scope.set('URIError', this.URIError = this.Error.makeErrorType(URIError)); 14235 14236 14237 scope.set('parseInt', EasyNativeFunction.makeForNative(this, parseInt)); 14238 scope.set('parseFloat', EasyNativeFunction.makeForNative(this, parseFloat)); 14239 scope.set('isNaN', EasyNativeFunction.makeForNative(this, isNaN)); 14240 scope.set('isFinite', EasyNativeFunction.makeForNative(this, isFinite)); 14241 14242 //scope.set('Date', this.fromNative(Date)); 14243 scope.set('eval', new EvalFunction(this)); 14244 scope.set('assert', new AssertClass(this)); 14245 14246 scope.thiz = scope.object; 14247 this.importCache = new WeakMap(); 14248 /** @type {Scope} */ 14249 this.globalScope = scope; 14250 } 14251 14252 lookupWellKnown(v) { 14253 if ( v === Object ) return this.Object; 14254 if ( v === Object.prototype ) return this.ObjectPrototype; 14255 if ( v === Function ) return this.Function; 14256 if ( v === Function.prototype ) return this.FunctionPrototype; 14257 if ( v === Math ) return this.Math; 14258 if ( v === Number ) return this.Number; 14259 if ( v === Number.prototype ) return this.NumberPrototype; 14260 if ( v === String ) return this.String; 14261 if ( v === String.prototype ) return this.StringPrototype; 14262 if ( v === Array ) return this.Array; 14263 if ( v === Array.prototype ) return this.ArrayPrototype; 14264 if ( v === RegExp ) return this.RegExp; 14265 if ( v === RegExp.prototype ) return this.RegExpPrototype; 14266 if ( typeof console !== 'undefined' && v === console ) return this.console; 14267 14268 } 14269 14270 valueFromNative(native) { 14271 return Value.fromNative(native, this); 14272 } 14273 14274 fromNative(native) { 14275 return Value.fromNative(native, this); 14276 } 14277 14278 import(native, modeHint) { 14279 if ( native instanceof Value ) return native; 14280 if ( native === undefined ) return Value.undef; 14281 14282 let prim = Value.fromPrimativeNative(native); 14283 if ( prim ) return prim; 14284 14285 //if ( this.importCache.has(native) ) { 14286 // return this.importCache.get(native); 14287 //} 14288 14289 if ( Value.hasBookmark(native) ) { 14290 return Value.getBookmark(native); 14291 } 14292 14293 let result; 14294 switch ( modeHint || this.options.foreignObjectMode ) { 14295 case 'bridge': 14296 result = BridgeValue.make(native, this); 14297 break; 14298 case 'smart': 14299 result = SmartLinkValue.make(native, this); 14300 break; 14301 case 'link': 14302 default: 14303 result = LinkValue.make(native, this); 14304 break; 14305 } 14306 14307 //this.importCache.set(native, result); 14308 return result; 14309 } 14310} 14311 14312Realm.prototype.makeForForeignObject = Realm.prototype.import;
14313 14314module.exports = Realm; 14315 14316},{"./ASTPreprocessor":102,"./CompletionRecord":103,"./EvaluatorInstruction":107,"./Scope":110,"./Value":111,"./stdlib/Array":113,"./stdlib/ArrayPrototype":114,"./stdlib/Assert":115,"./stdlib/Boolean":116,"./stdlib/BooleanPrototype":117,"./stdlib/Console":118,"./stdlib/Error":119,"./stdlib/ErrorPrototype":120,"./stdlib/Esper":121,"./stdlib/Function":122,"./stdlib/FunctionPrototype":123,"./stdlib/JSON":124,"./stdlib/Math.js":125,"./stdlib/Number":126,"./stdlib/NumberPrototype":127,"./stdlib/Object":128,"./stdlib/ObjectPrototype":129,"./stdlib/RegExp":130,"./stdlib/RegExpPrototype":131,"./stdlib/String":132,"./stdlib/StringPrototype":133,"./values/BridgeValue":135,"./values/EasyNativeFunction":137,"./values/LinkValue":142,"./values/ObjectValue":145,"./values/PrimitiveValue.js":146,"./values/PropertyDescriptor":147,"./values/SmartLinkValue":149,"./values/StringValue":150,"esprima":152}],110:[function(require,module,exports){ 14317'use strict'; 14318 14319const PropertyDescriptor = require('./values/PropertyDescriptor'); 14320 14321const Value = require('./Value'); 14322const ObjectValue = require('./values/ObjectValue'); 14323 14324class Scope { 14325 constructor(realm) { 14326 this.parent = null; 14327 this.object = new ObjectValue(realm); 14328 this.strict = false; 14329 this.realm = realm; 14330 this.global = this; 14331 this.writeTo = this.object; 14332 } 14333 14334 /** 14335 * @param {string} name - Identifier to retreive 14336 * @returns {Value} 14337 */ 14338 get(name) { 14339 //Fast property access in the common case. 14340 let prop = this.object.properties[name]; 14341 if ( !prop ) return Value.undef; 14342 if ( !prop.getter ) return prop.value; 14343 return this.object.getImmediate(name); 14344 } 14345 14346 ref(name) { 14347 var vhar = this.object.properties[name]; 14348 if (!vhar) return undefined; 14349 var that = this; 14350 var o = { 14351 setValue: vhar.setValue.bind(vhar, this), 14352 getValue: vhar.getValue.bind(vhar, this), 14353 isVariable: true 14354 }; 14355 return o; 14356 } 14357 14358 add(name, value) { 14359 this.writeTo.setImmediate(name, value); 14360 } 14361 14362 addConst(name, value) { 14363 this.set(name, value); 14364 this.writeTo.properties[name].writable = false; 14365 this.writeTo.properties[name].configurable = false; 14366 } 14367 14368 /** 14369 * Sets an identifier in the scope to some value. 14370 * 14371 * @param {string} name - Identifier to set 14372 * @param {Value} value - Value to set 14373 */ 14374 set(name, value) { 14375 this.writeTo.setImmediate(name, value); 14376 } 14377 14378 has(name) { 14379 return this.object.has(name); 14380 } 14381 14382 /** 14383 * Set the identifier in its nearest scope, or create a global. 14384 * @param {string} name - Identifier to retreive 14385 * @param {Value} value - New vaalue of variable 14386 * @param {Scope} s - Code scope to run setter functions in 14387 */ 14388 put(name, value, s) { 14389 let variable = this.object.properties[name]; 14390 if ( variable ) { 14391 return variable.setValue(this.object, value, s); 14392 } 14393 var v = new PropertyDescriptor(value, this); 14394 this.writeTo.properties[name] = v; 14395 return Value.undef.fastGen(); 14396 } 14397 14398 createChild() { 14399 let child = new Scope(this.realm); 14400 child.object.eraseAndSetPrototype(this.object); 14401 child.parent = this; 14402 child.strict = this.strict; 14403 child.global = this.global; 14404 child.realm = this.realm; 14405 return child; 14406 } 14407 14408 fromNative(value) { 14409 return this.realm.fromNative(value); 14410 } 14411 14412 getVariableNames() { 14413 let list = []; 14414 for ( var o in this.object.properties ) list.push(o); 14415 return list; 14416 } 14417 14418} 14419 14420module.exports = Scope; 14421 14422},{"./Value":111,"./values/ObjectValue":145,"./values/PropertyDescriptor":147}],111:[function(require,module,exports){ 14423'use strict'; 14424/* @flow */ 14425 14426const CompletionRecord = require('./CompletionRecord'); 14427const GenDash = require('./GenDash'); 14428 14429let undef, nil, tru, fals, nan, emptyString, zero, one, negone, negzero, smallIntValues; 14430let cache = new WeakMap(); 14431let bookmarks = new WeakMap(); 14432let ObjectValue, PrimitiveValue, StringValue, NumberValue, BridgeValue, Evaluator; 14433 14434 14435 14436let serial = 0; 14437/** 14438 * Represents a value a variable could take. 14439 */ 14440class Value { 14441 /** 14442 * Convert a native javascript primative value to a Value 14443 * @param {any} value - The value to convert 14444 */ 14445 static fromPrimativeNative(value) { 14446 if ( !value ) { 14447 if ( value === undefined ) return undef; 14448 if ( value === null ) return nil; 14449 if ( value === false ) return fals; 14450 if ( value === '' ) return emptyString; 14451 } 14452 14453 if ( value === true ) return tru; 14454 14455 if ( typeof value === 'number' ) { 14456 if ( value === 0 ) { 14457 return 1/value > 0 ? zero : negzero; 14458 } 14459 if ( value|0 === value ) { 14460 let snv = smallIntValues[value+1]; 14461 if ( snv ) return snv; 14462 } 14463 return new NumberValue(value); 14464 } 14465 if ( typeof value === 'string' ) return new StringValue(value); 14466 if ( typeof value === 'boolean' ) return new PrimitiveValue(value); 14467 } 14468 14469 static hasBookmark(native) { return bookmarks.has(native); } 14470 static getBookmark(native) { return bookmarks.get(native); } 14471 14472 /** 14473 * Convert a native javascript value to a Value 14474 * 14475 * @param {any} value - The value to convert 14476 * @param {Realm} realm - The realm of the new value. 14477 */ 14478 static fromNative(value, realm) { 14479 if ( value instanceof Value ) return value; 14480 let prim = Value.fromPrimativeNative(value); 14481 if ( prim ) return prim; 14482 14483 if ( value instanceof Error ) { 14484 if ( !realm ) throw new Error('We needed a realm, but we didnt have one. We were sad :('); 14485 if ( value instanceof TypeError ) return realm.TypeError.makeFrom(value); 14486 if ( value instanceof ReferenceError ) return realm.ReferenceError.makeFrom(value); 14487 if ( value instanceof SyntaxError ) return realm.SyntaxError.makeFrom(value); 14488 else return realm.Error.makeFrom(value); 14489 } 14490 14491 if ( Value.hasBookmark(value) ) { 14492 return Value.getBookmark(value); 14493 } 14494 14495 throw new TypeError('Tried to load an unsafe native value into the interperter:' + typeof value + ' / ' + value); 14496 //TODO: Is this cache dangerous? 14497 if ( !cache.has(value) ) { 14498 let nue = new BridgeValue(realm, value); 14499 cache.set(value, nue); 14500 return nue; 14501 } 14502 return cache.get(value); 14503 } 14504 14505 /** 14506 * Holds a value representing `undefined` 14507 * 14508 * @returns {UndefinedValue} 14509 */
14510 static get undef() { 14511 return undef; 14512 } 14513 14514 /** 14515 * Holds a value representing `null` 14516 * 14517 * @returns {NullValue} 14518 */ 14519 static get null() { 14520 return nil; 14521 } 14522 14523 /** 14524 * Holds a value representing `true` 14525 * 14526 * @returns {BooleanValue} true 14527 */ 14528 static get true() { 14529 return tru; 14530 } 14531 14532 /** 14533 * Holds a value representing `fasle` 14534 * 14535 * @returns {BooleanValue} false 14536 */ 14537 static get false() { 14538 return fals; 14539 } 14540 14541 /** 14542 * Holds a value representing `NaN` 14543 * 14544 * @returns {NumberValue} NaN 14545 */ 14546 static get nan() { 14547 return nan; 14548 } 14549 14550 /** 14551 * Holds a value representing `''` 14552 * 14553 * @returns {StringValue} '' 14554 */ 14555 static get emptyString() { 14556 return emptyString; 14557 } 14558 14559 /** 14560 * Holds a value representing `0` 14561 * 14562 * @returns {NumberValue} 0 14563 */ 14564 static get zero() { return zero; } 14565 14566 static createNativeBookmark(v, realm) { 14567 var out; 14568 let thiz = this; 14569 if ( typeof v.call === 'function' ) { 14570 switch ( realm.options.bookmarkInvocationMode ) { 14571 case 'loop': 14572 14573 out = function Bookmark() { 14574 let Evaluator = require('./Evaluator');
14575 let cthis = realm.makeForForeignObject(this); 14576 let c = v.call(cthis, [], realm.globalScope); 14577 let evalu = new Evaluator(realm, null, realm.globalScope); 14578 evalu.pushFrame({type: 'program', generator: c, scope: realm.globalScope}); 14579 let gen = evalu.generator(); 14580 let result; 14581 do { 14582 result = gen.next(); 14583 } while ( !result.done ); 14584 return result.value.toNative(); 14585 }; 14586 break; 14587 default: 14588 out = function Bookmark() { throw new Error('Atempted to invoke bookmark for ' + v.debugString); }; 14589 } 14590 } else { 14591 out = {}; 14592 } 14593 Object.defineProperties(out, { 14594 toString: {value: function() { return v.debugString; }, writable: true}, 14595 inspect: {value: function() { return v.debugString; }, writable: true}, 14596 }); 14597 bookmarks.set(out, v); 14598 return out; 14599 } 14600 14601 constructor() { 14602 this.serial = serial++; 14603 } 14604 14605 14606 /** 14607 * Converts this value to a native javascript value. 14608 * 14609 * @abstract 14610 * @returns {*} 14611 */ 14612 toNative() { 14613 throw new Error('Unimplemented: Value#toNative'); 14614 } 14615 14616 /** 14617 * A string representation of this Value suitable for display when 14618 * debugging. 14619 * @abstract 14620 * @returns {string} 14621 */ 14622 get debugString() { 14623 let native = this.toNative(); 14624 return native ? native.toString() : '???'; 14625 } 14626 14627 inspect() { return this.debugString; } 14628 14629 //TODO: Kill this 14630 fromNative(other, realm) { 14631 return Value.fromNative(other, realm); 14632 } 14633 14634 /** 14635 * Indexes the value to get the value of a property. 14636 * i.e. `value[name]` 14637 * @param {String} name 14638 * @param {Realm} realm 14639 * @abstract 14640 * @returns {Value} 14641 */ 14642 *get(name, realm) { 14643 let err = "Can't access get " + name + ' of that type: ' + require('util').inspect(this); 14644 return CompletionRecord.makeTypeError(realm, err); 14645 } 14646 14647 getImmediate(name) { 14648 return GenDash.syncGenHelper(this.get(name)); 14649 } 14650 14651 /** 14652 * Computes the javascript expression `!value` 14653 * @returns {Value} 14654 */ 14655 *not() { 14656 return !this.truthy ? Value.true : Value.false; 14657 } 14658 14659 /** 14660 * Computes the javascript expression `+value` 14661 * @returns {Value} 14662 */ 14663 *unaryPlus() { 14664 return Value.fromNative(+(yield * this.toNumberValue())); 14665 } 14666 14667 /** 14668 * Computes the javascript expression `-value` 14669 * @returns {Value} 14670 */ 14671 *unaryMinus() { 14672 return Value.fromNative(-(yield * this.toNumberValue())); 14673 } 14674 14675 /** 14676 * Computes the javascript expression `typeof value` 14677 * @returns {Value} 14678 */ 14679 *typeOf() { 14680 return Value.fromNative(this.jsTypeName); 14681 } 14682 14683 /** 14684 * Computes the javascript expression `!(value == other)` 14685 * @param {Value} other - The other value 14686 * @param {Realm} realm - The realm to use when creating resuls. 14687 * @returns {Value} 14688 */ 14689 *notEquals(other, realm) { 14690 var result = yield * this.doubleEquals(other, realm); 14691 return yield * result.not(); 14692 } 14693 14694 /** 14695 * Computes the javascript expression `!(value === other)` 14696 * @param {Value} other - The other value 14697 * @param {Realm} realm - The realm to use when creating resuls. 14698 * @returns {Value} 14699 */ 14700 *doubleNotEquals(other, realm) { 14701 var result = yield * this.tripleEquals(other, realm); 14702 return yield * result.not(); 14703 } 14704 14705 /** 14706 * Computes the javascript expression `value === other` 14707 * @param {Value} other - The other value 14708 * @param {Realm} realm - The realm to use when creating resuls. 14709 * @returns {Value} 14710 */ 14711 *tripleEquals(other, realm) { 14712 return other === this ? Value.true : Value.false; 14713 } 14714 14715 *makeThisForNew(realm) { 14716 var nue = new ObjectValue(realm); 14717 var p = this.properties['prototype']; 14718 if ( p ) nue.setPrototype(p.value); 14719 return nue; 14720 } 14721 14722 /** 14723 * Computes the javascript expression `value > other` 14724 * @param {Value} other - The other value 14725 * @returns {Value} 14726 */ 14727 *gt(other) { return this.fromNative((yield * this.toNumberNative()) > (yield * other.toNumberNative())); } 14728 14729 /** 14730 * Computes the javascript expression `value < other` 14731 * @param {Value} other - The other value 14732 * @returns {Value} 14733 */ 14734 *lt(other) { return this.fromNative((yield * this.toNumberNative()) < (yield * other.toNumberNative())); } 14735 14736 /** 14737 * Computes the javascript expression `value >= other` 14738 * @param {Value} other - The other value 14739 * @returns {Value} 14740 */
14741 *gte(other) { return this.fromNative((yield * this.toNumberNative()) >= (yield * other.toNumberNative())); } 14742 14743 /** 14744 * Computes the javascript expression `value <= other` 14745 * @param {Value} other - The other value 14746 * @returns {Value} 14747 */ 14748 *lte(other) { return this.fromNative((yield * this.toNumberNative()) <= (yield * other.toNumberNative())); } 14749 14750 /** 14751 * Computes the javascript expression `value - other` 14752 * @param {Value} other - The other value 14753 * @returns {Value} 14754 */ 14755 *subtract(other) { return this.fromNative((yield * this.toNumberNative()) - (yield * other.toNumberNative())); } 14756 14757 /** 14758 * Computes the javascript expression `value / other` 14759 * @param {Value} other - The other value 14760 * @returns {Value} 14761 */ 14762 *divide(other) { return this.fromNative((yield * this.toNumberNative()) / (yield * other.toNumberNative())); } 14763 14764 /** 14765 * Computes the javascript expression `value * other` 14766 * @param {Value} other - The other value 14767 * @returns {Value} 14768 */ 14769 *multiply(other) { return this.fromNative((yield * this.toNumberNative()) * (yield * other.toNumberNative())); } 14770 14771 /** 14772 * Computes the javascript expression `value % other` 14773 * @param {Value} other - The other value 14774 * @returns {Value} 14775 */ 14776 *mod(other) { return this.fromNative((yield * this.toNumberNative()) % (yield * other.toNumberNative())); } 14777 14778 *bitNot() { return this.fromNative(~(yield * this.toNumberNative())); } 14779 14780 *shiftLeft(other) { return this.fromNative((yield * this.toNumberNative()) << (yield * other.toNumberNative())); } 14781 *shiftRight(other) { return this.fromNative((yield * this.toNumberNative()) >> (yield * other.toNumberNative())); } 14782 *shiftRightZF(other) { return this.fromNative((yield * this.toNumberNative()) >>> (yield * other.toNumberNative())); } 14783 14784 *bitAnd(other) { return this.fromNative((yield * this.toNumberNative()) & (yield * other.toNumberNative())); } 14785 *bitOr(other) { return this.fromNative((yield * this.toNumberNative()) | (yield * other.toNumberNative())); } 14786 *bitXor(other) { return this.fromNative((yield * this.toNumberNative()) ^ (yield * other.toNumberNative())); } 14787 14788 /** 14789 * Is the value is truthy, i.e. `!!value` 14790 * 14791 * @abstract 14792 * @type {boolean} 14793 */ 14794 get truthy() { 14795 throw new Error('Unimplemented: Value#truthy'); 14796 } 14797 14798 get jsTypeName() { 14799 throw new Error('Unimplemented: Value#jsTypeName'); 14800 } 14801 14802 get specTypeName() { 14803 return this.jsTypeName; 14804 } 14805 14806 get isCallable() { 14807 return ( typeof this.call === 'function' ); 14808 } 14809 14810 *toNumberValue() { throw new Error('Unimplemented: Value#toNumberValue'); } 14811 *toStringValue() { throw new Error('Unimplemented: Value#StringValue'); } 14812 *toStringNative() { return (yield * this.toStringValue()).native; } 14813 14814 *toBooleanValue() { return this.truthy ? tru : fals; } 14815 14816 *toUIntNative() { 14817 let nv = yield * this.toNumberValue(); 14818 return Math.floor(nv.native); 14819 } 14820 14821 *toIntNative() { 14822 let nv = yield * this.toNumberValue(); 14823 return Math.floor(nv.native); 14824 } 14825 14826 *toNumberNative() { 14827 let nv = yield * this.toNumberValue(); 14828 return nv.native; 14829 } 14830 14831 *toPrimitiveValue(preferedType) { throw new Error('Unimplemented: Value#toPrimitiveValue'); } 14832 *toPrimitiveNative(preferedType) { return (yield * this.toPrimitiveValue(preferedType)).native; } 14833 14834 /** 14835 * Quickly make a generator for this value 14836 */ 14837 *fastGen() { return this; } 14838 14839} 14840module.exports = Value; 14841 14842ObjectValue = require('./values/ObjectValue'); 14843PrimitiveValue = require('./values/PrimitiveValue'); 14844StringValue = require('./values/StringValue'); 14845NumberValue = require('./values/NumberValue'); 14846const UndefinedValue = require('./values/UndefinedValue'); 14847const NullValue = require('./values/NullValue'); 14848 14849undef = new UndefinedValue(); 14850nil = new NullValue(); 14851tru = new PrimitiveValue(true); 14852fals = new PrimitiveValue(false); 14853nan = new PrimitiveValue(NaN); 14854emptyString = new StringValue(''); 14855 14856zero = new NumberValue(0); 14857negzero = new NumberValue(-0); 14858one = new NumberValue(1); 14859negone = new NumberValue(-1); 14860smallIntValues = [ 14861 negone, zero, 14862 one, new NumberValue(2), new NumberValue(3), new NumberValue(4), new NumberValue(5), 14863 new NumberValue(6), new NumberValue(7), new NumberValue(8), new NumberValue(9) 14864 ] 14865 14866},{"./CompletionRecord":103,"./Evaluator":105,"./GenDash":108,"./values/NullValue":143,"./values/NumberValue":144,"./values/ObjectValue":145,"./values/PrimitiveValue":146,"./values/StringValue":150,"./values/UndefinedValue":151,"util":245}],112:[function(require,module,exports){ 14867'use strict'; 14868/* @flow */ 14869 14870const Engine = require('./Engine'); 14871 14872function esper(opts) { 14873 return new Engine(opts); 14874} 14875 14876esper.Engine = Engine; 14877esper.Value = require('./Value'); 14878esper.ASTPreprocessor = require('./ASTPreprocessor'); 14879esper.FutureValue = require('./values/FutureValue'); 14880 14881esper.eval = function(source) { 14882 return new Engine().evalSync(source).toNative(); 14883}; 14884 14885esper.version = require('../package.json').version; 14886 14887module.exports = esper; 14888 14889},{"../package.json":101,"./ASTPreprocessor":102,"./Engine":104,"./Value":111,"./values/FutureValue":141}],113:[function(require,module,exports){ 14890'use strict'; 14891 14892const EasyObjectValue = require('../values/EasyObjectValue'); 14893const ObjectValue = require('../values/ObjectValue'); 14894const ArrayValue = require('../values/ArrayValue'); 14895
14896class ArrayObject extends EasyObjectValue { 14897 *call(thiz, args, s) { 14898 if ( args.length === 1 && args[0].jsTypeName === 'number' ) { 14899 let result = ArrayValue.make([], s.realm); 14900 yield * result.set('length', args[0]); 14901 return result; 14902 } 14903 return ArrayValue.make(args, s.realm); 14904 } 14905 14906 callPrototype(realm) { return realm.ArrayPrototype; } 14907 //objPrototype(realm) { return realm.Function; } 14908 14909 14910 14911 static *isArray(thiz, args) { 14912 if ( args.length < 1 ) return EasyObjectValue.false; 14913 return EasyObjectValue.fromNative(args[0] instanceof ArrayValue); 14914 } 14915} 14916 14917module.exports = ArrayObject; 14918 14919},{"../values/ArrayValue":134,"../values/EasyObjectValue":138,"../values/ObjectValue":145}],114:[function(require,module,exports){ 14920'use strict'; 14921 14922const EasyObjectValue = require('../values/EasyObjectValue'); 14923const ObjectValue = require('../values/ObjectValue'); 14924const ArrayValue = require('../values/ArrayValue'); 14925const PrimitiveValue = require('../values/PrimitiveValue'); 14926const CompletionRecord = require('../CompletionRecord'); 14927const Value = require('../Value'); 14928const _g = require('../GenDash'); 14929 14930function *forceArrayness(v) { 14931 if ( !v.has('length') ) { 14932 yield * v.set('length', Value.zero); 14933 } 14934} 14935 14936function *getLength(v) { 14937 let m = yield * v.get('length'); 14938 return yield * m.toUIntNative(); 14939} 14940 14941var defaultSeperator = Value.fromNative(','); 14942 14943function *shiftRight(arr, start, amt) { 14944 amt = amt || 1; 14945 let len = yield * getLength(arr); 14946 for ( let i = len - 1; i >= start; --i ) { 14947 let cur = yield * arr.get(i); 14948 yield * arr.set(i + amt, cur); 14949 } 14950 yield * arr.set(start, Value.undef); 14951} 14952 14953function *shiftLeft(arr, start, amt) { 14954 let len = yield * getLength(arr); 14955 for ( let i = start; i < len; ++i ) { 14956 let cur = yield * arr.get(i); 14957 yield * arr.set(i - amt, cur); 14958 } 14959 for ( let i = len - amt; i < len; ++i ) { 14960 delete arr.properties[i]; 14961 } 14962 yield * arr.set('length', Value.fromNative(len - amt)); 14963} 14964 14965 14966class ArrayPrototype extends EasyObjectValue { 14967 14968 static *concat$e(thiz, args, s) { 14969 let fx = Value.undef; 14970 let targ = Value.undef; 14971 if ( args.length > 0 ) fx = args[0]; 14972 if ( args.length > 1 ) targ = args[1]; 14973 14974 var out = []; 14975 var toCopy = [thiz].concat(args); 14976 14977 let idx = 0; 14978 for ( let arr of toCopy ) { 14979 if ( arr instanceof PrimitiveValue ) { 14980 out[idx++] = arr; 14981 } else if ( !arr.has('length') ) { 14982 out[idx++] = arr; 14983 } else { 14984 let l = yield * getLength(arr); 14985 for ( let i = 0; i < l; ++i ) { 14986 let tv = yield * arr.get(i, s.realm); 14987 out[idx++] = tv; 14988 } 14989 } 14990 } 14991 14992 return ArrayValue.make(out, s.realm); 14993 } 14994 14995 static *filter$e(thiz, args, s) { 14996 let fx = Value.undef; 14997 let targ = Value.undef; 14998 if ( args.length > 0 ) fx = args[0]; 14999 if ( args.length > 1 ) targ = args[1]; 15000 15001 let test = function *(v, i) { 15002 let res = yield * fx.call(targ, [v, Value.fromNative(i), thiz], s); 15003 return res.truthy; 15004 }; 15005 15006 var out = []; 15007 15008 let l = yield * getLength(thiz); 15009 for ( let i = 0; i < l; ++i ) { 15010 let tv = yield * thiz.get(i); 15011 let tru = yield * test(tv, i); 15012 if ( tru ) out.push(tv); 15013 } 15014 15015 return ArrayValue.make(out, s.realm); 15016 } 15017 15018 static *every$e(thiz, args, s) { 15019 let fx = Value.undef; 15020 let targ = Value.undef; 15021 if ( args.length > 0 ) fx = args[0]; 15022 if ( args.length > 1 ) targ = args[1]; 15023 15024 let test = function *(v, i) { 15025 let res = yield * fx.call(targ, [v, Value.fromNative(i), thiz], s); 15026 return res.truthy; 15027 }; 15028 15029 let l = yield * getLength(thiz); 15030 for ( let i = 0; i < l; ++i ) { 15031 let tv = yield * thiz.get(i); 15032 let tru = yield * test(tv, i); 15033 if ( !tru ) return Value.false; 15034 } 15035 15036 return Value.true; 15037 } 15038 15039 static *some$e(thiz, args, s) { 15040 let fx = Value.undef; 15041 let targ = Value.undef; 15042 if ( args.length > 0 ) fx = args[0]; 15043 if ( args.length > 1 ) targ = args[1]; 15044 15045 let test = function *(v, i) { 15046 let res = yield * fx.call(targ, [v, Value.fromNative(i), thiz], s); 15047 return res.truthy; 15048 }; 15049 15050 let l = yield * getLength(thiz); 15051 for ( let i = 0; i < l; ++i ) { 15052 let tv = yield * thiz.get(i); 15053 let tru = yield * test(tv, i); 15054 if ( tru ) return Value.true; 15055 } 15056 15057 return Value.false; 15058 } 15059 15060 static *map$e(thiz, args, s) { 15061 let fx = Value.undef; 15062 let targ = Value.undef; 15063 if ( args.length > 0 ) fx = args[0]; 15064 if ( !fx.isCallable ) return yield CompletionRecord.makeTypeError(s.realm, 'Arg2 not calalble.'); 15065 15066 if ( args.length > 1 ) targ = args[1]; 15067 15068 let l = yield * getLength(thiz); 15069 let out = new Array(l); 15070 for ( let i = 0; i < l; ++i ) { 15071 if ( !thiz.has(i) ) continue; 15072 let tv = yield * thiz.get(i); 15073 let v = yield yield * fx.call(targ, [tv, Value.fromNative(i), thiz], s); 15074 out[i] = v; 15075 } 15076 15077 return ArrayValue.make(out, s.realm); 15078 } 15079 15080 static *forEach$e(thiz, args, s) { 15081 let fx = Value.undef; 15082 let targ = Value.undef; 15083 if ( args.length > 0 ) fx = args[0]; 15084 if ( args.length > 1 ) targ = args[1]; 15085 15086 let l = yield * getLength(thiz); 15087 for ( let i = 0; i < l; ++i ) { 15088 if ( !thiz.has(i) ) continue; 15089 let v = yield * thiz.get(i); 15090 let res = yield * fx.call(targ, [v, Value.fromNative(i), thiz], s); 15091 } 15092 15093 return Value.undef; 15094 } 15095
15096 static *indexOf$e(thiz, args) { 15097 //TODO: Call ToObject() on thisz; 15098 let l = yield * getLength(thiz); 15099 let match = args[0] || Value.undef; 15100 let start = args[1] || Value.zero; 15101 let startn = (yield * start.toNumberValue()).native; 15102 15103 if ( isNaN(startn) ) startn = 0; 15104 else if ( startn < 0 ) startn = 0; 15105 15106 if ( l > startn ) { 15107 for ( let i = startn; i < l; ++i ) { 15108 let v = yield * thiz.get(i); 15109 if ( !v ) v = Value.undef; 15110 if ( (yield * v.tripleEquals(match)).truthy ) return Value.fromNative(i); 15111 15112 } 15113 } 15114 return Value.fromNative(-1); 15115 } 15116 15117 static *lastIndexOf$e(thiz, args) { 15118 //TODO: Call ToObject() on thisz; 15119 let l = yield * getLength(thiz); 15120 let match = args[0] || Value.undef; 15121 let startn = l - 1; 15122 15123 if ( args.length > 1 ) startn = yield * args[1].toIntNative(); 15124 if ( isNaN(startn) ) startn = 0; 15125 if ( startn < 0 ) startn += l; 15126 if ( startn > l ) startn = l; 15127 if ( startn < 0 ) return Value.fromNative(-1); 15128 15129 15130 //if ( isNaN(startn) ) startn = l - 1; 15131 15132 for ( let i = startn; i >= 0; --i ) { 15133 if ( !thiz.has(i) ) continue; 15134 let v = yield * thiz.get(i); 15135 if ( !v ) v = Value.undef; 15136 if ( (yield * v.tripleEquals(match)).truthy ) return Value.fromNative(i); 15137 15138 } 15139 15140 return Value.fromNative(-1); 15141 } 15142 15143 static *join$e(thiz, args) { 15144 //TODO: Call ToObject() on thisz; 15145 let l = yield * getLength(thiz); 15146 let seperator = args[0] || defaultSeperator; 15147 let sepstr = (yield * seperator.toStringValue()).native; 15148 let strings = new Array(l); 15149 for ( let i = 0; i < l; ++i ) { 15150 if ( !thiz.has(i) ) continue; 15151 let v = yield * thiz.get(i); 15152 if ( !v ) strings[i] = ''; 15153 else { 15154 if ( v.jsTypeName == 'undefined' ) { 15155 continue; 15156 } 15157 let sv = (yield * v.toStringValue()); 15158 if ( sv ) strings[i] = sv.native; 15159 else strings[i] = undefined; //TODO: THROW HERE? 15160 } 15161 } 15162 return Value.fromNative(strings.join(sepstr)); 15163 } 15164 15165 static *push$e(thiz, args) { 15166 let l = yield * getLength(thiz); 15167 15168 for ( let i = 0; i < args.length; ++i ) { 15169 yield * thiz.set(l + i, args[i]); 15170 } 15171 15172 let nl = Value.fromNative(l + args.length); 15173 yield * thiz.set('length', nl); 15174 return Value.fromNative(l + args.length); 15175 } 15176 15177 static *pop$e(thiz, args) { 15178 yield * forceArrayness(thiz); 15179 let l = yield * getLength(thiz); 15180 if ( l < 1 ) return Value.undef; 15181 let val = yield * thiz.get(l - 1); 15182 yield * thiz.set('length', Value.fromNative(l - 1)); 15183 return val; 15184 } 15185 15186 static *reverse$e(thiz, args, s) { 15187 let l = yield * getLength(thiz); 15188 for ( let i = 0; i < Math.floor(l / 2); ++i ) { 15189 let lv = yield * thiz.get(i); 15190 let rv = yield * thiz.get(l - i - 1); 15191 yield * thiz.set(l - i - 1, lv, s); 15192 yield * thiz.set(i, rv, s); 15193 } 15194 15195 return thiz; 15196 } 15197 15198 static *reduce$e(thiz, args, s) { 15199 let l = yield * getLength(thiz); 15200 let acc; 15201 let fx = args[0]; 15202 15203 if ( args.length < 1 || !fx.isCallable ) { 15204 return yield CompletionRecord.makeTypeError(s.realm, 'First argument to reduce must be a function.'); 15205 } 15206 15207 if ( args.length > 1 ) { 15208 acc = args[1]; 15209 } 15210 15211 for ( let i = 0; i < l; ++i ) { 15212 if ( !thiz.has(i) ) continue; 15213 let lv = yield * thiz.get(i); 15214 if ( !acc ) { 15215 acc = lv; 15216 continue; 15217 } 15218 acc = yield * fx.call(thiz, [acc, lv], s); 15219 } 15220 if ( !acc ) return yield CompletionRecord.makeTypeError(s.realm, 'Reduce an empty array with no initial value.'); 15221 return acc; 15222 } 15223 15224 //TODO: Factor some stuff out of reduce and reduce right into a common function. 15225 static *reduceRight$e(thiz, args, s) { 15226 let l = yield * getLength(thiz); 15227 let acc; 15228 let fx = args[0]; 15229 15230 if ( args.length < 1 || !fx.isCallable ) { 15231 return yield CompletionRecord.makeTypeError(s.realm, 'First argument to reduceRight must be a function.'); 15232 } 15233 15234 if ( args.length > 1 ) { 15235 acc = args[1]; 15236 } 15237 15238 for ( let i = l - 1; i >= 0; --i ) { 15239 if ( !thiz.has(i) ) continue; 15240 let lv = yield * thiz.get(i); 15241 if ( !acc ) { 15242 acc = lv; 15243 continue; 15244 } 15245 acc = yield * fx.call(thiz, [acc, lv], s); 15246 } 15247 15248 if ( !acc ) return yield CompletionRecord.makeTypeError(s.realm, 'Reduce an empty array with no initial value.'); 15249 return acc; 15250 } 15251 15252 static *shift$e(thiz, args) { 15253 yield * forceArrayness(thiz); 15254 let l = yield * getLength(thiz); 15255 if ( l < 1 ) return Value.undef; 15256 15257 let val = yield * thiz.get(0); 15258 yield * shiftLeft(thiz, 1, 1); 15259 return val; 15260 } 15261 15262 static *slice$e(thiz, args, s) { 15263 //TODO: Call ToObject() on thisz; 15264 let length = yield * getLength(thiz); 15265 let result = []; 15266 15267 let start = 0; 15268 let end = length; 15269 15270 15271 if ( args.length > 0 ) start = ( yield * args[0].toIntNative() ); 15272 if ( args.length > 1 ) end = ( yield * args[1].toIntNative() ); 15273 15274 if ( start < 0 ) start = length + start; 15275 if ( end < 0 ) end = length + end; 15276 15277 if ( end > length ) end = length; 15278 if ( start < 0 ) start = 0; 15279 15280 15281 for ( let i = start; i < end; ++i ) { 15282 result.push(yield * thiz.get('' + i )); 15283 } 15284 15285 15286 return ArrayValue.make(result, s.realm); 15287 } 15288 15289 static *splice$e(thiz, args, s) { 15290 //TODO: Call ToObject() on thisz; 15291 15292 15293 let result = []; 15294 15295 15296 let deleteCount; 15297 let len = yield * getLength(thiz); 15298 let start = len; 15299 15300 if ( isNaN(len) ) return thiz; 15301 15302 if ( args.length > 0 ) start = yield * args[0].toIntNative(); 15303 15304 if ( start > len ) start = len; 15305 else if ( start < 0 ) start = len - start; 15306 15307 if ( args.length > 1 ) deleteCount = yield * args[1].toIntNative(); 15308 else deleteCount = len - start; 15309 15310 if ( deleteCount > (len - start) ) deleteCount = len - start; 15311 if ( deleteCount < 0 ) deleteCount = 0; 15312 15313 let deleted = []; 15314 let toAdd = args.slice(2); 15315 let delta = toAdd.length - deleteCount; 15316 15317 for ( let i = start; i < start + deleteCount; ++i ) { 15318 deleted.push(yield * thiz.get(i)); 15319 } 15320 15321 if ( delta > 0 ) yield * shiftRight(thiz, start, delta); 15322 if ( delta < 0 ) yield * shiftLeft(thiz, start - delta, -delta); 15323 15324 for ( let i = 0; i < toAdd.length; ++i ) { 15325 yield * thiz.set(start + i, toAdd[i]); 15326 } 15327 15328 yield * thiz.set('length', Value.fromNative(len + delta)); 15329 15330 15331 return ArrayValue.make(deleted, s.realm); 15332 } 15333 15334 static *sort$e(thiz, args, s) { 15335 let length = yield * getLength(thiz); 15336 let vals = new Array(length); 15337 for ( let i = 0; i < length; ++i ) { 15338 vals[i] = yield * thiz.get(i); 15339 } 15340 15341 let comp = function *(left, right) { 15342 let l = yield * left.toStringValue(); 15343 if ( !l ) return false;
15344 let r = yield * right.toStringValue(); 15345 if ( !r ) return true; 15346 return (yield * l.lt(r)).truthy; 15347 }; 15348 15349 if ( args.length > 0 ) { 15350 let fx = args[0]; 15351 if ( !fx.isCallable ) return yield CompletionRecord.makeTypeError(s.realm, 'Arg2 not calalble.'); 15352 comp = function *(left, right) { 15353 let res = yield * fx.call(Value.undef, [left, right], s); 15354 return ( yield * res.lt(Value.fromNative(0)) ).truthy; 15355 }; 15356 } 15357 15358 let nue = yield * _g.sort(vals, comp); 15359 15360 for ( let i = 0; i < length; ++i ) { 15361 yield * thiz.set(i, nue[i]); 15362 } 15363 return thiz; 15364 } 15365 15366 static *toString$e(thiz, args, s) { 15367 let joinfn = yield * thiz.get('join'); 15368 if ( !joinfn || !joinfn.isCallable ) { 15369 let ots = yield * s.realm.ObjectPrototype.get('toString'); 15370 return yield * ots.call(thiz, []); 15371 } else { 15372 return yield * joinfn.call(thiz, [defaultSeperator]); 15373 } 15374 15375 } 15376 15377 static *unshift$e(thiz, args, s) { 15378 let amt = args.length; 15379 let len = yield * getLength(thiz); 15380 if ( isNaN(len) ) len = 0; 15381 yield * shiftRight(thiz, 0, amt); 15382 for ( let i = 0; i < amt; ++i ) { 15383 yield * thiz.set(i, args[i]); 15384 } 15385 15386 let nl = Value.fromNative(len + amt); 15387 yield * thiz.set('length', nl, s); 15388 return nl; 15389 } 15390 15391} 15392 15393ArrayPrototype.prototype.wellKnownName = '%ArrayPrototype%'; 15394 15395module.exports = ArrayPrototype; 15396 15397 15398},{"../CompletionRecord":103,"../GenDash":108,"../Value":111,"../values/ArrayValue":134,"../values/EasyObjectValue":138,"../values/ObjectValue":145,"../values/PrimitiveValue":146}],115:[function(require,module,exports){ 15399'use strict'; 15400 15401const Value = require('../Value'); 15402const CompletionRecord = require('../CompletionRecord'); 15403 15404const ObjectValue = require('../values/ObjectValue'); 15405 15406class AssertFunction extends ObjectValue { 15407 15408 *rawCall(n, evalu, scope) { 15409 if ( n.arguments.length == 0 ) return Value.undef; 15410 let args = new Array(n.arguments.length); 15411 let why = ''; 15412 let check = n.arguments[0]; 15413 switch ( check.type ) { 15414 case 'BinaryExpression': 15415 let left = yield * evalu.branch(check.left, scope); 15416 let right = yield * evalu.branch(check.right, scope); 15417 args[0] = yield * evalu.doBinaryEvaluation(check.operator, left, right, scope); 15418 why = n.arguments[0].srcName + ' (' + left.debugString + ' ' + check.operator + ' ' + right.debugString + ')'; 15419 break; 15420 default: 15421 why = (n.arguments[0].srcName || '???'); 15422 args[0] = yield * evalu.branch(n.arguments[0], scope); 15423 } 15424 15425 15426 for ( let i = 1; i < args.length; ++i ) { 15427 args[i] = yield * evalu.branch(n.arguments[i], scope); 15428 } 15429 15430 if ( args[0].truthy ) return Value.undef; 15431 if ( args.length > 1 ) why = yield * args[1].toStringNative(); 15432 let err = scope.realm.Error.make(why, 'AssertionError'); 15433 return new CompletionRecord(CompletionRecord.THROW, err); 15434 } 15435 15436 *call(thiz, args, scope, ext) { 15437 let val = Value.undef; 15438 if ( args.length > 0 ) return Value.undef; 15439 if ( val.truthy ) return Value.undef; 15440 let reason = ''; 15441 if ( args.length > 1 ) { 15442 reason = ( yield * args[1].toStringValue() ).toNative(); 15443 } else if ( ext.callNode && ext.callNode.arguments[0] ) { 15444 reason = (ext.callNode.arguments[0].srcName || '???'); 15445 } 15446 let err = scope.realm.Error.make(reason, 'AssertionError'); 15447 return new CompletionRecord(CompletionRecord.THROW, err); 15448 } 15449} 15450
15451module.exports = AssertFunction; 15452 15453},{"../CompletionRecord":103,"../Value":111,"../values/ObjectValue":145}],116:[function(require,module,exports){ 15454'use strict'; 15455 15456const Value = require('../Value'); 15457const EasyObjectValue = require('../values/EasyObjectValue'); 15458 15459 15460class Boolean extends EasyObjectValue { 15461 *call(thiz, args, scope, ext) { 15462 let asConstructor = ext && ext.asConstructor; 15463 if ( !asConstructor ) { 15464 if ( args.length < 1 ) return Value.false; 15465 return args[0].truthy ? Value.true : Value.false; 15466 } 15467 if ( args.length > 0 ) { 15468 let pv = args[0].truthy ? Value.true : Value.false; 15469 thiz.primativeValue = pv; 15470 } else { 15471 thiz.primativeValue = false; 15472 } 15473 } 15474 15475 callPrototype(realm) { return realm.BooleanPrototype; } 15476 constructorFor(realm) { return realm.BooleanPrototype; } 15477} 15478 15479module.exports = Boolean; 15480 15481},{"../Value":111,"../values/EasyObjectValue":138}],117:[function(require,module,exports){ 15482'use strict'; 15483 15484const EasyObjectValue = require('../values/EasyObjectValue'); 15485const Value = require('../Value'); 15486 15487class BooleanPrototype extends EasyObjectValue { 15488 static *toString$e(thiz, argz) { 15489 if ( thiz.primativeValue.truthy ) return Value.fromNative('true'); 15490 else return Value.fromNative('false'); 15491 } 15492} 15493 15494module.exports = BooleanPrototype; 15495 15496},{"../Value":111,"../values/EasyObjectValue":138}],118:[function(require,module,exports){ 15497'use strict'; 15498 15499const Value = require('../Value'); 15500const CompletionRecord = require('../CompletionRecord'); 15501 15502const EasyObjectValue = require('../values/EasyObjectValue'); 15503 15504function *proxy(op, thiz, args, s) { 15505 let realm = s.realm; 15506 let printer = realm.print; 15507 let strings = new Array(args.length); 15508 for ( let i = 0; i < args.length; ++i ) { 15509 strings[i] = yield * args[i].toStringNative(); 15510 } 15511 //console[op].apply(console, strings); 15512 printer.apply(realm, strings); 15513 return Value.undef; 15514} 15515 15516class Console extends EasyObjectValue { 15517 static *log(thiz, argz, s) { return yield * proxy('log', thiz, argz, s); } 15518 static *info(thiz, argz, s) { return yield * proxy('info', thiz, argz, s); } 15519 static *warn(thiz, argz, s) { return yield * proxy('warn', thiz, argz, s); } 15520 static *error(thiz, argz, s) { return yield * proxy('error', thiz, argz, s); } 15521 static *trace(thiz, argz, s) { return yield * proxy('trace', thiz, argz, s); } 15522} 15523 15524module.exports = Console; 15525 15526},{"../CompletionRecord":103,"../Value":111,"../values/EasyObjectValue":138}],119:[function(require,module,exports){ 15527'use strict'; 15528 15529const EasyObjectValue = require('../values/EasyObjectValue'); 15530const ObjectValue = require('../values/ObjectValue'); 15531const ArrayValue = require('../values/ArrayValue'); 15532const PrimitiveValue = require('../values/PrimitiveValue'); 15533const EmptyValue = require('../values/EmptyValue'); 15534const ErrorValue = require('../values/ErrorValue'); 15535const CompletionRecord = require('../CompletionRecord'); 15536const PropertyDescriptor = require('../values/PropertyDescriptor'); 15537const Value = require('../Value'); 15538 15539 15540 15541class ErrorObject extends EasyObjectValue { 15542 constructor(realm) { 15543 super(realm); 15544 this.realm = realm; 15545 } 15546 makeOne() { 15547 let nue = new ErrorValue(this.realm); 15548 let p = this.properties['prototype']; 15549 if ( p ) nue.setPrototype(p.value); 15550 return nue; 15551 } 15552 15553 make(message, name) { 15554 let nue = this.makeOne(); 15555 if ( message ) { 15556 nue.setImmediate('message', Value.fromNative(message)); 15557 nue.properties['message'].enumerable = false; 15558 nue.createNativeAnalog().message = message; 15559 } 15560 15561 if ( name ) { 15562 nue.setImmediate('name', Value.fromNative(name)); 15563 nue.properties['name'].enumerable = false; 15564 nue.createNativeAnalog().name = name; 15565 } 15566 15567 return nue; 15568 } 15569 15570 makeFrom(err) { 15571 let nue = this.makeOne(); 15572 if ( err.message ) nue.setImmediate('message', Value.fromNative(err.message)); 15573 if ( err.name ) nue.setImmediate('name', Value.fromNative(err.name)); 15574 err.native = err; 15575 return nue; 15576 } 15577 15578 *makeThisForNew() { 15579 return this.makeOne(); 15580 } 15581 15582 *call(thiz, args, s, e) { 15583 15584 if ( thiz instanceof EmptyValue ) { 15585 thiz = this.makeOne(); 15586 } 15587 15588 if ( args.length > 0 ) yield * thiz.set('message', args[0], s, {enumerable: false}); 15589 if ( args.length > 1 ) yield * thiz.set('fileName', args[1], s, {enumerable: false}); 15590 if ( args.length > 2 ) yield * thiz.set('lineNumber', args[2], s, {enumerable: false}); 15591 15592 return thiz; 15593 } 15594 15595 makeErrorType(type) { 15596 let proto = new ObjectValue(this.realm); 15597 proto.setPrototype(this.realm.ErrorPrototype); 15598 proto.setImmediate('name', Value.fromNative(type.name)); 15599 proto.properties.name.enumerable = false;
15600 proto.wellKnownName = `%${type.name}Prototype%`; 15601 proto.nativeClass = type; 15602 15603 let obj = new ErrorObject(this.realm); 15604 obj.setPrototype(proto); 15605 obj.properties.prototype.value = proto; 15606 obj.wellKnownName = `%${type.name}%`; 15607 proto.rawSetProperty('constructor', new PropertyDescriptor(obj, false)); 15608 return obj; 15609 15610 } 15611 15612 callPrototype(realm) { return realm.ErrorPrototype; } 15613 15614} 15615 15616ErrorObject.prototype.wellKnownName = '%Error%'; 15617 15618module.exports = ErrorObject; 15619 15620 15621},{"../CompletionRecord":103,"../Value":111,"../values/ArrayValue":134,"../values/EasyObjectValue":138,"../values/EmptyValue":139,"../values/ErrorValue":140,"../values/ObjectValue":145,"../values/PrimitiveValue":146,"../values/PropertyDescriptor":147}],120:[function(require,module,exports){ 15622'use strict'; 15623 15624const EasyObjectValue = require('../values/EasyObjectValue'); 15625const ObjectValue = require('../values/ObjectValue'); 15626const ArrayValue = require('../values/ArrayValue'); 15627const PrimitiveValue = require('../values/PrimitiveValue'); 15628const CompletionRecord = require('../CompletionRecord'); 15629const Value = require('../Value'); 15630 15631 15632 15633 15634class ErrorPrototype extends EasyObjectValue { 15635 15636 static get message() { return Value.emptyString; } 15637 static get name$() { return Value.fromNative('Error'); } 15638 15639 static *toString(thiz, argz, s) { 15640 let name = yield * (yield * thiz.get('name')).toStringNative(); 15641 let message = yield * (yield * thiz.get('message')).toStringNative(); 15642 if ( name && message ) return Value.fromNative(`${name}: ${message}`); 15643 else if ( message ) return Value.fromNative(message); 15644 else return Value.fromNative(name); 15645 } 15646 15647} 15648 15649ErrorPrototype.prototype.wellKnownName = '%ErrorPrototype%'; 15650 15651module.exports = ErrorPrototype; 15652 15653 15654},{"../CompletionRecord":103,"../Value":111,"../values/ArrayValue":134,"../values/EasyObjectValue":138,"../values/ObjectValue":145,"../values/PrimitiveValue":146}],121:[function(require,module,exports){ 15655'use strict'; 15656 15657const EasyObjectValue = require('../values/EasyObjectValue'); 15658const EasyNativeFunction = require('../values/EasyNativeFunction'); 15659const Value = require('../Value'); 15660 15661 15662class EsperObject extends EasyObjectValue { 15663 static *dump$cew(thiz, args) { 15664 console.log('Esper#dump:', args); 15665 if ( typeof window !== 'undefined' ) window.dumped = args[0]; 15666 return Value.undef; 15667 } 15668 15669 static *str$cew(thiz, args) { 15670 var t = Value.undef; 15671 if ( args.length > 0 ) t = args[0]; 15672 return this.fromNative(t.debugString); 15673 } 15674 15675 static *stack$cew(thiz, args, scope, extra) { 15676 return Value.fromNative(extra.evaluator.buildStacktrace().join('\n')); 15677 } 15678 15679 static *globals$cew(thiz, args, scope, extra) { 15680 return scope.global.object; 15681 } 15682 15683 static *scope$cew(thiz, args, scope, extra) { 15684 return scope.object; 15685 } 15686 15687 15688} 15689 15690 15691 15692module.exports = EsperObject; 15693 15694},{"../Value":111,"../values/EasyNativeFunction":137,"../values/EasyObjectValue":138}],122:[function(require,module,exports){ 15695'use strict'; 15696 15697const EasyObjectValue = require('../values/EasyObjectValue'); 15698const ClosureValue = require('../values/ClosureValue'); 15699const CompletionRecord = require('../CompletionRecord'); 15700const ASTPreprocessor = require('../ASTPreprocessor'); 15701const PropertyDescriptor = require('../values/PropertyDescriptor'); 15702 15703class FunctionObject extends EasyObjectValue { 15704 *call(thiz, args, scope) { 15705 let an = new Array(args.length - 1); 15706 for ( let i = 0; i < args.length - 1; ++i ) { 15707 an[i] = (yield * args[i].toStringValue()).toNative(); 15708 } 15709 let code = 'function name(' + an.join(', ') + ') {\n' + args[args.length - 1].toNative().toString() + '\n}'; 15710 let ast; 15711 try { 15712 let oast = scope.realm.parser(code, {loc: true}); 15713 ast = ASTPreprocessor.process(oast); 15714 } catch ( e ) { 15715 return new CompletionRecord(CompletionRecord.THROW, e); 15716 } 15717 15718 let fn = new ClosureValue(ast.body[0], scope.global); 15719 fn.boundScope = scope.global; 15720 return fn; 15721 } 15722 15723 _init(realm) { 15724 super._init(realm); 15725 let cs = new PropertyDescriptor(this); 15726 cs.configurable = false; 15727 cs.enumerable = false; 15728 this.properties['constructor'] = cs; 15729 } 15730 15731 callPrototype(realm) { return realm.FunctionPrototype; } 15732 get callLength() { return 1; } 15733 //objPrototype(realm) { return realm.Function; } 15734} 15735 15736module.exports = FunctionObject; 15737 15738},{"../ASTPreprocessor":102,"../CompletionRecord":103,"../values/ClosureValue":136,"../values/EasyObjectValue":138,"../values/PropertyDescriptor":147}],123:[function(require,module,exports){ 15739'use strict'; 15740 15741const EasyObjectValue = require('../values/EasyObjectValue'); 15742const ClosureValue = require('../values/ClosureValue'); 15743const Value = require('../Value'); 15744const ObjectValue = require('../values/ObjectValue'); 15745const CompletionRecord = require('../CompletionRecord'); 15746const PropertyDescriptor = require('../values/PropertyDescriptor'); 15747 15748class BoundFunction extends ObjectValue { 15749 constructor(func, realm) { 15750 super(realm); 15751 this.setPrototype(realm.FunctionPrototype); 15752 this.func = func; 15753 this.boundArgs = []; 15754 } 15755 15756 *call(thiz, args, s, ext) { 15757 let tt = thiz; 15758 let asConstructor = ext && ext.asConstructor; 15759 15760 if ( !asConstructor ) { 15761 tt = this.boundThis; 15762 } 15763 15764 let rargs = [].concat(this.boundArgs, args); 15765 return yield * this.func.call(tt, rargs, s, ext); 15766 } 15767 15768 15769 *constructorOf(other, realm) { 15770 return yield * this.func.constructorOf(other, realm); 15771 } 15772 15773 15774 *makeThisForNew(realm) { 15775 return yield * this.func.makeThisForNew(realm); 15776 } 15777 15778} 15779
15780class FunctionPrototype extends EasyObjectValue { 15781 static get caller$cew() { return null; } 15782 static get length$ew() { return '?'; } 15783 static get name$ew() { return ''; } 15784 15785 static *apply(thiz, args, s) { 15786 let vthis = args[0]; 15787 let arga = []; 15788 if ( args.length > 1 ) { 15789 let arr = args[1]; 15790 let length = yield * arr.get('length'); 15791 length = (yield * length.toNumberValue()).toNative(); 15792 for ( let i = 0; i < length; ++i ) { 15793 arga[i] = yield * arr.get(i); 15794 } 15795 } 15796 return yield * thiz.call(vthis, arga, s); 15797 } 15798 15799 static *bind(thiz, args, s) { 15800 let bthis = s.realm.globalScope.object; //TODO: is this actually null in scrict mode? 15801 if ( args.length > 0 ) { 15802 if ( args[0].jsTypeName !== 'undefined') bthis = args[0]; 15803 } 15804 var out = new BoundFunction(thiz, s.realm); 15805 if ( args.length > 1 ) out.boundArgs = args.slice(1); 15806 out.boundThis = bthis; 15807 15808 if ( thiz.properties['length'] ) { 15809 let newlen = thiz.properties['length'].value.toNative() - out.boundArgs.length; 15810 out.properties['length'] = new PropertyDescriptor(this.fromNative(newlen)); 15811 } 15812 return out; 15813 } 15814 15815 static *call(thiz, args, s) { 15816 let vthis = Value.undef; 15817 if ( args.length > 0 ) vthis = args.shift(); 15818 return yield * thiz.call(vthis, args, s); 15819 } 15820 static *toString(thiz, args, s) { 15821 if ( thiz instanceof ClosureValue ) { 15822 let astsrc = thiz.func.source(); 15823 if ( astsrc ) return this.fromNative(astsrc); 15824 return this.fromNative('function() { [AST] }'); 15825 } else if ( thiz instanceof BoundFunction ) { 15826 return this.fromNative('function() { [bound function] }'); 15827 } else if ( thiz instanceof EasyObjectValue.EasyNativeFunction ) { 15828 return this.fromNative('function() { [native code] }'); 15829 } 15830 return CompletionRecord.makeTypeError(s.realm, 'Function.prototype.toString is not generic'); 15831 15832 } 15833 15834 *call(thiz, args, s) { 15835 return EasyObjectValue.undef; 15836 } 15837 15838} 15839 15840FunctionPrototype.prototype.wellKnownName = '%FunctionPrototype%'; 15841 15842 15843module.exports = FunctionPrototype; 15844 15845},{"../CompletionRecord":103,"../Value":111,"../values/ClosureValue":136,"../values/EasyObjectValue":138,"../values/ObjectValue":145,"../values/PropertyDescriptor":147}],124:[function(require,module,exports){ 15846'use strict'; 15847 15848const Value = require('../Value'); 15849const EasyObjectValue = require('../values/EasyObjectValue'); 15850const ObjectValue = require('../values/ObjectValue'); 15851const PrimitiveValue = require('../values/PrimitiveValue'); 15852const ArrayValue = require('../values/ArrayValue'); 15853const CompletionRecord = require('../CompletionRecord'); 15854 15855class JSONUtils { 15856 static *genJSONTokens(arr, o, map, str, strincr) { 15857 let str2 = str !== undefined ? str + strincr : undefined; 15858 15859 if ( o instanceof PrimitiveValue ) { 15860 return arr.push(JSON.stringify(o.native)); 15861 } 15862 15863 15864 if ( map.has(o) ) { 15865 return arr.push('[Circular]'); 15866 } 15867 map.set(o, true); 15868 15869 if ( o instanceof ArrayValue ) { 15870 arr.push('['); 15871 let length = yield * (yield * o.get('length')).toIntNative(); 15872 for ( let i = 0; i < length; ++i ) { 15873 if ( i > 0 ) arr.push(','); 15874 if ( str !== undefined ) arr.push('\n'); 15875 let m = yield * o.get(i); 15876 if ( str !== undefined ) arr.push(str2); 15877 if ( m ) { 15878 if ( m.jsTypeName == 'undefined' ) arr.push('null'); 15879 else yield * JSONUtils.genJSONTokens(arr, m, map, str2, strincr); 15880 } 15881 } 15882 if ( str !== undefined ) arr.push('\n'); 15883 if ( str !== undefined ) arr.push(str); 15884 arr.push(']'); 15885 return; 15886 } 15887 15888 arr.push('{'); 15889 15890 let first = true; 15891 for ( let p of Object.keys(o.properties)) { 15892 let po = o.properties[p]; 15893 if ( !po.enumerable ) continue; 15894 let v = yield * o.get(p); 15895 if ( v.jsTypeName === 'function' ) continue; 15896 15897 if ( first ) first = false; 15898 else arr.push(','); 15899 if ( str !== undefined ) arr.push('\n', str2); 15900 15901 15902 15903 arr.push(JSON.stringify(p), ':'); 15904 if ( str !== undefined ) arr.push(' '); 15905 yield * JSONUtils.genJSONTokens(arr, v, map, str2, strincr); 15906 15907 15908 } 15909 if ( str !== undefined ) arr.push('\n'); 15910 arr.push('}'); 15911 } 15912} 15913 15914class JSONObject extends EasyObjectValue { 15915 static *parse(thiz, args, s) { 15916 let str = Value.emptyString; 15917 if ( args.length > 0 ) str = yield * args[0].toStringNative(); 15918 try { 15919 var out = JSON.parse(str, (k, o) => { 15920 if ( o === undefined ) return Value.undef; 15921 if ( o === null ) return Value.null; 15922 15923 let prim = Value.fromPrimativeNative(o); 15924 if ( prim ) return prim; 15925 15926 15927 if ( Array.isArray(o) ) { 15928 return ArrayValue.make(o, s.realm); 15929 } 15930 15931 let v = new ObjectValue(s.realm); 15932 for ( var p in o ) { 15933 v.setImmediate(p, o[p]); 15934 } 15935 return v; 15936 }); 15937 return out; 15938 } catch ( e ) { 15939 yield new CompletionRecord(CompletionRecord.THROW, Value.fromNative(e, s.realm)); 15940 } 15941 } 15942 15943 static *stringify(thiz, args, s) { 15944 let arr = []; 15945 let v = Value.undef; 15946 let replacer = null; 15947 let str; 15948 let strincr; 15949 15950 if ( args.length > 0 ) v = args[0]; 15951 if ( args.length > 1 ) replacer = args[1]; 15952 if ( args.length > 2 ) { 15953 str = ''; 15954 if ( args[2].jsTypeName === 'number' ) { 15955 let len = yield * args[2].toIntNative();
15956 strincr = new Array(1 + len).join(' '); 15957 } else { 15958 strincr = yield * args[2].toStringNative(); 15959 } 15960 15961 } 15962 if ( v.jsTypeName === 'undefined' ) return Value.undef; 15963 15964 yield * JSONUtils.genJSONTokens(arr, v, new WeakMap(), str, strincr); 15965 return Value.fromNative(arr.join('')); 15966 } 15967 15968 15969} 15970 15971module.exports = JSONObject; 15972 15973},{"../CompletionRecord":103,"../Value":111,"../values/ArrayValue":134,"../values/EasyObjectValue":138,"../values/ObjectValue":145,"../values/PrimitiveValue":146}],125:[function(require,module,exports){ 15974'use strict'; 15975 15976const EasyObjectValue = require('../values/EasyObjectValue'); 15977const Value = require('../Value'); 15978 15979function makeNumber(num) { 15980 return 0 + num.toNative(); 15981} 15982 15983function wrapMathFunction(name) { 15984 let fn = Math[name]; 15985 return function*(thiz, args, realm) { 15986 let length = args.length; 15987 let argz = new Array(length); 15988 for ( let i = 0; i < length; ++i ) { 15989 if ( i < args.length ) argz[i] = args[i].toNative(); 15990 else argz[i] = undefined; 15991 } 15992 15993 let result = fn.apply(Math, argz); 15994 return Value.fromPrimativeNative(result); 15995 }; 15996 15997} 15998 15999class MathObject extends EasyObjectValue { 16000 16001 16002 static get E$cew() { return Math.E; } 16003 static get LN10$cew() { return Math.LN10; } 16004 static get LN2$cew() { return Math.LN2; } 16005 static get LOG10E$cew() { return Math.LOG10E; } 16006 static get LOG2E$cew() { return Math.LOG2E; } 16007 static get PI$cew() { return Math.PI; } 16008 static get SQRT1_2$cew() { return Math.SQRT1_2; } 16009 static get SQRT2$cew() { return Math.SQRT2; } 16010} 16011 16012MathObject.sqrt = wrapMathFunction('sqrt'); 16013MathObject.atanh = wrapMathFunction('atanh'); 16014MathObject.log2 = wrapMathFunction('log2'); 16015MathObject.asinh = wrapMathFunction('asinh'); 16016MathObject.log = wrapMathFunction('log'); 16017MathObject.trunc = wrapMathFunction('trunc'); 16018MathObject.max = wrapMathFunction('max'); 16019MathObject.log10 = wrapMathFunction('log10'); 16020MathObject.atan2 = wrapMathFunction('atan2'); 16021MathObject.round = wrapMathFunction('round'); 16022MathObject.exp = wrapMathFunction('exp'); 16023MathObject.tan = wrapMathFunction('tan'); 16024MathObject.floor = wrapMathFunction('floor'); 16025MathObject.sign = wrapMathFunction('sign'); 16026MathObject.fround = wrapMathFunction('fround'); 16027MathObject.sin = wrapMathFunction('sin'); 16028MathObject.tanh = wrapMathFunction('tanh'); 16029MathObject.expm1 = wrapMathFunction('expm1'); 16030MathObject.cbrt = wrapMathFunction('cbrt'); 16031MathObject.cos = wrapMathFunction('cos'); 16032MathObject.abs = wrapMathFunction('abs'); 16033MathObject.acosh = wrapMathFunction('acosh'); 16034MathObject.asin = wrapMathFunction('asin'); 16035MathObject.ceil = wrapMathFunction('ceil'); 16036MathObject.atan = wrapMathFunction('atan'); 16037MathObject.cosh = wrapMathFunction('cosh'); 16038MathObject.random = wrapMathFunction('random'); 16039MathObject.log1p = wrapMathFunction('log1p'); 16040MathObject.imul = wrapMathFunction('imul'); 16041MathObject.hypot = wrapMathFunction('hypot'); 16042MathObject.pow = wrapMathFunction('pow'); 16043MathObject.sinh = wrapMathFunction('sinh'); 16044MathObject.acos = wrapMathFunction('acos'); 16045MathObject.min = wrapMathFunction('min'); 16046MathObject.max = wrapMathFunction('max'); 16047 16048 16049MathObject.prototype.clazz = 'Math'; 16050 16051module.exports = MathObject; 16052 16053},{"../Value":111,"../values/EasyObjectValue":138}],126:[function(require,module,exports){ 16054'use strict'; 16055 16056const EasyObjectValue = require('../values/EasyObjectValue'); 16057const CompletionRecord = require('../CompletionRecord'); 16058 16059 16060class NumberObject extends EasyObjectValue { 16061 *call(thiz, args, scope, ext) { 16062 let asConstructor = ext && ext.asConstructor; 16063 if ( !asConstructor ) { 16064 if ( args.length < 1 ) return EasyObjectValue.zero; 16065 return yield * args[0].toNumberValue(); 16066 } 16067 let pv = EasyObjectValue.zero; 16068 if ( args.length > 0 ) pv = yield * args[0].toNumberValue(); 16069 thiz.primativeValue = pv; 16070 } 16071 16072 callPrototype(realm) { return realm.NumberPrototype; } 16073 constructorFor(realm) { return realm.NumberPrototype; } 16074 16075 static get MAX_VALUE$cew() { return Number.MAX_VALUE; } 16076 static get MIN_VALUE$cew() { return Number.MIN_VALUE; } 16077 static get POSITIVE_INFINITY$cew() { return Number.POSITIVE_INFINITY; } 16078 static get NEGATIVE_INFINITY$cew() { return Number.NEGATIVE_INFINITY; } 16079 static get NaN$cew() { return EasyObjectValue.nan; } 16080 16081} 16082 16083NumberObject.prototype.wellKnownName = '%Number%'; 16084module.exports = NumberObject; 16085 16086 16087},{"../CompletionRecord":103,"../values/EasyObjectValue":138}],127:[function(require,module,exports){ 16088'use strict'; 16089 16090const EasyObjectValue = require('../values/EasyObjectValue'); 16091 16092
16093class NumberPrototype extends EasyObjectValue { 16094 16095 static *valueOf(thiz) { 16096 if ( thiz.specTypeName === 'number' ) return thiz; 16097 if ( thiz.specTypeName === 'object' ) { 16098 let pv = thiz.primativeValue; 16099 if ( pv.specTypeName === 'number' ) return pv; 16100 } 16101 throw new TypeError('Couldnt get there.'); 16102 } 16103 16104 16105 static *toExponential(thiz, argz) { 16106 let a; 16107 if ( argz.length > 0 ) { 16108 a = yield * argz[0].toNumberNative(); 16109 } 16110 let num = yield * thiz.toNumberNative(thiz); 16111 return this.fromNative(num.toExponential(a)); 16112 } 16113 16114 static *toFixed(thiz, argz) { 16115 let a; 16116 if ( argz.length > 0 ) { 16117 a = yield * argz[0].toNumberNative(); 16118 } 16119 let num = yield * thiz.toNumberNative(thiz); 16120 return this.fromNative(num.toFixed(a)); 16121 } 16122 16123 static *toPrecision(thiz, argz) { 16124 let a; 16125 if ( argz.length > 0 ) { 16126 a = yield * argz[0].toNumberNative(); 16127 } 16128 let num = yield * thiz.toNumberNative(thiz); 16129 return this.fromNative(num.toPrecision(a)); 16130 } 16131 16132 static *toString(thiz, argz) { 16133 let a; 16134 if ( argz.length > 0 ) { 16135 a = yield * argz[0].toNumberNative(); 16136 } 16137 let num = yield * thiz.toNumberNative(thiz); 16138 return this.fromNative(num.toString(a)); 16139 } 16140 16141 16142} 16143 16144 16145NumberPrototype.prototype.wellKnownName = '%NumberPrototype%'; 16146module.exports = NumberPrototype; 16147 16148},{"../values/EasyObjectValue":138}],128:[function(require,module,exports){ 16149'use strict'; 16150 16151const EasyObjectValue = require('../values/EasyObjectValue'); 16152const ObjectValue = require('../values/ObjectValue'); 16153const ArrayValue = require('../values/ArrayValue'); 16154const CompletionRecord = require('../CompletionRecord'); 16155const Value = require('../Value'); 16156const PropertyDescriptor = require('../values/PropertyDescriptor'); 16157const EmptyValue = require('../values/EmptyValue'); 16158 16159function *defObjectProperty(obj, name, desc, realm) { 16160 if ( name instanceof Value ) { 16161 name = (yield * name.toStringNative()); 16162 } 16163 16164 let value = yield * desc.get('value', realm); 16165 16166 16167 let v = new PropertyDescriptor(value); 16168 16169 16170 if ( desc.has('enumerable') ) { 16171 let enu = yield * desc.get('enumerable', realm); 16172 if ( !(enu instanceof EmptyValue) ) { 16173 v.enumerable = enu.truthy; 16174 } 16175 } else { 16176 v.enumerable = false; 16177 } 16178 16179 if ( desc.has('writable') ) { 16180 let wri = yield * desc.get('writable', realm); 16181 if ( !(wri instanceof EmptyValue) ) { 16182 v.writable = wri.truthy; 16183 } 16184 } else { 16185 v.writable = false; 16186 } 16187 16188 if ( desc.has('configurable') ) { 16189 let conf = yield * desc.get('configurable', realm); 16190 if ( !(conf instanceof EmptyValue) ) { 16191 v.writable = conf.truthy; 16192 } 16193 } else { 16194 v.writable = false; 16195 } 16196 16197 16198 if ( desc.has('get') ) { 16199 let get = yield * desc.get('get', realm); 16200 if ( !(get instanceof EmptyValue) ) { 16201 v.getter = get; 16202 } 16203 } 16204 16205 if ( desc.has('set') ) { 16206 let set = yield * desc.get('set', realm); 16207 if ( !(set instanceof EmptyValue) ) { 16208 v.setter = set; 16209 } 16210 } 16211 16212 obj.rawSetProperty(name, v); 16213 return true; 16214} 16215 16216function *getDescriptor(target, name, realm) { 16217 if ( !Object.hasOwnProperty.call(target.properties, name) ) { 16218 return Value.undef; 16219 } 16220 16221 let pdesc = target.properties[name]; 16222 let out = new ObjectValue(realm); 16223 16224 if ( pdesc.value ) yield * out.set('value', pdesc.value); 16225 if ( pdesc.getter ) yield * out.set('get', pdesc.getter); 16226 if ( pdesc.setter ) yield * out.set('set', pdesc.setter); 16227 16228 yield * out.set('writable', Value.fromNative(pdesc.writable)); 16229 yield * out.set('enumerable', Value.fromNative(pdesc.enumerable)); 16230 yield * out.set('configurable', Value.fromNative(pdesc.configurable)); 16231 return out; 16232} 16233 16234function *objOrThrow(i, realm) { 16235 let val = i ? i : Value.undef; 16236 16237 if ( val instanceof EmptyValue ) { 16238 return yield CompletionRecord.makeTypeError(realm, 'Cannot convert undefined or null to object'); 16239 } 16240 16241 if ( !(val instanceof ObjectValue) ) { 16242 return yield CompletionRecord.makeTypeError(realm, 'Need an object'); 16243 } 16244 return val; 16245} 16246 16247class ObjectObject extends EasyObjectValue { 16248 *call(thiz, args, s, ext) { 16249 let asConstructor = ext && ext.asConstructor; 16250 if ( asConstructor ) { 16251 return new ObjectValue(s.realm); 16252 } 16253 } 16254 16255 callPrototype(realm) { return realm.ObjectPrototype; } 16256 //objPrototype(realm) { return realm.Function; } 16257 16258 static *create$e(thiz, args, s) { 16259 let v = new ObjectValue(s.realm); 16260 let p = Value.undef; 16261 if ( args.length > 0 ) { 16262 p = args[0]; 16263 } 16264 16265 if ( p.jsTypeName !== 'object' && p.jsTypeName !== 'function' ) { 16266 return yield CompletionRecord.makeTypeError(s.realm, 'Object prototype may only be an Object or null'); 16267 } 16268 16269 v.setPrototype(p); 16270 16271 if ( args.length > 1 ) { 16272 let propsobj = args[1]; 16273 for ( let p of propsobj.observableProperties(s.realm) ) { 16274 let strval = p.native; 16275 let podesc = yield * propsobj.get(strval, s.realm); 16276 yield * defObjectProperty(v, p, podesc, s.realm); 16277 } 16278 } 16279 return v; 16280 } 16281 16282 static *defineProperty(thiz, args, s) { 16283 let target = yield * objOrThrow(args[0], s.realm); 16284 let name = yield * args[1].toStringNative(); 16285 let desc = args[2]; 16286 yield * defObjectProperty(target, name, desc, s.realm); 16287 return Value.true; 16288 } 16289 16290 static *defineProperties(thiz, args, s) { 16291 16292 let target = yield * objOrThrow(args[0], s.realm); 16293 //let props = yield * objOrThrow(args[1], s.realm); 16294 16295 let propsobj = yield * objOrThrow(args[1], s.realm); 16296 16297 for ( let p of propsobj.observableProperties(s.realm) ) { 16298 let strval = p.native; 16299 let podesc = yield * propsobj.get(strval, s.realm); 16300 yield * defObjectProperty(target, p, podesc, s.realm); 16301 } 16302 return Value.true; 16303 } 16304 16305 static *seal$e(thiz, args, s) { 16306 let target = yield * objOrThrow(args[0], s.realm); 16307 16308 target.extensable = false;
16309 for ( let p of Object.keys(target.properties) ) { 16310 target.properties[p].configurable = false; 16311 } 16312 return target; 16313 } 16314 16315 static *isSealed(thiz, args, s) { 16316 let target = yield * objOrThrow(args[0], s.realm); 16317 if ( target.extensable ) return Value.false; 16318 for ( let p of Object.keys(target.properties) ) { 16319 let ps = target.properties[p]; 16320 if ( ps.configurable ) return Value.false; 16321 } 16322 return Value.true; 16323 } 16324 16325 static *freeze$e(thiz, args, s) { 16326 let target = yield * objOrThrow(args[0], s.realm); 16327 target.extensable = false; 16328 for ( let p in target.properties ) { 16329 if ( !Object.prototype.hasOwnProperty.call(target.properties, p) ) continue; 16330 target.properties[p].configurable = false; 16331 target.properties[p].writable = false; 16332 } 16333 return target; 16334 } 16335 16336 static *isFrozen(thiz, args, s) { 16337 let target = yield * objOrThrow(args[0], s.realm); 16338 if ( target.extensable ) return Value.false; 16339 for ( let p of Object.keys(target.properties) ) { 16340 let ps = target.properties[p]; 16341 if ( ps.configurable ) return Value.false; 16342 if ( ps.writable ) return Value.false; 16343 } 16344 return Value.true; 16345 } 16346 16347 static *preventExtensions$e(thiz, args, s) { 16348 let target = yield * objOrThrow(args[0], s.realm); 16349 target.extensable = false; 16350 return target; 16351 } 16352 16353 static *isExtensible$e(thiz, args, s) { 16354 let target = yield * objOrThrow(args[0], s.realm); 16355 return this.fromNative(target.extensable); 16356 } 16357 16358 static *keys$e(thiz, args, s) { 16359 let target = yield * objOrThrow(args[0], s.realm); 16360 let result = []; 16361 for ( let p of Object.keys(target.properties) ) { 16362 if ( !target.properties[p].enumerable ) continue; 16363 result.push(p); 16364 } 16365 return ArrayValue.make(result, s.realm); 16366 } 16367 16368 static *getOwnPropertyNames$e(thiz, args, s) { 16369 let target = yield * objOrThrow(args[0], s.realm); 16370 return ArrayValue.make(Object.getOwnPropertyNames(target.properties), s.realm); 16371 } 16372 16373 static *getOwnPropertyDescriptor(thiz, args, s) { 16374 let target = yield * objOrThrow(args[0], s.realm); 16375 let name = yield * args[1].toStringNative(); 16376 return yield * getDescriptor(target, name, s.realm); 16377 } 16378 16379 static *getPrototypeOf(thiz, args, s) { 16380 let target = EasyObjectValue.undef; 16381 if ( args.length > 0 ) target = args[0]; 16382 if ( !target.getPrototype ) return yield CompletionRecord.makeTypeError(s.realm, 'No prototype.'); 16383 let proto = target.getPrototype(s.realm); 16384 if ( proto ) return proto; 16385 return EasyObjectValue.null; 16386 } 16387 16388 toNativeCounterpart() { return Object; } 16389} 16390 16391ObjectObject.prototype.wellKnownName = '%Object%'; 16392 16393module.exports = ObjectObject; 16394 16395},{"../CompletionRecord":103,"../Value":111,"../values/ArrayValue":134,"../values/EasyObjectValue":138,"../values/EmptyValue":139,"../values/ObjectValue":145,"../values/PropertyDescriptor":147}],129:[function(require,module,exports){ 16396'use strict'; 16397 16398const ObjectValue = require('../values/ObjectValue'); 16399const EasyObjectValue = require('../values/EasyObjectValue'); 16400const Value = require('../Value'); 16401const NullValue = require('../values/NullValue'); 16402const UndefinedValue = require('../values/UndefinedValue'); 16403 16404class ObjectPrototype extends EasyObjectValue { 16405 constructor(realm) { 16406 super(realm); 16407 this.setPrototype(null); 16408 } 16409 16410 static *hasOwnProperty$e(thiz, args) { 16411 let name = yield * args[0].toStringNative(); 16412 if ( !(thiz instanceof ObjectValue) ) return Value.false; 16413 else if ( thiz.hasOwnProperty(name) ) return Value.true; 16414 return Value.false; 16415 } 16416 16417 16418 static *isPrototypeOf$e(thiz, args, s) { 16419 if ( args.length < 1 ) return Value.false; 16420 let target = args[0]; //TODO: Call ToObject(); 16421 if ( !target.getPrototype ) return yield CompletionRecord.makeTypeError(s.realm, 'No prototype.'); 16422 let pt = target.getPrototype(s.realm); 16423 let checked = [pt]; 16424 while ( pt ) { 16425 if ( pt === thiz ) return Value.true; 16426 pt = pt.getPrototype(s.realm); 16427 if ( checked.indexOf(pt) !== -1 ) break; 16428 checked.push(pt); 16429 } 16430 return Value.false; 16431 } 16432 16433 static *propertyIsEnumerable$e(thiz, args) { 16434 let nam = yield * args[0].toStringNative(); 16435 let pd = thiz.properties[nam]; 16436 return this.fromNative(pd.enumerable); 16437 } 16438 static *toLocaleString$e(thiz, args) { return yield * ObjectPrototype.toString$e(thiz, args
16438); } 16439 16440 static *toString$e(thiz, args) { 16441 if ( thiz instanceof UndefinedValue ) return this.fromNative('[object Undefined]'); 16442 if ( thiz instanceof NullValue ) return this.fromNative('[object Null]'); 16443 return this.fromNative('[object ' + thiz.clazz + ']'); 16444 } 16445 16446 static *valueOf$e(thiz, args) { 16447 if ( thiz.specTypeName === 'object' ) return thiz; 16448 //TODO: Need to follow the ToObject() conversion 16449 return thiz; 16450 } 16451 16452} 16453ObjectPrototype.prototype.wellKnownName = '%ObjectPrototype%'; 16454 16455module.exports = ObjectPrototype; 16456 16457},{"../Value":111,"../values/EasyObjectValue":138,"../values/NullValue":143,"../values/ObjectValue":145,"../values/UndefinedValue":151}],130:[function(require,module,exports){ 16458'use strict'; 16459 16460const Value = require('../Value'); 16461const CompletionRecord = require('../CompletionRecord'); 16462 16463const EasyObjectValue = require('../values/EasyObjectValue'); 16464const RegExpValue = require('../values/RegExpValue'); 16465 16466 16467class RegExpObject extends EasyObjectValue { 16468 16469 *call(thiz, args, s) { 16470 let pattern = ''; 16471 let flags = ''; 16472 16473 if ( (args.length > 0) && (args[0] instanceof RegExpValue) ) { 16474 if ( args.length > 1 && args[1].truthy ) return yield CompletionRecord.makeTypeError(s.realm, 'Cannot supply flags when constructing one RegExp from another'); 16475 return RegExpValue.make(new RegExp(args[0].regexp), s.realm); 16476 } 16477 16478 if ( args.length > 0 && args[0].jsTypeName !== 'undefined' ) pattern = yield * args[0].toStringNative(); 16479 if ( args.length > 1 && args[1].jsTypeName !== 'undefined' ) flags = yield * args[1].toStringNative(); 16480 16481 let rx; 16482 try { 16483 rx = new RegExp(pattern, flags); 16484 } catch ( ex ) { 16485 return yield new CompletionRecord(CompletionRecord.THROW, Value.fromNative(ex, s.realm)); 16486 } 16487 16488 return RegExpValue.make(rx, s.realm); 16489 } 16490 16491 callPrototype(realm) { return realm.RegExpPrototype; } 16492 get callLength() { return 2; } 16493} 16494 16495RegExpObject.prototype.wellKnownName = '%RegExp%'; 16496 16497module.exports = RegExpObject; 16498 16499},{"../CompletionRecord":103,"../Value":111,"../values/EasyObjectValue":138,"../values/RegExpValue":148}],131:[function(require,module,exports){ 16500'use strict'; 16501 16502const Value = require('../Value'); 16503const ArrayValue = require('../values/ArrayValue'); 16504 16505const CompletionRecord = require('../CompletionRecord'); 16506 16507const EasyObjectValue = require('../values/EasyObjectValue'); 16508const _g = require('../GenDash'); 16509 16510function *toRegexp(x, realm) { 16511 if ( !x.regexp ) { 16512 return yield CompletionRecord.makeTypeError(realm, 'Calling regex method on non regex.'); 16513 } 16514 return x.regexp; 16515} 16516 16517class RegExpProtoype extends EasyObjectValue { 16518 constructor(realm) { 16519 super(realm); 16520 this.regexp = new RegExp(); 16521 } 16522 static *test(thiz, args, s) { 16523 var rx = yield * toRegexp(thiz, s.realm); 16524 var str = undefined; 16525 if ( args.length > 0 ) str = yield * args[0].toStringNative(); 16526 return this.fromNative(rx.test(str)); 16527 } 16528 16529 static *exec(thiz, args, s) { 16530 var rx = yield * toRegexp(thiz, s.realm); 16531 let li = yield * thiz.get('lastIndex'); 16532 li = yield * li.toIntNative(); 16533 if ( li < 0 ) li = 0; //Work around incorrect V8 behavior. 16534 rx.lastIndex = li; 16535 var str = undefined; 16536 if ( args.length > 0 ) str = yield * args[0].toStringNative(); 16537 16538 var result = rx.exec(str); 16539 yield * thiz.set('lastIndex', Value.fromNative(rx.lastIndex)); 16540 if ( result === null ) return Value.null; 16541 16542 let wraped = yield * _g.map(result, function *(c) { return Value.fromNative(c, s.realm); }); 16543 16544 let out = ArrayValue.make(wraped, s.realm); 16545 yield * out.set('index', Value.fromNative(result.index)); 16546 yield * out.set('input', Value.fromNative(result.input)); 16547 return out; 16548 } 16549 16550 static *compile(thiz, args, s) { 16551 yield * toRegexp(thiz, s.realm); 16552 let rv = yield * s.realm.RegExp.call(Value.null, args, s); 16553 let regexp = rv.regexp; 16554 thiz.regexp = regexp; 16555 yield * thiz.set('source', Value.fromNative(regexp.source)); 16556 yield * thiz.set('global', Value.fromNative(regexp.global)); 16557 yield * thiz.set('ignoreCase', Value.fromNative(regexp.ignoreCase)); 16558 yield * thiz.set('multiline', Value.fromNative(regexp.multiline)); 16559 yield * thiz.set('lastIndex', Value.zero); 16560 return Value.undef; 16561 } 16562 16563 static get source$cw() { return Value.fromNative('(?:)'); } 16564 static get global$cw() { return Value.fromNative(false); } 16565 static get ignoreCase$cw() { return Value.fromNative(false); } 16566 static get multiline$cw() { return Value.fromNative(false); } 16567 16568 static *toString(thiz, args, s) { 16569 var rx = yield * toRegexp(thiz, s.realm); 16570 return Value.fromNative(rx.toString()); 16571 } 16572 16573 16574 static get lastIndex() { return Value.fromNative(0); } 16575} 16576
16577RegExpProtoype.prototype.wellKnownName = '%RegExpProtoype%'; 16578RegExpProtoype.prototype.clazz = 'RegExp'; 16579 16580module.exports = RegExpProtoype; 16581 16582},{"../CompletionRecord":103,"../GenDash":108,"../Value":111,"../values/ArrayValue":134,"../values/EasyObjectValue":138}],132:[function(require,module,exports){ 16583'use strict'; 16584 16585const EasyObjectValue = require('../values/EasyObjectValue'); 16586const CompletionRecord = require('../CompletionRecord'); 16587const PropertyDescriptor = require('../values/PropertyDescriptor'); 16588 16589class StringObject extends EasyObjectValue { 16590 *call(thiz, args, scope, ext) { 16591 let asConstructor = ext && ext.asConstructor; 16592 if ( !asConstructor ) { 16593 //Called as a function... 16594 return yield * args[0].toStringValue(); 16595 } 16596 let len = 0; 16597 if ( args.length > 0 ) { 16598 let pv = yield * args[0].toStringValue(); 16599 len = pv.native.length; 16600 thiz.primativeValue = pv; 16601 } else { 16602 thiz.primativeValue = EasyObjectValue.emptyString; 16603 } 16604 16605 var plen = new PropertyDescriptor(scope.realm.fromNative(len)); 16606 plen.enumerable = false; 16607 plen.configurable = false; 16608 plen.writable = false; 16609 thiz.rawSetProperty('length', plen); 16610 return thiz; 16611 } 16612 16613 callPrototype(realm) { return realm.StringPrototype; } 16614 constructorFor(realm) { return realm.StringPrototype; } 16615 16616 static *fromCharCode(thiz, args) { 16617 let argz = new Array(args.length); 16618 for ( let i = 0; i < args.length; ++i ) { 16619 argz[i] = (yield * args[i].toNumberValue()).toNative(); 16620 } 16621 16622 return this.fromNative(String.fromCharCode.apply(String, argz)); 16623 } 16624 16625} 16626 16627module.exports = StringObject; 16628 16629},{"../CompletionRecord":103,"../values/EasyObjectValue":138,"../values/PropertyDescriptor":147}],133:[function(require,module,exports){ 16630'use strict'; 16631 16632const EasyObjectValue = require('../values/EasyObjectValue'); 16633const CompletionRecord = require('../CompletionRecord'); 16634const EmptyValue = require('../values/EmptyValue'); 16635const ArrayValue = require('../values/ArrayValue'); 16636const _g = require('../GenDash'); 16637 16638function wrapStringPrototype(name) { 16639 let fx = String.prototype[name]; 16640 let genfx = function *(thiz, args, s) { 16641 if ( thiz instanceof EmptyValue ) { 16642 return yield CompletionRecord.makeTypeError(s.realm, 'called String function on null or undefined?'); 16643 } 16644 let sv = yield * thiz.toStringValue(s.realm); 16645 var argz = new Array(args.length); 16646 for ( let i = 0; i < args.length; ++i ) { 16647 argz[i] = args[i].toNative(); 16648 } 16649 16650 let result = fx.apply(sv.toNative(), argz); 16651 16652 if ( Array.isArray(result) ) { 16653 var vals = new Array(result.length); 16654 for ( let i = 0; i < vals.length; ++i ) { 16655 vals[i] = s.realm.fromNative(result[i]); 16656 } 16657 return ArrayValue.make(vals, s.realm); 16658 } else { 16659 let nv = s.realm.fromNative(result); 16660 return nv; 16661 } 16662 }; 16663 genfx.esperLength = fx.length; 16664 return genfx; 16665} 16666 16667class StringPrototype extends EasyObjectValue { 16668 static get length$cew() { return StringPrototype.fromNative(0); } 16669 16670 static *valueOf(thiz) { 16671 if ( thiz.specTypeName === 'string' ) return thiz; 16672 if ( thiz.specTypeName === 'object' ) { 16673 let pv = thiz.primativeValue; 16674 if ( pv.specTypeName == 'string' ) return pv; 16675 } 16676 throw new TypeError('Couldnt get there.'); 16677 } 16678 16679 static *concat(thiz, args, realm) { 16680 let base = yield * thiz.toStringNative(); 16681 let realArgs = yield * _g.map(args, function*(v) { return yield * v.toStringNative(); }); 16682 let out = String.prototype.concat.apply(base, realArgs); 16683 return realm.fromNative(out); 16684 } 16685 16686 static *toString(thiz) { 16687 return yield * StringPrototype.valueOf(thiz); 16688 } 16689} 16690 16691 16692StringPrototype.prototype.wellKnownName = '%StringProtoype%'; 16693StringPrototype.prototype.clazz = 'String'; 16694 16695StringPrototype.charAt = wrapStringPrototype('charAt'); 16696StringPrototype.charCodeAt = wrapStringPrototype('charCodeAt'); 16697StringPrototype.substring = wrapStringPrototype('substring'); 16698StringPrototype.substr = wrapStringPrototype('substr'); 16699StringPrototype.split = wrapStringPrototype('split'); 16700StringPrototype.slice = wrapStringPrototype('slice'); 16701StringPrototype.lastIndexOf = wrapStringPrototype('lastIndexOf'); 16702StringPrototype.indexOf = wrapStringPrototype('indexOf'); 16703StringPrototype.search = wrapStringPrototype('search'); 16704StringPrototype.trim = wrapStringPrototype('trim'); 16705StringPrototype.toUpperCase = wrapStringPrototype('toUpperCase'); 16706StringPrototype.toLocaleUpperCase = wrapStringPrototype('toLocaleUpperCase'); 16707StringPrototype.toLowerCase = wrapStringPrototype('toLowerCase'); 16708StringPrototype.toLocaleLowerCase = wrapStringPrototype('toLocaleLowerCase'); 16709StringPrototype.localeCompare = wrapStringPrototype('localeCompare'); 16710 16711 16712module.exports = StringPrototype; 16713 16714},{"../CompletionRecord":103,"../GenDash":108,"../values/ArrayValue":134,"../values/EasyObjectValue":138,"../values/EmptyValue":139}],134:[function(require,module,exports){ 16715'use strict'; 16716 16717 16718const PrimitiveValue = require('./PrimitiveValue'); 16719const ObjectValue = require('./ObjectValue'); 16720const Value = require('../Value'); 16721let NumberValue; 16722 16723 16724class ArrayValue extends ObjectValue { 16725 16726 constructor(realm) { 16727 super(realm, realm.ArrayPrototype); 16728 } 16729 16730 *get(name, realm) { 16731 return yield * super.get(name, realm); 16732 } 16733 16734 adjustLength(name) { 16735 if ( !isNaN(parseInt(name)) ) { 16736 let length = this.properties.length.value.native;
16737 if ( name >= length ) { 16738 this.properties.length.value = Value.fromNative(name + 1); 16739 } 16740 } 16741 } 16742 16743 set(name, v) { 16744 this.adjustLength(name); 16745 return super.set(name, v); 16746 } 16747 16748 setImmediate(name, v) { 16749 this.adjustLength(name); 16750 return super.setImmediate(name, v); 16751 } 16752 16753 16754 toNative() { 16755 let out = new Array(); 16756 16757 for ( let i of Object.keys(this.properties)) { 16758 let po = this.properties[i]; 16759 if ( po && po.value ) out[i] = po.value.toNative(); 16760 } 16761 return out; 16762 } 16763 16764 static make(vals, realm) { 16765 16766 let av = new ArrayValue(realm); 16767 16768 av.setImmediate('length', Value.fromNative(0)); 16769 av.properties.length.enumerable = false; 16770 16771 for ( let i = 0; i < vals.length; ++i ) { 16772 let v = vals[i]; 16773 if ( !(v instanceof Value) ) v = realm.fromNative(v); 16774 av.setImmediate(i, v); 16775 } 16776 return av; 16777 } 16778 16779 get debugString() { 16780 if ( !this.properties.length ) return super.debugString; 16781 let length = this.properties.length.value.native; 16782 16783 let loop = Math.min(length, 20); 16784 let r = new Array(loop); 16785 for ( let i = 0; i < loop; ++i ) { 16786 let po = this.properties[i]; 16787 if ( po && po.value ) r[i] = po.value.debugString; 16788 else r[i] = ''; 16789 } 16790 return '[' + r.join(', ') + ( loop < length ? '...' : '' ) + ']'; 16791 } 16792} 16793 16794ArrayValue.prototype.clazz = 'Array'; 16795 16796module.exports = ArrayValue; 16797 16798NumberValue = require('./NumberValue'); 16799 16800},{"../Value":111,"./NumberValue":144,"./ObjectValue":145,"./PrimitiveValue":146}],135:[function(require,module,exports){ 16801'use strict'; 16802/* @flow */ 16803 16804const Value = require('../Value'); 16805const CompletionRecord = require('../CompletionRecord'); 16806/** 16807 * Represents a value that maps directly to an untrusted local value. 16808 */ 16809class BridgeValue extends Value { 16810 16811 constructor(value) { 16812 super(); 16813 this.native = value; 16814 } 16815 16816 makeBridge(value) { 16817 return BridgeValue.make(value); 16818 } 16819 16820 static make(native) { 16821 if ( native === undefined ) return Value.undef; 16822 let prim = Value.fromPrimativeNative(native); 16823 if ( prim ) return prim; 16824 16825 if ( Value.hasBookmark(native) ) { 16826 return Value.getBookmark(native); 16827 } 16828 16829 return new BridgeValue(native); 16830 } 16831 16832 ref(name) { 16833 let that = this; 16834 let out = Object.create(null); 16835 let str = (value) => that.native[name] = value.toNative(); 16836 out.getValue = function *() { return that.native[name]; }; 16837 out.setValue = function *(to) { return str(to); }; 16838 16839 return out; 16840 } 16841 16842 toNative() { 16843 return this.native; 16844 } 16845 16846 *asString() { 16847 return this.native.toString(); 16848 } 16849 16850 *doubleEquals(other) { return this.makeBridge(this.native == other.toNative()); } 16851 *tripleEquals(other) { return this.makeBridge(this.native === other.toNative()); } 16852 16853 *add(other) { return this.makeBridge(this.native + other.toNative()); } 16854 *subtract(other) { return this.makeBridge(this.native - other.toNative()); } 16855 *multiply(other) { return this.makeBridge(this.native * other.toNative()); } 16856 *divide(other) { return this.makeBridge(this.native / other.toNative()); } 16857 *mod(other) { return this.makeBridge(this.native % other.toNative()); } 16858 16859 *shiftLeft(other) { return this.makeBridge(this.native << other.toNative()); } 16860 *shiftRight(other) { return this.makeBridge(this.native >> other.toNative()); } 16861 *shiftRightZF(other) { return this.makeBridge(this.native >>> other.toNative()); } 16862 16863 *bitAnd(other) { return this.makeBridge(this.native & other.toNative()); } 16864 *bitOr(other) { return this.makeBridge(this.native | other.toNative()); } 16865 *bitXor(other) { return this.makeBridge(this.native ^ other.toNative()); } 16866 16867 *gt(other) { return this.makeBridge(this.native > other.toNative()); } 16868 *lt(other) { return this.makeBridge(this.native < other.toNative()); } 16869 *gte(other) { return this.makeBridge(this.native >= other.toNative()); } 16870 *lte(other) { return this.makeBridge(this.native <= other.toNative()); } 16871 16872 *inOperator(other) { return this.makeBridge(this.native in other.toNative()); } 16873 *instanceOf(other) { return this.makeBridge(this.native instanceof other.toNative()); } 16874 16875 *unaryPlus() { return this.makeBridge(+this.native); } 16876 *unaryMinus() { return this.makeBridge(-this.native); } 16877 *not() { return this.makeBridge(!this.native); } 16878 16879 16880 16881 *get(name) { 16882 return this.makeBridge(this.native[name]); 16883 } 16884 16885 *set(name, value) { 16886 this.native[name] = value.toNative(); 16887 } 16888 16889 *observableProperties(realm) { 16890 for ( let p in this.native ) { 16891 yield this.makeBridge(p); 16892 } 16893 return; 16894 } 16895 16896 /** 16897 * 16898 * @param {Value} thiz 16899 * @param {Value[]} args 16900 */
16901 *call(thiz, args) { 16902 let realArgs = new Array(args.length); 16903 for ( let i = 0; i < args.length; ++i ) { 16904 realArgs[i] = args[i].toNative(); 16905 } 16906 try { 16907 let result = this.native.apply(thiz ? thiz.toNative() : undefined, realArgs); 16908 return this.makeBridge(result); 16909 } catch ( e ) { 16910 let result = this.makeBridge(e); 16911 return new CompletionRecord(CompletionRecord.THROW, result); 16912 } 16913 16914 } 16915 16916 *makeThisForNew() { 16917 return this.makeBridge(Object.create(this.native.prototype)); 16918 } 16919 16920 get debugString() { 16921 return '[Bridge: ' + this.native + ']'; 16922 } 16923 16924 get truthy() { 16925 return !!this.native; 16926 } 16927 16928 get jsTypeName() { 16929 return typeof this.native; 16930 } 16931} 16932 16933module.exports = BridgeValue; 16934 16935},{"../CompletionRecord":103,"../Value":111}],136:[function(require,module,exports){ 16936'use strict'; 16937/* @flow */ 16938 16939const Value = require('../Value'); 16940const PropertyDescriptor = require('./PropertyDescriptor'); 16941const ObjectValue = require('./ObjectValue'); 16942const EvaluatorInstruction = require('../EvaluatorInstruction'); 16943 16944/** 16945 * Represents a value that maps directly to an untrusted local value. 16946 */ 16947class ClosureValue extends ObjectValue { 16948 16949 /** 16950 * @param {object} func - AST Node for function 16951 * @param {Scope} scope - Functions up-values. 16952 */ 16953 constructor(func, scope) { 16954 let realm = scope.realm; 16955 super(realm, realm.FunctionPrototype); 16956 this.realm = scope.realm; 16957 this.func = func; 16958 this.scope = scope; 16959 this.returnLastValue = false; 16960 this.properties['prototype'] = new PropertyDescriptor(new ObjectValue(realm)); 16961 this.properties['name'] = new PropertyDescriptor(this.fromNative(func.id ? func.id.name : undefined)); 16962 this.properties['length'] = new PropertyDescriptor(this.fromNative(func.params.length)); 16963 16964 16965 } 16966 16967 toNative() { 16968 return Value.createNativeBookmark(this, this.realm); 16969 } 16970 16971 get debugString() { 16972 if ( this.func && this.func.id ) return `[Function ${this.func.id.name}]`; 16973 return '[Function]'; 16974 } 16975 16976 get truthy() { 16977 return !true; 16978 } 16979 16980 *doubleEquals(other) { 16981 return other === this ? Value.true : Value.false; 16982 } 16983 16984 /** 16985 * 16986 * @param {Value} thiz 16987 * @param {Value[]} args 16988 * @param {Scope} scope 16989 */ 16990 *call(thiz, args, scope, extra) { 16991 //TODO: This way of scoping is entirelly wrong. 16992 if ( !scope ) scope = this.scope; 16993 let invokeScope; 16994 if ( this.boundScope ) { 16995 invokeScope = this.boundScope.createChild(); 16996 invokeScope.writeTo = this.boundScope.object; 16997 invokeScope.thiz = this.thiz || /* thiz ||*/ this.boundScope.thiz; 16998 } else { 16999 invokeScope = scope.createChild(); 17000 invokeScope.thiz = this.thiz || thiz; 17001 } 17002 17003 if ( this.func.strict === true ) invokeScope.strict = true; 17004 17005 let obj = this.scope.object; 17006 if ( this.func.upvars ) { 17007 for ( let n in this.func.upvars ) { 17008 //TODO: There should be a method that does this. 17009 invokeScope.object.rawSetProperty(n, obj.properties[n]); 17010 } 17011 } 17012 17013 //Do Var Hoisting 17014 if ( this.func.vars ) { 17015 for ( let v in this.func.vars ) { 17016 invokeScope.add(v, Value.undef); 17017 invokeScope.object.properties[v].isVariable = true; 17018 } 17019 } 17020 17021 if ( this.func.funcs ) { 17022 for ( let fn in this.func.funcs ) { 17023 let n = this.func.funcs[fn]; 17024 let closure = new ClosureValue(n, scope); 17025 invokeScope.add(n.id.name, closure); 17026 } 17027 } 17028 17029 let argn = Math.max(args.length, this.func.params.length); 17030 let argvars = new Array(argn); 17031 let argsObj = new ObjectValue(scope.realm); 17032 17033 for ( let i = 0; i < argn; ++i ) { 17034 let vv = Value.undef; 17035 if ( i < args.length ) vv = args[i]; 17036 17037 let v = new PropertyDescriptor(vv); 17038 argvars[i] = v; 17039 17040 if ( invokeScope.strict ) { 17041 yield * argsObj.set(i, vv); 17042 } else { 17043 argsObj.rawSetProperty(i, v); 17044 } 17045 } 17046 17047 if ( !invokeScope.strict ) { 17048 yield * argsObj.set('callee', this); 17049 } 17050 17051 yield * argsObj.set('length', this.fromNative(args.length)); 17052 17053 invokeScope.add('arguments', argsObj); 17054 17055 for ( let i = 0; i < this.func.params.length; ++i ) { 17056 let name = this.func.params[i].name; 17057 if ( scope.strict ) { 17058 //Scope is strict, so we make a copy for the args variable 17059 invokeScope.add(name, i < args.length ? args[i] : Value.undef); 17060 } else { 17061 //Scope isnt strict, magic happens. 17062 invokeScope.object.rawSetProperty(name, argvars[i]); 17063 } 17064 } 17065 let opts = {returnLastValue: this.returnLastValue}; 17066 if ( extra && extra.evaluator && extra.evaluator.debug ) { 17067 opts['profileName'] = extra.callNode.callee.srcName; 17068 } 17069 if ( this.func.nonUserCode ) { 17070 opts.yieldPower = -1; 17071 } 17072 var result = yield EvaluatorInstruction.branch('function', this.func.body, invokeScope, opts); 17073 return result; 17074 } 17075 17076 get jsTypeName() { return 'function'; } 17077 get specTypeName() { return 'object'; } 17078 17079}
17079 17080ClosureValue.prototype.clazz = 'Function'; 17081 17082module.exports = ClosureValue; 17083 17084},{"../EvaluatorInstruction":107,"../Value":111,"./ObjectValue":145,"./PropertyDescriptor":147}],137:[function(require,module,exports){ 17085'use strict'; 17086/* @flow */ 17087 17088const Value = require('../Value'); 17089const ObjectValue = require('./ObjectValue'); 17090const CompletionRecord = require('../CompletionRecord'); 17091 17092class EasyNativeFunction extends ObjectValue { 17093 constructor(realm) { 17094 super(realm, realm.FunctionPrototype); 17095 } 17096 17097 static make(realm, fx, binding) { 17098 let out = new EasyNativeFunction(realm); 17099 out.fn = fx; 17100 out.binding = binding; 17101 return out; 17102 } 17103 17104 static makeForNative(realm, fx) { 17105 let out = new EasyNativeFunction(realm); 17106 out.fn = function *(thiz, args) { 17107 let rargs = new Array(args.length); 17108 for ( let i = 0; i < args.length; ++i ) { 17109 rargs[i] = args[i].toNative(); 17110 } 17111 let nt = thiz.toNative(); 17112 let nr = fx.apply(nt, rargs); 17113 return Value.fromNative(nr); 17114 }; 17115 return out; 17116 } 17117 17118 *call(thiz, argz, scope, extra) { 17119 let profile = false; 17120 let start = 0; 17121 try { 17122 if ( extra && extra.evaluator && extra.evaluator.debug ) { 17123 profile = true; 17124 start = Date.now(); 17125 } 17126 let s = scope ? scope.createChild() : scope; 17127 if ( s ) s.strict = true; 17128 let o = yield * this.fn.apply(this.binding, arguments, s, extra); 17129 if ( o instanceof CompletionRecord ) return o; 17130 if ( !(o instanceof Value) ) o = scope.realm.makeForForeignObject(o); 17131 if ( profile ) extra.evaluator.incrCtr('fxTime', extra.callNode.callee.srcName, Date.now() - start); 17132 return new CompletionRecord(CompletionRecord.NORMAL, o); 17133 17134 } catch ( e ) { 17135 if ( profile ) extra.evaluator.incrCtr('fxTime', extra.callNode.callee.srcName, Date.now() - start); 17136 return new CompletionRecord(CompletionRecord.THROW, scope.realm.makeForForeignObject(e)); 17137 } 17138 } 17139 17140 *makeThisForNew(realm) { 17141 return yield CompletionRecord.makeTypeError(realm, 'function is not a constructor'); 17142 } 17143 17144 get debugString() { 17145 return 'function() { [Native Code] }'; 17146 } 17147} 17148EasyNativeFunction.prototype.clazz = 'Function'; 17149 17150module.exports = EasyNativeFunction; 17151 17152},{"../CompletionRecord":103,"../Value":111,"./ObjectValue":145}],138:[function(require,module,exports){ 17153'use strict'; 17154/* @flow */ 17155 17156const Value = require('../Value'); 17157const PropertyDescriptor = require('./PropertyDescriptor'); 17158const ObjectValue = require('./ObjectValue'); 17159const CompletionRecord = require('../CompletionRecord'); 17160const EasyNativeFunction = require('./EasyNativeFunction'); 17161 17162class EasyObjectValue extends ObjectValue { 17163 constructor(realm) { 17164 super(realm); 17165 17166 let objProto = realm.ObjectPrototype; 17167 if ( typeof this.objPrototype === 'function' ) { 17168 objProto = this.objPrototype(realm); 17169 } else if ( typeof this.call === 'function' ) { 17170 objProto = realm.FunctionPrototype; 17171 } 17172 if ( this.call == 'function' ) this.clazz = 'Function'; 17173 this.setPrototype(objProto); 17174 17175 this._init(realm); 17176 } 17177 17178 _init(realm) { 17179 var clazz = Object.getPrototypeOf(this); 17180 for ( let p of Object.getOwnPropertyNames(clazz.constructor) ) { 17181 if ( p === 'length' ) continue; 17182 if ( p === 'name' ) continue; 17183 if ( p === 'prototype' ) continue; 17184 if ( p === 'constructor' ) continue; 17185 if ( p === 'caller' ) continue; 17186 if ( p === 'callee') continue; 17187 if ( p === 'arguments' ) continue; 17188 let parts = p.split(/\$/); 17189 let name = parts[0]; 17190 let flags = parts[1] || ''; 17191 let d = Object.getOwnPropertyDescriptor(clazz.constructor, p); 17192 let v = new PropertyDescriptor(); 17193 let length = 1; 17194 17195 if ( d.get ) { 17196 //Its a property 17197 let val = d.get(); 17198 if ( val instanceof Value ) v.value = val; 17199 else v.value = this.fromNative(val); 17200 } else { 17201 if ( d.value.esperLength !== undefined ) length = d.value.esperLength; 17202 let rb = EasyNativeFunction.make(realm, d.value, this); 17203 let rblen = new PropertyDescriptor(Value.fromNative(length)); 17204 rblen.configurable = false; 17205 rblen.writable = false; 17206 rblen.enumerable = false; 17207 rb.properties['length'] = rblen; 17208 v.value = rb; 17209 } 17210 if ( flags.indexOf('e') !== -1 ) v.enumerable = false; 17211 if ( flags.indexOf('w') !== -1 ) v.writable = false;
17212 if ( flags.indexOf('c') !== -1 ) v.configurable = false; 17213 if ( flags.indexOf('g') !== -1 ) { 17214 v.getter = v.value; 17215 delete v.value; 17216 } 17217 this.properties[name] = v; 17218 } 17219 17220 if ( this.callPrototype ) { 17221 let pt = new PropertyDescriptor(this.callPrototype(realm)); 17222 pt.configurable = false; 17223 pt.enumerable = false; 17224 pt.writable = false; 17225 this.properties['prototype'] = pt; 17226 } 17227 17228 if ( this.callLength !== undefined ) { 17229 let rblen = new PropertyDescriptor(Value.fromNative(this.callLength)); 17230 rblen.configurable = false; 17231 rblen.writable = false; 17232 rblen.enumerable = false; 17233 this.properties['length'] = rblen; 17234 } 17235 17236 if ( this.constructorFor ) { 17237 let target = this.constructorFor(realm); 17238 if ( target ) { 17239 let cs = new PropertyDescriptor(this); 17240 cs.configurable = false; 17241 cs.enumerable = false; 17242 target.properties['constructor'] = cs; 17243 } 17244 } 17245 17246 if ( realm.Function ) { 17247 let cs = new PropertyDescriptor(realm.Function); 17248 cs.configurable = false; 17249 cs.enumerable = false; 17250 this.properties['constructor'] = cs; 17251 } 17252 17253 } 17254 17255 get jsTypeName() { return typeof this.call === 'function' ? 'function' : 'object'; } 17256} 17257 17258EasyObjectValue.EasyNativeFunction = EasyNativeFunction; 17259 17260module.exports = EasyObjectValue; 17261 17262},{"../CompletionRecord":103,"../Value":111,"./EasyNativeFunction":137,"./ObjectValue":145,"./PropertyDescriptor":147}],139:[function(require,module,exports){ 17263'use strict'; 17264 17265const Value = require('../Value'); 17266const BridgeValue = require('./BridgeValue'); 17267const CompletionRecord = require('../CompletionRecord'); 17268 17269class EmptyValue extends Value { 17270 constructor() { 17271 super(null); 17272 } 17273 17274 get truthy() { return false; } 17275 17276 *not() { return Value.fromNative(true); } 17277 17278 *doubleEquals(other) { 17279 if ( other instanceof EmptyValue ) return Value.true; 17280 else if ( other instanceof BridgeValue ) return this.fromNative(this.toNative() == other.toNative()); 17281 else return Value.false; 17282 } 17283 17284 *observableProperties(realm) { 17285 return; 17286 } 17287 17288 *instanceOf() { 17289 return Value.false; 17290 } 17291 17292 /** 17293 * @param {String} name 17294 * @param {Realm} realm 17295 * @returns {CompletionRecord} Indexing empty values is a type error. 17296 */ 17297 *get(name, realm) { 17298 let str = 'Cannot read property \'' + name + '\' of ' + this.specTypeName; 17299 let err = CompletionRecord.makeTypeError(realm, str); 17300 yield * err.addExtra({code: 'IndexEmpty', target: this, prop: name}); 17301 return err; 17302 } 17303 17304} 17305 17306module.exports = EmptyValue; 17307 17308},{"../CompletionRecord":103,"../Value":111,"./BridgeValue":135}],140:[function(require,module,exports){ 17309'use strict'; 17310 17311 17312const PrimitiveValue = require('./PrimitiveValue'); 17313const ObjectValue = require('./ObjectValue'); 17314const Value = require('../Value'); 17315const EvaluatorInstruction = require('../EvaluatorInstruction'); 17316 17317class ErrorInstance extends ObjectValue { 17318 createNativeAnalog() { 17319 if ( !this.native ) { 17320 let NativeClass = this.proto.nativeClass || Error; 17321 this.native = new NativeClass(); 17322 17323 let frames = this.native.stack.split(/\n/); 17324 let header = frames.shift(); 17325 while ( /at (ErrorInstance.createNativeAnalog|ErrorObject.make|Function.makeTypeError)/.test(frames[0]) ) { 17326 frames.shift(); 17327 } 17328 this.native.stack = header + '\n' + frames.join('\n'); 17329 for ( var k in this.extra ) this.native[k] = this.extra[k]; 17330 17331 } 17332 return this.native; 17333 } 17334 toNative() { 17335 let out = this.createNativeAnalog(); 17336 let msg = this.properties['message'].value; 17337 if ( msg ) out.message = msg.toNative(); 17338 17339 if ( this.properties['stack'] ) { 17340 msg.stack = this.properties['stack'].value.native; 17341 } 17342 17343 return out; 17344 } 17345 17346 *addExtra(extra) { 17347 if ( !this.realm.options.extraErrorInfo ) return; 17348 let evaluator = yield EvaluatorInstruction.getEvaluator(); 17349 if ( evaluator ) { 17350 let scope = evaluator.topFrame.scope; 17351 let ast = extra.ast = evaluator.topFrame.ast; 17352 extra.scope = scope; 17353 17354 if ( extra.ast.loc ) { 17355 extra.line = extra.ast.loc.start.line; 17356 } 17357 17358 switch ( extra.code ) { 17359 case 'UndefinedVariable': 17360 case 'SmartAccessDenied': 17361 extra.candidates = scope.getVariableNames(); 17362 break; 17363 case 'CallNonFunction': 17364 let list; 17365 if ( extra.base && extra.base.getPropertyValueMap ) { 17366 list = extra.base.getPropertyValueMap(); 17367 } else { 17368 list = scope.object.getPropertyValueMap(); 17369 } 17370 17371 extra.candidates = []; 17372 for ( let k in list ) { 17373 let v = list[k]; 17374 if ( v && v.isCallable ) { 17375 extra.candidates.push(k); 17376 } 17377 } 17378 break; 17379 case 'IndexEmpty': 17380 break; 17381 } 17382 } 17383 if ( this.native ) { 17384 for ( var k in extra ) { 17385 if ( ['ast', 'scope', 'candidates', 'targetAst'].indexOf(k) !== -1 ) { 17386 Object.defineProperty(this.native, k, { 17387 value: extra[k], 17388 enumerable: false 17389 }); 17390 } else { 17391 this.native[k] = extra[k]; 17392 } 17393 } 17394 } 17395 this.extra = extra; 17396 } 17397} 17398 17399module.exports = ErrorInstance; 17400 17401},{"../EvaluatorInstruction":107,"../Value":111,"./ObjectValue":145,"./PrimitiveValue":146}],141:[function(require,module,exports){ 17402'use strict'; 17403const EmptyValue = require('./EmptyValue'); 17404const Value = require('../Value'); 17405 17406function defer() { 17407 var resolve, reject; 17408 var promise = new Promise(function(a, b) { 17409 resolve = a; 17410 reject = b; 17411 }); 17412 return { 17413 resolve: resolve, 17414 reject: reject, 17415 promise: promise 17416 }; 17417} 17418 17419class FutureValue extends Value { 17420 17421 constructor(realm) { 17422 super(realm); 17423 this.resolved = false;
17424 this.successful = undefined; 17425 this.value = undefined; 17426 this.defered = defer(); 17427 } 17428 17429 /** 17430 * Creates a new future value wraping the promise p. 17431 * @param {Promise} promise 17432 */ 17433 static make(promise) { 17434 var fv = new FutureValue(null); 17435 promise.then(function(resolved) { 17436 fv.resolve(Value.fromNative(resolved)); 17437 }, function(caught) { 17438 fv.reject(Value.fromNative(caught)); 17439 }); 17440 return fv; 17441 } 17442 17443 resolve(value) { 17444 this.value = value; 17445 this.resolved = true; 17446 this.successful = true; 17447 this.defered.resolve(value); 17448 } 17449 17450 reject(value) { 17451 this.value = value; 17452 this.resolved = true; 17453 this.successful = false; 17454 this.defered.resolve(value); 17455 } 17456 17457 then() { 17458 var p = this.defered.promise; 17459 return p.then.apply(p, arguments); 17460 } 17461 17462 get jsTypeName() { return 'internal:future'; } 17463 get debugString() { return '[Future]'; } 17464} 17465 17466module.exports = FutureValue; 17467 17468},{"../Value":111,"./EmptyValue":139}],142:[function(require,module,exports){ 17469'use strict'; 17470/* @flow */ 17471 17472const Value = require('../Value'); 17473const CompletionRecord = require('../CompletionRecord'); 17474const ArrayValue = require('./ArrayValue'); 17475 17476function invoke(target, thiz, args) { 17477 return Function.prototype.apply.call(target, thiz, args); 17478} 17479 17480/** 17481 * Represents a value that maps directly to an untrusted local value. 17482 */ 17483class LinkValue extends Value { 17484 17485 constructor(value, realm) { 17486 super(); 17487 this.native = value; 17488 this.realm = realm; 17489 } 17490 17491 static make(native, realm) { 17492 let wellKnown = realm.lookupWellKnown(native); 17493 if ( wellKnown ) return wellKnown; 17494 17495 if ( Array.isArray(native) ) { 17496 var ia = new Array(native.length); 17497 for ( let i = 0; i < native.length; ++i ) { 17498 ia[i] = LinkValue.make(native[i], realm); 17499 } 17500 return ArrayValue.make(ia, realm); 17501 } 17502 17503 return new LinkValue(native, realm); 17504 } 17505 17506 ref(name, realm) { 17507 17508 let that = this; 17509 let out = Object.create(null); 17510 17511 let getter; 17512 if ( this.native.hasOwnProperty(name) ) { 17513 getter = () => realm.import(this.native[name], this.linkKind); 17514 } else { 17515 getter = () => realm.import(this.native, this.linkKind).ref(name, realm).value; 17516 } 17517 17518 out.getValue = function *() { return getter(); }; 17519 out.setValue = function *(to) { return yield * that.set(name, to); }; 17520 out.del = function() { return false; }; 17521 17522 return out; 17523 } 17524 17525 *set(name, value, s, extra) { 17526 this.native[name] = value.toNative(); 17527 } 17528 17529 toNative() { 17530 return this.native; 17531 } 17532 17533 *asString() { 17534 return this.native.toString(); 17535 } 17536 17537 makeLink(value) { 17538 return this.realm.import(value, this.linkKind); 17539 } 17540 17541 *doubleEquals(other) { return this.makeLink(this.native == other.toNative()); } 17542 *tripleEquals(other) { return this.makeLink(this.native === other.toNative()); } 17543 17544 *add(other) { return this.makeLink(this.native + other.toNative()); } 17545 *subtract(other) { return this.makeLink(this.native - other.toNative()); } 17546 *multiply(other) { return this.makeLink(this.native * other.toNative()); } 17547 *divide(other) { return this.makeLink(this.native / other.toNative()); } 17548 *mod(other) { return this.makeLink(this.native % other.toNative()); } 17549 17550 *shiftLeft(other) { return this.makeLink(this.native << other.toNative()); } 17551 *shiftRight(other) { return this.makeLink(this.native >> other.toNative()); } 17552 *shiftRightZF(other) { return this.makeLink(this.native >>> other.toNative()); } 17553 17554 *bitAnd(other) { return this.makeLink(this.native & other.toNative()); } 17555 *bitOr(other) { return this.makeLink(this.native | other.toNative()); } 17556 *bitXor(other) { return this.makeLink(this.native ^ other.toNative()); } 17557 17558 *gt(other) { return this.makeLink(this.native > other.toNative()); } 17559 *lt(other) { return this.makeLink(this.native < other.toNative()); } 17560 *gte(other) { return this.makeLink(this.native >= other.toNative()); } 17561 *lte(other) { return this.makeLink(this.native <= other.toNative()); } 17562 17563 *inOperator(other) { return this.makeLink(other.toNative() in this.native); } 17564 *instanceOf(other) { return this.makeLink(this.native instanceof other.toNative()); } 17565 17566 *unaryPlus() { return this.makeLink(+this.native); } 17567 *unaryMinus() { return this.makeLink(-this.native); } 17568 *not() { return this.makeLink(!this.native); } 17569 17570 17571 17572 *get(name, realm) { 17573 if ( this.native.hasOwnProperty(name) ) { 17574 return this.makeLink(this.native[name], realm); 17575 } 17576 17577 return yield * this.makeLink(Object.getPrototypeOf(this.native), realm).get(name, realm); 17578 } 17579 17580 17581 *observableProperties(realm) { 17582 for ( let p in this.native ) { 17583 yield this.makeLink(p); 17584 } 17585 return; 17586 } 17587 17588 /** 17589 * 17590 * @param {Value} thiz 17591 * @param {Value[]} args 17592 * @param {Scope} s 17593 */ 17594 *call(thiz, args, s) { 17595 let realArgs = new Array(args.length); 17596 for ( let i = 0; i < args.length; ++i ) { 17597 realArgs[i] = args[i].toNative(); 17598 } 17599 try { 17600 let result = invoke(this.native, thiz ? thiz.toNative() : undefined, realArgs); 17601 let val = this.makeLink(result, s.realm); 17602 if ( typeof s.realm.options.linkValueCallReturnValueWrapper === 'function' ) { 17603 val = s.realm.options.linkValueCallReturnValueWrapper(val); 17604 } 17605 return val; 17606 } catch ( e ) { 17607 let result = this.makeLink(e, s.realm); 17608 return new CompletionRecord(CompletionRecord.THROW, result); 17609 } 17610 17611 } 17612 17613 get isCallable() { 17614 return ( typeof this.native === 'function' ); 17615 } 17616 17617 getPropertyValueMap() { 17618 let list = {}; 17619 for ( let p in this.native ) { 17620 let v = this.native[p]; 17621 list[p] = this.makeLink(v); 17622 } 17623 return list; 17624 } 17625 17626 *toNumberValue() { return Value.fromNative((Number(this.native))); } 17627 *toStringValue() { return Value.fromNative((String(this.native))); } 17628 17629 getPrototype(realm) { 17630 return realm.ObjectPrototype; 17631 } 17632 17633 *makeThisForNew() { 17634 return Value.undef; 17635 } 17636 17637 get debugString() { 17638 return '[Link: ' + this.native + ']'; 17639 } 17640 17641 get truthy() { 17642 return !!this.native; 17643 } 17644 17645 get jsTypeName() { 17646 return typeof this.native; 17647 } 17648 17649 *toPrimitiveValue(preferedType) { 17650 switch ( preferedType ) { 17651 case 'string': 17652 return Value.fromNative(this.native.toString()); 17653 default: 17654 return Value.fromNative(this.native.valueOf()); 17655 } 17656 } 17657 17658 get linkKind() { return 'link'; } 17659} 17660 17661module.exports = LinkValue; 17662 17663},{"../CompletionRecord":103,"../Value":111,"./ArrayValue":134}],143:[function(require,module,exports){ 17664'use strict'; 17665 17666const EmptyValue = require('./EmptyValue'); 17667const Value = require('../Value'); 17668
17669class NullValue extends EmptyValue { 17670 toNative() { return null; } 17671 17672 get jsTypeName() { return 'object'; } 17673 get specTypeName() { return 'null'; } 17674 17675 *tripleEquals(other, realm) { 17676 return other instanceof NullValue ? Value.true : Value.false; 17677 } 17678 17679 *asString() { 17680 return 'null'; 17681 } 17682 17683 *toPrimitiveValue(preferedType) { return this; } 17684 *toNumberValue() { return Value.zero; } 17685 *toStringValue() { return Value.fromNative('null'); } 17686 17687 get debugString() { return 'null'; } 17688} 17689 17690module.exports = NullValue; 17691 17692},{"../Value":111,"./EmptyValue":139}],144:[function(require,module,exports){ 17693'use strict'; 17694 17695const PrimitiveValue = require('./PrimitiveValue'); 17696const Value = require('../Value'); 17697let StringValue; 17698 17699class NumberValue extends PrimitiveValue { 17700 17701 17702 *doubleEquals(other) { 17703 if ( other instanceof NumberValue) { 17704 return Value.fromNative(this.native == other.native); 17705 } else if ( other instanceof StringValue ) { 17706 let on = yield * other.toNumberValue(); 17707 return yield * this.doubleEquals(on); 17708 } else { 17709 let on = yield * other.toNumberValue(); 17710 return yield * this.doubleEquals(on); 17711 } 17712 17713 return Value.false; 17714 17715 } 17716 17717 *add(other) { return this.fromNative(this.native + (yield * other.toPrimitiveNative())); } 17718} 17719 17720module.exports = NumberValue; 17721 17722StringValue = require('./StringValue'); 17723 17724},{"../Value":111,"./PrimitiveValue":146,"./StringValue":150}],145:[function(require,module,exports){ 17725'use strict'; 17726/* @flow */ 17727 17728const Value = require('../Value'); 17729const PropertyDescriptor = require('./PropertyDescriptor'); 17730const CompletionRecord = require('../CompletionRecord'); 17731const PrimitiveValue = require('./PrimitiveValue'); 17732const NullValue = require('./NullValue'); 17733const GenDash = require('../GenDash'); 17734 17735let alwaysFalse = () => false; 17736let undefinedReturningGenerator = function*() { return Value.undef; } 17737 17738class ObjRefrence { 17739 constructor(object, name, ctxthis) { 17740 this.object = object; 17741 this.name = name; 17742 this.ctxthis = ctxthis; 17743 } 17744 del(s) { return this.object.delete(this.name, s); } 17745 getValue(s) { return this.object.get(this.name, this.ctxthis || this.object, s) } 17746 setValue(value, s) { return this.object.set(this.name, value, s); } 17747} 17748 17749/** 17750 * Represents an Object. 17751 */ 17752class ObjectValue extends Value { 17753 17754 constructor(realm, proto) { 17755 super(); 17756 this.extensable = true; 17757 this.realm = realm; 17758 if ( proto ) this.eraseAndSetPrototype(proto); 17759 else if ( realm ) this.eraseAndSetPrototype(realm.ObjectPrototype); 17760 else this.properties = Object.create(null); 17761 } 17762 17763 ref(name, ctxthis) { 17764 var existing = this.properties[name]; 17765 let thiz = this; 17766 17767 let get; 17768 if ( existing ) { 17769 return new ObjRefrence(this, name, ctxthis); 17770 } else { 17771 return { 17772 name: name, 17773 object: thiz, 17774 isVariable: false, 17775 del: alwaysFalse, 17776 getValue: undefinedReturningGenerator, 17777 setValue: function (to, s) { return this.object.set(this.name, to, s); } 17778 }; 17779 17780 } 17781 } 17782 17783 //Note: Returns generator by tailcall. 17784 set(name, value, s, extra) { 17785 let thiz = this; 17786 extra = extra || {}; 17787 if ( !Object.prototype.hasOwnProperty.call(this.properties, name) ) { 17788 if ( !this.extensable ) { 17789 //TODO: Should we throw here in strict mode? 17790 return Value.undef.fastGen(); 17791 } 17792 let v = new PropertyDescriptor(value); 17793 v.enumerable = 'enumerable' in extra ? extra.enumerable : true; 17794 this.properties[name] = v; 17795 17796 return v.setValue(this, value, s); 17797 } 17798 17799 return this.properties[name].setValue(this, value, s); 17800 17801 } 17802 17803 rawSetProperty(name, value) { 17804 this.properties[name] = value; 17805 } 17806 17807 setImmediate(name, value) { 17808 if ( name in this.properties ) { 17809 if ( Object.prototype.hasOwnProperty.call(this.properties, name) ) { 17810 if ( this.properties[name].direct ) { 17811 this.properties[name].value = value; 17812 return; 17813 } 17814 } 17815 } else if ( this.extensable ) { 17816 let v = new PropertyDescriptor(value); 17817 v.del = this.delete.bind(this, name); 17818 this.properties[name] = v; 17819 return; 17820 } 17821 return GenDash.syncGenHelper(this.set(name, value, this.realm)); 17822 } 17823 17824 17825 17826 has(name) { 17827 return name in this.properties; 17828 } 17829 17830 delete(name, s) { 17831 let po = this.properties[name]; 17832 if ( !po.configurable ) { 17833 if ( s.strict ) return CompletionRecord.makeTypeError(s.realm, "Can't delete nonconfigurable object"); 17834 else return false;
17835 } 17836 return delete this.properties[name]; 17837 } 17838 17839 toNative() { 17840 17841 //TODO: This is really a mess and should maybe be somewhere else. 17842 var bk = Value.createNativeBookmark(this, this.realm); 17843 if ( this.jsTypeName === 'function' ) return bk; 17844 17845 for ( let p in this.properties ) { 17846 let name = p; //work around bug in FF where the scope of p is incorrect 17847 let po = this.properties[name]; 17848 if ( Object.prototype.hasOwnProperty.call(bk, name) ) continue; 17849 if ( bk[p] !== undefined ) continue; 17850 17851 Object.defineProperty(bk, p, { 17852 get: () => { 17853 var c = this.properties[name].value; 17854 return c === undefined ? undefined : c.toNative(); 17855 }, 17856 set: (v) => { this.properties[name].value = Value.fromNative(v, this.realm); }, 17857 enumerable: po.enumerable, 17858 configurable: po.configurable 17859 }); 17860 } 17861 return bk; 17862 17863 } 17864 17865 17866 *add(other) { return yield * (yield * this.toPrimitiveValue()).add(other); } 17867 *doubleEquals(other) { 17868 if ( other instanceof PrimitiveValue ) { 17869 let hint = ( other.jsTypeName == 'string' ? 'string' : 'number' ); 17870 let pv = yield * this.toPrimitiveValue(hint); 17871 return yield * pv.doubleEquals(other); 17872 } 17873 let pthis = yield * this.toPrimitiveValue('string'); 17874 return yield * pthis.doubleEquals(other); 17875 } 17876 *inOperator(str) { 17877 let svalue = yield * str.toStringValue(); 17878 return this.has(svalue.toNative()) ? Value.true : Value.false; 17879 } 17880 17881 *get(name, realm, ctxthis) { 17882 var existing = this.properties[name]; 17883 if ( !existing ) return Value.undef; 17884 if ( existing.direct ) return existing.value; 17885 return yield * existing.getValue(ctxthis || this); 17886 } 17887 17888 getImmediate(name, realm, ctxthis) { 17889 var existing = this.properties[name]; 17890 if ( !existing ) return Value.undef; 17891 if ( existing.direct ) return existing.value; 17892 return GenDash.syncGenHelper(existing.getValue(ctxthis || this)); 17893 } 17894 17895 *instanceOf(other, realm) { 17896 return yield * other.constructorOf(this, realm); 17897 } 17898 17899 *constructorOf(what, realm) { 17900 let target = yield * this.get('prototype'); 17901 let pt = what.getPrototype(realm); 17902 let checked = []; 17903 17904 while ( pt ) { 17905 if ( pt === target ) return Value.true; 17906 checked.push(pt); 17907 pt = pt.getPrototype(realm); 17908 if ( checked.indexOf(pt) !== -1 ) return Value.false; 17909 } 17910 return Value.false; 17911 } 17912 17913 *observableProperties(realm) { 17914 for ( let p in this.properties ) { 17915 if ( !this.properties[p].enumerable ) continue; 17916 yield this.fromNative(p); 17917 } 17918 return; 17919 } 17920 17921 getPropertyValueMap() { 17922 let list = {}; 17923 for ( let p in this.properties ) { 17924 let v = this.properties[p]; 17925 if ( v.value ) { 17926 list[p] = v.value; 17927 } 17928 } 17929 return list; 17930 } 17931 17932 hasOwnProperty(name) { 17933 return Object.prototype.hasOwnProperty.call(this.properties, name); 17934 } 17935 17936 setPrototype(val) { 17937 if ( !this.properties ) return this.eraseAndSetPrototype(val); 17938 if ( val === null || val === undefined || val instanceof NullValue ) { 17939 Object.setPrototypeOf(this.properties, null); 17940 this.proto = null; 17941 return; 17942 } 17943 this.proto = val; 17944 Object.setPrototypeOf(this.properties, val.properties); 17945 } 17946 17947 eraseAndSetPrototype(val) { 17948 if ( val === null || val === undefined || val instanceof NullValue ) { 17949 this.proto = null; 17950 this.properties = Object.create(null); 17951 } else { 17952 this.proto = val; 17953 this.properties = Object.create(val.properties); 17954 } 17955 } 17956 17957 getPrototype() { 17958 return this.proto; 17959 } 17960 17961 get debugString() { 17962 let strProps = ['{','[', this.clazz,']']; 17963 let delim = []; 17964 if ( this.wellKnownName ) { 17965 strProps.push('(', this.wellKnownName , ')'); 17966 } 17967 if ( this.proto ) { 17968 delim.push('[[Prototype]]: ' + (this.proto.wellKnownName || this.proto.clazz || this.proto.jsTypeName) ); 17969 } 17970 for ( let n in this.properties ) { 17971 if ( !Object.prototype.hasOwnProperty.call(this.properties, n) ) continue; 17972 let val = this.properties[n].value; 17973 if ( this.properties[n].getter || this.properties[n].setter ) delim.push(n + ': [Getter/Setter]'); 17974 else if ( val.specTypeName === 'object' ) delim.push(n + ': [Object]'); 17975 else if ( val.specTypeName === 'function' ) delim.push(n + ': [Function]'); 17976 else delim.push(n + ': ' + val.debugString); 17977 } 17978 strProps.push(delim.join(', ')); 17979 strProps.push('} ]'); 17980 return strProps.join(' '); 17981 } 17982 17983 *toPrimitiveValue(preferedType) { 17984 let methodNames; 17985 if ( preferedType == 'string') { 17986 methodNames = ['toString', 'valueOf']; 17987 } else { 17988 methodNames = ['valueOf', 'toString']; 17989 } 17990 17991 for ( let name of methodNames ) { 17992 let method = yield * this.get(name); 17993 if ( method && method.call ) { 17994 let rescr = yield (yield * method.call(this, [], this.realm.globalScope)); //TODO: There should be more aruments here 17995 let res = Value.undef; 17996 if ( !(rescr instanceof CompletionRecord) ) res = rescr; 17997 else if ( rescr.type == CompletionRecord.RETURN ) res = rescr.value; 17998 else if ( rescr.type != CompletionRecord.NORMAL ) continue; 17999 if ( res.specTypeName !== 'object' ) return res; 18000 } 18001 } 18002 return yield CompletionRecord.makeTypeError(this.realm, 'Cannot convert object to primitive value'); 18003 } 18004 18005 *toNumberValue() { 18006 let prim = yield * this.toPrimitiveValue('number'); 18007 return yield * prim.toNumberValue(); 18008 } 18009 18010 *toObjectValue(realm) { return this; } 18011 18012 *toStringValue() { 18013 let prim = yield * this.toPrimitiveValue('string'); 18014 let gen = prim.toStringValue(); 18015 return yield * gen; 18016 } 18017 18018 get truthy() { 18019 return true; 18020 } 18021 18022 get jsTypeName() { 18023 if ( typeof this.call !== 'function' ) return 'object'; 18024 return 'function'; 18025 } 18026 18027 get specTypeName() { 18028 return 'object'; 18029 } 18030} 18031 18032ObjectValue.prototype.clazz = 'Object'; 18033 18034module.exports = ObjectValue; 18035 18036},{"../CompletionRecord":103,"../GenDash":108,"../Value":111,"./NullValue":143,"./PrimitiveValue":146,"./PropertyDescriptor":147}],146:[function(require,module,exports){ 18037'use strict'; 18038/* @flow */ 18039 18040const Value = require('../Value'); 18041const CompletionRecord = require('../CompletionRecord'); 18042let StringValue; 18043 18044/** 18045 * Represents a primitive value. 18046 */ 18047class PrimitiveValue extends Value { 18048 18049 constructor(value) { 18050 super(null); 18051 this.native = value; 18052 //Object.defineProperty(this, 'native', { 18053 // 'value': value, 18054 // 'enumerable': true 18055 //}); 18056 } 18057 18058 ref(name, realm) { 18059 var that = this; 18060 let out = Object.create(null); 18061 out.getValue = function *() { return yield * that.get(name, realm); };
18062 out.setValue = function *(to) { yield * that.set(name, to, realm); }; 18063 return out; 18064 } 18065 18066 *get(what, realm) { 18067 return yield * this.derivePrototype(realm).get(what, realm); 18068 } 18069 18070 *set(what, to, realm) { 18071 //Can't set primative properties. 18072 } 18073 18074 18075 derivePrototype(realm) { 18076 switch ( typeof this.native ) { 18077 case 'string': return realm.StringPrototype; 18078 case 'number': return realm.NumberPrototype; 18079 case 'boolean': return realm.BooleanPrototype; 18080 } 18081 } 18082 18083 toNative() { 18084 return this.native; 18085 } 18086 18087 get debugString() { 18088 if ( typeof this.native === 'object' ) return '[native object]'; 18089 else if ( typeof this.native === 'function' ) return '[native function]'; 18090 else if ( typeof this.native === 'string' ) return JSON.stringify(this.native); 18091 else return '' + this.native; 18092 18093 } 18094 18095 *asString() { 18096 return this.native.toString(); 18097 } 18098 18099 *doubleEquals(other) { 18100 let native = this.native; 18101 if ( other instanceof PrimitiveValue) { 18102 return Value.fromNative(this.native == other.native); 18103 } else if ( typeof native === 'number' ) { 18104 if ( other instanceof StringValue ) { 18105 let num = yield * other.toNumberValue(); 18106 return Value.from(native === num.toNative()); 18107 } else { 18108 return Value.false; 18109 } 18110 } else if ( typeof native == 'boolean' ) { 18111 return yield * this.toNumberValue().doubleEquals(other); 18112 } 18113 18114 return Value.false; 18115 18116 } 18117 *tripleEquals(other) { return this.native === other.toNative() ? Value.true : Value.false; } 18118 18119 *add(other) { return this.fromNative(this.native + (yield * other.toPrimitiveNative())); } 18120 18121 *inOperator(other) { return this.fromNative(this.native in other.toNative()); } 18122 *instanceOf(other) { return Value.false; } 18123 18124 *unaryPlus() { return this.fromNative(+this.native); } 18125 *unaryMinus() { return this.fromNative(-this.native); } 18126 *not() { return this.fromNative(!this.native); } 18127 18128 18129 18130 *get(name, realm) { 18131 let pt = this.derivePrototype(realm); 18132 return yield * pt.get(name, realm, this); 18133 } 18134 18135 *observableProperties(realm) { 18136 yield * this.derivePrototype(realm).observableProperties(realm); 18137 } 18138 18139 *makeThisForNew() { 18140 throw new Error('Naw'); 18141 } 18142 18143 getPrototype(realm) { 18144 return this.derivePrototype(realm); 18145 } 18146 18147 get truthy() { 18148 return !!this.native; 18149 } 18150 18151 get jsTypeName() { 18152 return typeof this.native; 18153 } 18154 18155 *toPrimitiveValue(preferedType) { return this; } 18156 *toStringValue() { 18157 if ( typeof this.native === 'string' ) return this; 18158 return this.fromNative(String(this.native)); 18159 } 18160 18161 *toNumberValue() { 18162 if ( typeof this.native === 'number' ) return this; 18163 return this.fromNative(Number(this.native)); 18164 } 18165 18166 18167} 18168module.exports = PrimitiveValue; 18169 18170StringValue = require('./StringValue'); 18171 18172 18173 18174},{"../CompletionRecord":103,"../Value":111,"./StringValue":150}],147:[function(require,module,exports){ 18175'use strict'; 18176/* @flow */ 18177 18178const Value = require('../Value'); 18179const CompletionRecord = require('../CompletionRecord'); 18180 18181let serial = 0; 18182 18183//TODO: We should call this a PropertyDescriptor, not a variable. 18184 18185class PropertyDescriptor { 18186 constructor(value, enumerable) { 18187 this.value = value; 18188 this.serial = serial++; 18189 this.configurable = true; 18190 this.enumerable = enumerable !== undefined ? !!enumerable : true; 18191 this.writable = true; 18192 this.getter = undefined; 18193 this.setter = undefined; 18194 } 18195 18196 get direct() { 18197 return !this.getter && !this.setter && this.writable; 18198 } 18199 18200 *getValue(thiz) { 18201 thiz = thiz || Value.null; 18202 if ( this.getter ) { 18203 return yield * this.getter.call(thiz, []); 18204 } 18205 return this.value; 18206 } 18207 18208 *setValue(thiz, to, s) { 18209 thiz = thiz || Value.null; 18210 if ( this.setter ) { 18211 return yield * this.setter.call(thiz, [to], s); 18212 } 18213 if ( !this.writable ) { 18214 if ( !s || !s.strict ) { 18215 return this.value; 18216 } 18217 return yield CompletionRecord.makeTypeError(s.realm, "Can't write to non-writable value."); 18218 } 18219 this.value = to; 18220 return this.value; 18221 } 18222} 18223 18224module.exports = PropertyDescriptor; 18225 18226},{"../CompletionRecord":103,"../Value":111}],148:[function(require,module,exports){ 18227'use strict'; 18228 18229 18230const PrimitiveValue = require('./PrimitiveValue'); 18231const ObjectValue = require('./ObjectValue'); 18232const Value = require('../Value'); 18233 18234 18235class RegExpValue extends ObjectValue { 18236 18237 constructor(realm) { 18238 super(realm, realm.RegExpPrototype); 18239 } 18240 18241 static make(regexp, realm) { 18242 18243 let av = new RegExpValue(realm); 18244 av.regexp = regexp; 18245 av.setImmediate('source', Value.fromNative(regexp.source)); 18246 av.properties['source'].enumerable = false;
18247 av.setImmediate('global', Value.fromNative(regexp.global)); 18248 av.properties['global'].enumerable = false; 18249 av.setImmediate('ignoreCase', Value.fromNative(regexp.ignoreCase)); 18250 av.properties['ignoreCase'].enumerable = false; 18251 av.setImmediate('multiline', Value.fromNative(regexp.multiline)); 18252 av.properties['multiline'].enumerable = false; 18253 return av; 18254 } 18255 18256 toNative() { return this.regexp; } 18257 18258 get debugString() { 18259 return this.regexp.toString(); 18260 } 18261} 18262 18263RegExpValue.prototype.clazz = 'RegExp'; 18264 18265module.exports = RegExpValue; 18266 18267},{"../Value":111,"./ObjectValue":145,"./PrimitiveValue":146}],149:[function(require,module,exports){ 18268'use strict'; 18269/* @flow */ 18270 18271const Value = require('../Value'); 18272const LinkValue = require('./LinkValue'); 18273const CompletionRecord = require('../CompletionRecord'); 18274const ArrayValue = require('./ArrayValue'); 18275/** 18276 * Represents a value that maps directly to an untrusted local value. 18277 */ 18278class SmartLinkValue extends LinkValue { 18279 18280 constructor(value, realm) { 18281 super(value, realm); 18282 } 18283 18284 allowRead(name) { 18285 //if ( name === 'call' ) return true; 18286 //return true; 18287 if ( name.indexOf('esper_') === 0 ) return true; 18288 if ( name === 'hasOwnProperty' ) return true; 18289 let props = this.apiProperties; 18290 if ( props === null ) return true; 18291 return props.indexOf(name) !== -1; 18292 } 18293 18294 allowWrite(name) { 18295 var allowed = []; 18296 var native = this.native; 18297 if ( native.apiUserProperties ) { 18298 Array.prototype.push.apply(allowed, native.apiUserProperties); 18299 } 18300 18301 return allowed.indexOf(name) != -1; 18302 } 18303 18304 getPropertyValueMap() { 18305 let list = {}; 18306 for ( let p in this.native ) { 18307 let v = this.native[p]; 18308 if ( this.allowRead(p) ) { 18309 list[p] = this.makeLink(v); 18310 } 18311 } 18312 return list; 18313 } 18314 18315 static make(native, realm) { 18316 let wellKnown = realm.lookupWellKnown(native); 18317 if ( wellKnown ) return wellKnown; 18318 18319 if ( Array.isArray(native) ) { 18320 var ia = new Array(native.length); 18321 for ( let i = 0; i < native.length; ++i ) { 18322 ia[i] = realm.import(native[i], 'smart'); 18323 } 18324 return ArrayValue.make(ia, realm); 18325 } 18326 18327 return new SmartLinkValue(native, realm); 18328 } 18329 18330 makeLink(value) { 18331 return this.realm.import(value, 'smart'); 18332 } 18333 18334 18335 ref(name, realm) { 18336 let out = super.ref(name, realm); 18337 let native = this.native; 18338 if ( name in native ) { 18339 let noWrite = function *() { 18340 let err = CompletionRecord.makeTypeError(realm, "Can't write to protected property: " + name); 18341 yield * err.addExtra({code: 'SmartAccessDenied', when: 'write', ident: name}); 18342 return yield err; 18343 }; 18344 let noRead = function *() { 18345 let err = CompletionRecord.makeTypeError(realm, "Can't read protected property: " + name); 18346 yield * err.addExtra({code: 'SmartAccessDenied', when: 'read', ident: name}); 18347 return yield err; 18348 }; 18349 if ( !this.allowRead(name) ) { 18350 return { 18351 getValue: noRead, 18352 setValue: noWrite, 18353 del: () => false 18354 }; 18355 } else if ( !this.allowWrite(name) ) { 18356 out.setValue = noWrite; 18357 } 18358 18359 } else { 18360 let defaultAction = out.setValue; 18361 if ( !native.apiUserProperties ) native.apiUserProperties = []; 18362 18363 if ( native.apiUserProperties.indexOf(name) == -1 ) { 18364 out.setValue = function *() { 18365 let ret = yield * defaultAction.apply(this, arguments); 18366 native.apiUserProperties.push(name); 18367 return ret; 18368 }; 18369 } 18370 } 18371 18372 return out; 18373 } 18374 18375 *set(name, value, s, extra) { 18376 18377 if ( name in this.native ) { 18378 if ( !this.allowWrite(name) ) return yield CompletionRecord.makeTypeError(s.realm, "Can't write to protected property: " + name); 18379 } else { 18380 //TODO: Mark value as having been written by user so they retain write permissions to it. 18381 } 18382 18383 return yield * super.set(name, value, s, extra); 18384 18385 } 18386 18387 *get(name, realm) { 18388 if ( !(name in this.native) ) { 18389 return Value.undef; 18390 } 18391 18392 if ( ('esper_' + name) in this.native ) name = 'esper_' + name; 18393 18394 if ( !this.allowRead(name) ) { 18395 return yield CompletionRecord.makeTypeError(realm, "Can't read protected property: " + name); 18396 } 18397 18398 return yield * super.get(name, realm); 18399 } 18400 18401 get apiProperties() { 18402 let allowed = []; 18403 let native = this.native; 18404 18405 if ( native.apiProperties === undefined && native.apiMethods === undefined ) return null; 18406 18407 if ( native.apiProperties ) { 18408 Array.prototype.push.apply(allowed, native.apiProperties); 18409 } 18410 18411 if ( native.apiUserProperties ) { 18412 Array.prototype.push.apply(allowed, native.apiUserProperties); 18413 } 18414 18415 if ( native.apiMethods ) { 18416 Array.prototype.push.apply(allowed, native.apiMethods); 18417 } 18418 18419 18420 if ( native.apiOwnMethods ) { 18421 Array.prototype.push.apply(allowed, native.apiOwnMethods); 18422 } 18423 18424 18425 if ( native.programmableProperties ) { 18426 Array.prototype.push.apply(allowed, native.programmableProperties); 18427 } 18428 18429 return allowed; 18430 } 18431 18432 get debugString() { 18433 let props = this.apiProperties; 18434 return '[SmartLink: ' + this.native + ', props: ' + (props ? props.join(',') : '[none]') + ']'; 18435 } 18436 18437} 18438 18439module.exports = SmartLinkValue; 18440 18441},{"../CompletionRecord":103,"../Value":111,"./ArrayValue":134,"./LinkValue":142}],150:[function(require,module,exports){ 18442'use strict'; 18443 18444const PrimitiveValue = require('./PrimitiveValue'); 18445const Value = require('../Value'); 18446let NumberValue; 18447 18448 18449class StringValue extends PrimitiveValue { 18450 *get(name, realm) { 18451 let idx = Number(name); 18452 if ( !isNaN(idx) ) { 18453 return StringValue.fromNative(this.native[idx]); 18454 } 18455 if ( name === 'length' ) return StringValue.fromNative(this.native.length); 18456 return yield * super.get(name, realm); 18457 } 18458 18459 *doubleEquals(other) { 18460 18461 if ( other instanceof StringValue) { 18462 return Value.fromNative(this.native == other.native); 18463 } else if ( other instanceof NumberValue ) { 18464 let rv = yield * this.toNumberValue(); 18465 return yield * rv.doubleEquals(other); 18466 } 18467 18468 return Value.false; 18469 18470 } 18471
18472 *gt(other) { return this.fromNative(this.native > (yield * other.toStringNative())); } 18473 *lt(other) { return this.fromNative(this.native < (yield * other.toStringNative())); } 18474 *gte(other) { return this.fromNative(this.native >= (yield * other.toStringNative())); } 18475 *lte(other) { return this.fromNative(this.native <= (yield * other.toStringNative())); } 18476 *add(other) { return this.fromNative(this.native + (yield * other.toPrimitiveNative('string'))); } 18477 18478} 18479 18480module.exports = StringValue; 18481 18482NumberValue = require('./NumberValue'); 18483 18484},{"../Value":111,"./NumberValue":144,"./PrimitiveValue":146}],151:[function(require,module,exports){ 18485'use strict'; 18486const EmptyValue = require('./EmptyValue'); 18487const Value = require('../Value'); 18488 18489class UndefinedValue extends EmptyValue { 18490 toNative() { return undefined; } 18491 get jsTypeName() { return 'undefined'; } 18492 *tripleEquals(other, realm) { 18493 return other instanceof UndefinedValue ? Value.true : Value.false; 18494 } 18495 18496 *add(other) { return this.fromNative(undefined + other.toNative()); } 18497 18498 *asString() { 18499 return 'undefined'; 18500 } 18501 18502 *toPrimitiveValue(preferedType) { return this; } 18503 *toNumberValue() { return Value.nan; } 18504 *toStringValue() { return Value.fromNative('undefined'); } 18505 18506 get debugString() { return 'undefined'; } 18507} 18508 18509module.exports = UndefinedValue; 18510 18511},{"../Value":111,"./EmptyValue":139}],152:[function(require,module,exports){ 18512/* 18513 Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved. 18514 18515 Redistribution and use in source and binary forms, with or without 18516 modification, are permitted provided that the following conditions are met: 18517 18518 * Redistributions of source code must retain the above copyright 18519 notice, this list of conditions and the following disclaimer. 18520 * Redistributions in binary form must reproduce the above copyright 18521 notice, this list of conditions and the following disclaimer in the 18522 documentation and/or other materials provided with the distribution. 18523 18524 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18525 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18526 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 18527 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY 18528 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18529 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 18530 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 18531 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 18532 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 18533 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 18534*/ 18535 18536(function (root, factory) { 18537 'use strict'; 18538 18539 // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, 18540 // Rhino, and plain browser loading. 18541 18542 /* istanbul ignore next */ 18543 if (typeof define === 'function' && define.amd) { 18544 define(['exports'], factory); 18545 } else if (typeof exports !== 'undefined') { 18546 factory(exports); 18547 } else { 18548 factory((root.esprima = {})); 18549 } 18550}(this, function (exports) { 18551 'use strict'; 18552 18553 var Token, 18554 TokenName, 18555 FnExprTokens, 18556 Syntax, 18557 PlaceHolders, 18558 Messages, 18559 Regex, 18560 source, 18561 strict, 18562 index, 18563 lineNumber, 18564 lineStart, 18565 hasLineTerminator, 18566 lastIndex, 18567 lastLineNumber, 18568 lastLineStart, 18569 startIndex, 18570 startLineNumber, 18571 startLineStart, 18572 scanning, 18573 length, 18574 lookahead, 18575 state, 18576 extra, 18577 isBindingElement, 18578 isAssignmentTarget, 18579 firstCoverInitializedNameError; 18580 18581 Token = { 18582 BooleanLiteral: 1, 18583 EOF: 2, 18584 Identifier: 3, 18585 Keyword: 4, 18586 NullLiteral: 5, 18587 NumericLiteral: 6, 18588 Punctuator: 7, 18589 StringLiteral: 8, 18590 RegularExpression: 9, 18591 Template: 10 18592 }; 18593 18594 TokenName = {}; 18595 TokenName[Token.BooleanLiteral] = 'Boolean'; 18596 TokenName[Token.EOF] = '<end>'; 18597 TokenName[Token.Identifier] = 'Identifier'; 18598 TokenName[Token.Keyword] = 'Keyword'; 18599 TokenName[Token.NullLiteral] = 'Null'; 18600 TokenName[Token.NumericLiteral] = 'Numeric'; 18601 TokenName[Token.Punctuator] = 'Punctuator'; 18602 TokenName[Token.StringLiteral] = 'String'; 18603 TokenName[Token.RegularExpression] = 'RegularExpression';
18604 TokenName[Token.Template] = 'Template'; 18605 18606 // A function following one of those tokens is an expression. 18607 FnExprTokens = ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', 18608 'return', 'case', 'delete', 'throw', 'void', 18609 // assignment operators 18610 '=', '+=', '-=', '*=', '/=', '%=', '<<=', '>>=', '>>>=', 18611 '&=', '|=', '^=', ',', 18612 // binary/unary operators 18613 '+', '-', '*', '/', '%', '++', '--', '<<', '>>', '>>>', '&', 18614 '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', 18615 '<=', '<', '>', '!=', '!==']; 18616 18617 Syntax = { 18618 AssignmentExpression: 'AssignmentExpression', 18619 AssignmentPattern: 'AssignmentPattern', 18620 ArrayExpression: 'ArrayExpression', 18621 ArrayPattern: 'ArrayPattern', 18622 ArrowFunctionExpression: 'ArrowFunctionExpression', 18623 BlockStatement: 'BlockStatement', 18624 BinaryExpression: 'BinaryExpression', 18625 BreakStatement: 'BreakStatement', 18626 CallExpression: 'CallExpression', 18627 CatchClause: 'CatchClause', 18628 ClassBody: 'ClassBody', 18629 ClassDeclaration: 'ClassDeclaration', 18630 ClassExpression: 'ClassExpression', 18631 ConditionalExpression: 'ConditionalExpression', 18632 ContinueStatement: 'ContinueStatement', 18633 DoWhileStatement: 'DoWhileStatement', 18634 DebuggerStatement: 'DebuggerStatement', 18635 EmptyStatement: 'EmptyStatement', 18636 ExportAllDeclaration: 'ExportAllDeclaration', 18637 ExportDefaultDeclaration: 'ExportDefaultDeclaration', 18638 ExportNamedDeclaration: 'ExportNamedDeclaration', 18639 ExportSpecifier: 'ExportSpecifier', 18640 ExpressionStatement: 'ExpressionStatement', 18641 ForStatement: 'ForStatement', 18642 ForOfStatement: 'ForOfStatement', 18643 ForInStatement: 'ForInStatement', 18644 FunctionDeclaration: 'FunctionDeclaration', 18645 FunctionExpression: 'FunctionExpression', 18646 Identifier: 'Identifier', 18647 IfStatement: 'IfStatement', 18648 ImportDeclaration: 'ImportDeclaration', 18649 ImportDefaultSpecifier: 'ImportDefaultSpecifier', 18650 ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', 18651 ImportSpecifier: 'ImportSpecifier', 18652 Literal: 'Literal', 18653 LabeledStatement: 'LabeledStatement', 18654 LogicalExpression: 'LogicalExpression', 18655 MemberExpression: 'MemberExpression', 18656 MetaProperty: 'MetaProperty', 18657 MethodDefinition: 'MethodDefinition', 18658 NewExpression: 'NewExpression', 18659 ObjectExpression: 'ObjectExpression', 18660 ObjectPattern: 'ObjectPattern', 18661 Program: 'Program', 18662 Property: 'Property', 18663 RestElement: 'RestElement', 18664 ReturnStatement: 'ReturnStatement', 18665 SequenceExpression: 'SequenceExpression', 18666 SpreadElement: 'SpreadElement', 18667 Super: 'Super', 18668 SwitchCase: 'SwitchCase', 18669 SwitchStatement: 'SwitchStatement', 18670 TaggedTemplateExpression: 'TaggedTemplateExpression', 18671 TemplateElement: 'TemplateElement', 18672 TemplateLiteral: 'TemplateLiteral', 18673 ThisExpression: 'ThisExpression', 18674 ThrowStatement: 'ThrowStatement', 18675 TryStatement: 'TryStatement', 18676 UnaryExpression: 'UnaryExpression', 18677 UpdateExpression: 'UpdateExpression', 18678 VariableDeclaration: 'VariableDeclaration', 18679 VariableDeclarator: 'VariableDeclarator', 18680 WhileStatement: 'WhileStatement', 18681 WithStatement: 'WithStatement', 18682 YieldExpression: 'YieldExpression' 18683 }; 18684 18685 PlaceHolders = { 18686 ArrowParameterPlaceHolder: 'ArrowParameterPlaceHolder' 18687 }; 18688 18689 // Error messages should be identical to V8. 18690 Messages = { 18691 UnexpectedToken: 'Unexpected token %0', 18692 UnexpectedNumber: 'Unexpected number', 18693 UnexpectedString: 'Unexpected string', 18694 UnexpectedIdentifier: 'Unexpected identifier', 18695 UnexpectedReserved: 'Unexpected reserved word', 18696 UnexpectedTemplate: 'Unexpected quasi %0', 18697 UnexpectedEOS: 'Unexpected end of input', 18698 NewlineAfterThrow: 'Illegal newline after throw', 18699 InvalidRegExp: 'Invalid regular expression', 18700 UnterminatedRegExp: 'Invalid regular expression: missing /', 18701 InvalidLHSInAssignment: 'Invalid left-hand side in assignment', 18702 InvalidLHSInForIn: 'Invalid left-hand side in for-in', 18703 InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', 18704 MultipleDefaultsInSwitch: 'More than one default clause in switch statement', 18705 NoCatchOrFinally: 'Missing catch or finally after try', 18706 UnknownLabel: 'Undefined label \'%0\'', 18707 Redeclaration: '%0 \'%1\' has already been declared', 18708 IllegalContinue: 'Illegal continue statement', 18709 IllegalBreak: 'Illegal break statement', 18710 IllegalReturn: 'Illegal return statement',
18711 StrictModeWith: 'Strict mode code may not include a with statement', 18712 StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', 18713 StrictVarName: 'Variable name may not be eval or arguments in strict mode', 18714 StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', 18715 StrictParamDupe: 'Strict mode function may not have duplicate parameter names', 18716 StrictFunctionName: 'Function name may not be eval or arguments in strict mode', 18717 StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', 18718 StrictDelete: 'Delete of an unqualified identifier in strict mode.', 18719 StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', 18720 StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', 18721 StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', 18722 StrictReservedWord: 'Use of future reserved word in strict mode', 18723 TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', 18724 ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', 18725 DefaultRestParameter: 'Unexpected token =', 18726 ObjectPatternAsRestParameter: 'Unexpected token {', 18727 DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', 18728 ConstructorSpecialMethod: 'Class constructor may not be an accessor', 18729 DuplicateConstructor: 'A class may only have one constructor', 18730 StaticPrototype: 'Classes may not have static property named prototype', 18731 MissingFromClause: 'Unexpected token', 18732 NoAsAfterImportNamespace: 'Unexpected token', 18733 InvalidModuleSpecifier: 'Unexpected token', 18734 IllegalImportDeclaration: 'Unexpected token', 18735 IllegalExportDeclaration: 'Unexpected token', 18736 DuplicateBinding: 'Duplicate binding %0' 18737 }; 18738 18739 // See also tools/generate-unicode-regex.js. 18740 Regex = { 18741 // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierStart: 18742 NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFB
18742D3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/, 18743 18744 // ECMAScript 6/Unicode v7.0.0 NonAsciiIdentifierPart: 18745 NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFB
18745D3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ 18746 }; 18747 18748 // Ensure the condition is true, otherwise throw an error. 18749 // This is only to have a better contract semantic, i.e. another safety net 18750 // to catch a logic error. The condition shall be fulfilled in normal case. 18751 // Do NOT use this to enforce a certain condition on any user input. 18752 18753 function assert(condition, message) { 18754 /* istanbul ignore if */ 18755 if (!condition) { 18756 throw new Error('ASSERT: ' + message); 18757 } 18758 } 18759 18760 function isDecimalDigit(ch) { 18761 return (ch >= 0x30 && ch <= 0x39); // 0..9 18762 } 18763 18764 function isHexDigit(ch) { 18765 return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; 18766 } 18767 18768 function isOctalDigit(ch) { 18769 return '01234567'.indexOf(ch) >= 0; 18770 } 18771 18772 function octalToDecimal(ch) { 18773 // \0 is not octal escape sequence 18774 var octal = (ch !== '0'), code = '01234567'.indexOf(ch); 18775 18776 if (index < length && isOctalDigit(source[index])) { 18777 octal = true; 18778 code = code * 8 + '01234567'.indexOf(source[index++]); 18779 18780 // 3 digits are only allowed when string starts 18781 // with 0, 1, 2, 3 18782 if ('0123'.indexOf(ch) >= 0 && 18783 index < length && 18784 isOctalDigit(source[index])) { 18785 code = code * 8 + '01234567'.indexOf(source[index++]); 18786 } 18787 } 18788 18789 return { 18790 code: code, 18791 octal: octal 18792 }; 18793 } 18794 18795 // ECMA-262 11.2 White Space 18796 18797 function isWhiteSpace(ch) { 18798 return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || 18799 (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); 18800 } 18801 18802 // ECMA-262 11.3 Line Terminators 18803 18804 function isLineTerminator(ch) { 18805 return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); 18806 } 18807 18808 // ECMA-262 11.6 Identifier Names and Identifiers 18809
18810 function fromCodePoint(cp) { 18811 return (cp < 0x10000) ? String.fromCharCode(cp) : 18812 String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + 18813 String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); 18814 } 18815 18816 function isIdentifierStart(ch) { 18817 return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) 18818 (ch >= 0x41 && ch <= 0x5A) || // A..Z 18819 (ch >= 0x61 && ch <= 0x7A) || // a..z 18820 (ch === 0x5C) || // \ (backslash) 18821 ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch))); 18822 } 18823 18824 function isIdentifierPart(ch) { 18825 return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) 18826 (ch >= 0x41 && ch <= 0x5A) || // A..Z 18827 (ch >= 0x61 && ch <= 0x7A) || // a..z 18828 (ch >= 0x30 && ch <= 0x39) || // 0..9 18829 (ch === 0x5C) || // \ (backslash) 18830 ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch))); 18831 } 18832 18833 // ECMA-262 11.6.2.2 Future Reserved Words 18834 18835 function isFutureReservedWord(id) { 18836 switch (id) { 18837 case 'enum': 18838 case 'export': 18839 case 'import': 18840 case 'super': 18841 return true; 18842 default: 18843 return false; 18844 } 18845 } 18846 18847 function isStrictModeReservedWord(id) { 18848 switch (id) { 18849 case 'implements': 18850 case 'interface': 18851 case 'package': 18852 case 'private': 18853 case 'protected': 18854 case 'public': 18855 case 'static': 18856 case 'yield': 18857 case 'let': 18858 return true; 18859 default: 18860 return false; 18861 } 18862 } 18863 18864 function isRestrictedWord(id) { 18865 return id === 'eval' || id === 'arguments'; 18866 } 18867 18868 // ECMA-262 11.6.2.1 Keywords 18869 18870 function isKeyword(id) { 18871 switch (id.length) { 18872 case 2: 18873 return (id === 'if') || (id === 'in') || (id === 'do'); 18874 case 3: 18875 return (id === 'var') || (id === 'for') || (id === 'new') || 18876 (id === 'try') || (id === 'let'); 18877 case 4: 18878 return (id === 'this') || (id === 'else') || (id === 'case') || 18879 (id === 'void') || (id === 'with') || (id === 'enum'); 18880 case 5: 18881 return (id === 'while') || (id === 'break') || (id === 'catch') || 18882 (id === 'throw') || (id === 'const') || (id === 'yield') || 18883 (id === 'class') || (id === 'super'); 18884 case 6: 18885 return (id === 'return') || (id === 'typeof') || (id === 'delete') || 18886 (id === 'switch') || (id === 'export') || (id === 'import'); 18887 case 7: 18888 return (id === 'default') || (id === 'finally') || (id === 'extends'); 18889 case 8: 18890 return (id === 'function') || (id === 'continue') || (id === 'debugger'); 18891 case 10: 18892 return (id === 'instanceof'); 18893 default: 18894 return false; 18895 } 18896 } 18897 18898 // ECMA-262 11.4 Comments 18899 18900 function addComment(type, value, start, end, loc) { 18901 var comment; 18902 18903 assert(typeof start === 'number', 'Comment must have valid position'); 18904 18905 state.lastCommentStart = start; 18906 18907 comment = { 18908 type: type, 18909 value: value 18910 }; 18911 if (extra.range) { 18912 comment.range = [start, end]; 18913 } 18914 if (extra.loc) { 18915 comment.loc = loc; 18916 } 18917 extra.comments.push(comment); 18918 if (extra.attachComment) { 18919 extra.leadingComments.push(comment); 18920 extra.trailingComments.push(comment); 18921 } 18922 if (extra.tokenize) { 18923 comment.type = comment.type + 'Comment'; 18924 if (extra.delegate) { 18925 comment = extra.delegate(comment); 18926 } 18927 extra.tokens.push(comment); 18928 } 18929 } 18930 18931 function skipSingleLineComment(offset) { 18932 var start, loc, ch, comment; 18933 18934 start = index - offset; 18935 loc = { 18936 start: { 18937 line: lineNumber, 18938 column: index - lineStart - offset 18939 } 18940 }; 18941 18942 while (index < length) { 18943 ch = source.charCodeAt(index); 18944 ++index; 18945 if (isLineTerminator(ch)) { 18946 hasLineTerminator = true; 18947 if (extra.comments) { 18948 comment = source.slice(start + offset, index - 1); 18949 loc.end = { 18950 line: lineNumber, 18951 column: index - lineStart - 1 18952 }; 18953 addComment('Line', comment, start, index - 1, loc); 18954 } 18955 if (ch === 13 && source.charCodeAt(index) === 10) { 18956 ++index; 18957 } 18958 ++lineNumber; 18959 lineStart = index; 18960 return; 18961 } 18962 } 18963 18964 if (extra.comments) { 18965 comment = source.slice(start + offset, index); 18966 loc.end = { 18967 line: lineNumber, 18968 column: index - lineStart 18969 }; 18970 addComment('Line', comment, start, index, loc); 18971 } 18972 } 18973 18974 function skipMultiLineComment() { 18975 var start, loc, ch, comment; 18976 18977 if (extra.comments) { 18978 start = index - 2; 18979 loc = { 18980 start: { 18981 line: lineNumber, 18982 column: index - lineStart - 2 18983 } 18984 }; 18985 } 18986 18987 while (index < length) { 18988 ch = source.charCodeAt(index); 18989 if (isLineTerminator(ch)) { 18990 if (ch === 0x0D && source.charCodeAt(index + 1) === 0x0A) { 18991 ++index; 18992 } 18993 hasLineTerminator = true; 18994 ++lineNumber; 18995 ++index; 18996 lineStart = index; 18997 } else if (ch === 0x2A) { 18998 // Block comment ends with '*/'. 18999 if (source.charCodeAt(index + 1) === 0x2F) { 19000 ++index; 19001 ++index; 19002 if (extra.comments) { 19003 comment = source.slice(start + 2, index - 2); 19004 loc.end = { 19005 line: lineNumber, 19006 column: index - lineStart 19007 }; 19008 addComment('Block', comment, start, index, loc); 19009 } 19010 return; 19011 } 19012 ++index; 19013 } else { 19014 ++index; 19015 } 19016 } 19017 19018 // Ran off the end of the file - the whole thing is a comment 19019 if (extra.comments) { 19020 loc.end = { 19021 line: lineNumber, 19022 column: index - lineStart 19023 }; 19024 comment = source.slice(start + 2, index); 19025 addComment('Block', comment, start, index, loc); 19026 } 19027 tolerateUnexpectedToken(); 19028 } 19029 19030 function skipComment() { 19031 var ch, start; 19032 hasLineTerminator = false;
19033 19034 start = (index === 0); 19035 while (index < length) { 19036 ch = source.charCodeAt(index); 19037 19038 if (isWhiteSpace(ch)) { 19039 ++index; 19040 } else if (isLineTerminator(ch)) { 19041 hasLineTerminator = true; 19042 ++index; 19043 if (ch === 0x0D && source.charCodeAt(index) === 0x0A) { 19044 ++index; 19045 } 19046 ++lineNumber; 19047 lineStart = index; 19048 start = true; 19049 } else if (ch === 0x2F) { // U+002F is '/' 19050 ch = source.charCodeAt(index + 1); 19051 if (ch === 0x2F) { 19052 ++index; 19053 ++index; 19054 skipSingleLineComment(2); 19055 start = true; 19056 } else if (ch === 0x2A) { // U+002A is '*' 19057 ++index; 19058 ++index; 19059 skipMultiLineComment(); 19060 } else { 19061 break; 19062 } 19063 } else if (start && ch === 0x2D) { // U+002D is '-' 19064 // U+003E is '>' 19065 if ((source.charCodeAt(index + 1) === 0x2D) && (source.charCodeAt(index + 2) === 0x3E)) { 19066 // '-->' is a single-line comment 19067 index += 3; 19068 skipSingleLineComment(3); 19069 } else { 19070 break; 19071 } 19072 } else if (ch === 0x3C) { // U+003C is '<' 19073 if (source.slice(index + 1, index + 4) === '!--') { 19074 ++index; // `<` 19075 ++index; // `!` 19076 ++index; // `-` 19077 ++index; // `-` 19078 skipSingleLineComment(4); 19079 } else { 19080 break; 19081 } 19082 } else { 19083 break; 19084 } 19085 } 19086 } 19087 19088 function scanHexEscape(prefix) { 19089 var i, len, ch, code = 0; 19090 19091 len = (prefix === 'u') ? 4 : 2; 19092 for (i = 0; i < len; ++i) { 19093 if (index < length && isHexDigit(source[index])) { 19094 ch = source[index++]; 19095 code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); 19096 } else { 19097 return ''; 19098 } 19099 } 19100 return String.fromCharCode(code); 19101 } 19102 19103 function scanUnicodeCodePointEscape() { 19104 var ch, code; 19105 19106 ch = source[index]; 19107 code = 0; 19108 19109 // At least, one hex digit is required. 19110 if (ch === '}') { 19111 throwUnexpectedToken(); 19112 } 19113 19114 while (index < length) { 19115 ch = source[index++]; 19116 if (!isHexDigit(ch)) { 19117 break; 19118 } 19119 code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); 19120 } 19121 19122 if (code > 0x10FFFF || ch !== '}') { 19123 throwUnexpectedToken(); 19124 } 19125 19126 return fromCodePoint(code); 19127 } 19128 19129 function codePointAt(i) { 19130 var cp, first, second; 19131 19132 cp = source.charCodeAt(i); 19133 if (cp >= 0xD800 && cp <= 0xDBFF) { 19134 second = source.charCodeAt(i + 1); 19135 if (second >= 0xDC00 && second <= 0xDFFF) { 19136 first = cp; 19137 cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; 19138 } 19139 } 19140 19141 return cp; 19142 } 19143 19144 function getComplexIdentifier() { 19145 var cp, ch, id; 19146 19147 cp = codePointAt(index); 19148 id = fromCodePoint(cp); 19149 index += id.length; 19150 19151 // '\u' (U+005C, U+0075) denotes an escaped character. 19152 if (cp === 0x5C) { 19153 if (source.charCodeAt(index) !== 0x75) { 19154 throwUnexpectedToken(); 19155 } 19156 ++index; 19157 if (source[index] === '{') { 19158 ++index; 19159 ch = scanUnicodeCodePointEscape(); 19160 } else { 19161 ch = scanHexEscape('u'); 19162 cp = ch.charCodeAt(0); 19163 if (!ch || ch === '\\' || !isIdentifierStart(cp)) { 19164 throwUnexpectedToken(); 19165 } 19166 } 19167 id = ch; 19168 } 19169 19170 while (index < length) { 19171 cp = codePointAt(index); 19172 if (!isIdentifierPart(cp)) { 19173 break; 19174 }
19175 ch = fromCodePoint(cp); 19176 id += ch; 19177 index += ch.length; 19178 19179 // '\u' (U+005C, U+0075) denotes an escaped character. 19180 if (cp === 0x5C) { 19181 id = id.substr(0, id.length - 1); 19182 if (source.charCodeAt(index) !== 0x75) { 19183 throwUnexpectedToken(); 19184 } 19185 ++index; 19186 if (source[index] === '{') { 19187 ++index; 19188 ch = scanUnicodeCodePointEscape(); 19189 } else { 19190 ch = scanHexEscape('u'); 19191 cp = ch.charCodeAt(0); 19192 if (!ch || ch === '\\' || !isIdentifierPart(cp)) { 19193 throwUnexpectedToken(); 19194 } 19195 } 19196 id += ch; 19197 } 19198 } 19199 19200 return id; 19201 } 19202 19203 function getIdentifier() { 19204 var start, ch; 19205 19206 start = index++; 19207 while (index < length) { 19208 ch = source.charCodeAt(index); 19209 if (ch === 0x5C) { 19210 // Blackslash (U+005C) marks Unicode escape sequence. 19211 index = start; 19212 return getComplexIdentifier(); 19213 } else if (ch >= 0xD800 && ch < 0xDFFF) { 19214 // Need to handle surrogate pairs. 19215 index = start; 19216 return getComplexIdentifier(); 19217 } 19218 if (isIdentifierPart(ch)) { 19219 ++index; 19220 } else { 19221 break; 19222 } 19223 } 19224 19225 return source.slice(start, index); 19226 } 19227 19228 function scanIdentifier() { 19229 var start, id, type; 19230 19231 start = index; 19232 19233 // Backslash (U+005C) starts an escaped character. 19234 id = (source.charCodeAt(index) === 0x5C) ? getComplexIdentifier() : getIdentifier(); 19235 19236 // There is no keyword or literal with only one character. 19237 // Thus, it must be an identifier. 19238 if (id.length === 1) { 19239 type = Token.Identifier; 19240 } else if (isKeyword(id)) { 19241 type = Token.Keyword; 19242 } else if (id === 'null') { 19243 type = Token.NullLiteral; 19244 } else if (id === 'true' || id === 'false') { 19245 type = Token.BooleanLiteral; 19246 } else { 19247 type = Token.Identifier; 19248 } 19249 19250 return { 19251 type: type, 19252 value: id, 19253 lineNumber: lineNumber, 19254 lineStart: lineStart, 19255 start: start, 19256 end: index 19257 }; 19258 } 19259 19260 19261 // ECMA-262 11.7 Punctuators 19262 19263 function scanPunctuator() { 19264 var token, str; 19265 19266 token = { 19267 type: Token.Punctuator, 19268 value: '', 19269 lineNumber: lineNumber, 19270 lineStart: lineStart, 19271 start: index, 19272 end: index 19273 }; 19274 19275 // Check for most common single-character punctuators. 19276 str = source[index]; 19277 switch (str) { 19278 19279 case '(': 19280 if (extra.tokenize) { 19281 extra.openParenToken = extra.tokenValues.length; 19282 } 19283 ++index; 19284 break; 19285 19286 case '{': 19287 if (extra.tokenize) { 19288 extra.openCurlyToken = extra.tokenValues.length; 19289 } 19290 state.curlyStack.push('{'); 19291 ++index; 19292 break; 19293 19294 case '.': 19295 ++index; 19296 if (source[index] === '.' && source[index + 1] === '.') { 19297 // Spread operator: ... 19298 index += 2; 19299 str = '...'; 19300 } 19301 break; 19302 19303 case '}': 19304 ++index; 19305 state.curlyStack.pop(); 19306 break; 19307 case ')': 19308 case ';': 19309 case ',': 19310 case '[': 19311 case ']': 19312 case ':': 19313 case '?': 19314 case '~': 19315 ++index; 19316 break; 19317 19318 default: 19319 // 4-character punctuator. 19320 str = source.substr(index, 4); 19321 if (str === '>>>=') { 19322 index += 4; 19323 } else { 19324 19325 // 3-character punctuators. 19326 str = str.substr(0, 3); 19327 if (str === '===' || str === '!==' || str === '>>>' || 19328 str === '<<=' || str === '>>=') { 19329 index += 3; 19330 } else { 19331 19332 // 2-character punctuators. 19333 str = str.substr(0, 2); 19334 if (str === '&&' || str === '||' || str === '==' || str === '!=' || 19335 str === '+=' || str === '-=' || str === '*=' || str === '/=' || 19336 str === '++' || str === '--' || str === '<<' || str === '>>' || 19337 str === '&=' || str === '|=' || str === '^=' || str === '%=' || 19338 str === '<=' || str === '>=' || str === '=>') { 19339 index += 2; 19340 } else { 19341 19342 // 1-character punctuators. 19343 str = source[index]; 19344 if ('<>=!+-*%&|^/'.indexOf(str) >= 0) { 19345 ++index; 19346 } 19347 } 19348 } 19349 } 19350 } 19351 19352 if (index === token.start) { 19353 throwUnexpectedToken(); 19354 } 19355 19356 token.end = index; 19357 token.value = str; 19358 return token; 19359 } 19360 19361 // ECMA-262 11.8.3 Numeric Literals 19362 19363 function scanHexLiteral(start) { 19364 var number = ''; 19365 19366 while (index < length) { 19367 if (!isHexDigit(source[index])) { 19368 break; 19369 } 19370 number += source[index++]; 19371 } 19372 19373 if (number.length === 0) { 19374 throwUnexpectedToken(); 19375 } 19376 19377 if (isIdentifierStart(source.charCodeAt(index))) { 19378 throwUnexpectedToken(); 19379 } 19380 19381 return { 19382 type: Token.NumericLiteral, 19383 value: parseInt('0x' + number, 16), 19384 lineNumber: lineNumber, 19385 lineStart: lineStart, 19386 start: start, 19387 end: index 19388 }; 19389 } 19390 19391 function scanBinaryLiteral(start) { 19392 var ch, number; 19393 19394 number = ''; 19395 19396 while (index < length) { 19397 ch = source[index]; 19398 if (ch !== '0' && ch !== '1') { 19399 break; 19400 } 19401 number += source[index++]; 19402 } 19403 19404 if (number.length === 0) { 19405 // only 0b or 0B 19406 throwUnexpectedToken(); 19407 } 19408 19409 if (index < length) { 19410 ch = source.charCodeAt(index); 19411 /* istanbul ignore else */ 19412 if (isIdentifierStart(ch) || isDecimalDigit(ch)) { 19413 throwUnexpectedToken(); 19414 } 19415 } 19416 19417 return { 19418 type: Token.NumericLiteral, 19419 value: parseInt(number, 2), 19420 lineNumber: lineNumber, 19421 lineStart: lineStart, 19422 start: start, 19423 end: index 19424 }; 19425 } 19426 19427 function scanOctalLiteral(prefix, start) { 19428 var number, octal; 19429 19430 if (isOctalDigit(prefix)) { 19431 octal = true; 19432 number = '0' + source[index++]; 19433 } else { 19434 octal = false;
19435 ++index; 19436 number = ''; 19437 } 19438 19439 while (index < length) { 19440 if (!isOctalDigit(source[index])) { 19441 break; 19442 } 19443 number += source[index++]; 19444 } 19445 19446 if (!octal && number.length === 0) { 19447 // only 0o or 0O 19448 throwUnexpectedToken(); 19449 } 19450 19451 if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { 19452 throwUnexpectedToken(); 19453 } 19454 19455 return { 19456 type: Token.NumericLiteral, 19457 value: parseInt(number, 8), 19458 octal: octal, 19459 lineNumber: lineNumber, 19460 lineStart: lineStart, 19461 start: start, 19462 end: index 19463 }; 19464 } 19465 19466 function isImplicitOctalLiteral() { 19467 var i, ch; 19468 19469 // Implicit octal, unless there is a non-octal digit. 19470 // (Annex B.1.1 on Numeric Literals) 19471 for (i = index + 1; i < length; ++i) { 19472 ch = source[i]; 19473 if (ch === '8' || ch === '9') { 19474 return false; 19475 } 19476 if (!isOctalDigit(ch)) { 19477 return true; 19478 } 19479 } 19480 19481 return true; 19482 } 19483 19484 function scanNumericLiteral() { 19485 var number, start, ch; 19486 19487 ch = source[index]; 19488 assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 19489 'Numeric literal must start with a decimal digit or a decimal point'); 19490 19491 start = index; 19492 number = ''; 19493 if (ch !== '.') { 19494 number = source[index++]; 19495 ch = source[index]; 19496 19497 // Hex number starts with '0x'. 19498 // Octal number starts with '0'. 19499 // Octal number in ES6 starts with '0o'. 19500 // Binary number in ES6 starts with '0b'. 19501 if (number === '0') { 19502 if (ch === 'x' || ch === 'X') { 19503 ++index; 19504 return scanHexLiteral(start); 19505 } 19506 if (ch === 'b' || ch === 'B') { 19507 ++index; 19508 return scanBinaryLiteral(start); 19509 } 19510 if (ch === 'o' || ch === 'O') { 19511 return scanOctalLiteral(ch, start); 19512 } 19513 19514 if (isOctalDigit(ch)) { 19515 if (isImplicitOctalLiteral()) { 19516 return scanOctalLiteral(ch, start); 19517 } 19518 } 19519 } 19520 19521 while (isDecimalDigit(source.charCodeAt(index))) { 19522 number += source[index++]; 19523 } 19524 ch = source[index]; 19525 } 19526 19527 if (ch === '.') { 19528 number += source[index++]; 19529 while (isDecimalDigit(source.charCodeAt(index))) { 19530 number += source[index++]; 19531 } 19532 ch = source[index]; 19533 } 19534 19535 if (ch === 'e' || ch === 'E') { 19536 number += source[index++]; 19537 19538 ch = source[index]; 19539 if (ch === '+' || ch === '-') { 19540 number += source[index++]; 19541 } 19542 if (isDecimalDigit(source.charCodeAt(index))) { 19543 while (isDecimalDigit(source.charCodeAt(index))) { 19544 number += source[index++]; 19545 } 19546 } else { 19547 throwUnexpectedToken(); 19548 } 19549 } 19550 19551 if (isIdentifierStart(source.charCodeAt(index))) { 19552 throwUnexpectedToken(); 19553 } 19554 19555 return { 19556 type: Token.NumericLiteral, 19557 value: parseFloat(number), 19558 lineNumber: lineNumber, 19559 lineStart: lineStart, 19560 start: start, 19561 end: index 19562 }; 19563 } 19564 19565 // ECMA-262 11.8.4 String Literals 19566 19567 function scanStringLiteral() { 19568 var str = '', quote, start, ch, unescaped, octToDec, octal = false; 19569 19570 quote = source[index]; 19571 assert((quote === '\'' || quote === '"'), 19572 'String literal must starts with a quote'); 19573 19574 start = index; 19575 ++index; 19576 19577 while (index < length) { 19578 ch = source[index++]; 19579 19580 if (ch === quote) { 19581 quote = ''; 19582 break; 19583 } else if (ch === '\\') { 19584 ch = source[index++];
19585 if (!ch || !isLineTerminator(ch.charCodeAt(0))) { 19586 switch (ch) { 19587 case 'u': 19588 case 'x': 19589 if (source[index] === '{') { 19590 ++index; 19591 str += scanUnicodeCodePointEscape(); 19592 } else { 19593 unescaped = scanHexEscape(ch); 19594 if (!unescaped) { 19595 throw throwUnexpectedToken(); 19596 } 19597 str += unescaped; 19598 } 19599 break; 19600 case 'n': 19601 str += '\n'; 19602 break; 19603 case 'r': 19604 str += '\r'; 19605 break; 19606 case 't': 19607 str += '\t'; 19608 break; 19609 case 'b': 19610 str += '\b'; 19611 break; 19612 case 'f': 19613 str += '\f'; 19614 break; 19615 case 'v': 19616 str += '\x0B'; 19617 break; 19618 case '8': 19619 case '9': 19620 str += ch; 19621 tolerateUnexpectedToken(); 19622 break; 19623 19624 default: 19625 if (isOctalDigit(ch)) { 19626 octToDec = octalToDecimal(ch); 19627 19628 octal = octToDec.octal || octal; 19629 str += String.fromCharCode(octToDec.code); 19630 } else { 19631 str += ch; 19632 } 19633 break; 19634 } 19635 } else { 19636 ++lineNumber; 19637 if (ch === '\r' && source[index] === '\n') { 19638 ++index; 19639 } 19640 lineStart = index; 19641 } 19642 } else if (isLineTerminator(ch.charCodeAt(0))) { 19643 break; 19644 } else { 19645 str += ch; 19646 } 19647 } 19648 19649 if (quote !== '') { 19650 index = start; 19651 throwUnexpectedToken(); 19652 } 19653 19654 return { 19655 type: Token.StringLiteral, 19656 value: str, 19657 octal: octal, 19658 lineNumber: startLineNumber, 19659 lineStart: startLineStart, 19660 start: start, 19661 end: index 19662 }; 19663 } 19664 19665 // ECMA-262 11.8.6 Template Literal Lexical Components 19666 19667 function scanTemplate() { 19668 var cooked = '', ch, start, rawOffset, terminated, head, tail, restore, unescaped; 19669 19670 terminated = false; 19671 tail = false; 19672 start = index; 19673 head = (source[index] === '`'); 19674 rawOffset = 2; 19675 19676 ++index; 19677 19678 while (index < length) { 19679 ch = source[index++]; 19680 if (ch === '`') { 19681 rawOffset = 1; 19682 tail = true; 19683 terminated = true; 19684 break; 19685 } else if (ch === '$') { 19686 if (source[index] === '{') { 19687 state.curlyStack.push('${'); 19688 ++index; 19689 terminated = true; 19690 break; 19691 } 19692 cooked += ch; 19693 } else if (ch === '\\') { 19694 ch = source[index++]; 19695 if (!isLineTerminator(ch.charCodeAt(0))) { 19696 switch (ch) { 19697 case 'n': 19698 cooked += '\n'; 19699 break; 19700 case 'r': 19701 cooked += '\r'; 19702 break; 19703 case 't': 19704 cooked += '\t'; 19705 break; 19706 case 'u': 19707 case 'x': 19708 if (source[index] === '{') { 19709 ++index; 19710 cooked += scanUnicodeCodePointEscape(); 19711 } else { 19712 restore = index; 19713 unescaped = scanHexEscape(ch); 19714 if (unescaped) { 19715 cooked += unescaped; 19716 } else { 19717 index = restore; 19718 cooked += ch; 19719 } 19720 } 19721 break; 19722 case 'b': 19723 cooked += '\b'; 19724 break; 19725 case 'f': 19726 cooked += '\f'; 19727 break; 19728 case 'v': 19729 cooked += '\v'; 19730 break; 19731 19732 default: 19733 if (ch === '0') { 19734 if (isDecimalDigit(source.charCodeAt(index))) { 19735 // Illegal: \01 \02 and so on 19736 throwError(Messages.TemplateOctalLiteral); 19737 } 19738 cooked += '\0'; 19739 } else if (isOctalDigit(ch)) { 19740 // Illegal: \1 \2 19741 throwError(Messages.TemplateOctalLiteral); 19742 } else { 19743 cooked += ch; 19744 } 19745 break; 19746 } 19747 } else { 19748 ++lineNumber; 19749 if (ch === '\r' && source[index] === '\n') { 19750 ++index; 19751 } 19752 lineStart = index; 19753 } 19754 }
19754 else if (isLineTerminator(ch.charCodeAt(0))) { 19755 ++lineNumber; 19756 if (ch === '\r' && source[index] === '\n') { 19757 ++index; 19758 } 19759 lineStart = index; 19760 cooked += '\n'; 19761 } else { 19762 cooked += ch; 19763 } 19764 } 19765 19766 if (!terminated) { 19767 throwUnexpectedToken(); 19768 } 19769 19770 if (!head) { 19771 state.curlyStack.pop(); 19772 } 19773 19774 return { 19775 type: Token.Template, 19776 value: { 19777 cooked: cooked, 19778 raw: source.slice(start + 1, index - rawOffset) 19779 }, 19780 head: head, 19781 tail: tail, 19782 lineNumber: lineNumber, 19783 lineStart: lineStart, 19784 start: start, 19785 end: index 19786 }; 19787 } 19788 19789 // ECMA-262 11.8.5 Regular Expression Literals 19790 19791 function testRegExp(pattern, flags) { 19792 // The BMP character to use as a replacement for astral symbols when 19793 // translating an ES6 "u"-flagged pattern to an ES5-compatible 19794 // approximation. 19795 // Note: replacing with '\uFFFF' enables false positives in unlikely 19796 // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid 19797 // pattern that would not be detected by this substitution. 19798 var astralSubstitute = '\uFFFF', 19799 tmp = pattern; 19800 19801 if (flags.indexOf('u') >= 0) { 19802 tmp = tmp 19803 // Replace every Unicode escape sequence with the equivalent 19804 // BMP character or a constant ASCII code point in the case of 19805 // astral symbols. (See the above note on `astralSubstitute` 19806 // for more information.) 19807 .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) { 19808 var codePoint = parseInt($1 || $2, 16); 19809 if (codePoint > 0x10FFFF) { 19810 throwUnexpectedToken(null, Messages.InvalidRegExp); 19811 } 19812 if (codePoint <= 0xFFFF) { 19813 return String.fromCharCode(codePoint); 19814 } 19815 return astralSubstitute; 19816 }) 19817 // Replace each paired surrogate with a single ASCII symbol to 19818 // avoid throwing on regular expressions that are only valid in 19819 // combination with the "u" flag. 19820 .replace( 19821 /[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 19822 astralSubstitute 19823 ); 19824 } 19825 19826 // First, detect invalid regular expressions. 19827 try { 19828 RegExp(tmp); 19829 } catch (e) { 19830 throwUnexpectedToken(null, Messages.InvalidRegExp); 19831 } 19832 19833 // Return a regular expression object for this pattern-flag pair, or 19834 // `null` in case the current environment doesn't support the flags it 19835 // uses. 19836 try { 19837 return new RegExp(pattern, flags); 19838 } catch (exception) { 19839 /* istanbul ignore next */ 19840 return null; 19841 } 19842 } 19843 19844 function scanRegExpBody() { 19845 var ch, str, classMarker, terminated, body; 19846 19847 ch = source[index]; 19848 assert(ch === '/', 'Regular expression literal must start with a slash'); 19849 str = source[index++]; 19850 19851 classMarker = false;
19852 terminated = false; 19853 while (index < length) { 19854 ch = source[index++]; 19855 str += ch; 19856 if (ch === '\\') { 19857 ch = source[index++]; 19858 // ECMA-262 7.8.5 19859 if (isLineTerminator(ch.charCodeAt(0))) { 19860 throwUnexpectedToken(null, Messages.UnterminatedRegExp); 19861 } 19862 str += ch; 19863 } else if (isLineTerminator(ch.charCodeAt(0))) { 19864 throwUnexpectedToken(null, Messages.UnterminatedRegExp); 19865 } else if (classMarker) { 19866 if (ch === ']') { 19867 classMarker = false; 19868 } 19869 } else { 19870 if (ch === '/') { 19871 terminated = true; 19872 break; 19873 } else if (ch === '[') { 19874 classMarker = true; 19875 } 19876 } 19877 } 19878 19879 if (!terminated) { 19880 throwUnexpectedToken(null, Messages.UnterminatedRegExp); 19881 } 19882 19883 // Exclude leading and trailing slash. 19884 body = str.substr(1, str.length - 2); 19885 return { 19886 value: body, 19887 literal: str 19888 }; 19889 } 19890 19891 function scanRegExpFlags() { 19892 var ch, str, flags, restore; 19893 19894 str = ''; 19895 flags = ''; 19896 while (index < length) { 19897 ch = source[index]; 19898 if (!isIdentifierPart(ch.charCodeAt(0))) { 19899 break; 19900 } 19901 19902 ++index; 19903 if (ch === '\\' && index < length) { 19904 ch = source[index]; 19905 if (ch === 'u') { 19906 ++index; 19907 restore = index; 19908 ch = scanHexEscape('u'); 19909 if (ch) { 19910 flags += ch; 19911 for (str += '\\u'; restore < index; ++restore) { 19912 str += source[restore]; 19913 } 19914 } else { 19915 index = restore; 19916 flags += 'u'; 19917 str += '\\u'; 19918 } 19919 tolerateUnexpectedToken(); 19920 } else { 19921 str += '\\'; 19922 tolerateUnexpectedToken(); 19923 } 19924 } else { 19925 flags += ch; 19926 str += ch; 19927 } 19928 } 19929 19930 return { 19931 value: flags, 19932 literal: str 19933 }; 19934 } 19935 19936 function scanRegExp() { 19937 var start, body, flags, value; 19938 scanning = true; 19939 19940 lookahead = null; 19941 skipComment(); 19942 start = index; 19943 19944 body = scanRegExpBody(); 19945 flags = scanRegExpFlags(); 19946 value = testRegExp(body.value, flags.value); 19947 scanning = false; 19948 if (extra.tokenize) { 19949 return { 19950 type: Token.RegularExpression, 19951 value: value, 19952 regex: { 19953 pattern: body.value, 19954 flags: flags.value 19955 }, 19956 lineNumber: lineNumber, 19957 lineStart: lineStart, 19958 start: start, 19959 end: index 19960 }; 19961 } 19962 19963 return { 19964 literal: body.literal + flags.literal, 19965 value: value, 19966 regex: { 19967 pattern: body.value, 19968 flags: flags.value 19969 }, 19970 start: start, 19971 end: index 19972 }; 19973 } 19974 19975 function collectRegex() { 19976 var pos, loc, regex, token; 19977 19978 skipComment(); 19979 19980 pos = index; 19981 loc = { 19982 start: { 19983 line: lineNumber, 19984 column: index - lineStart 19985 } 19986 }; 19987 19988 regex = scanRegExp(); 19989 19990 loc.end = { 19991 line: lineNumber, 19992 column: index - lineStart 19993 }; 19994 19995 /* istanbul ignore next */ 19996 if (!extra.tokenize) { 19997 // Pop the previous token, which is likely '/' or '/=' 19998 if (extra.tokens.length > 0) { 19999 token = extra.tokens[extra.tokens.length - 1]; 20000 if (token.range[0] === pos && token.type === 'Punctuator') { 20001 if (token.value === '/' || token.value === '/=') { 20002 extra.tokens.pop(); 20003 } 20004 } 20005 } 20006 20007 extra.tokens.push({ 20008 type: 'RegularExpression', 20009 value: regex.literal, 20010 regex: regex.regex, 20011 range: [pos, index], 20012 loc: loc 20013 }); 20014 } 20015 20016 return regex; 20017 } 20018 20019 function isIdentifierName(token) { 20020 return token.type === Token.Identifier || 20021 token.type === Token.Keyword || 20022 token.type === Token.BooleanLiteral || 20023 token.type === Token.NullLiteral; 20024 } 20025 20026 // Using the following algorithm: 20027 // https://github.com/mozilla/sweet.js/wiki/design 20028 20029 function advanceSlash() { 20030 var regex, previous, check; 20031 20032 function testKeyword(value) { 20033 return value && (value.length > 1) && (value[0] >= 'a') && (value[0] <= 'z'); 20034 } 20035 20036 previous = extra.tokenValues[extra.tokenValues.length - 1]; 20037 regex = (previous !== null); 20038 20039 switch (previous) { 20040 case 'this': 20041 case ']': 20042 regex = false;
20043 break; 20044 20045 case ')': 20046 check = extra.tokenValues[extra.openParenToken - 1]; 20047 regex = (check === 'if' || check === 'while' || check === 'for' || check === 'with'); 20048 break; 20049 20050 case '}': 20051 // Dividing a function by anything makes little sense, 20052 // but we have to check for that. 20053 regex = false; 20054 if (testKeyword(extra.tokenValues[extra.openCurlyToken - 3])) { 20055 // Anonymous function, e.g. function(){} /42 20056 check = extra.tokenValues[extra.openCurlyToken - 4]; 20057 regex = check ? (FnExprTokens.indexOf(check) < 0) : false; 20058 } else if (testKeyword(extra.tokenValues[extra.openCurlyToken - 4])) { 20059 // Named function, e.g. function f(){} /42/ 20060 check = extra.tokenValues[extra.openCurlyToken - 5]; 20061 regex = check ? (FnExprTokens.indexOf(check) < 0) : true; 20062 } 20063 } 20064 20065 return regex ? collectRegex() : scanPunctuator(); 20066 } 20067 20068 function advance() { 20069 var cp, token; 20070 20071 if (index >= length) { 20072 return { 20073 type: Token.EOF, 20074 lineNumber: lineNumber, 20075 lineStart: lineStart, 20076 start: index, 20077 end: index 20078 }; 20079 } 20080 20081 cp = source.charCodeAt(index); 20082 20083 if (isIdentifierStart(cp)) { 20084 token = scanIdentifier(); 20085 if (strict && isStrictModeReservedWord(token.value)) { 20086 token.type = Token.Keyword; 20087 } 20088 return token; 20089 } 20090 20091 // Very common: ( and ) and ; 20092 if (cp === 0x28 || cp === 0x29 || cp === 0x3B) { 20093 return scanPunctuator(); 20094 } 20095 20096 // String literal starts with single quote (U+0027) or double quote (U+0022). 20097 if (cp === 0x27 || cp === 0x22) { 20098 return scanStringLiteral(); 20099 } 20100 20101 // Dot (.) U+002E can also start a floating-point number, hence the need 20102 // to check the next character. 20103 if (cp === 0x2E) { 20104 if (isDecimalDigit(source.charCodeAt(index + 1))) { 20105 return scanNumericLiteral(); 20106 } 20107 return scanPunctuator(); 20108 } 20109 20110 if (isDecimalDigit(cp)) { 20111 return scanNumericLiteral(); 20112 } 20113 20114 // Slash (/) U+002F can also start a regex. 20115 if (extra.tokenize && cp === 0x2F) { 20116 return advanceSlash(); 20117 } 20118 20119 // Template literals start with ` (U+0060) for template head 20120 // or } (U+007D) for template middle or template tail. 20121 if (cp === 0x60 || (cp === 0x7D && state.curlyStack[state.curlyStack.length - 1] === '${')) { 20122 return scanTemplate(); 20123 } 20124 20125 // Possible identifier start in a surrogate pair. 20126 if (cp >= 0xD800 && cp < 0xDFFF) { 20127 cp = codePointAt(index); 20128 if (isIdentifierStart(cp)) { 20129 return scanIdentifier(); 20130 } 20131 } 20132 20133 return scanPunctuator(); 20134 } 20135 20136 function collectToken() { 20137 var loc, token, value, entry; 20138 20139 loc = { 20140 start: { 20141 line: lineNumber, 20142 column: index - lineStart 20143 } 20144 }; 20145 20146 token = advance(); 20147 loc.end = { 20148 line: lineNumber, 20149 column: index - lineStart 20150 }; 20151 20152 if (token.type !== Token.EOF) { 20153 value = source.slice(token.start, token.end); 20154 entry = { 20155 type: TokenName[token.type], 20156 value: value, 20157 range: [token.start, token.end], 20158 loc: loc 20159 }; 20160 if (token.regex) { 20161 entry.regex = { 20162 pattern: token.regex.pattern, 20163 flags: token.regex.flags 20164 }; 20165 } 20166 if (extra.tokenValues) { 20167 extra.tokenValues.push((entry.type === 'Punctuator' || entry.type === 'Keyword') ? entry.value : null); 20168 } 20169 if (extra.tokenize) { 20170 if (!extra.range) { 20171 delete entry.range; 20172 } 20173 if (!extra.loc) { 20174 delete entry.loc; 20175 } 20176 if (extra.delegate) { 20177 entry = extra.delegate(entry); 20178 } 20179 } 20180 extra.tokens.push(entry); 20181 } 20182 20183 return token; 20184 } 20185 20186 function lex() { 20187 var token; 20188 scanning = true; 20189 20190 lastIndex = index; 20191 lastLineNumber = lineNumber; 20192 lastLineStart = lineStart; 20193 20194 skipComment(); 20195 20196 token = lookahead; 20197 20198 startIndex = index; 20199 startLineNumber = lineNumber; 20200 startLineStart = lineStart; 20201 20202 lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); 20203 scanning = false;
20204 return token; 20205 } 20206 20207 function peek() { 20208 scanning = true; 20209 20210 skipComment(); 20211 20212 lastIndex = index; 20213 lastLineNumber = lineNumber; 20214 lastLineStart = lineStart; 20215 20216 startIndex = index; 20217 startLineNumber = lineNumber; 20218 startLineStart = lineStart; 20219 20220 lookahead = (typeof extra.tokens !== 'undefined') ? collectToken() : advance(); 20221 scanning = false; 20222 } 20223 20224 function Position() { 20225 this.line = startLineNumber; 20226 this.column = startIndex - startLineStart; 20227 } 20228 20229 function SourceLocation() { 20230 this.start = new Position(); 20231 this.end = null; 20232 } 20233 20234 function WrappingSourceLocation(startToken) { 20235 this.start = { 20236 line: startToken.lineNumber, 20237 column: startToken.start - startToken.lineStart 20238 }; 20239 this.end = null; 20240 } 20241 20242 function Node() { 20243 if (extra.range) { 20244 this.range = [startIndex, 0]; 20245 } 20246 if (extra.loc) { 20247 this.loc = new SourceLocation(); 20248 } 20249 } 20250 20251 function WrappingNode(startToken) { 20252 if (extra.range) { 20253 this.range = [startToken.start, 0]; 20254 } 20255 if (extra.loc) { 20256 this.loc = new WrappingSourceLocation(startToken); 20257 } 20258 } 20259 20260 WrappingNode.prototype = Node.prototype = { 20261 20262 processComment: function () { 20263 var lastChild, 20264 innerComments, 20265 leadingComments, 20266 trailingComments, 20267 bottomRight = extra.bottomRightStack, 20268 i, 20269 comment, 20270 last = bottomRight[bottomRight.length - 1]; 20271 20272 if (this.type === Syntax.Program) { 20273 if (this.body.length > 0) { 20274 return; 20275 } 20276 } 20277 /** 20278 * patch innnerComments for properties empty block 20279 * `function a() {/** comments **\/}` 20280 */ 20281 20282 if (this.type === Syntax.BlockStatement && this.body.length === 0) { 20283 innerComments = []; 20284 for (i = extra.leadingComments.length - 1; i >= 0; --i) { 20285 comment = extra.leadingComments[i]; 20286 if (this.range[1] >= comment.range[1]) { 20287 innerComments.unshift(comment); 20288 extra.leadingComments.splice(i, 1); 20289 extra.trailingComments.splice(i, 1); 20290 } 20291 } 20292 if (innerComments.length) { 20293 this.innerComments = innerComments; 20294 //bottomRight.push(this); 20295 return; 20296 } 20297 } 20298 20299 if (extra.trailingComments.length > 0) { 20300 trailingComments = []; 20301 for (i = extra.trailingComments.length - 1; i >= 0; --i) { 20302 comment = extra.trailingComments[i]; 20303 if (comment.range[0] >= this.range[1]) { 20304 trailingComments.unshift(comment); 20305 extra.trailingComments.splice(i, 1); 20306 } 20307 } 20308 extra.trailingComments = []; 20309 } else { 20310 if (last && last.trailingComments && last.trailingComments[0].range[0] >= this.range[1]) { 20311 trailingComments = last.trailingComments; 20312 delete last.trailingComments; 20313 } 20314 } 20315 20316 // Eating the stack. 20317 while (last && last.range[0] >= this.range[0]) { 20318 lastChild = bottomRight.pop(); 20319 last = bottomRight[bottomRight.length - 1]; 20320 } 20321 20322 if (lastChild) { 20323 if (lastChild.leadingComments) { 20324 leadingComments = []; 20325 for (i = lastChild.leadingComments.length - 1; i >= 0; --i) { 20326 comment = lastChild.leadingComments[i]; 20327 if (comment.range[1] <= this.range[0]) { 20328 leadingComments.unshift(comment); 20329 lastChild.leadingComments.splice(i, 1); 20330 } 20331 } 20332 20333 if (!lastChild.leadingComments.length) { 20334 lastChild.leadingComments = undefined; 20335 } 20336 } 20337 } else if (extra.leadingComments.length > 0) { 20338 leadingComments = []; 20339 for (i = extra.leadingComments.length - 1; i >= 0; --i) { 20340 comment = extra.leadingComments[i]; 20341 if (comment.range[1] <= this.range[0]) { 20342 leadingComments.unshift(comment); 20343 extra.leadingComments.splice(i, 1); 20344 } 20345 } 20346 } 20347 20348 20349 if (leadingComments && leadingComments.length > 0) { 20350 this.leadingComments = leadingComments; 20351 } 20352 if (trailingComments && trailingComments.length > 0) { 20353 this.trailingComments = trailingComments; 20354 } 20355 20356 bottomRight.push(this); 20357 }, 20358 20359 finish: function () { 20360 if (extra.range) { 20361 this.range[1] = lastIndex; 20362 } 20363 if (extra.loc) { 20364 this.loc.end = { 20365 line: lastLineNumber, 20366 column: lastIndex - lastLineStart 20367 }; 20368 if (extra.source) { 20369 this.loc.source = extra.source; 20370 } 20371 } 20372 20373 if (extra.attachComment) { 20374 this.processComment(); 20375 } 20376 }, 20377 20378 finishArrayExpression: function (elements) { 20379 this.type = Syntax.ArrayExpression; 20380 this.elements = elements; 20381 this.finish(); 20382 return this; 20383 }, 20384 20385 finishArrayPattern: function (elements) { 20386 this.type = Syntax.ArrayPattern; 20387 this.elements = elements; 20388 this.finish(); 20389 return this; 20390 }, 20391 20392 finishArrowFunctionExpression: function (params, defaults, body, expression) { 20393 this.type = Syntax.ArrowFunctionExpression; 20394 this.id = null; 20395 this.params = params; 20396 this.defaults = defaults; 20397 this.body = body; 20398 this.generator = false;
20399 this.expression = expression; 20400 this.finish(); 20401 return this; 20402 }, 20403 20404 finishAssignmentExpression: function (operator, left, right) { 20405 this.type = Syntax.AssignmentExpression; 20406 this.operator = operator; 20407 this.left = left; 20408 this.right = right; 20409 this.finish(); 20410 return this; 20411 }, 20412 20413 finishAssignmentPattern: function (left, right) { 20414 this.type = Syntax.AssignmentPattern; 20415 this.left = left; 20416 this.right = right; 20417 this.finish(); 20418 return this; 20419 }, 20420 20421 finishBinaryExpression: function (operator, left, right) { 20422 this.type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; 20423 this.operator = operator; 20424 this.left = left; 20425 this.right = right; 20426 this.finish(); 20427 return this; 20428 }, 20429 20430 finishBlockStatement: function (body) { 20431 this.type = Syntax.BlockStatement; 20432 this.body = body; 20433 this.finish(); 20434 return this; 20435 }, 20436 20437 finishBreakStatement: function (label) { 20438 this.type = Syntax.BreakStatement; 20439 this.label = label; 20440 this.finish(); 20441 return this; 20442 }, 20443 20444 finishCallExpression: function (callee, args) { 20445 this.type = Syntax.CallExpression; 20446 this.callee = callee; 20447 this.arguments = args; 20448 this.finish(); 20449 return this; 20450 }, 20451 20452 finishCatchClause: function (param, body) { 20453 this.type = Syntax.CatchClause; 20454 this.param = param; 20455 this.body = body; 20456 this.finish(); 20457 return this; 20458 }, 20459 20460 finishClassBody: function (body) { 20461 this.type = Syntax.ClassBody; 20462 this.body = body; 20463 this.finish(); 20464 return this; 20465 }, 20466 20467 finishClassDeclaration: function (id, superClass, body) { 20468 this.type = Syntax.ClassDeclaration; 20469 this.id = id; 20470 this.superClass = superClass; 20471 this.body = body; 20472 this.finish(); 20473 return this; 20474 }, 20475 20476 finishClassExpression: function (id, superClass, body) { 20477 this.type = Syntax.ClassExpression; 20478 this.id = id; 20479 this.superClass = superClass; 20480 this.body = body; 20481 this.finish(); 20482 return this; 20483 }, 20484 20485 finishConditionalExpression: function (test, consequent, alternate) { 20486 this.type = Syntax.ConditionalExpression; 20487 this.test = test; 20488 this.consequent = consequent; 20489 this.alternate = alternate; 20490 this.finish(); 20491 return this; 20492 }, 20493 20494 finishContinueStatement: function (label) { 20495 this.type = Syntax.ContinueStatement; 20496 this.label = label; 20497 this.finish(); 20498 return this; 20499 }, 20500 20501 finishDebuggerStatement: function () { 20502 this.type = Syntax.DebuggerStatement; 20503 this.finish(); 20504 return this; 20505 }, 20506 20507 finishDoWhileStatement: function (body, test) { 20508 this.type = Syntax.DoWhileStatement; 20509 this.body = body; 20510 this.test = test; 20511 this.finish(); 20512 return this; 20513 }, 20514 20515 finishEmptyStatement: function () { 20516 this.type = Syntax.EmptyStatement; 20517 this.finish(); 20518 return this; 20519 }, 20520 20521 finishExpressionStatement: function (expression) { 20522 this.type = Syntax.ExpressionStatement; 20523 this.expression = expression; 20524 this.finish(); 20525 return this; 20526 }, 20527 20528 finishForStatement: function (init, test, update, body) { 20529 this.type = Syntax.ForStatement; 20530 this.init = init; 20531 this.test = test; 20532 this.update = update; 20533 this.body = body; 20534 this.finish(); 20535 return this; 20536 }, 20537 20538 finishForOfStatement: function (left, right, body) { 20539 this.type = Syntax.ForOfStatement; 20540 this.left = left; 20541 this.right = right; 20542 this.body = body; 20543 this.finish(); 20544 return this; 20545 }, 20546 20547 finishForInStatement: function (left, right, body) { 20548 this.type = Syntax.ForInStatement; 20549 this.left = left; 20550 this.right = right; 20551 this.body = body; 20552 this.each = false;
20553 this.finish(); 20554 return this; 20555 }, 20556 20557 finishFunctionDeclaration: function (id, params, defaults, body, generator) { 20558 this.type = Syntax.FunctionDeclaration; 20559 this.id = id; 20560 this.params = params; 20561 this.defaults = defaults; 20562 this.body = body; 20563 this.generator = generator; 20564 this.expression = false; 20565 this.finish(); 20566 return this; 20567 }, 20568 20569 finishFunctionExpression: function (id, params, defaults, body, generator) { 20570 this.type = Syntax.FunctionExpression; 20571 this.id = id; 20572 this.params = params; 20573 this.defaults = defaults; 20574 this.body = body; 20575 this.generator = generator; 20576 this.expression = false; 20577 this.finish(); 20578 return this; 20579 }, 20580 20581 finishIdentifier: function (name) { 20582 this.type = Syntax.Identifier; 20583 this.name = name; 20584 this.finish(); 20585 return this; 20586 }, 20587 20588 finishIfStatement: function (test, consequent, alternate) { 20589 this.type = Syntax.IfStatement; 20590 this.test = test; 20591 this.consequent = consequent; 20592 this.alternate = alternate; 20593 this.finish(); 20594 return this; 20595 }, 20596 20597 finishLabeledStatement: function (label, body) { 20598 this.type = Syntax.LabeledStatement; 20599 this.label = label; 20600 this.body = body; 20601 this.finish(); 20602 return this; 20603 }, 20604 20605 finishLiteral: function (token) { 20606 this.type = Syntax.Literal; 20607 this.value = token.value; 20608 this.raw = source.slice(token.start, token.end); 20609 if (token.regex) { 20610 this.regex = token.regex; 20611 } 20612 this.finish(); 20613 return this; 20614 }, 20615 20616 finishMemberExpression: function (accessor, object, property) { 20617 this.type = Syntax.MemberExpression; 20618 this.computed = accessor === '['; 20619 this.object = object; 20620 this.property = property; 20621 this.finish(); 20622 return this; 20623 }, 20624 20625 finishMetaProperty: function (meta, property) { 20626 this.type = Syntax.MetaProperty; 20627 this.meta = meta; 20628 this.property = property; 20629 this.finish(); 20630 return this; 20631 }, 20632 20633 finishNewExpression: function (callee, args) { 20634 this.type = Syntax.NewExpression; 20635 this.callee = callee; 20636 this.arguments = args; 20637 this.finish(); 20638 return this; 20639 }, 20640 20641 finishObjectExpression: function (properties) { 20642 this.type = Syntax.ObjectExpression; 20643 this.properties = properties; 20644 this.finish(); 20645 return this; 20646 }, 20647 20648 finishObjectPattern: function (properties) { 20649 this.type = Syntax.ObjectPattern; 20650 this.properties = properties; 20651 this.finish(); 20652 return this; 20653 }, 20654 20655 finishPostfixExpression: function (operator, argument) { 20656 this.type = Syntax.UpdateExpression; 20657 this.operator = operator; 20658 this.argument = argument; 20659 this.prefix = false; 20660 this.finish(); 20661 return this; 20662 }, 20663 20664 finishProgram: function (body, sourceType) { 20665 this.type = Syntax.Program; 20666 this.body = body; 20667 this.sourceType = sourceType; 20668 this.finish(); 20669 return this; 20670 }, 20671 20672 finishProperty: function (kind, key, computed, value, method, shorthand) { 20673 this.type = Syntax.Property; 20674 this.key = key; 20675 this.computed = computed; 20676 this.value = value; 20677 this.kind = kind; 20678 this.method = method; 20679 this.shorthand = shorthand; 20680 this.finish(); 20681 return this; 20682 }, 20683 20684 finishRestElement: function (argument) { 20685 this.type = Syntax.RestElement; 20686 this.argument = argument; 20687 this.finish(); 20688 return this; 20689 }, 20690 20691 finishReturnStatement: function (argument) { 20692 this.type = Syntax.ReturnStatement; 20693 this.argument = argument; 20694 this.finish(); 20695 return this; 20696 }, 20697 20698 finishSequenceExpression: function (expressions) { 20699 this.type = Syntax.SequenceExpression; 20700 this.expressions = expressions; 20701 this.finish(); 20702 return this; 20703 }, 20704 20705 finishSpreadElement: function (argument) { 20706 this.type = Syntax.SpreadElement; 20707 this.argument = argument; 20708 this.finish(); 20709 return this; 20710 }, 20711 20712 finishSwitchCase: function (test, consequent) { 20713 this.type = Syntax.SwitchCase; 20714 this.test = test; 20715 this.consequent = consequent; 20716 this.finish(); 20717 return this; 20718 }, 20719 20720 finishSuper: function () { 20721 this.type = Syntax.Super; 20722 this.finish(); 20723 return this; 20724 }, 20725 20726 finishSwitchStatement: function (discriminant, cases) { 20727 this.type = Syntax.SwitchStatement; 20728 this.discriminant = discriminant; 20729 this.cases = cases; 20730 this.finish(); 20731 return this; 20732 }, 20733 20734 finishTaggedTemplateExpression: function (tag, quasi) { 20735 this.type = Syntax.TaggedTemplateExpression; 20736 this.tag = tag; 20737 this.quasi = quasi; 20738 this.finish(); 20739 return this; 20740 }, 20741 20742 finishTemplateElement: function (value, tail) { 20743 this.type = Syntax.TemplateElement; 20744 this.value = value; 20745 this.tail = tail; 20746 this.finish(); 20747 return this; 20748 }, 20749
20750 finishTemplateLiteral: function (quasis, expressions) { 20751 this.type = Syntax.TemplateLiteral; 20752 this.quasis = quasis; 20753 this.expressions = expressions; 20754 this.finish(); 20755 return this; 20756 }, 20757 20758 finishThisExpression: function () { 20759 this.type = Syntax.ThisExpression; 20760 this.finish(); 20761 return this; 20762 }, 20763 20764 finishThrowStatement: function (argument) { 20765 this.type = Syntax.ThrowStatement; 20766 this.argument = argument; 20767 this.finish(); 20768 return this; 20769 }, 20770 20771 finishTryStatement: function (block, handler, finalizer) { 20772 this.type = Syntax.TryStatement; 20773 this.block = block; 20774 this.guardedHandlers = []; 20775 this.handlers = handler ? [handler] : []; 20776 this.handler = handler; 20777 this.finalizer = finalizer; 20778 this.finish(); 20779 return this; 20780 }, 20781 20782 finishUnaryExpression: function (operator, argument) { 20783 this.type = (operator === '++' || operator === '--') ? Syntax.UpdateExpression : Syntax.UnaryExpression; 20784 this.operator = operator; 20785 this.argument = argument; 20786 this.prefix = true; 20787 this.finish(); 20788 return this; 20789 }, 20790 20791 finishVariableDeclaration: function (declarations) { 20792 this.type = Syntax.VariableDeclaration; 20793 this.declarations = declarations; 20794 this.kind = 'var'; 20795 this.finish(); 20796 return this; 20797 }, 20798 20799 finishLexicalDeclaration: function (declarations, kind) { 20800 this.type = Syntax.VariableDeclaration; 20801 this.declarations = declarations; 20802 this.kind = kind; 20803 this.finish(); 20804 return this; 20805 }, 20806 20807 finishVariableDeclarator: function (id, init) { 20808 this.type = Syntax.VariableDeclarator; 20809 this.id = id; 20810 this.init = init; 20811 this.finish(); 20812 return this; 20813 }, 20814 20815 finishWhileStatement: function (test, body) { 20816 this.type = Syntax.WhileStatement; 20817 this.test = test; 20818 this.body = body; 20819 this.finish(); 20820 return this; 20821 }, 20822 20823 finishWithStatement: function (object, body) { 20824 this.type = Syntax.WithStatement; 20825 this.object = object; 20826 this.body = body; 20827 this.finish(); 20828 return this; 20829 }, 20830 20831 finishExportSpecifier: function (local, exported) { 20832 this.type = Syntax.ExportSpecifier; 20833 this.exported = exported || local; 20834 this.local = local; 20835 this.finish(); 20836 return this; 20837 }, 20838 20839 finishImportDefaultSpecifier: function (local) { 20840 this.type = Syntax.ImportDefaultSpecifier; 20841 this.local = local; 20842 this.finish(); 20843 return this; 20844 }, 20845 20846 finishImportNamespaceSpecifier: function (local) { 20847 this.type = Syntax.ImportNamespaceSpecifier; 20848 this.local = local; 20849 this.finish(); 20850 return this; 20851 }, 20852 20853 finishExportNamedDeclaration: function (declaration, specifiers, src) { 20854 this.type = Syntax.ExportNamedDeclaration; 20855 this.declaration = declaration; 20856 this.specifiers = specifiers; 20857 this.source = src; 20858 this.finish(); 20859 return this; 20860 }, 20861 20862 finishExportDefaultDeclaration: function (declaration) { 20863 this.type = Syntax.ExportDefaultDeclaration; 20864 this.declaration = declaration; 20865 this.finish(); 20866 return this; 20867 }, 20868 20869 finishExportAllDeclaration: function (src) { 20870 this.type = Syntax.ExportAllDeclaration; 20871 this.source = src; 20872 this.finish(); 20873 return this; 20874 }, 20875 20876 finishImportSpecifier: function (local, imported) { 20877 this.type = Syntax.ImportSpecifier; 20878 this.local = local || imported; 20879 this.imported = imported; 20880 this.finish(); 20881 return this; 20882 }, 20883 20884 finishImportDeclaration: function (specifiers, src) { 20885 this.type = Syntax.ImportDeclaration; 20886 this.specifiers = specifiers; 20887 this.source = src; 20888 this.finish(); 20889 return this; 20890 }, 20891 20892 finishYieldExpression: function (argument, delegate) { 20893 this.type = Syntax.YieldExpression; 20894 this.argument = argument; 20895 this.delegate = delegate; 20896 this.finish(); 20897 return this; 20898 } 20899 }; 20900 20901 20902 function recordError(error) { 20903 var e, existing; 20904 20905 for (e = 0; e < extra.errors.length; e++) { 20906 existing = extra.errors[e]; 20907 // Prevent duplicated error. 20908 /* istanbul ignore next */ 20909 if (existing.index === error.index && existing.message === error.message) { 20910 return; 20911 } 20912 } 20913 20914 extra.errors.push(error); 20915 } 20916 20917 function constructError(msg, column) { 20918 var error = new Error(msg); 20919 try { 20920 throw error; 20921 } catch (base) { 20922 /* istanbul ignore else */ 20923 if (Object.create && Object.defineProperty) { 20924 error = Object.create(base); 20925 Object.defineProperty(error, 'column', { value: column }); 20926 } 20927 } finally { 20928 return error; 20929 } 20930 } 20931 20932 function createError(line, pos, description) { 20933 var msg, column, error; 20934
20935 msg = 'Line ' + line + ': ' + description; 20936 column = pos - (scanning ? lineStart : lastLineStart) + 1; 20937 error = constructError(msg, column); 20938 error.lineNumber = line; 20939 error.description = description; 20940 error.index = pos; 20941 return error; 20942 } 20943 20944 // Throw an exception 20945 20946 function throwError(messageFormat) { 20947 var args, msg; 20948 20949 args = Array.prototype.slice.call(arguments, 1); 20950 msg = messageFormat.replace(/%(\d)/g, 20951 function (whole, idx) { 20952 assert(idx < args.length, 'Message reference must be in range'); 20953 return args[idx]; 20954 } 20955 ); 20956 20957 throw createError(lastLineNumber, lastIndex, msg); 20958 } 20959 20960 function tolerateError(messageFormat) { 20961 var args, msg, error; 20962 20963 args = Array.prototype.slice.call(arguments, 1); 20964 /* istanbul ignore next */ 20965 msg = messageFormat.replace(/%(\d)/g, 20966 function (whole, idx) { 20967 assert(idx < args.length, 'Message reference must be in range'); 20968 return args[idx]; 20969 } 20970 ); 20971 20972 error = createError(lineNumber, lastIndex, msg); 20973 if (extra.errors) { 20974 recordError(error); 20975 } else { 20976 throw error; 20977 } 20978 } 20979 20980 // Throw an exception because of the token. 20981 20982 function unexpectedTokenError(token, message) { 20983 var value, msg = message || Messages.UnexpectedToken; 20984 20985 if (token) { 20986 if (!message) { 20987 msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS : 20988 (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier : 20989 (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber : 20990 (token.type === Token.StringLiteral) ? Messages.UnexpectedString : 20991 (token.type === Token.Template) ? Messages.UnexpectedTemplate : 20992 Messages.UnexpectedToken; 20993 20994 if (token.type === Token.Keyword) { 20995 if (isFutureReservedWord(token.value)) { 20996 msg = Messages.UnexpectedReserved; 20997 } else if (strict && isStrictModeReservedWord(token.value)) { 20998 msg = Messages.StrictReservedWord; 20999 } 21000 } 21001 } 21002 21003 value = (token.type === Token.Template) ? token.value.raw : token.value; 21004 } else { 21005 value = 'ILLEGAL'; 21006 } 21007 21008 msg = msg.replace('%0', value); 21009 21010 return (token && typeof token.lineNumber === 'number') ? 21011 createError(token.lineNumber, token.start, msg) : 21012 createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg); 21013 } 21014 21015 function throwUnexpectedToken(token, message) { 21016 throw unexpectedTokenError(token, message); 21017 } 21018 21019 function tolerateUnexpectedToken(token, message) { 21020 var error = unexpectedTokenError(token, message); 21021 if (extra.errors) { 21022 recordError(error); 21023 } else { 21024 throw error; 21025 } 21026 } 21027 21028 // Expect the next token to match the specified punctuator. 21029 // If not, an exception will be thrown. 21030 21031 function expect(value) { 21032 var token = lex(); 21033 if (token.type !== Token.Punctuator || token.value !== value) { 21034 throwUnexpectedToken(token); 21035 } 21036 } 21037 21038 /** 21039 * @name expectCommaSeparator 21040 * @description Quietly expect a comma when in tolerant mode, otherwise delegates 21041 * to <code>expect(value)</code> 21042 * @since 2.0 21043 */
21044 function expectCommaSeparator() { 21045 var token; 21046 21047 if (extra.errors) { 21048 token = lookahead; 21049 if (token.type === Token.Punctuator && token.value === ',') { 21050 lex(); 21051 } else if (token.type === Token.Punctuator && token.value === ';') { 21052 lex(); 21053 tolerateUnexpectedToken(token); 21054 } else { 21055 tolerateUnexpectedToken(token, Messages.UnexpectedToken); 21056 } 21057 } else { 21058 expect(','); 21059 } 21060 } 21061 21062 // Expect the next token to match the specified keyword. 21063 // If not, an exception will be thrown. 21064 21065 function expectKeyword(keyword) { 21066 var token = lex(); 21067 if (token.type !== Token.Keyword || token.value !== keyword) { 21068 throwUnexpectedToken(token); 21069 } 21070 } 21071 21072 // Return true if the next token matches the specified punctuator. 21073 21074 function match(value) { 21075 return lookahead.type === Token.Punctuator && lookahead.value === value; 21076 } 21077 21078 // Return true if the next token matches the specified keyword 21079 21080 function matchKeyword(keyword) { 21081 return lookahead.type === Token.Keyword && lookahead.value === keyword; 21082 } 21083 21084 // Return true if the next token matches the specified contextual keyword 21085 // (where an identifier is sometimes a keyword depending on the context) 21086 21087 function matchContextualKeyword(keyword) { 21088 return lookahead.type === Token.Identifier && lookahead.value === keyword; 21089 } 21090 21091 // Return true if the next token is an assignment operator 21092 21093 function matchAssign() { 21094 var op; 21095 21096 if (lookahead.type !== Token.Punctuator) { 21097 return false; 21098 } 21099 op = lookahead.value; 21100 return op === '=' || 21101 op === '*=' || 21102 op === '/=' || 21103 op === '%=' || 21104 op === '+=' || 21105 op === '-=' || 21106 op === '<<=' || 21107 op === '>>=' || 21108 op === '>>>=' || 21109 op === '&=' || 21110 op === '^=' || 21111 op === '|='; 21112 } 21113 21114 function consumeSemicolon() { 21115 // Catch the very common case first: immediately a semicolon (U+003B). 21116 if (source.charCodeAt(startIndex) === 0x3B || match(';')) { 21117 lex(); 21118 return; 21119 } 21120 21121 if (hasLineTerminator) { 21122 return; 21123 } 21124 21125 // FIXME(ikarienator): this is seemingly an issue in the previous location info convention. 21126 lastIndex = startIndex; 21127 lastLineNumber = startLineNumber; 21128 lastLineStart = startLineStart; 21129 21130 if (lookahead.type !== Token.EOF && !match('}')) { 21131 throwUnexpectedToken(lookahead); 21132 } 21133 } 21134 21135 // Cover grammar support. 21136 // 21137 // When an assignment expression position starts with an left parenthesis, the determination of the type 21138 // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) 21139 // or the first comma. This situation also defers the determination of all the expressions nested in the pair. 21140 // 21141 // There are three productions that can be parsed in a parentheses pair that needs to be determined 21142 // after the outermost pair is closed. They are: 21143 // 21144 // 1. AssignmentExpression 21145 // 2. BindingElements 21146 // 3. AssignmentTargets 21147 // 21148 // In order to avoid exponential backtracking, we use two flags to denote if the production can be 21149 // binding element or assignment target. 21150 // 21151 // The three productions have the relationship: 21152 // 21153 // BindingElements â AssignmentTargets â AssignmentExpression 21154 // 21155 // with a single exception that CoverInitializedName when used directly in an Expression, generates 21156 // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the 21157 // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. 21158 // 21159 // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not 21160 // effect the current flags. This means the production the parser parses is only used as an expression. Therefore 21161 // the CoverInitializedName check is conducted. 21162 // 21163 // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates 21164 // the flags outside of the parser. This means the production the parser parses is used as a part of a potential 21165 // pattern. The CoverInitializedName check is deferred. 21166 function isolateCoverGrammar(parser) { 21167 var oldIsBindingElement = isBindingElement, 21168 oldIsAssignmentTarget = isAssignmentTarget, 21169 oldFirstCoverInitializedNameError = firstCoverInitializedNameError, 21170 result; 21171 isBindingElement = true; 21172 isAssignmentTarget = true; 21173 firstCoverInitializedNameError = null; 21174 result = parser(); 21175 if (firstCoverInitializedNameError !== null) { 21176 throwUnexpectedToken(firstCoverInitializedNameError); 21177 } 21178 isBindingElement = oldIsBindingElement; 21179 isAssignmentTarget = oldIsAssignmentTarget; 21180 firstCoverInitializedNameError = oldFirstCoverInitializedNameError; 21181 return result; 21182 } 21183 21184 function inheritCoverGrammar(parser) { 21185 var oldIsBindingElement = isBindingElement, 21186 oldIsAssignmentTarget = isAssignmentTarget, 21187 oldFirstCoverInitializedNameError = firstCoverInitializedNameError, 21188 result; 21189 isBindingElement = true; 21190 isAssignmentTarget = true; 21191 firstCoverInitializedNameError = null; 21192 result = parser(); 21193 isBindingElement = isBindingElement && oldIsBindingElement; 21194 isAssignmentTarget = isAssignmentTarget && oldIsAssignmentTarget; 21195 firstCoverInitializedNameError = oldFirstCoverInitializedNameError || firstCoverInitializedNameError; 21196 return result; 21197 } 21198 21199 // ECMA-262 13.3.3 Destructuring Binding Patterns 21200 21201 function parseArrayPattern(params, kind) { 21202 var node = new Node(), elements = [], rest, restNode; 21203 expect('['); 21204 21205 while (!match(']')) { 21206 if (match(',')) { 21207 lex(); 21208 elements.push(null); 21209 } else { 21210 if (match('...')) { 21211 restNode = new Node(); 21212 lex(); 21213 params.push(lookahead); 21214 rest = parseVariableIdentifier(kind); 21215 elements.push(restNode.finishRestElement(rest)); 21216 break; 21217 } else { 21218 elements.push(parsePatternWithDefault(params, kind)); 21219 } 21220 if (!match(']')) { 21221 expect(','); 21222 } 21223 } 21224 21225 } 21226 21227 expect(']'); 21228 21229 return node.finishArrayPattern(elements); 21230 } 21231 21232 function parsePropertyPattern(params, kind) { 21233 var node = new Node(), key, keyToken, computed = match('['), init; 21234 if (lookahead.type === Token.Identifier) { 21235 keyToken = lookahead; 21236 key = parseVariableIdentifier(); 21237 if (match('=')) { 21238 params.push(keyToken); 21239 lex(); 21240 init = parseAssignmentExpression(); 21241 21242 return node.finishProperty( 21243 'init', key, false, 21244 new WrappingNode(keyToken).finishAssignmentPattern(key, init), false, true); 21245 } else if (!match(':')) { 21246 params.push(keyToken); 21247 return node.finishProperty('init', key, false, key, false, true); 21248 } 21249 } else { 21250 key = parseObjectPropertyKey(); 21251 } 21252 expect(':'); 21253 init = parsePatternWithDefault(params, kind); 21254 return node.finishProperty('init', key, computed, init, false, false); 21255 } 21256 21257 function parseObjectPattern(params, kind) { 21258 var node = new Node(), properties = []; 21259 21260 expect('{'); 21261 21262 while (!match('}')) { 21263 properties.push(parsePropertyPattern(params, kind)); 21264 if (!match('}')) { 21265 expect(','); 21266 } 21267 } 21268 21269 lex(); 21270 21271 return node.finishObjectPattern(properties); 21272 } 21273 21274 function parsePattern(params, kind) { 21275 if (match('[')) { 21276 return parseArrayPattern(params, kind); 21277 } else if (match('{')) { 21278 return parseObjectPattern(params, kind); 21279 } else if (matchKeyword('let')) { 21280 if (kind === 'const' || kind === 'let') { 21281 tolerateUnexpectedToken(lookahead, Messages.UnexpectedToken); 21282 } 21283 } 21284 21285 params.push(lookahead); 21286 return parseVariableIdentifier(kind); 21287 } 21288 21289 function parsePatternWithDefault(params, kind) { 21290 var startToken = lookahead, pattern, previousAllowYield, right; 21291 pattern = parsePattern(params, kind); 21292 if (match('=')) { 21293 lex(); 21294 previousAllowYield = state.allowYield; 21295 state.allowYield = true; 21296 right = isolateCoverGrammar(parseAssignmentExpression); 21297 state.allowYield = previousAllowYield; 21298 pattern = new WrappingNode(startToken).finishAssignmentPattern(pattern, right); 21299 } 21300 return pattern; 21301 } 21302 21303 // ECMA-262 12.2.5 Array Initializer 21304 21305 function parseArrayInitializer() { 21306 var elements = [], node = new Node(), restSpread; 21307 21308 expect('['); 21309 21310 while (!match(']')) { 21311 if (match(',')) { 21312 lex(); 21313 elements.push(null); 21314 } else if (match('...')) { 21315 restSpread = new Node(); 21316 lex(); 21317 restSpread.finishSpreadElement(inheritCoverGrammar(parseAssignmentExpression)); 21318 21319 if (!match(']')) { 21320 isAssignmentTarget = isBindingElement = false;
21321 expect(','); 21322 } 21323 elements.push(restSpread); 21324 } else { 21325 elements.push(inheritCoverGrammar(parseAssignmentExpression)); 21326 21327 if (!match(']')) { 21328 expect(','); 21329 } 21330 } 21331 } 21332 21333 lex(); 21334 21335 return node.finishArrayExpression(elements); 21336 } 21337 21338 // ECMA-262 12.2.6 Object Initializer 21339 21340 function parsePropertyFunction(node, paramInfo, isGenerator) { 21341 var previousStrict, body; 21342 21343 isAssignmentTarget = isBindingElement = false; 21344 21345 previousStrict = strict; 21346 body = isolateCoverGrammar(parseFunctionSourceElements); 21347 21348 if (strict && paramInfo.firstRestricted) { 21349 tolerateUnexpectedToken(paramInfo.firstRestricted, paramInfo.message); 21350 } 21351 if (strict && paramInfo.stricted) { 21352 tolerateUnexpectedToken(paramInfo.stricted, paramInfo.message); 21353 } 21354 21355 strict = previousStrict; 21356 return node.finishFunctionExpression(null, paramInfo.params, paramInfo.defaults, body, isGenerator); 21357 } 21358 21359 function parsePropertyMethodFunction() { 21360 var params, method, node = new Node(), 21361 previousAllowYield = state.allowYield; 21362 21363 state.allowYield = false; 21364 params = parseParams(); 21365 state.allowYield = previousAllowYield; 21366 21367 state.allowYield = false; 21368 method = parsePropertyFunction(node, params, false); 21369 state.allowYield = previousAllowYield; 21370 21371 return method; 21372 } 21373 21374 function parseObjectPropertyKey() { 21375 var token, node = new Node(), expr; 21376 21377 token = lex(); 21378 21379 // Note: This function is called only from parseObjectProperty(), where 21380 // EOF and Punctuator tokens are already filtered out. 21381 21382 switch (token.type) { 21383 case Token.StringLiteral: 21384 case Token.NumericLiteral: 21385 if (strict && token.octal) { 21386 tolerateUnexpectedToken(token, Messages.StrictOctalLiteral); 21387 } 21388 return node.finishLiteral(token); 21389 case Token.Identifier: 21390 case Token.BooleanLiteral: 21391 case Token.NullLiteral: 21392 case Token.Keyword: 21393 return node.finishIdentifier(token.value); 21394 case Token.Punctuator: 21395 if (token.value === '[') { 21396 expr = isolateCoverGrammar(parseAssignmentExpression); 21397 expect(']'); 21398 return expr; 21399 } 21400 break; 21401 } 21402 throwUnexpectedToken(token); 21403 } 21404 21405 function lookaheadPropertyName() { 21406 switch (lookahead.type) { 21407 case Token.Identifier: 21408 case Token.StringLiteral: 21409 case Token.BooleanLiteral: 21410 case Token.NullLiteral: 21411 case Token.NumericLiteral: 21412 case Token.Keyword: 21413 return true; 21414 case Token.Punctuator: 21415 return lookahead.value === '['; 21416 } 21417 return false; 21418 } 21419 21420 // This function is to try to parse a MethodDefinition as defined in 14.3. But in the case of object literals, 21421 // it might be called at a position where there is in fact a short hand identifier pattern or a data property. 21422 // This can only be determined after we consumed up to the left parentheses. 21423 // 21424 // In order to avoid back tracking, it returns `null` if the position is not a MethodDefinition and the caller 21425 // is responsible to visit other options. 21426 function tryParseMethodDefinition(token, key, computed, node) { 21427 var value, options, methodNode, params, 21428 previousAllowYield = state.allowYield; 21429 21430 if (token.type === Token.Identifier) { 21431 // check for `get` and `set`; 21432 21433 if (token.value === 'get' && lookaheadPropertyName()) { 21434 computed = match('['); 21435 key = parseObjectPropertyKey(); 21436 methodNode = new Node(); 21437 expect('('); 21438 expect(')'); 21439 21440 state.allowYield = false; 21441 value = parsePropertyFunction(methodNode, { 21442 params: [], 21443 defaults: [],
21444 stricted: null, 21445 firstRestricted: null, 21446 message: null 21447 }, false); 21448 state.allowYield = previousAllowYield; 21449 21450 return node.finishProperty('get', key, computed, value, false, false); 21451 } else if (token.value === 'set' && lookaheadPropertyName()) { 21452 computed = match('['); 21453 key = parseObjectPropertyKey(); 21454 methodNode = new Node(); 21455 expect('('); 21456 21457 options = { 21458 params: [], 21459 defaultCount: 0, 21460 defaults: [], 21461 firstRestricted: null, 21462 paramSet: {} 21463 }; 21464 if (match(')')) { 21465 tolerateUnexpectedToken(lookahead); 21466 } else { 21467 state.allowYield = false; 21468 parseParam(options); 21469 state.allowYield = previousAllowYield; 21470 if (options.defaultCount === 0) { 21471 options.defaults = []; 21472 } 21473 } 21474 expect(')'); 21475 21476 state.allowYield = false; 21477 value = parsePropertyFunction(methodNode, options, false); 21478 state.allowYield = previousAllowYield; 21479 21480 return node.finishProperty('set', key, computed, value, false, false); 21481 } 21482 } else if (token.type === Token.Punctuator && token.value === '*' && lookaheadPropertyName()) { 21483 computed = match('['); 21484 key = parseObjectPropertyKey(); 21485 methodNode = new Node(); 21486 21487 state.allowYield = true; 21488 params = parseParams(); 21489 state.allowYield = previousAllowYield; 21490 21491 state.allowYield = false; 21492 value = parsePropertyFunction(methodNode, params, true); 21493 state.allowYield = previousAllowYield; 21494 21495 return node.finishProperty('init', key, computed, value, true, false); 21496 } 21497 21498 if (key && match('(')) { 21499 value = parsePropertyMethodFunction(); 21500 return node.finishProperty('init', key, computed, value, true, false); 21501 } 21502 21503 // Not a MethodDefinition. 21504 return null; 21505 } 21506 21507 function parseObjectProperty(hasProto) { 21508 var token = lookahead, node = new Node(), computed, key, maybeMethod, proto, value; 21509 21510 computed = match('['); 21511 if (match('*')) { 21512 lex(); 21513 } else { 21514 key = parseObjectPropertyKey(); 21515 } 21516 maybeMethod = tryParseMethodDefinition(token, key, computed, node); 21517 if (maybeMethod) { 21518 return maybeMethod; 21519 } 21520 21521 if (!key) { 21522 throwUnexpectedToken(lookahead); 21523 } 21524 21525 // Check for duplicated __proto__ 21526 if (!computed) { 21527 proto = (key.type === Syntax.Identifier && key.name === '__proto__') || 21528 (key.type === Syntax.Literal && key.value === '__proto__'); 21529 if (hasProto.value && proto) { 21530 tolerateError(Messages.DuplicateProtoProperty); 21531 } 21532 hasProto.value |= proto; 21533 } 21534 21535 if (match(':')) { 21536 lex(); 21537 value = inheritCoverGrammar(parseAssignmentExpression); 21538 return node.finishProperty('init', key, computed, value, false, false); 21539 } 21540 21541 if (token.type === Token.Identifier) { 21542 if (match('=')) { 21543 firstCoverInitializedNameError = lookahead; 21544 lex(); 21545 value = isolateCoverGrammar(parseAssignmentExpression); 21546 return node.finishProperty('init', key, computed, 21547 new WrappingNode(token).finishAssignmentPattern(key, value), false, true); 21548 } 21549 return node.finishProperty('init', key, computed, key, false, true); 21550 } 21551 21552 throwUnexpectedToken(lookahead); 21553 } 21554 21555 function parseObjectInitializer() { 21556 var properties = [], hasProto = {value: false}, node = new Node(); 21557 21558 expect('{'); 21559 21560 while (!match('}')) { 21561 properties.push(parseObjectProperty(hasProto)); 21562 21563 if (!match('}')) { 21564 expectCommaSeparator(); 21565 } 21566 } 21567 21568 expect('}'); 21569 21570 return node.finishObjectExpression(properties); 21571 } 21572 21573 function reinterpretExpressionAsPattern(expr) { 21574 var i; 21575 switch (expr.type) { 21576 case Syntax.Identifier: 21577 case Syntax.MemberExpression: 21578 case Syntax.RestElement: 21579 case Syntax.AssignmentPattern: 21580 break; 21581 case Syntax.SpreadElement: 21582 expr.type = Syntax.RestElement; 21583 reinterpretExpressionAsPattern(expr.argument); 21584 break; 21585 case Syntax.ArrayExpression: 21586 expr.type = Syntax.ArrayPattern; 21587 for (i = 0; i < expr.elements.length; i++) { 21588 if (expr.elements[i] !== null) { 21589 reinterpretExpressionAsPattern(expr.elements[i]); 21590 } 21591 } 21592 break; 21593 case Syntax.ObjectExpression: 21594 expr.type = Syntax.ObjectPattern; 21595 for (i = 0; i < expr.properties.length; i++) { 21596 reinterpretExpressionAsPattern(expr.properties[i].value); 21597 } 21598 break; 21599 case Syntax.AssignmentExpression: 21600 expr.type = Syntax.AssignmentPattern; 21601 reinterpretExpressionAsPattern(expr.left); 21602 break; 21603 default: 21604 // Allow other node type for tolerant parsing. 21605 break; 21606 } 21607 } 21608 21609 // ECMA-262 12.2.9 Template Literals 21610 21611 function parseTemplateElement(option) { 21612 var node, token; 21613 21614 if (lookahead.type !== Token.Template || (option.head && !lookahead.head)) { 21615 throwUnexpectedToken(); 21616 } 21617 21618 node = new Node(); 21619 token = lex(); 21620 21621 return node.finishTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail); 21622 } 21623 21624 function parseTemplateLiteral() { 21625 var quasi, quasis, expressions, node = new Node(); 21626 21627 quasi = parseTemplateElement({ head: true }); 21628 quasis = [quasi]; 21629 expressions = []; 21630 21631 while (!quasi.tail) { 21632 expressions.push(parseExpression()); 21633 quasi = parseTemplateElement({ head: false }); 21634 quasis.push(quasi); 21635 } 21636 21637 return node.finishTemplateLiteral(quasis, expressions); 21638 } 21639 21640 // ECMA-262 12.2.10 The Grouping Operator 21641 21642 function parseGroupExpression() { 21643 var expr, expressions, startToken, i, params = []; 21644 21645 expect('('); 21646 21647 if (match(')')) { 21648 lex(); 21649 if (!match('=>')) { 21650 expect('=>'); 21651 } 21652 return { 21653 type: PlaceHolders.ArrowParameterPlaceHolder, 21654 params: [], 21655 rawParams: [] 21656 }; 21657 } 21658 21659 startToken = lookahead; 21660 if (match('...')) { 21661 expr = parseRestElement(params); 21662 expect(')'); 21663 if (!match('=>')) { 21664 expect('=>'); 21665 } 21666 return { 21667 type: PlaceHolders.ArrowParameterPlaceHolder, 21668 params: [expr] 21669 }; 21670 } 21671 21672 isBindingElement = true; 21673 expr = inheritCoverGrammar(parseAssignmentExpression); 21674 21675 if (match(',')) { 21676 isAssignmentTarget = false;
21677 expressions = [expr]; 21678 21679 while (startIndex < length) { 21680 if (!match(',')) { 21681 break; 21682 } 21683 lex(); 21684 21685 if (match('...')) { 21686 if (!isBindingElement) { 21687 throwUnexpectedToken(lookahead); 21688 } 21689 expressions.push(parseRestElement(params)); 21690 expect(')'); 21691 if (!match('=>')) { 21692 expect('=>'); 21693 } 21694 isBindingElement = false; 21695 for (i = 0; i < expressions.length; i++) { 21696 reinterpretExpressionAsPattern(expressions[i]); 21697 } 21698 return { 21699 type: PlaceHolders.ArrowParameterPlaceHolder, 21700 params: expressions 21701 }; 21702 } 21703 21704 expressions.push(inheritCoverGrammar(parseAssignmentExpression)); 21705 } 21706 21707 expr = new WrappingNode(startToken).finishSequenceExpression(expressions); 21708 } 21709 21710 21711 expect(')'); 21712 21713 if (match('=>')) { 21714 if (expr.type === Syntax.Identifier && expr.name === 'yield') { 21715 return { 21716 type: PlaceHolders.ArrowParameterPlaceHolder, 21717 params: [expr] 21718 }; 21719 } 21720 21721 if (!isBindingElement) { 21722 throwUnexpectedToken(lookahead); 21723 } 21724 21725 if (expr.type === Syntax.SequenceExpression) { 21726 for (i = 0; i < expr.expressions.length; i++) { 21727 reinterpretExpressionAsPattern(expr.expressions[i]); 21728 } 21729 } else { 21730 reinterpretExpressionAsPattern(expr); 21731 } 21732 21733 expr = { 21734 type: PlaceHolders.ArrowParameterPlaceHolder, 21735 params: expr.type === Syntax.SequenceExpression ? expr.expressions : [expr] 21736 }; 21737 } 21738 isBindingElement = false; 21739 return expr; 21740 } 21741 21742 21743 // ECMA-262 12.2 Primary Expressions 21744 21745 function parsePrimaryExpression() { 21746 var type, token, expr, node; 21747 21748 if (match('(')) { 21749 isBindingElement = false; 21750 return inheritCoverGrammar(parseGroupExpression); 21751 } 21752 21753 if (match('[')) { 21754 return inheritCoverGrammar(parseArrayInitializer); 21755 } 21756 21757 if (match('{')) { 21758 return inheritCoverGrammar(parseObjectInitializer); 21759 } 21760 21761 type = lookahead.type; 21762 node = new Node(); 21763 21764 if (type === Token.Identifier) { 21765 if (state.sourceType === 'module' && lookahead.value === 'await') { 21766 tolerateUnexpectedToken(lookahead); 21767 } 21768 expr = node.finishIdentifier(lex().value); 21769 } else if (type === Token.StringLiteral || type === Token.NumericLiteral) { 21770 isAssignmentTarget = isBindingElement = false; 21771 if (strict && lookahead.octal) { 21772 tolerateUnexpectedToken(lookahead, Messages.StrictOctalLiteral); 21773 } 21774 expr = node.finishLiteral(lex()); 21775 } else if (type === Token.Keyword) { 21776 if (!strict && state.allowYield && matchKeyword('yield')) { 21777 return parseNonComputedProperty(); 21778 } 21779 if (!strict && matchKeyword('let')) { 21780 return node.finishIdentifier(lex().value); 21781 } 21782 isAssignmentTarget = isBindingElement = false; 21783 if (matchKeyword('function')) { 21784 return parseFunctionExpression(); 21785 } 21786 if (matchKeyword('this')) { 21787 lex(); 21788 return node.finishThisExpression(); 21789 } 21790 if (matchKeyword('class')) { 21791 return parseClassExpression(); 21792 } 21793 throwUnexpectedToken(lex()); 21794 } else if (type === Token.BooleanLiteral) { 21795 isAssignmentTarget = isBindingElement = false; 21796 token = lex(); 21797 token.value = (token.value === 'true'); 21798 expr = node.finishLiteral(token); 21799 } else if (type === Token.NullLiteral) { 21800 isAssignmentTarget = isBindingElement = false;
21801 token = lex(); 21802 token.value = null; 21803 expr = node.finishLiteral(token); 21804 } else if (match('/') || match('/=')) { 21805 isAssignmentTarget = isBindingElement = false; 21806 index = startIndex; 21807 21808 if (typeof extra.tokens !== 'undefined') { 21809 token = collectRegex(); 21810 } else { 21811 token = scanRegExp(); 21812 } 21813 lex(); 21814 expr = node.finishLiteral(token); 21815 } else if (type === Token.Template) { 21816 expr = parseTemplateLiteral(); 21817 } else { 21818 throwUnexpectedToken(lex()); 21819 } 21820 21821 return expr; 21822 } 21823 21824 // ECMA-262 12.3 Left-Hand-Side Expressions 21825 21826 function parseArguments() { 21827 var args = [], expr; 21828 21829 expect('('); 21830 21831 if (!match(')')) { 21832 while (startIndex < length) { 21833 if (match('...')) { 21834 expr = new Node(); 21835 lex(); 21836 expr.finishSpreadElement(isolateCoverGrammar(parseAssignmentExpression)); 21837 } else { 21838 expr = isolateCoverGrammar(parseAssignmentExpression); 21839 } 21840 args.push(expr); 21841 if (match(')')) { 21842 break; 21843 } 21844 expectCommaSeparator(); 21845 } 21846 } 21847 21848 expect(')'); 21849 21850 return args; 21851 } 21852 21853 function parseNonComputedProperty() { 21854 var token, node = new Node(); 21855 21856 token = lex(); 21857 21858 if (!isIdentifierName(token)) { 21859 throwUnexpectedToken(token); 21860 } 21861 21862 return node.finishIdentifier(token.value); 21863 } 21864 21865 function parseNonComputedMember() { 21866 expect('.'); 21867 21868 return parseNonComputedProperty(); 21869 } 21870 21871 function parseComputedMember() { 21872 var expr; 21873 21874 expect('['); 21875 21876 expr = isolateCoverGrammar(parseExpression); 21877 21878 expect(']'); 21879 21880 return expr; 21881 } 21882 21883 // ECMA-262 12.3.3 The new Operator 21884 21885 function parseNewExpression() { 21886 var callee, args, node = new Node(); 21887 21888 expectKeyword('new'); 21889 21890 if (match('.')) { 21891 lex(); 21892 if (lookahead.type === Token.Identifier && lookahead.value === 'target') { 21893 if (state.inFunctionBody) { 21894 lex(); 21895 return node.finishMetaProperty('new', 'target'); 21896 } 21897 } 21898 throwUnexpectedToken(lookahead); 21899 } 21900 21901 callee = isolateCoverGrammar(parseLeftHandSideExpression); 21902 args = match('(') ? parseArguments() : []; 21903 21904 isAssignmentTarget = isBindingElement = false; 21905 21906 return node.finishNewExpression(callee, args); 21907 } 21908 21909 // ECMA-262 12.3.4 Function Calls 21910 21911 function parseLeftHandSideExpressionAllowCall() { 21912 var quasi, expr, args, property, startToken, previousAllowIn = state.allowIn; 21913 21914 startToken = lookahead; 21915 state.allowIn = true; 21916 21917 if (matchKeyword('super') && state.inFunctionBody) { 21918 expr = new Node(); 21919 lex(); 21920 expr = expr.finishSuper(); 21921 if (!match('(') && !match('.') && !match('[')) { 21922 throwUnexpectedToken(lookahead); 21923 } 21924 } else { 21925 expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression); 21926 } 21927 21928 for (;;) { 21929 if (match('.')) { 21930 isBindingElement = false; 21931 isAssignmentTarget = true; 21932 property = parseNonComputedMember(); 21933 expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property); 21934 } else if (match('(')) { 21935 isBindingElement = false; 21936 isAssignmentTarget = false;
21937 args = parseArguments(); 21938 expr = new WrappingNode(startToken).finishCallExpression(expr, args); 21939 } else if (match('[')) { 21940 isBindingElement = false; 21941 isAssignmentTarget = true; 21942 property = parseComputedMember(); 21943 expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property); 21944 } else if (lookahead.type === Token.Template && lookahead.head) { 21945 quasi = parseTemplateLiteral(); 21946 expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi); 21947 } else { 21948 break; 21949 } 21950 } 21951 state.allowIn = previousAllowIn; 21952 21953 return expr; 21954 } 21955 21956 // ECMA-262 12.3 Left-Hand-Side Expressions 21957 21958 function parseLeftHandSideExpression() { 21959 var quasi, expr, property, startToken; 21960 assert(state.allowIn, 'callee of new expression always allow in keyword.'); 21961 21962 startToken = lookahead; 21963 21964 if (matchKeyword('super') && state.inFunctionBody) { 21965 expr = new Node(); 21966 lex(); 21967 expr = expr.finishSuper(); 21968 if (!match('[') && !match('.')) { 21969 throwUnexpectedToken(lookahead); 21970 } 21971 } else { 21972 expr = inheritCoverGrammar(matchKeyword('new') ? parseNewExpression : parsePrimaryExpression); 21973 } 21974 21975 for (;;) { 21976 if (match('[')) { 21977 isBindingElement = false; 21978 isAssignmentTarget = true; 21979 property = parseComputedMember(); 21980 expr = new WrappingNode(startToken).finishMemberExpression('[', expr, property); 21981 } else if (match('.')) { 21982 isBindingElement = false; 21983 isAssignmentTarget = true; 21984 property = parseNonComputedMember(); 21985 expr = new WrappingNode(startToken).finishMemberExpression('.', expr, property); 21986 } else if (lookahead.type === Token.Template && lookahead.head) { 21987 quasi = parseTemplateLiteral(); 21988 expr = new WrappingNode(startToken).finishTaggedTemplateExpression(expr, quasi); 21989 } else { 21990 break; 21991 } 21992 } 21993 return expr; 21994 } 21995 21996 // ECMA-262 12.4 Postfix Expressions 21997 21998 function parsePostfixExpression() { 21999 var expr, token, startToken = lookahead; 22000 22001 expr = inheritCoverGrammar(parseLeftHandSideExpressionAllowCall); 22002 22003 if (!hasLineTerminator && lookahead.type === Token.Punctuator) { 22004 if (match('++') || match('--')) { 22005 // ECMA-262 11.3.1, 11.3.2 22006 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { 22007 tolerateError(Messages.StrictLHSPostfix); 22008 } 22009 22010 if (!isAssignmentTarget) { 22011 tolerateError(Messages.InvalidLHSInAssignment); 22012 } 22013 22014 isAssignmentTarget = isBindingElement = false; 22015 22016 token = lex(); 22017 expr = new WrappingNode(startToken).finishPostfixExpression(token.value, expr); 22018 } 22019 } 22020 22021 return expr; 22022 } 22023 22024 // ECMA-262 12.5 Unary Operators 22025 22026 function parseUnaryExpression() { 22027 var token, expr, startToken; 22028 22029 if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { 22030 expr = parsePostfixExpression(); 22031 } else if (match('++') || match('--')) { 22032 startToken = lookahead; 22033 token = lex(); 22034 expr = inheritCoverGrammar(parseUnaryExpression); 22035 // ECMA-262 11.4.4, 11.4.5 22036 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { 22037 tolerateError(Messages.StrictLHSPrefix); 22038 } 22039 22040 if (!isAssignmentTarget) { 22041 tolerateError(Messages.InvalidLHSInAssignment); 22042 } 22043 expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr); 22044 isAssignmentTarget = isBindingElement = false; 22045 } else if (match('+') || match('-') || match('~') || match('!')) { 22046 startToken = lookahead; 22047 token = lex(); 22048 expr = inheritCoverGrammar(parseUnaryExpression); 22049 expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr); 22050 isAssignmentTarget = isBindingElement = false;
22051 } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { 22052 startToken = lookahead; 22053 token = lex(); 22054 expr = inheritCoverGrammar(parseUnaryExpression); 22055 expr = new WrappingNode(startToken).finishUnaryExpression(token.value, expr); 22056 if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { 22057 tolerateError(Messages.StrictDelete); 22058 } 22059 isAssignmentTarget = isBindingElement = false; 22060 } else { 22061 expr = parsePostfixExpression(); 22062 } 22063 22064 return expr; 22065 } 22066 22067 function binaryPrecedence(token, allowIn) { 22068 var prec = 0; 22069 22070 if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { 22071 return 0; 22072 } 22073 22074 switch (token.value) { 22075 case '||': 22076 prec = 1; 22077 break; 22078 22079 case '&&': 22080 prec = 2; 22081 break; 22082 22083 case '|': 22084 prec = 3; 22085 break; 22086 22087 case '^': 22088 prec = 4; 22089 break; 22090 22091 case '&': 22092 prec = 5; 22093 break; 22094 22095 case '==': 22096 case '!=': 22097 case '===': 22098 case '!==': 22099 prec = 6; 22100 break; 22101 22102 case '<': 22103 case '>': 22104 case '<=': 22105 case '>=': 22106 case 'instanceof': 22107 prec = 7; 22108 break; 22109 22110 case 'in': 22111 prec = allowIn ? 7 : 0; 22112 break; 22113 22114 case '<<': 22115 case '>>': 22116 case '>>>': 22117 prec = 8; 22118 break; 22119 22120 case '+': 22121 case '-': 22122 prec = 9; 22123 break; 22124 22125 case '*': 22126 case '/': 22127 case '%': 22128 prec = 11; 22129 break; 22130 22131 default: 22132 break; 22133 } 22134 22135 return prec; 22136 } 22137 22138 // ECMA-262 12.6 Multiplicative Operators 22139 // ECMA-262 12.7 Additive Operators 22140 // ECMA-262 12.8 Bitwise Shift Operators 22141 // ECMA-262 12.9 Relational Operators 22142 // ECMA-262 12.10 Equality Operators 22143 // ECMA-262 12.11 Binary Bitwise Operators 22144 // ECMA-262 12.12 Binary Logical Operators 22145 22146 function parseBinaryExpression() { 22147 var marker, markers, expr, token, prec, stack, right, operator, left, i; 22148 22149 marker = lookahead; 22150 left = inheritCoverGrammar(parseUnaryExpression); 22151 22152 token = lookahead; 22153 prec = binaryPrecedence(token, state.allowIn); 22154 if (prec === 0) { 22155 return left; 22156 } 22157 isAssignmentTarget = isBindingElement = false; 22158 token.prec = prec; 22159 lex(); 22160 22161 markers = [marker, lookahead]; 22162 right = isolateCoverGrammar(parseUnaryExpression); 22163 22164 stack = [left, token, right]; 22165 22166 while ((prec = binaryPrecedence(lookahead, state.allowIn)) > 0) { 22167 22168 // Reduce: make a binary expression from the three topmost entries. 22169 while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { 22170 right = stack.pop(); 22171 operator = stack.pop().value; 22172 left = stack.pop(); 22173 markers.pop(); 22174 expr = new WrappingNode(markers[markers.length - 1]).finishBinaryExpression(operator, left, right); 22175 stack.push(expr); 22176 } 22177 22178 // Shift. 22179 token = lex(); 22180 token.prec = prec; 22181 stack.push(token); 22182 markers.push(lookahead); 22183 expr = isolateCoverGrammar(parseUnaryExpression); 22184 stack.push(expr); 22185 } 22186 22187 // Final reduce to clean-up the stack. 22188 i = stack.length - 1; 22189 expr = stack[i]; 22190 markers.pop(); 22191 while (i > 1) { 22192 expr = new WrappingNode(markers.pop()).finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr); 22193 i -= 2; 22194 } 22195 22196 return expr; 22197 } 22198 22199 22200 // ECMA-262 12.13 Conditional Operator 22201 22202 function parseConditionalExpression() { 22203 var expr, previousAllowIn, consequent, alternate, startToken; 22204 22205 startToken = lookahead; 22206 22207 expr = inheritCoverGrammar(parseBinaryExpression); 22208 if (match('?')) { 22209 lex(); 22210 previousAllowIn = state.allowIn; 22211 state.allowIn = true; 22212 consequent = isolateCoverGrammar(parseAssignmentExpression); 22213 state.allowIn = previousAllowIn; 22214 expect(':'); 22215 alternate = isolateCoverGrammar(parseAssignmentExpression); 22216 22217 expr = new WrappingNode(startToken).finishConditionalExpression(expr, consequent, alternate); 22218 isAssignmentTarget = isBindingElement = false;
22219 } 22220 22221 return expr; 22222 } 22223 22224 // ECMA-262 14.2 Arrow Function Definitions 22225 22226 function parseConciseBody() { 22227 if (match('{')) { 22228 return parseFunctionSourceElements(); 22229 } 22230 return isolateCoverGrammar(parseAssignmentExpression); 22231 } 22232 22233 function checkPatternParam(options, param) { 22234 var i; 22235 switch (param.type) { 22236 case Syntax.Identifier: 22237 validateParam(options, param, param.name); 22238 break; 22239 case Syntax.RestElement: 22240 checkPatternParam(options, param.argument); 22241 break; 22242 case Syntax.AssignmentPattern: 22243 checkPatternParam(options, param.left); 22244 break; 22245 case Syntax.ArrayPattern: 22246 for (i = 0; i < param.elements.length; i++) { 22247 if (param.elements[i] !== null) { 22248 checkPatternParam(options, param.elements[i]); 22249 } 22250 } 22251 break; 22252 case Syntax.YieldExpression: 22253 break; 22254 default: 22255 assert(param.type === Syntax.ObjectPattern, 'Invalid type'); 22256 for (i = 0; i < param.properties.length; i++) { 22257 checkPatternParam(options, param.properties[i].value); 22258 } 22259 break; 22260 } 22261 } 22262 function reinterpretAsCoverFormalsList(expr) { 22263 var i, len, param, params, defaults, defaultCount, options, token; 22264 22265 defaults = []; 22266 defaultCount = 0; 22267 params = [expr]; 22268 22269 switch (expr.type) { 22270 case Syntax.Identifier: 22271 break; 22272 case PlaceHolders.ArrowParameterPlaceHolder: 22273 params = expr.params; 22274 break; 22275 default: 22276 return null; 22277 } 22278 22279 options = { 22280 paramSet: {} 22281 }; 22282 22283 for (i = 0, len = params.length; i < len; i += 1) { 22284 param = params[i]; 22285 switch (param.type) { 22286 case Syntax.AssignmentPattern: 22287 params[i] = param.left; 22288 if (param.right.type === Syntax.YieldExpression) { 22289 if (param.right.argument) { 22290 throwUnexpectedToken(lookahead); 22291 } 22292 param.right.type = Syntax.Identifier; 22293 param.right.name = 'yield'; 22294 delete param.right.argument; 22295 delete param.right.delegate; 22296 } 22297 defaults.push(param.right); 22298 ++defaultCount; 22299 checkPatternParam(options, param.left); 22300 break; 22301 default: 22302 checkPatternParam(options, param); 22303 params[i] = param; 22304 defaults.push(null); 22305 break; 22306 } 22307 } 22308 22309 if (strict || !state.allowYield) { 22310 for (i = 0, len = params.length; i < len; i += 1) { 22311 param = params[i]; 22312 if (param.type === Syntax.YieldExpression) { 22313 throwUnexpectedToken(lookahead); 22314 } 22315 } 22316 } 22317 22318 if (options.message === Messages.StrictParamDupe) { 22319 token = strict ? options.stricted : options.firstRestricted; 22320 throwUnexpectedToken(token, options.message); 22321 } 22322 22323 if (defaultCount === 0) { 22324 defaults = []; 22325 } 22326 22327 return { 22328 params: params, 22329 defaults: defaults, 22330 stricted: options.stricted, 22331 firstRestricted: options.firstRestricted, 22332 message: options.message 22333 }; 22334 } 22335 22336 function parseArrowFunctionExpression(options, node) { 22337 var previousStrict, previousAllowYield, body; 22338 22339 if (hasLineTerminator) { 22340 tolerateUnexpectedToken(lookahead); 22341 } 22342 expect('=>'); 22343 22344 previousStrict = strict; 22345 previousAllowYield = state.allowYield; 22346 state.allowYield = true; 22347 22348 body = parseConciseBody(); 22349 22350 if (strict && options.firstRestricted) { 22351 throwUnexpectedToken(options.firstRestricted, options.message); 22352 } 22353 if (strict && options.stricted) { 22354 tolerateUnexpectedToken(options.stricted, options.message); 22355 } 22356
22357 strict = previousStrict; 22358 state.allowYield = previousAllowYield; 22359 22360 return node.finishArrowFunctionExpression(options.params, options.defaults, body, body.type !== Syntax.BlockStatement); 22361 } 22362 22363 // ECMA-262 14.4 Yield expression 22364 22365 function parseYieldExpression() { 22366 var argument, expr, delegate, previousAllowYield; 22367 22368 argument = null; 22369 expr = new Node(); 22370 delegate = false; 22371 22372 expectKeyword('yield'); 22373 22374 if (!hasLineTerminator) { 22375 previousAllowYield = state.allowYield; 22376 state.allowYield = false; 22377 delegate = match('*'); 22378 if (delegate) { 22379 lex(); 22380 argument = parseAssignmentExpression(); 22381 } else { 22382 if (!match(';') && !match('}') && !match(')') && lookahead.type !== Token.EOF) { 22383 argument = parseAssignmentExpression(); 22384 } 22385 } 22386 state.allowYield = previousAllowYield; 22387 } 22388 22389 return expr.finishYieldExpression(argument, delegate); 22390 } 22391 22392 // ECMA-262 12.14 Assignment Operators 22393 22394 function parseAssignmentExpression() { 22395 var token, expr, right, list, startToken; 22396 22397 startToken = lookahead; 22398 token = lookahead; 22399 22400 if (!state.allowYield && matchKeyword('yield')) { 22401 return parseYieldExpression(); 22402 } 22403 22404 expr = parseConditionalExpression(); 22405 22406 if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) { 22407 isAssignmentTarget = isBindingElement = false; 22408 list = reinterpretAsCoverFormalsList(expr); 22409 22410 if (list) { 22411 firstCoverInitializedNameError = null; 22412 return parseArrowFunctionExpression(list, new WrappingNode(startToken)); 22413 } 22414 22415 return expr; 22416 } 22417 22418 if (matchAssign()) { 22419 if (!isAssignmentTarget) { 22420 tolerateError(Messages.InvalidLHSInAssignment); 22421 } 22422 22423 // ECMA-262 12.1.1 22424 if (strict && expr.type === Syntax.Identifier) { 22425 if (isRestrictedWord(expr.name)) { 22426 tolerateUnexpectedToken(token, Messages.StrictLHSAssignment); 22427 } 22428 if (isStrictModeReservedWord(expr.name)) { 22429 tolerateUnexpectedToken(token, Messages.StrictReservedWord); 22430 } 22431 } 22432 22433 if (!match('=')) { 22434 isAssignmentTarget = isBindingElement = false; 22435 } else { 22436 reinterpretExpressionAsPattern(expr); 22437 } 22438 22439 token = lex(); 22440 right = isolateCoverGrammar(parseAssignmentExpression); 22441 expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right); 22442 firstCoverInitializedNameError = null; 22443 } 22444 22445 return expr; 22446 } 22447 22448 // ECMA-262 12.15 Comma Operator 22449 22450 function parseExpression() { 22451 var expr, startToken = lookahead, expressions; 22452 22453 expr = isolateCoverGrammar(parseAssignmentExpression); 22454 22455 if (match(',')) { 22456 expressions = [expr]; 22457 22458 while (startIndex < length) { 22459 if (!match(',')) { 22460 break; 22461 } 22462 lex(); 22463 expressions.push(isolateCoverGrammar(parseAssignmentExpression)); 22464 } 22465 22466 expr = new WrappingNode(startToken).finishSequenceExpression(expressions); 22467 } 22468 22469 return expr; 22470 } 22471 22472 // ECMA-262 13.2 Block 22473 22474 function parseStatementListItem() { 22475 if (lookahead.type === Token.Keyword) { 22476 switch (lookahead.value) { 22477 case 'export': 22478 if (state.sourceType !== 'module') { 22479 tolerateUnexpectedToken(lookahead, Messages.IllegalExportDeclaration); 22480 } 22481 return parseExportDeclaration(); 22482 case 'import': 22483 if (state.sourceType !== 'module') { 22484 tolerateUnexpectedToken(lookahead, Messages.IllegalImportDeclaration); 22485 } 22486 return parseImportDeclaration(); 22487 case 'const': 22488 return parseLexicalDeclaration({inFor: false}); 22489 case 'function': 22490 return parseFunctionDeclaration(new Node()); 22491 case 'class': 22492 return parseClassDeclaration(); 22493 } 22494 } 22495 22496 if (matchKeyword('let') && isLexicalDeclaration()) { 22497 return parseLexicalDeclaration({inFor: false}); 22498 } 22499
22500 return parseStatement(); 22501 } 22502 22503 function parseStatementList() { 22504 var list = []; 22505 while (startIndex < length) { 22506 if (match('}')) { 22507 break; 22508 } 22509 list.push(parseStatementListItem()); 22510 } 22511 22512 return list; 22513 } 22514 22515 function parseBlock() { 22516 var block, node = new Node(); 22517 22518 expect('{'); 22519 22520 block = parseStatementList(); 22521 22522 expect('}'); 22523 22524 return node.finishBlockStatement(block); 22525 } 22526 22527 // ECMA-262 13.3.2 Variable Statement 22528 22529 function parseVariableIdentifier(kind) { 22530 var token, node = new Node(); 22531 22532 token = lex(); 22533 22534 if (token.type === Token.Keyword && token.value === 'yield') { 22535 if (strict) { 22536 tolerateUnexpectedToken(token, Messages.StrictReservedWord); 22537 } if (!state.allowYield) { 22538 throwUnexpectedToken(token); 22539 } 22540 } else if (token.type !== Token.Identifier) { 22541 if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) { 22542 tolerateUnexpectedToken(token, Messages.StrictReservedWord); 22543 } else { 22544 if (strict || token.value !== 'let' || kind !== 'var') { 22545 throwUnexpectedToken(token); 22546 } 22547 } 22548 } else if (state.sourceType === 'module' && token.type === Token.Identifier && token.value === 'await') { 22549 tolerateUnexpectedToken(token); 22550 } 22551 22552 return node.finishIdentifier(token.value); 22553 } 22554 22555 function parseVariableDeclaration(options) { 22556 var init = null, id, node = new Node(), params = []; 22557 22558 id = parsePattern(params, 'var'); 22559 22560 // ECMA-262 12.2.1 22561 if (strict && isRestrictedWord(id.name)) { 22562 tolerateError(Messages.StrictVarName); 22563 } 22564 22565 if (match('=')) { 22566 lex(); 22567 init = isolateCoverGrammar(parseAssignmentExpression); 22568 } else if (id.type !== Syntax.Identifier && !options.inFor) { 22569 expect('='); 22570 } 22571 22572 return node.finishVariableDeclarator(id, init); 22573 } 22574 22575 function parseVariableDeclarationList(options) { 22576 var opt, list; 22577 22578 opt = { inFor: options.inFor }; 22579 list = [parseVariableDeclaration(opt)]; 22580 22581 while (match(',')) { 22582 lex(); 22583 list.push(parseVariableDeclaration(opt)); 22584 } 22585 22586 return list; 22587 } 22588 22589 function parseVariableStatement(node) { 22590 var declarations; 22591 22592 expectKeyword('var'); 22593 22594 declarations = parseVariableDeclarationList({ inFor: false }); 22595 22596 consumeSemicolon(); 22597 22598 return node.finishVariableDeclaration(declarations); 22599 } 22600 22601 // ECMA-262 13.3.1 Let and Const Declarations 22602 22603 function parseLexicalBinding(kind, options) { 22604 var init = null, id, node = new Node(), params = []; 22605 22606 id = parsePattern(params, kind); 22607 22608 // ECMA-262 12.2.1 22609 if (strict && id.type === Syntax.Identifier && isRestrictedWord(id.name)) { 22610 tolerateError(Messages.StrictVarName); 22611 } 22612 22613 if (kind === 'const') { 22614 if (!matchKeyword('in') && !matchContextualKeyword('of')) { 22615 expect('='); 22616 init = isolateCoverGrammar(parseAssignmentExpression); 22617 } 22618 } else if ((!options.inFor && id.type !== Syntax.Identifier) || match('=')) { 22619 expect('='); 22620 init = isolateCoverGrammar(parseAssignmentExpression); 22621 } 22622 22623 return node.finishVariableDeclarator(id, init); 22624 } 22625 22626 function parseBindingList(kind, options) { 22627 var list = [parseLexicalBinding(kind, options)]; 22628 22629 while (match(',')) { 22630 lex(); 22631 list.push(parseLexicalBinding(kind, options)); 22632 } 22633 22634 return list; 22635 } 22636 22637 22638 function tokenizerState() { 22639 return { 22640 index: index, 22641 lineNumber: lineNumber, 22642 lineStart: lineStart, 22643 hasLineTerminator: hasLineTerminator, 22644 lastIndex: lastIndex, 22645 lastLineNumber: lastLineNumber, 22646 lastLineStart: lastLineStart, 22647 startIndex: startIndex, 22648 startLineNumber: startLineNumber, 22649 startLineStart: startLineStart, 22650 lookahead: lookahead, 22651 tokenCount: extra.tokens ? extra.tokens.length : 0 22652 }; 22653 } 22654 22655 function resetTokenizerState(ts) { 22656 index = ts.index; 22657 lineNumber = ts.lineNumber; 22658 lineStart = ts.lineStart;
22659 hasLineTerminator = ts.hasLineTerminator; 22660 lastIndex = ts.lastIndex; 22661 lastLineNumber = ts.lastLineNumber; 22662 lastLineStart = ts.lastLineStart; 22663 startIndex = ts.startIndex; 22664 startLineNumber = ts.startLineNumber; 22665 startLineStart = ts.startLineStart; 22666 lookahead = ts.lookahead; 22667 if (extra.tokens) { 22668 extra.tokens.splice(ts.tokenCount, extra.tokens.length); 22669 } 22670 } 22671 22672 function isLexicalDeclaration() { 22673 var lexical, ts; 22674 22675 ts = tokenizerState(); 22676 22677 lex(); 22678 lexical = (lookahead.type === Token.Identifier) || match('[') || match('{') || 22679 matchKeyword('let') || matchKeyword('yield'); 22680 22681 resetTokenizerState(ts); 22682 22683 return lexical; 22684 } 22685 22686 function parseLexicalDeclaration(options) { 22687 var kind, declarations, node = new Node(); 22688 22689 kind = lex().value; 22690 assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); 22691 22692 declarations = parseBindingList(kind, options); 22693 22694 consumeSemicolon(); 22695 22696 return node.finishLexicalDeclaration(declarations, kind); 22697 } 22698 22699 function parseRestElement(params) { 22700 var param, node = new Node(); 22701 22702 lex(); 22703 22704 if (match('{')) { 22705 throwError(Messages.ObjectPatternAsRestParameter); 22706 } 22707 22708 params.push(lookahead); 22709 22710 param = parseVariableIdentifier(); 22711 22712 if (match('=')) { 22713 throwError(Messages.DefaultRestParameter); 22714 } 22715 22716 if (!match(')')) { 22717 throwError(Messages.ParameterAfterRestParameter); 22718 } 22719 22720 return node.finishRestElement(param); 22721 } 22722 22723 // ECMA-262 13.4 Empty Statement 22724 22725 function parseEmptyStatement(node) { 22726 expect(';'); 22727 return node.finishEmptyStatement(); 22728 } 22729 22730 // ECMA-262 12.4 Expression Statement 22731 22732 function parseExpressionStatement(node) { 22733 var expr = parseExpression(); 22734 consumeSemicolon(); 22735 return node.finishExpressionStatement(expr); 22736 } 22737 22738 // ECMA-262 13.6 If statement 22739 22740 function parseIfStatement(node) { 22741 var test, consequent, alternate; 22742 22743 expectKeyword('if'); 22744 22745 expect('('); 22746 22747 test = parseExpression(); 22748 22749 expect(')'); 22750 22751 consequent = parseStatement(); 22752 22753 if (matchKeyword('else')) { 22754 lex(); 22755 alternate = parseStatement(); 22756 } else { 22757 alternate = null; 22758 } 22759 22760 return node.finishIfStatement(test, consequent, alternate); 22761 } 22762 22763 // ECMA-262 13.7 Iteration Statements 22764 22765 function parseDoWhileStatement(node) { 22766 var body, test, oldInIteration; 22767 22768 expectKeyword('do'); 22769 22770 oldInIteration = state.inIteration; 22771 state.inIteration = true; 22772 22773 body = parseStatement(); 22774 22775 state.inIteration = oldInIteration; 22776 22777 expectKeyword('while'); 22778 22779 expect('('); 22780 22781 test = parseExpression(); 22782 22783 expect(')'); 22784 22785 if (match(';')) { 22786 lex(); 22787 } 22788 22789 return node.finishDoWhileStatement(body, test); 22790 } 22791 22792 function parseWhileStatement(node) { 22793 var test, body, oldInIteration; 22794 22795 expectKeyword('while'); 22796 22797 expect('('); 22798 22799 test = parseExpression(); 22800 22801 expect(')'); 22802 22803 oldInIteration = state.inIteration; 22804 state.inIteration = true; 22805 22806 body = parseStatement(); 22807 22808 state.inIteration = oldInIteration; 22809 22810 return node.finishWhileStatement(test, body); 22811 } 22812 22813 function parseForStatement(node) { 22814 var init, forIn, initSeq, initStartToken, test, update, left, right, kind, declarations, 22815 body, oldInIteration, previousAllowIn = state.allowIn; 22816 22817 init = test = update = null; 22818 forIn = true; 22819 22820 expectKeyword('for'); 22821 22822 expect('('); 22823 22824 if (match(';')) { 22825 lex(); 22826 } else { 22827 if (matchKeyword('var')) { 22828 init = new Node(); 22829 lex(); 22830 22831 state.allowIn = false; 22832 declarations = parseVariableDeclarationList({ inFor: true }); 22833 state.allowIn = previousAllowIn; 22834 22835 if (declarations.length === 1 && matchKeyword('in')) { 22836 init = init.finishVariableDeclaration(declarations); 22837 lex(); 22838 left = init; 22839 right = parseExpression(); 22840 init = null; 22841 } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) { 22842 init = init.finishVariableDeclaration(declarations); 22843 lex(); 22844 left = init; 22845 right = parseAssignmentExpression(); 22846 init = null; 22847 forIn = false;
22848 } else { 22849 init = init.finishVariableDeclaration(declarations); 22850 expect(';'); 22851 } 22852 } else if (matchKeyword('const') || matchKeyword('let')) { 22853 init = new Node(); 22854 kind = lex().value; 22855 22856 if (!strict && lookahead.value === 'in') { 22857 init = init.finishIdentifier(kind); 22858 lex(); 22859 left = init; 22860 right = parseExpression(); 22861 init = null; 22862 } else { 22863 state.allowIn = false; 22864 declarations = parseBindingList(kind, {inFor: true}); 22865 state.allowIn = previousAllowIn; 22866 22867 if (declarations.length === 1 && declarations[0].init === null && matchKeyword('in')) { 22868 init = init.finishLexicalDeclaration(declarations, kind); 22869 lex(); 22870 left = init; 22871 right = parseExpression(); 22872 init = null; 22873 } else if (declarations.length === 1 && declarations[0].init === null && matchContextualKeyword('of')) { 22874 init = init.finishLexicalDeclaration(declarations, kind); 22875 lex(); 22876 left = init; 22877 right = parseAssignmentExpression(); 22878 init = null; 22879 forIn = false; 22880 } else { 22881 consumeSemicolon(); 22882 init = init.finishLexicalDeclaration(declarations, kind); 22883 } 22884 } 22885 } else { 22886 initStartToken = lookahead; 22887 state.allowIn = false; 22888 init = inheritCoverGrammar(parseAssignmentExpression); 22889 state.allowIn = previousAllowIn; 22890 22891 if (matchKeyword('in')) { 22892 if (!isAssignmentTarget) { 22893 tolerateError(Messages.InvalidLHSInForIn); 22894 } 22895 22896 lex(); 22897 reinterpretExpressionAsPattern(init); 22898 left = init; 22899 right = parseExpression(); 22900 init = null; 22901 } else if (matchContextualKeyword('of')) { 22902 if (!isAssignmentTarget) { 22903 tolerateError(Messages.InvalidLHSInForLoop); 22904 } 22905 22906 lex(); 22907 reinterpretExpressionAsPattern(init); 22908 left = init; 22909 right = parseAssignmentExpression(); 22910 init = null; 22911 forIn = false; 22912 } else { 22913 if (match(',')) { 22914 initSeq = [init]; 22915 while (match(',')) { 22916 lex(); 22917 initSeq.push(isolateCoverGrammar(parseAssignmentExpression)); 22918 } 22919 init = new WrappingNode(initStartToken).finishSequenceExpression(initSeq); 22920 } 22921 expect(';'); 22922 } 22923 } 22924 } 22925 22926 if (typeof left === 'undefined') { 22927 22928 if (!match(';')) { 22929 test = parseExpression(); 22930 } 22931 expect(';'); 22932 22933 if (!match(')')) { 22934 update = parseExpression(); 22935 } 22936 } 22937 22938 expect(')'); 22939 22940 oldInIteration = state.inIteration; 22941 state.inIteration = true; 22942 22943 body = isolateCoverGrammar(parseStatement); 22944 22945 state.inIteration = oldInIteration; 22946 22947 return (typeof left === 'undefined') ? 22948 node.finishForStatement(init, test, update, body) : 22949 forIn ? node.finishForInStatement(left, right, body) : 22950 node.finishForOfStatement(left, right, body); 22951 } 22952 22953 // ECMA-262 13.8 The continue statement 22954 22955 function parseContinueStatement(node) { 22956 var label = null, key; 22957 22958 expectKeyword('continue'); 22959 22960 // Optimize the most common form: 'continue;'. 22961 if (source.charCodeAt(startIndex) === 0x3B) { 22962 lex(); 22963 22964 if (!state.inIteration) { 22965 throwError(Messages.IllegalContinue); 22966 } 22967
22968 return node.finishContinueStatement(null); 22969 } 22970 22971 if (hasLineTerminator) { 22972 if (!state.inIteration) { 22973 throwError(Messages.IllegalContinue); 22974 } 22975 22976 return node.finishContinueStatement(null); 22977 } 22978 22979 if (lookahead.type === Token.Identifier) { 22980 label = parseVariableIdentifier(); 22981 22982 key = '$' + label.name; 22983 if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { 22984 throwError(Messages.UnknownLabel, label.name); 22985 } 22986 } 22987 22988 consumeSemicolon(); 22989 22990 if (label === null && !state.inIteration) { 22991 throwError(Messages.IllegalContinue); 22992 } 22993 22994 return node.finishContinueStatement(label); 22995 } 22996 22997 // ECMA-262 13.9 The break statement 22998 22999 function parseBreakStatement(node) { 23000 var label = null, key; 23001 23002 expectKeyword('break'); 23003 23004 // Catch the very common case first: immediately a semicolon (U+003B). 23005 if (source.charCodeAt(lastIndex) === 0x3B) { 23006 lex(); 23007 23008 if (!(state.inIteration || state.inSwitch)) { 23009 throwError(Messages.IllegalBreak); 23010 } 23011 23012 return node.finishBreakStatement(null); 23013 } 23014 23015 if (hasLineTerminator) { 23016 if (!(state.inIteration || state.inSwitch)) { 23017 throwError(Messages.IllegalBreak); 23018 } 23019 } else if (lookahead.type === Token.Identifier) { 23020 label = parseVariableIdentifier(); 23021 23022 key = '$' + label.name; 23023 if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { 23024 throwError(Messages.UnknownLabel, label.name); 23025 } 23026 } 23027 23028 consumeSemicolon(); 23029 23030 if (label === null && !(state.inIteration || state.inSwitch)) { 23031 throwError(Messages.IllegalBreak); 23032 } 23033 23034 return node.finishBreakStatement(label); 23035 } 23036 23037 // ECMA-262 13.10 The return statement 23038
23039 function parseReturnStatement(node) { 23040 var argument = null; 23041 23042 expectKeyword('return'); 23043 23044 if (!state.inFunctionBody) { 23045 tolerateError(Messages.IllegalReturn); 23046 } 23047 23048 // 'return' followed by a space and an identifier is very common. 23049 if (source.charCodeAt(lastIndex) === 0x20) { 23050 if (isIdentifierStart(source.charCodeAt(lastIndex + 1))) { 23051 argument = parseExpression(); 23052 consumeSemicolon(); 23053 return node.finishReturnStatement(argument); 23054 } 23055 } 23056 23057 if (hasLineTerminator) { 23058 // HACK 23059 return node.finishReturnStatement(null); 23060 } 23061 23062 if (!match(';')) { 23063 if (!match('}') && lookahead.type !== Token.EOF) { 23064 argument = parseExpression(); 23065 } 23066 } 23067 23068 consumeSemicolon(); 23069 23070 return node.finishReturnStatement(argument); 23071 } 23072 23073 // ECMA-262 13.11 The with statement 23074 23075 function parseWithStatement(node) { 23076 var object, body; 23077 23078 if (strict) { 23079 tolerateError(Messages.StrictModeWith); 23080 } 23081 23082 expectKeyword('with'); 23083 23084 expect('('); 23085 23086 object = parseExpression(); 23087 23088 expect(')'); 23089 23090 body = parseStatement(); 23091 23092 return node.finishWithStatement(object, body); 23093 } 23094 23095 // ECMA-262 13.12 The switch statement 23096 23097 function parseSwitchCase() { 23098 var test, consequent = [], statement, node = new Node(); 23099 23100 if (matchKeyword('default')) { 23101 lex(); 23102 test = null; 23103 } else { 23104 expectKeyword('case'); 23105 test = parseExpression(); 23106 } 23107 expect(':'); 23108 23109 while (startIndex < length) { 23110 if (match('}') || matchKeyword('default') || matchKeyword('case')) { 23111 break; 23112 } 23113 statement = parseStatementListItem(); 23114 consequent.push(statement); 23115 } 23116 23117 return node.finishSwitchCase(test, consequent); 23118 } 23119 23120 function parseSwitchStatement(node) { 23121 var discriminant, cases, clause, oldInSwitch, defaultFound; 23122 23123 expectKeyword('switch'); 23124 23125 expect('('); 23126 23127 discriminant = parseExpression(); 23128 23129 expect(')'); 23130 23131 expect('{'); 23132 23133 cases = []; 23134 23135 if (match('}')) { 23136 lex(); 23137 return node.finishSwitchStatement(discriminant, cases); 23138 } 23139 23140 oldInSwitch = state.inSwitch; 23141 state.inSwitch = true; 23142 defaultFound = false; 23143 23144 while (startIndex < length) { 23145 if (match('}')) { 23146 break; 23147 } 23148 clause = parseSwitchCase(); 23149 if (clause.test === null) { 23150 if (defaultFound) { 23151 throwError(Messages.MultipleDefaultsInSwitch); 23152 } 23153 defaultFound = true; 23154 } 23155 cases.push(clause); 23156 } 23157 23158 state.inSwitch = oldInSwitch; 23159 23160 expect('}'); 23161 23162 return node.finishSwitchStatement(discriminant, cases); 23163 } 23164 23165 // ECMA-262 13.14 The throw statement 23166 23167 function parseThrowStatement(node) { 23168 var argument; 23169 23170 expectKeyword('throw'); 23171 23172 if (hasLineTerminator) { 23173 throwError(Messages.NewlineAfterThrow); 23174 } 23175 23176 argument = parseExpression(); 23177 23178 consumeSemicolon(); 23179 23180 return node.finishThrowStatement(argument); 23181 } 23182 23183 // ECMA-262 13.15 The try statement 23184 23185 function parseCatchClause() { 23186 var param, params = [], paramMap = {}, key, i, body, node = new Node(); 23187 23188 expectKeyword('catch'); 23189 23190 expect('('); 23191 if (match(')')) { 23192 throwUnexpectedToken(lookahead); 23193 } 23194 23195 param = parsePattern(params); 23196 for (i = 0; i < params.length; i++) { 23197 key = '$' + params[i].value; 23198 if (Object.prototype.hasOwnProperty.call(paramMap, key)) { 23199 tolerateError(Messages.DuplicateBinding, params[i].value); 23200 } 23201 paramMap[key] = true; 23202 } 23203 23204 // ECMA-262 12.14.1 23205 if (strict && isRestrictedWord(param.name)) { 23206 tolerateError(Messages.StrictCatchVariable); 23207 } 23208 23209 expect(')'); 23210 body = parseBlock(); 23211 return node.finishCatchClause(param, body); 23212 } 23213
23214 function parseTryStatement(node) { 23215 var block, handler = null, finalizer = null; 23216 23217 expectKeyword('try'); 23218 23219 block = parseBlock(); 23220 23221 if (matchKeyword('catch')) { 23222 handler = parseCatchClause(); 23223 } 23224 23225 if (matchKeyword('finally')) { 23226 lex(); 23227 finalizer = parseBlock(); 23228 } 23229 23230 if (!handler && !finalizer) { 23231 throwError(Messages.NoCatchOrFinally); 23232 } 23233 23234 return node.finishTryStatement(block, handler, finalizer); 23235 } 23236 23237 // ECMA-262 13.16 The debugger statement 23238 23239 function parseDebuggerStatement(node) { 23240 expectKeyword('debugger'); 23241 23242 consumeSemicolon(); 23243 23244 return node.finishDebuggerStatement(); 23245 } 23246 23247 // 13 Statements 23248 23249 function parseStatement() { 23250 var type = lookahead.type, 23251 expr, 23252 labeledBody, 23253 key, 23254 node; 23255 23256 if (type === Token.EOF) { 23257 throwUnexpectedToken(lookahead); 23258 } 23259 23260 if (type === Token.Punctuator && lookahead.value === '{') { 23261 return parseBlock(); 23262 } 23263 isAssignmentTarget = isBindingElement = true; 23264 node = new Node(); 23265 23266 if (type === Token.Punctuator) { 23267 switch (lookahead.value) { 23268 case ';': 23269 return parseEmptyStatement(node); 23270 case '(': 23271 return parseExpressionStatement(node); 23272 default: 23273 break; 23274 } 23275 } else if (type === Token.Keyword) { 23276 switch (lookahead.value) { 23277 case 'break': 23278 return parseBreakStatement(node); 23279 case 'continue': 23280 return parseContinueStatement(node); 23281 case 'debugger': 23282 return parseDebuggerStatement(node); 23283 case 'do': 23284 return parseDoWhileStatement(node); 23285 case 'for': 23286 return parseForStatement(node); 23287 case 'function': 23288 return parseFunctionDeclaration(node); 23289 case 'if': 23290 return parseIfStatement(node); 23291 case 'return':
23292 return parseReturnStatement(node); 23293 case 'switch': 23294 return parseSwitchStatement(node); 23295 case 'throw': 23296 return parseThrowStatement(node); 23297 case 'try': 23298 return parseTryStatement(node); 23299 case 'var': 23300 return parseVariableStatement(node); 23301 case 'while': 23302 return parseWhileStatement(node); 23303 case 'with': 23304 return parseWithStatement(node); 23305 default: 23306 break; 23307 } 23308 } 23309 23310 expr = parseExpression(); 23311 23312 // ECMA-262 12.12 Labelled Statements 23313 if ((expr.type === Syntax.Identifier) && match(':')) { 23314 lex(); 23315 23316 key = '$' + expr.name; 23317 if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) { 23318 throwError(Messages.Redeclaration, 'Label', expr.name); 23319 } 23320 23321 state.labelSet[key] = true; 23322 labeledBody = parseStatement(); 23323 delete state.labelSet[key]; 23324 return node.finishLabeledStatement(expr, labeledBody); 23325 } 23326 23327 consumeSemicolon(); 23328 23329 return node.finishExpressionStatement(expr); 23330 } 23331 23332 // ECMA-262 14.1 Function Definition 23333 23334 function parseFunctionSourceElements() { 23335 var statement, body = [], token, directive, firstRestricted, 23336 oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, 23337 node = new Node(); 23338 23339 expect('{'); 23340 23341 while (startIndex < length) { 23342 if (lookahead.type !== Token.StringLiteral) { 23343 break; 23344 } 23345 token = lookahead; 23346 23347 statement = parseStatementListItem(); 23348 body.push(statement); 23349 if (statement.expression.type !== Syntax.Literal) { 23350 // this is not directive 23351 break; 23352 } 23353 directive = source.slice(token.start + 1, token.end - 1); 23354 if (directive === 'use strict') { 23355 strict = true; 23356 if (firstRestricted) { 23357 tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral); 23358 } 23359 } else { 23360 if (!firstRestricted && token.octal) { 23361 firstRestricted = token; 23362 } 23363 } 23364 } 23365 23366 oldLabelSet = state.labelSet; 23367 oldInIteration = state.inIteration; 23368 oldInSwitch = state.inSwitch; 23369 oldInFunctionBody = state.inFunctionBody; 23370 23371 state.labelSet = {}; 23372 state.inIteration = false; 23373 state.inSwitch = false; 23374 state.inFunctionBody = true; 23375 23376 while (startIndex < length) { 23377 if (match('}')) { 23378 break; 23379 } 23380 body.push(parseStatementListItem()); 23381 } 23382 23383 expect('}'); 23384 23385 state.labelSet = oldLabelSet; 23386 state.inIteration = oldInIteration; 23387 state.inSwitch = oldInSwitch; 23388 state.inFunctionBody = oldInFunctionBody; 23389 23390 return node.finishBlockStatement(body); 23391 } 23392 23393 function validateParam(options, param, name) { 23394 var key = '$' + name; 23395 if (strict) { 23396 if (isRestrictedWord(name)) { 23397 options.stricted = param; 23398 options.message = Messages.StrictParamName; 23399 } 23400 if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { 23401 options.stricted = param; 23402 options.message = Messages.StrictParamDupe; 23403 } 23404 } else if (!options.firstRestricted) { 23405 if (isRestrictedWord(name)) { 23406 options.firstRestricted = param; 23407 options.message = Messages.StrictParamName; 23408 } else if (isStrictModeReservedWord(name)) { 23409 options.firstRestricted = param; 23410 options.message = Messages.StrictReservedWord; 23411 } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { 23412 options.stricted = param; 23413 options.message = Messages.StrictParamDupe; 23414 } 23415 } 23416 options.paramSet[key] = true; 23417 } 23418 23419 function parseParam(options) { 23420 var token, param, params = [], i, def; 23421 23422 token = lookahead; 23423 if (token.value === '...') { 23424 param = parseRestElement(params); 23425 validateParam(options, param.argument, param.argument.name); 23426 options.params.push(param); 23427 options.defaults.push(null); 23428 return false;
23429 } 23430 23431 param = parsePatternWithDefault(params); 23432 for (i = 0; i < params.length; i++) { 23433 validateParam(options, params[i], params[i].value); 23434 } 23435 23436 if (param.type === Syntax.AssignmentPattern) { 23437 def = param.right; 23438 param = param.left; 23439 ++options.defaultCount; 23440 } 23441 23442 options.params.push(param); 23443 options.defaults.push(def); 23444 23445 return !match(')'); 23446 } 23447 23448 function parseParams(firstRestricted) { 23449 var options; 23450 23451 options = { 23452 params: [], 23453 defaultCount: 0, 23454 defaults: [], 23455 firstRestricted: firstRestricted 23456 }; 23457 23458 expect('('); 23459 23460 if (!match(')')) { 23461 options.paramSet = {}; 23462 while (startIndex < length) { 23463 if (!parseParam(options)) { 23464 break; 23465 } 23466 expect(','); 23467 } 23468 } 23469 23470 expect(')'); 23471 23472 if (options.defaultCount === 0) { 23473 options.defaults = []; 23474 } 23475 23476 return { 23477 params: options.params, 23478 defaults: options.defaults, 23479 stricted: options.stricted, 23480 firstRestricted: options.firstRestricted, 23481 message: options.message 23482 }; 23483 } 23484 23485 function parseFunctionDeclaration(node, identifierIsOptional) { 23486 var id = null, params = [], defaults = [], body, token, stricted, tmp, firstRestricted, message, previousStrict, 23487 isGenerator, previousAllowYield; 23488 23489 previousAllowYield = state.allowYield; 23490 23491 expectKeyword('function'); 23492 23493 isGenerator = match('*'); 23494 if (isGenerator) { 23495 lex(); 23496 } 23497 23498 if (!identifierIsOptional || !match('(')) { 23499 token = lookahead; 23500 id = parseVariableIdentifier(); 23501 if (strict) { 23502 if (isRestrictedWord(token.value)) { 23503 tolerateUnexpectedToken(token, Messages.StrictFunctionName); 23504 } 23505 } else { 23506 if (isRestrictedWord(token.value)) { 23507 firstRestricted = token; 23508 message = Messages.StrictFunctionName; 23509 } else if (isStrictModeReservedWord(token.value)) { 23510 firstRestricted = token; 23511 message = Messages.StrictReservedWord; 23512 } 23513 } 23514 } 23515 23516 state.allowYield = !isGenerator; 23517 tmp = parseParams(firstRestricted); 23518 params = tmp.params; 23519 defaults = tmp.defaults; 23520 stricted = tmp.stricted; 23521 firstRestricted = tmp.firstRestricted; 23522 if (tmp.message) { 23523 message = tmp.message; 23524 } 23525 23526 23527 previousStrict = strict; 23528 body = parseFunctionSourceElements(); 23529 if (strict && firstRestricted) { 23530 throwUnexpectedToken(firstRestricted, message); 23531 } 23532 if (strict && stricted) { 23533 tolerateUnexpectedToken(stricted, message); 23534 } 23535 23536 strict = previousStrict; 23537 state.allowYield = previousAllowYield; 23538 23539 return node.finishFunctionDeclaration(id, params, defaults, body, isGenerator); 23540 } 23541 23542 function parseFunctionExpression() { 23543 var token, id = null, stricted, firstRestricted, message, tmp, 23544 params = [], defaults = [], body, previousStrict, node = new Node(), 23545 isGenerator, previousAllowYield; 23546 23547 previousAllowYield = state.allowYield; 23548 23549 expectKeyword('function'); 23550 23551 isGenerator = match('*'); 23552 if (isGenerator) { 23553 lex(); 23554 } 23555 23556 state.allowYield = !isGenerator; 23557 if (!match('(')) { 23558 token = lookahead; 23559 id = (!strict && !isGenerator && matchKeyword('yield')) ? parseNonComputedProperty() : parseVariableIdentifier(); 23560 if (strict) { 23561 if (isRestrictedWord(token.value)) { 23562 tolerateUnexpectedToken(token, Messages.StrictFunctionName); 23563 } 23564 } else { 23565 if (isRestrictedWord(token.value)) { 23566 firstRestricted = token; 23567 message = Messages.StrictFunctionName; 23568 } else if (isStrictModeReservedWord(token.value)) { 23569 firstRestricted = token; 23570 message = Messages.StrictReservedWord; 23571 } 23572 } 23573 } 23574 23575 tmp = parseParams(firstRestricted); 23576 params = tmp.params; 23577 defaults = tmp.defaults;
23578 stricted = tmp.stricted; 23579 firstRestricted = tmp.firstRestricted; 23580 if (tmp.message) { 23581 message = tmp.message; 23582 } 23583 23584 previousStrict = strict; 23585 body = parseFunctionSourceElements(); 23586 if (strict && firstRestricted) { 23587 throwUnexpectedToken(firstRestricted, message); 23588 } 23589 if (strict && stricted) { 23590 tolerateUnexpectedToken(stricted, message); 23591 } 23592 strict = previousStrict; 23593 state.allowYield = previousAllowYield; 23594 23595 return node.finishFunctionExpression(id, params, defaults, body, isGenerator); 23596 } 23597 23598 // ECMA-262 14.5 Class Definitions 23599 23600 function parseClassBody() { 23601 var classBody, token, isStatic, hasConstructor = false, body, method, computed, key; 23602 23603 classBody = new Node(); 23604 23605 expect('{'); 23606 body = []; 23607 while (!match('}')) { 23608 if (match(';')) { 23609 lex(); 23610 } else { 23611 method = new Node(); 23612 token = lookahead; 23613 isStatic = false; 23614 computed = match('['); 23615 if (match('*')) { 23616 lex(); 23617 } else { 23618 key = parseObjectPropertyKey(); 23619 if (key.name === 'static' && (lookaheadPropertyName() || match('*'))) { 23620 token = lookahead; 23621 isStatic = true; 23622 computed = match('['); 23623 if (match('*')) { 23624 lex(); 23625 } else { 23626 key = parseObjectPropertyKey(); 23627 } 23628 } 23629 } 23630 method = tryParseMethodDefinition(token, key, computed, method); 23631 if (method) { 23632 method['static'] = isStatic; // jscs:ignore requireDotNotation 23633 if (method.kind === 'init') { 23634 method.kind = 'method'; 23635 } 23636 if (!isStatic) { 23637 if (!method.computed && (method.key.name || method.key.value.toString()) === 'constructor') { 23638 if (method.kind !== 'method' || !method.method || method.value.generator) { 23639 throwUnexpectedToken(token, Messages.ConstructorSpecialMethod); 23640 } 23641 if (hasConstructor) { 23642 throwUnexpectedToken(token, Messages.DuplicateConstructor); 23643 } else { 23644 hasConstructor = true; 23645 } 23646 method.kind = 'constructor'; 23647 } 23648 } else { 23649 if (!method.computed && (method.key.name || method.key.value.toString()) === 'prototype') { 23650 throwUnexpectedToken(token, Messages.StaticPrototype); 23651 } 23652 } 23653 method.type = Syntax.MethodDefinition; 23654 delete method.method; 23655 delete method.shorthand; 23656 body.push(method); 23657 } else { 23658 throwUnexpectedToken(lookahead); 23659 } 23660 } 23661 } 23662 lex(); 23663 return classBody.finishClassBody(body); 23664 } 23665 23666 function parseClassDeclaration(identifierIsOptional) { 23667 var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict; 23668 strict = true; 23669 23670 expectKeyword('class'); 23671 23672 if (!identifierIsOptional || lookahead.type === Token.Identifier) { 23673 id = parseVariableIdentifier(); 23674 } 23675 23676 if (matchKeyword('extends')) { 23677 lex(); 23678 superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall); 23679 } 23680 classBody = parseClassBody(); 23681 strict = previousStrict; 23682 23683 return classNode.finishClassDeclaration(id, superClass, classBody); 23684 } 23685 23686 function parseClassExpression() { 23687 var id = null, superClass = null, classNode = new Node(), classBody, previousStrict = strict;
23688 strict = true; 23689 23690 expectKeyword('class'); 23691 23692 if (lookahead.type === Token.Identifier) { 23693 id = parseVariableIdentifier(); 23694 } 23695 23696 if (matchKeyword('extends')) { 23697 lex(); 23698 superClass = isolateCoverGrammar(parseLeftHandSideExpressionAllowCall); 23699 } 23700 classBody = parseClassBody(); 23701 strict = previousStrict; 23702 23703 return classNode.finishClassExpression(id, superClass, classBody); 23704 } 23705 23706 // ECMA-262 15.2 Modules 23707 23708 function parseModuleSpecifier() { 23709 var node = new Node(); 23710 23711 if (lookahead.type !== Token.StringLiteral) { 23712 throwError(Messages.InvalidModuleSpecifier); 23713 } 23714 return node.finishLiteral(lex()); 23715 } 23716 23717 // ECMA-262 15.2.3 Exports 23718 23719 function parseExportSpecifier() { 23720 var exported, local, node = new Node(), def; 23721 if (matchKeyword('default')) { 23722 // export {default} from 'something'; 23723 def = new Node(); 23724 lex(); 23725 local = def.finishIdentifier('default'); 23726 } else { 23727 local = parseVariableIdentifier(); 23728 } 23729 if (matchContextualKeyword('as')) { 23730 lex(); 23731 exported = parseNonComputedProperty(); 23732 } 23733 return node.finishExportSpecifier(local, exported); 23734 } 23735 23736 function parseExportNamedDeclaration(node) { 23737 var declaration = null, 23738 isExportFromIdentifier, 23739 src = null, specifiers = []; 23740 23741 // non-default export 23742 if (lookahead.type === Token.Keyword) { 23743 // covers: 23744 // export var f = 1; 23745 switch (lookahead.value) { 23746 case 'let': 23747 case 'const': 23748 declaration = parseLexicalDeclaration({inFor: false}); 23749 return node.finishExportNamedDeclaration(declaration, specifiers, null); 23750 case 'var': 23751 case 'class': 23752 case 'function': 23753 declaration = parseStatementListItem(); 23754 return node.finishExportNamedDeclaration(declaration, specifiers, null); 23755 } 23756 } 23757 23758 expect('{'); 23759 while (!match('}')) { 23760 isExportFromIdentifier = isExportFromIdentifier || matchKeyword('default'); 23761 specifiers.push(parseExportSpecifier()); 23762 if (!match('}')) { 23763 expect(','); 23764 if (match('}')) { 23765 break; 23766 } 23767 } 23768 } 23769 expect('}'); 23770 23771 if (matchContextualKeyword('from')) { 23772 // covering: 23773 // export {default} from 'foo'; 23774 // export {foo} from 'foo'; 23775 lex(); 23776 src = parseModuleSpecifier(); 23777 consumeSemicolon(); 23778 } else if (isExportFromIdentifier) { 23779 // covering: 23780 // export {default}; // missing fromClause 23781 throwError(lookahead.value ? 23782 Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); 23783 } else { 23784 // cover 23785 // export {foo}; 23786 consumeSemicolon(); 23787 } 23788 return node.finishExportNamedDeclaration(declaration, specifiers, src); 23789 } 23790 23791 function parseExportDefaultDeclaration(node) { 23792 var declaration = null, 23793 expression = null; 23794 23795 // covers: 23796 // export default ... 23797 expectKeyword('default'); 23798 23799 if (matchKeyword('function')) { 23800 // covers: 23801 // export default function foo () {} 23802 // export default function () {} 23803 declaration = parseFunctionDeclaration(new Node(), true); 23804 return node.finishExportDefaultDeclaration(declaration); 23805 } 23806 if (matchKeyword('class')) { 23807 declaration = parseClassDeclaration(true); 23808 return node.finishExportDefaultDeclaration(declaration); 23809 } 23810 23811 if (matchContextualKeyword('from')) { 23812 throwError(Messages.UnexpectedToken, lookahead.value); 23813 } 23814 23815 // covers: 23816 // export default {}; 23817 // export default []; 23818 // export default (1 + 2); 23819 if (match('{')) { 23820 expression = parseObjectInitializer(); 23821 } else if (match('[')) { 23822 expression = parseArrayInitializer(); 23823 } else { 23824 expression = parseAssignmentExpression(); 23825 } 23826 consumeSemicolon(); 23827 return node.finishExportDefaultDeclaration(expression); 23828 } 23829 23830 function parseExportAllDeclaration(node) { 23831 var src; 23832 23833 // covers: 23834 // export * from 'foo'; 23835 expect('*'); 23836 if (!matchContextualKeyword('from')) { 23837 throwError(lookahead.value ? 23838 Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); 23839 } 23840 lex(); 23841 src = parseModuleSpecifier(); 23842 consumeSemicolon(); 23843 23844 return node.finishExportAllDeclaration(src); 23845 } 23846 23847 function parseExportDeclaration() { 23848 var node = new Node(); 23849 if (state.inFunctionBody) { 23850 throwError(Messages.IllegalExportDeclaration); 23851 } 23852 23853 expectKeyword('export'); 23854 23855 if (matchKeyword('default')) { 23856 return parseExportDefaultDeclaration(node); 23857 } 23858 if (match('*')) { 23859 return parseExportAllDeclaration(node); 23860 } 23861 return parseExportNamedDeclaration(node); 23862 } 23863 23864 // ECMA-262 15.2.2 Imports 23865 23866 function parseImportSpecifier() { 23867 // import {<foo as bar>} ...; 23868 var local, imported, node = new Node(); 23869 23870 imported = parseNonComputedProperty(); 23871 if (matchContextualKeyword('as')) { 23872 lex(); 23873 local = parseVariableIdentifier(); 23874 } 23875 23876 return node.finishImportSpecifier(local, imported); 23877 } 23878 23879 function parseNamedImports() { 23880 var specifiers = []; 23881 // {foo, bar as bas} 23882 expect('{'); 23883 while (!match('}')) { 23884 specifiers.push(parseImportSpecifier()); 23885 if (!match('}')) { 23886 expect(','); 23887 if (match('}')) { 23888 break; 23889 } 23890 } 23891 } 23892 expect('}'); 23893 return specifiers; 23894 } 23895 23896 function parseImportDefaultSpecifier() { 23897 // import <foo> ...; 23898 var local, node = new Node(); 23899 23900 local = parseNonComputedProperty(); 23901 23902 return node.finishImportDefaultSpecifier(local); 23903 } 23904 23905 function parseImportNamespaceSpecifier() { 23906 // import <* as foo> ...; 23907 var local, node = new Node(); 23908 23909 expect('*'); 23910 if (!matchContextualKeyword('as')) { 23911 throwError(Messages.NoAsAfterImportNamespace); 23912 } 23913 lex(); 23914 local = parseNonComputedProperty(); 23915 23916 return node.finishImportNamespaceSpecifier(local); 23917 } 23918 23919 function parseImportDeclaration() { 23920 var specifiers = [], src, node = new Node(); 23921 23922 if (state.inFunctionBody) { 23923 throwError(Messages.IllegalImportDeclaration); 23924 } 23925 23926 expectKeyword('import'); 23927 23928 if (lookahead.type === Token.StringLiteral) { 23929 // import 'foo'; 23930 src = parseModuleSpecifier(); 23931 } else { 23932 23933 if (match('{')) { 23934 // import {bar} 23935 specifiers = specifiers.concat(parseNamedImports()); 23936 } else if (match('*')) { 23937 // import * as foo 23938 specifiers.push(parseImportNamespaceSpecifier()); 23939 } else if (isIdentifierName(lookahead) && !matchKeyword('default')) { 23940 // import foo 23941 specifiers.push(parseImportDefaultSpecifier()); 23942 if (match(',')) { 23943 lex(); 23944 if (match('*')) { 23945 // import foo, * as foo 23946 specifiers.push(parseImportNamespaceSpecifier()); 23947 } else if (match('{')) { 23948 // import foo, {bar} 23949 specifiers = specifiers.concat(parseNamedImports()); 23950 } else { 23951 throwUnexpectedToken(lookahead); 23952 } 23953 } 23954 } else { 23955 throwUnexpectedToken(lex()); 23956 } 23957 23958 if (!matchContextualKeyword('from')) { 23959 throwError(lookahead.value ? 23960 Messages.UnexpectedToken : Messages.MissingFromClause, lookahead.value); 23961 } 23962 lex(); 23963 src = parseModuleSpecifier(); 23964 } 23965 23966 consumeSemicolon(); 23967 return node.finishImportDeclaration(specifiers, src); 23968 } 23969 23970 // ECMA-262 15.1 Scripts 23971 23972 function parseScriptBody() { 23973 var statement, body = [], token, directive, firstRestricted; 23974 23975 while (startIndex < length) { 23976 token = lookahead; 23977 if (token.type !== Token.StringLiteral) { 23978 break; 23979 } 23980 23981 statement = parseStatementListItem(); 23982 body.push(statement); 23983 if (statement.expression.type !== Syntax.Literal) { 23984 // this is not directive 23985 break; 23986 } 23987 directive = source.slice(token.start + 1, token.end - 1); 23988 if (directive === 'use strict') {
23989 strict = true; 23990 if (firstRestricted) { 23991 tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral); 23992 } 23993 } else { 23994 if (!firstRestricted && token.octal) { 23995 firstRestricted = token; 23996 } 23997 } 23998 } 23999 24000 while (startIndex < length) { 24001 statement = parseStatementListItem(); 24002 /* istanbul ignore if */ 24003 if (typeof statement === 'undefined') { 24004 break; 24005 } 24006 body.push(statement); 24007 } 24008 return body; 24009 } 24010 24011 function parseProgram() { 24012 var body, node; 24013 24014 peek(); 24015 node = new Node(); 24016 24017 body = parseScriptBody(); 24018 return node.finishProgram(body, state.sourceType); 24019 } 24020 24021 function filterTokenLocation() { 24022 var i, entry, token, tokens = []; 24023 24024 for (i = 0; i < extra.tokens.length; ++i) { 24025 entry = extra.tokens[i]; 24026 token = { 24027 type: entry.type, 24028 value: entry.value 24029 }; 24030 if (entry.regex) { 24031 token.regex = { 24032 pattern: entry.regex.pattern, 24033 flags: entry.regex.flags 24034 }; 24035 } 24036 if (extra.range) { 24037 token.range = entry.range; 24038 } 24039 if (extra.loc) { 24040 token.loc = entry.loc; 24041 } 24042 tokens.push(token); 24043 } 24044 24045 extra.tokens = tokens; 24046 } 24047 24048 function tokenize(code, options, delegate) { 24049 var toString, 24050 tokens; 24051 24052 toString = String; 24053 if (typeof code !== 'string' && !(code instanceof String)) { 24054 code = toString(code); 24055 } 24056 24057 source = code; 24058 index = 0; 24059 lineNumber = (source.length > 0) ? 1 : 0; 24060 lineStart = 0; 24061 startIndex = index; 24062 startLineNumber = lineNumber; 24063 startLineStart = lineStart; 24064 length = source.length; 24065 lookahead = null; 24066 state = { 24067 allowIn: true, 24068 allowYield: true, 24069 labelSet: {}, 24070 inFunctionBody: false, 24071 inIteration: false, 24072 inSwitch: false, 24073 lastCommentStart: -1, 24074 curlyStack: [] 24075 }; 24076 24077 extra = {}; 24078 24079 // Options matching. 24080 options = options || {}; 24081 24082 // Of course we collect tokens here. 24083 options.tokens = true; 24084 extra.tokens = []; 24085 extra.tokenValues = []; 24086 extra.tokenize = true; 24087 extra.delegate = delegate; 24088 24089 // The following two fields are necessary to compute the Regex tokens. 24090 extra.openParenToken = -1; 24091 extra.openCurlyToken = -1; 24092 24093 extra.range = (typeof options.range === 'boolean') && options.range; 24094 extra.loc = (typeof options.loc === 'boolean') && options.loc; 24095 24096 if (typeof options.comment === 'boolean' && options.comment) { 24097 extra.comments = []; 24098 } 24099 if (typeof options.tolerant === 'boolean' && options.tolerant) { 24100 extra.errors = []; 24101 } 24102 24103 try { 24104 peek(); 24105 if (lookahead.type === Token.EOF) { 24106 return extra.tokens; 24107 } 24108 24109 lex(); 24110 while (lookahead.type !== Token.EOF) { 24111 try { 24112 lex(); 24113 } catch (lexError) { 24114 if (extra.errors) { 24115 recordError(lexError); 24116 // We have to break on the first error 24117 // to avoid infinite loops. 24118 break; 24119 } else { 24120 throw lexError; 24121 } 24122 } 24123 } 24124 24125 tokens = extra.tokens; 24126 if (typeof extra.errors !== 'undefined') { 24127 tokens.errors = extra.errors; 24128 } 24129 } catch (e) { 24130 throw e; 24131 } finally { 24132 extra = {}; 24133 } 24134 return tokens; 24135 } 24136 24137 function parse(code, options) { 24138 var program, toString; 24139 24140 toString = String; 24141 if (typeof code !== 'string' && !(code instanceof String)) { 24142 code = toString(code); 24143 } 24144 24145 source = code; 24146 index = 0; 24147 lineNumber = (source.length > 0) ? 1 : 0; 24148 lineStart = 0; 24149 startIndex = index; 24150 startLineNumber = lineNumber; 24151 startLineStart = lineStart; 24152 length = source.length; 24153 lookahead = null; 24154 state = { 24155 allowIn: true, 24156 allowYield: true, 24157 labelSet: {}, 24158 inFunctionBody: false, 24159 inIteration: false, 24160 inSwitch: false, 24161 lastCommentStart: -1, 24162 curlyStack: [], 24163 sourceType: 'script' 24164 };
24165 strict = false; 24166 24167 extra = {}; 24168 if (typeof options !== 'undefined') { 24169 extra.range = (typeof options.range === 'boolean') && options.range; 24170 extra.loc = (typeof options.loc === 'boolean') && options.loc; 24171 extra.attachComment = (typeof options.attachComment === 'boolean') && options.attachComment; 24172 24173 if (extra.loc && options.source !== null && options.source !== undefined) { 24174 extra.source = toString(options.source); 24175 } 24176 24177 if (typeof options.tokens === 'boolean' && options.tokens) { 24178 extra.tokens = []; 24179 } 24180 if (typeof options.comment === 'boolean' && options.comment) { 24181 extra.comments = []; 24182 } 24183 if (typeof options.tolerant === 'boolean' && options.tolerant) { 24184 extra.errors = []; 24185 } 24186 if (extra.attachComment) { 24187 extra.range = true; 24188 extra.comments = []; 24189 extra.bottomRightStack = []; 24190 extra.trailingComments = []; 24191 extra.leadingComments = []; 24192 } 24193 if (options.sourceType === 'module') { 24194 // very restrictive condition for now 24195 state.sourceType = options.sourceType; 24196 strict = true; 24197 } 24198 } 24199 24200 try { 24201 program = parseProgram(); 24202 if (typeof extra.comments !== 'undefined') { 24203 program.comments = extra.comments; 24204 } 24205 if (typeof extra.tokens !== 'undefined') { 24206 filterTokenLocation(); 24207 program.tokens = extra.tokens; 24208 } 24209 if (typeof extra.errors !== 'undefined') { 24210 program.errors = extra.errors; 24211 } 24212 } catch (e) { 24213 throw e; 24214 } finally { 24215 extra = {}; 24216 } 24217 24218 return program; 24219 } 24220 24221 // Sync with *.json manifests. 24222 exports.version = '2.7.3'; 24223 24224 exports.tokenize = tokenize; 24225 24226 exports.parse = parse; 24227 24228 // Deep copy. 24229 /* istanbul ignore next */ 24230 exports.Syntax = (function () { 24231 var name, types = {}; 24232 24233 if (typeof Object.create === 'function') { 24234 types = Object.create(null); 24235 } 24236 24237 for (name in Syntax) { 24238 if (Syntax.hasOwnProperty(name)) { 24239 types[name] = Syntax[name]; 24240 } 24241 } 24242 24243 if (typeof Object.freeze === 'function') { 24244 Object.freeze(types); 24245 } 24246 24247 return types; 24248 }()); 24249 24250})); 24251/* vim: set sw=4 ts=4 et tw=80 : */ 24252 24253},{}],153:[function(require,module,exports){ 24254var stream = require('stream') 24255 24256module.exports = function(url, opts) { 24257 if (!opts) opts = {} 24258 24259 var es = new EventSource(url) 24260 var rs = new stream.Readable({objectMode:true}) 24261 24262 var json = !!opts.json 24263 var decode = function (data) { 24264 try { 24265 if (json) return JSON.parse(data) 24266 return data 24267 } catch (err) { 24268 return undefined 24269 } 24270 } 24271 24272 rs._read = function() {} 24273 24274 es.onmessage = function(e) { 24275 rs.push(decode(e.data)) 24276 } 24277 24278 es.onerror = function(err) { 24279 if (rs.listeners('error').length) rs.emit('error', err) 24280 } 24281 24282 es.onopen = function () { 24283 rs.emit('open') 24284 } 24285 24286 var destroyed = false 24287 rs.destroy = function() { 24288 if (destroyed) return 24289 destroyed = true 24290 es.close() 24291 rs.emit('close') 24292 } 24293 24294 return rs 24295} 24296},{"stream":237}],154:[function(require,module,exports){ 24297// Copyright Joyent, Inc. and other Node contributors. 24298// 24299// Permission is hereby granted, free of charge, to any person obtaining a 24300// copy of this software and associated documentation files (the 24301// "Software"), to deal in the Software without restriction, including 24302// without limitation the rights to use, copy, modify, merge, publish, 24303// distribute, sublicense, and/or sell copies of the Software, and to permit 24304// persons to whom the Software is furnished to do so, subject to the 24305// following conditions: 24306// 24307// The above copyright notice and this permission notice shall be included 24308// in all copies or substantial portions of the Software. 24309// 24310// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 24311// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 24312// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 24313// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 24314// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 24315// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 24316// USE OR OTHER DEALINGS IN THE SOFTWARE. 24317 24318function EventEmitter() { 24319 this._events = this._events || {}; 24320 this._maxListeners = this._maxListeners || undefined; 24321} 24322module.exports = EventEmitter; 24323 24324// Backwards-compat with node 0.10.x 24325EventEmitter.EventEmitter = EventEmitter; 24326 24327EventEmitter.prototype._events = undefined; 24328EventEmitter.prototype._maxListeners = undefined; 24329 24330// By default EventEmitters will print a warning if more than 10 listeners are 24331// added to it. This is a useful default which helps finding memory leaks. 24332EventEmitter.defaultMaxListeners = 10; 24333 24334// Obviously not all Emitters should be limited to 10. This function allows 24335// that to be increased. Set to zero for unlimited. 24336EventEmitter.prototype.setMaxListeners = function(n) { 24337 if (!isNumber(n) || n < 0 || isNaN(n)) 24338 throw TypeError('n must be a positive number'); 24339 this._maxListeners = n; 24340 return this; 24341}; 24342 24343EventEmitter.prototype.emit = function(type) { 24344 var er, handler, len, args, i, listeners; 24345 24346 if (!this._events) 24347 this._events = {}; 24348 24349 // If there is no 'error' event listener then throw. 24350 if (type === 'error') { 24351 if (!this._events.error || 24352 (isObject(this._events.error) && !this._events.error.length)) { 24353 er = arguments[1]; 24354 if (er instanceof Error) { 24355 throw er; // Unhandled 'error' event 24356 } else { 24357 // At least give some kind of context to the user 24358 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); 24359 err.context = er; 24360 throw err; 24361 } 24362 } 24363 } 24364 24365 handler = this._events[type]; 24366 24367 if (isUndefined(handler)) 24368 return false;
vendor: 6,096 bytes, lines 24369-24617
24369 24370 if (isFunction(handler)) { 24371 switch (arguments.length) { 24372 // fast cases 24373 case 1: 24374 handler.call(this); 24375 break; 24376 case 2: 24377 handler.call(this, arguments[1]); 24378 break; 24379 case 3: 24380 handler.call(this, arguments[1], arguments[2]); 24381 break; 24382 // slower 24383 default: 24384 args = Array.prototype.slice.call(arguments, 1); 24385 handler.apply(this, args); 24386 } 24387 } else if (isObject(handler)) { 24388 args = Array.prototype.slice.call(arguments, 1); 24389 listeners = handler.slice(); 24390 len = listeners.length; 24391 for (i = 0; i < len; i++) 24392 listeners[i].apply(this, args); 24393 } 24394 24395 return true; 24396}; 24397 24398EventEmitter.prototype.addListener = function(type, listener) { 24399 var m; 24400 24401 if (!isFunction(listener)) 24402 throw TypeError('listener must be a function'); 24403 24404 if (!this._events) 24405 this._events = {}; 24406 24407 // To avoid recursion in the case that type === "newListener"! Before 24408 // adding it to the listeners, first emit "newListener". 24409 if (this._events.newListener) 24410 this.emit('newListener', type, 24411 isFunction(listener.listener) ? 24412 listener.listener : listener); 24413 24414 if (!this._events[type]) 24415 // Optimize the case of one listener. Don't need the extra array object. 24416 this._events[type] = listener; 24417 else if (isObject(this._events[type])) 24418 // If we've already got an array, just append. 24419 this._events[type].push(listener); 24420 else 24421 // Adding the second element, need to change to array. 24422 this._events[type] = [this._events[type], listener]; 24423 24424 // Check for listener leak 24425 if (isObject(this._events[type]) && !this._events[type].warned) { 24426 if (!isUndefined(this._maxListeners)) { 24427 m = this._maxListeners; 24428 } else { 24429 m = EventEmitter.defaultMaxListeners; 24430 } 24431 24432 if (m && m > 0 && this._events[type].length > m) { 24433 this._events[type].warned = true; 24434 console.error('(node) warning: possible EventEmitter memory ' + 24435 'leak detected. %d listeners added. ' + 24436 'Use emitter.setMaxListeners() to increase limit.', 24437 this._events[type].length); 24438 if (typeof console.trace === 'function') { 24439 // not supported in IE 10 24440 console.trace(); 24441 } 24442 } 24443 } 24444 24445 return this; 24446}; 24447 24448EventEmitter.prototype.on = EventEmitter.prototype.addListener; 24449 24450EventEmitter.prototype.once = function(type, listener) { 24451 if (!isFunction(listener)) 24452 throw TypeError('listener must be a function'); 24453 24454 var fired = false; 24455 24456 function g() { 24457 this.removeListener(type, g); 24458 24459 if (!fired) { 24460 fired = true; 24461 listener.apply(this, arguments); 24462 } 24463 } 24464 24465 g.listener = listener; 24466 this.on(type, g); 24467 24468 return this; 24469}; 24470 24471// emits a 'removeListener' event iff the listener was removed 24472EventEmitter.prototype.removeListener = function(type, listener) { 24473 var list, position, length, i; 24474 24475 if (!isFunction(listener)) 24476 throw TypeError('listener must be a function'); 24477 24478 if (!this._events || !this._events[type]) 24479 return this; 24480 24481 list = this._events[type]; 24482 length = list.length; 24483 position = -1; 24484 24485 if (list === listener || 24486 (isFunction(list.listener) && list.listener === listener)) { 24487 delete this._events[type]; 24488 if (this._events.removeListener) 24489 this.emit('removeListener', type, listener); 24490 24491 } else if (isObject(list)) { 24492 for (i = length; i-- > 0;) { 24493 if (list[i] === listener || 24494 (list[i].listener && list[i].listener === listener)) { 24495 position = i; 24496 break; 24497 } 24498 } 24499 24500 if (position < 0) 24501 return this; 24502 24503 if (list.length === 1) { 24504 list.length = 0; 24505 delete this._events[type]; 24506 } else { 24507 list.splice(position, 1); 24508 } 24509 24510 if (this._events.removeListener) 24511 this.emit('removeListener', type, listener); 24512 } 24513 24514 return this; 24515}; 24516 24517EventEmitter.prototype.removeAllListeners = function(type) { 24518 var key, listeners; 24519 24520 if (!this._events) 24521 return this; 24522 24523 // not listening for removeListener, no need to emit 24524 if (!this._events.removeListener) { 24525 if (arguments.length === 0) 24526 this._events = {}; 24527 else if (this._events[type]) 24528 delete this._events[type]; 24529 return this; 24530 } 24531 24532 // emit removeListener for all listeners on all events 24533 if (arguments.length === 0) { 24534 for (key in this._events) { 24535 if (key === 'removeListener') continue; 24536 this.removeAllListeners(key); 24537 } 24538 this.removeAllListeners('removeListener'); 24539 this._events = {}; 24540 return this; 24541 } 24542 24543 listeners = this._events[type]; 24544 24545 if (isFunction(listeners)) { 24546 this.removeListener(type, listeners); 24547 } else if (listeners) { 24548 // LIFO order 24549 while (listeners.length) 24550 this.removeListener(type, listeners[listeners.length - 1]); 24551 } 24552 delete this._events[type]; 24553 24554 return this; 24555}; 24556 24557EventEmitter.prototype.listeners = function(type) { 24558 var ret; 24559 if (!this._events || !this._events[type]) 24560 ret = []; 24561 else if (isFunction(this._events[type])) 24562 ret = [this._events[type]]; 24563 else 24564 ret = this._events[type].slice(); 24565 return ret; 24566}; 24567 24568EventEmitter.prototype.listenerCount = function(type) { 24569 if (this._events) { 24570 var evlistener = this._events[type]; 24571 24572 if (isFunction(evlistener)) 24573 return 1; 24574 else if (evlistener) 24575 return evlistener.length; 24576 } 24577 return 0; 24578}; 24579 24580EventEmitter.listenerCount = function(emitter, type) { 24581 return emitter.listenerCount(type); 24582}; 24583 24584function isFunction(arg) { 24585 return typeof arg === 'function'; 24586} 24587 24588function isNumber(arg) { 24589 return typeof arg === 'number'; 24590} 24591 24592function isObject(arg) { 24593 return typeof arg === 'object' && arg !== null; 24594} 24595 24596function isUndefined(arg) { 24597 return arg === void 0; 24598} 24599 24600},{}],155:[function(require,module,exports){ 24601var isFunction = require('is-function') 24602 24603module.exports = forEach 24604 24605var toString = Object.prototype.toString 24606var hasOwnProperty = Object.prototype.hasOwnProperty 24607 24608function forEach(list, iterator, context) { 24609 if (!isFunction(iterator)) { 24610 throw new TypeError('iterator must be a function') 24611 } 24612 24613 if (arguments.length < 3) { 24614 context = this 24615 } 24616 24617 if (toString.call(list) === '[object Array]')
24618 forEachArray(list, iterator, context) 24619 else if (typeof list === 'string') 24620 forEachString(list, iterator, context) 24621 else 24622 forEachObject(list, iterator, context) 24623} 24624 24625function forEachArray(array, iterator, context) { 24626 for (var i = 0, len = array.length; i < len; i++) { 24627 if (hasOwnProperty.call(array, i)) { 24628 iterator.call(context, array[i], i, array) 24629 } 24630 } 24631} 24632 24633function forEachString(string, iterator, context) { 24634 for (var i = 0, len = string.length; i < len; i++) { 24635 // no such thing as a sparse string. 24636 iterator.call(context, string.charAt(i), i, string) 24637 } 24638} 24639 24640function forEachObject(object, iterator, context) { 24641 for (var k in object) { 24642 if (hasOwnProperty.call(object, k)) { 24643 iterator.call(context, object[k], k, object) 24644 } 24645 } 24646} 24647 24648},{"is-function":169}],156:[function(require,module,exports){ 24649// originally pulled out of simple-peer 24650 24651module.exports = function getBrowserRTC () { 24652 if (typeof window === 'undefined') return null 24653 var wrtc = { 24654 RTCPeerConnection: window.RTCPeerConnection || window.mozRTCPeerConnection || 24655 window.webkitRTCPeerConnection, 24656 RTCSessionDescription: window.RTCSessionDescription || 24657 window.mozRTCSessionDescription || window.webkitRTCSessionDescription, 24658 RTCIceCandidate: window.RTCIceCandidate || window.mozRTCIceCandidate || 24659 window.webkitRTCIceCandidate 24660 } 24661 if (!wrtc.RTCPeerConnection) return null 24662 return wrtc 24663} 24664 24665},{}],157:[function(require,module,exports){ 24666(function (global){ 24667var topLevel = typeof global !== 'undefined' ? global : 24668 typeof window !== 'undefined' ? window : {} 24669var minDoc = require('min-document'); 24670 24671if (typeof document !== 'undefined') { 24672 module.exports = document; 24673} else { 24674 var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; 24675 24676 if (!doccy) { 24677 doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; 24678 } 24679 24680 module.exports = doccy; 24681} 24682 24683}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 24684},{"min-document":83}],158:[function(require,module,exports){ 24685(function (global){ 24686if (typeof window !== "undefined") { 24687 module.exports = window; 24688} else if (typeof global !== "undefined") { 24689 module.exports = global; 24690} else if (typeof self !== "undefined"){ 24691 module.exports = self; 24692} else { 24693 module.exports = {}; 24694} 24695 24696}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 24697},{}],159:[function(require,module,exports){ 24698module.exports = require('./lib/heap'); 24699 24700},{"./lib/heap":160}],160:[function(require,module,exports){ 24701// Generated by CoffeeScript 1.8.0 24702(function() { 24703 var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup; 24704 24705 floor = Math.floor, min = Math.min; 24706 24707 24708 /* 24709 Default comparison function to be used 24710 */ 24711 24712 defaultCmp = function(x, y) { 24713 if (x < y) { 24714 return -1; 24715 } 24716 if (x > y) { 24717 return 1; 24718 } 24719 return 0; 24720 }; 24721 24722 24723 /* 24724 Insert item x in list a, and keep it sorted assuming a is sorted. 24725 24726 If x is already in a, insert it to the right of the rightmost x. 24727 24728 Optional args lo (default 0) and hi (default a.length) bound the slice 24729 of a to be searched. 24730 */ 24731 24732 insort = function(a, x, lo, hi, cmp) { 24733 var mid; 24734 if (lo == null) { 24735 lo = 0; 24736 } 24737 if (cmp == null) { 24738 cmp = defaultCmp; 24739 } 24740 if (lo < 0) { 24741 throw new Error('lo must be non-negative'); 24742 } 24743 if (hi == null) { 24744 hi = a.length; 24745 } 24746 while (lo < hi) { 24747 mid = floor((lo + hi) / 2); 24748 if (cmp(x, a[mid]) < 0) { 24749 hi = mid; 24750 } else { 24751 lo = mid + 1; 24752 } 24753 } 24754 return ([].splice.apply(a, [lo, lo - lo].concat(x)), x); 24755 }; 24756 24757 24758 /* 24759 Push item onto heap, maintaining the heap invariant. 24760 */ 24761 24762 heappush = function(array, item, cmp) { 24763 if (cmp == null) { 24764 cmp = defaultCmp; 24765 } 24766 array.push(item); 24767 return _siftdown(array, 0, array.length - 1, cmp); 24768 }; 24769 24770 24771 /* 24772 Pop the smallest item off the heap, maintaining the heap invariant. 24773 */ 24774 24775 heappop = function(array, cmp) { 24776 var lastelt, returnitem; 24777 if (cmp == null) { 24778 cmp = defaultCmp; 24779 } 24780 lastelt = array.pop(); 24781 if (array.length) { 24782 returnitem = array[0]; 24783 array[0] = lastelt; 24784 _siftup(array, 0, cmp); 24785 } else { 24786 returnitem = lastelt; 24787 } 24788 return returnitem; 24789 }; 24790 24791 24792 /* 24793 Pop and return the current smallest value, and add the new item. 24794 24795 This is more efficient than heappop() followed by heappush(), and can be 24796 more appropriate when using a fixed size heap. Note that the value 24797 returned may be larger than item! That constrains reasonable use of 24798 this routine unless written as part of a conditional replacement: 24799 if item > array[0] 24800 item = heapreplace(array, item) 24801 */ 24802 24803 heapreplace = function(array, item, cmp) { 24804 var returnitem; 24805 if (cmp == null) { 24806 cmp = defaultCmp; 24807 } 24808 returnitem = array[0]; 24809 array[0] = item; 24810 _siftup(array, 0, cmp); 24811 return returnitem; 24812 }; 24813 24814 24815 /* 24816 Fast version of a heappush followed by a heappop. 24817 */ 24818 24819 heappushpop = function(array, item, cmp) { 24820 var _ref; 24821 if (cmp == null) { 24822 cmp = defaultCmp; 24823 } 24824 if (array.length && cmp(array[0], item) < 0) { 24825 _ref = [array[0], item], item = _ref[0], array[0] = _ref[1]; 24826 _siftup(array, 0, cmp); 24827 } 24828 return item; 24829 }; 24830 24831 24832 /* 24833 Transform list into a heap, in-place, in O(array.length) time. 24834 */ 24835 24836 heapify = function(array, cmp) { 24837 var i, _i, _j, _len, _ref, _ref1, _results, _results1; 24838 if (cmp == null) { 24839 cmp = defaultCmp; 24840 } 24841 _ref1 = (function() { 24842 _results1 = []; 24843 for (var _j = 0, _ref = floor(array.length / 2); 0 <= _ref ? _j < _ref : _j > _ref; 0 <= _ref ? _j++ : _j--){ _results1.push(_j); } 24844 return _results1; 24845 }).apply(this).reverse(); 24846 _results = []; 24847 for (_i = 0, _len = _ref1.length; _i < _len; _i++) { 24848 i = _ref1[_i]; 24849 _results.push(_siftup(array, i, cmp)); 24850 } 24851 return _results; 24852 }; 24853 24854 24855 /* 24856 Update the position of the given item in the heap. 24857 This function should be called every time the item is being modified. 24858 */ 24859 24860 updateItem = function(array, item, cmp) { 24861 var pos; 24862 if (cmp == null) { 24863 cmp = defaultCmp; 24864 } 24865 pos = array.indexOf(item); 24866 if (pos === -1) { 24867 return; 24868 } 24869 _siftdown(array, 0, pos, cmp); 24870 return _siftup(array, pos, cmp); 24871 }; 24872 24873 24874 /* 24875 Find the n largest elements in a dataset. 24876 */ 24877 24878 nlargest = function(array, n, cmp) { 24879 var elem, result, _i, _len, _ref; 24880 if (cmp == null) { 24881 cmp = defaultCmp; 24882 } 24883 result = array.slice(0, n); 24884 if (!result.length) { 24885 return result; 24886 } 24887 heapify(result, cmp); 24888 _ref = array.slice(n); 24889 for (_i = 0, _len = _ref.length; _i < _len; _i++) { 24890 elem = _ref[_i]; 24891 heappushpop(result, elem, cmp); 24892 } 24893 return result.sort(cmp).reverse(); 24894 }; 24895 24896 24897 /* 24898 Find the n smallest elements in a dataset. 24899 */ 24900 24901 nsmallest = function(array, n, cmp) { 24902 var elem, i, los, result, _i, _j, _len, _ref, _ref1, _results; 24903 if (cmp == null) { 24904 cmp = defaultCmp; 24905 } 24906 if (n * 10 <= array.length) { 24907 result = array.slice(0, n).sort(cmp); 24908 if (!result.length) { 24909 return result; 24910 } 24911 los = result[result.length - 1]; 24912 _ref = array.slice(n); 24913 for (_i = 0, _len = _ref.length; _i < _len; _i++) { 24914 elem = _ref[_i]; 24915 if (cmp(elem, los) < 0) { 24916 insort(result, elem, 0, null, cmp); 24917 result.pop(); 24918 los = result[result.length - 1]; 24919 } 24920 } 24921 return result; 24922 } 24923 heapify(array, cmp); 24924 _results = []; 24925 for (i = _j = 0, _ref1 = min(n, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i = 0 <= _ref1 ? ++_j : --_j) { 24926 _results.push(heappop(array, cmp)); 24927 } 24928 return _results; 24929 }; 24930 24931 _siftdown = function(array, startpos, pos, cmp) { 24932 var newitem, parent, parentpos; 24933 if (cmp == null) { 24934 cmp = defaultCmp; 24935 } 24936 newitem = array[pos]; 24937 while (pos > startpos) { 24938 parentpos = (pos - 1) >> 1; 24939 parent = array[parentpos]; 24940 if (cmp(newitem, parent) < 0) { 24941 array[pos] = parent; 24942 pos = parentpos; 24943 continue; 24944 } 24945 break; 24946 } 24947 return array[pos] = newitem; 24948 }; 24949 24950 _siftup = function(array, pos, cmp) { 24951 var childpos, endpos, newitem, rightpos, startpos; 24952 if (cmp == null) { 24953 cmp = defaultCmp; 24954 } 24955 endpos = array.length; 24956 startpos = pos; 24957 newitem = array[pos]; 24958 childpos = 2 * pos + 1; 24959 while (childpos < endpos) { 24960 rightpos = childpos + 1; 24961 if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) { 24962 childpos = rightpos; 24963 } 24964 array[pos] = array[childpos]; 24965 pos = childpos; 24966 childpos = 2 * pos + 1; 24967 } 24968 array[pos] = newitem; 24969 return _siftdown(array, startpos, pos, cmp); 24970 }; 24971 24972 Heap = (function() { 24973 Heap.push = heappush; 24974 24975 Heap.pop = heappop; 24976 24977 Heap.replace = heapreplace; 24978 24979 Heap.pushpop = heappushpop; 24980 24981 Heap.heapify = heapify; 24982 24983 Heap.updateItem = updateItem; 24984 24985 Heap.nlargest = nlargest; 24986 24987 Heap.nsmallest = nsmallest; 24988
24989 function Heap(cmp) { 24990 this.cmp = cmp != null ? cmp : defaultCmp; 24991 this.nodes = []; 24992 } 24993 24994 Heap.prototype.push = function(x) { 24995 return heappush(this.nodes, x, this.cmp); 24996 }; 24997 24998 Heap.prototype.pop = function() { 24999 return heappop(this.nodes, this.cmp); 25000 }; 25001 25002 Heap.prototype.peek = function() { 25003 return this.nodes[0]; 25004 }; 25005 25006 Heap.prototype.contains = function(x) { 25007 return this.nodes.indexOf(x) !== -1; 25008 }; 25009 25010 Heap.prototype.replace = function(x) { 25011 return heapreplace(this.nodes, x, this.cmp); 25012 }; 25013 25014 Heap.prototype.pushpop = function(x) { 25015 return heappushpop(this.nodes, x, this.cmp); 25016 }; 25017 25018 Heap.prototype.heapify = function() { 25019 return heapify(this.nodes, this.cmp); 25020 }; 25021 25022 Heap.prototype.updateItem = function(x) { 25023 return updateItem(this.nodes, x, this.cmp); 25024 }; 25025 25026 Heap.prototype.clear = function() { 25027 return this.nodes = []; 25028 }; 25029 25030 Heap.prototype.empty = function() { 25031 return this.nodes.length === 0; 25032 }; 25033 25034 Heap.prototype.size = function() { 25035 return this.nodes.length; 25036 }; 25037 25038 Heap.prototype.clone = function() { 25039 var heap; 25040 heap = new Heap(); 25041 heap.nodes = this.nodes.slice(0); 25042 return heap; 25043 }; 25044 25045 Heap.prototype.toArray = function() { 25046 return this.nodes.slice(0); 25047 }; 25048 25049 Heap.prototype.insert = Heap.prototype.push; 25050 25051 Heap.prototype.top = Heap.prototype.peek; 25052 25053 Heap.prototype.front = Heap.prototype.peek; 25054 25055 Heap.prototype.has = Heap.prototype.contains; 25056 25057 Heap.prototype.copy = Heap.prototype.clone; 25058 25059 return Heap; 25060 25061 })(); 25062 25063 if (typeof module !== "undefined" && module !== null ? module.exports : void 0) { 25064 module.exports = Heap; 25065 } else { 25066 window.Heap = Heap; 25067 } 25068 25069}).call(this); 25070 25071},{}],161:[function(require,module,exports){ 25072module.exports = attributeToProperty 25073 25074var transform = { 25075 'class': 'className', 25076 'for': 'htmlFor', 25077 'http-equiv': 'httpEquiv' 25078} 25079 25080function attributeToProperty (h) { 25081 return function (tagName, attrs, children) { 25082 for (var attr in attrs) { 25083 if (attr in transform) { 25084 attrs[transform[attr]] = attrs[attr] 25085 delete attrs[attr] 25086 } 25087 } 25088 return h(tagName, attrs, children) 25089 } 25090} 25091 25092},{}],162:[function(require,module,exports){ 25093var attrToProp = require('hyperscript-attribute-to-property') 25094 25095var VAR = 0, TEXT = 1, OPEN = 2, CLOSE = 3, ATTR = 4 25096var ATTR_KEY = 5, ATTR_KEY_W = 6 25097var ATTR_VALUE_W = 7, ATTR_VALUE = 8 25098var ATTR_VALUE_SQ = 9, ATTR_VALUE_DQ = 10 25099var ATTR_EQ = 11, ATTR_BREAK = 12 25100var COMMENT = 13 25101 25102module.exports = function (h, opts) { 25103 if (!opts) opts = {} 25104 var concat = opts.concat || function (a, b) { 25105 return String(a) + String(b) 25106 } 25107 if (opts.attrToProp !== false) { 25108 h = attrToProp(h) 25109 } 25110 25111 return function (strings) { 25112 var state = TEXT, reg = '' 25113 var arglen = arguments.length 25114 var parts = [] 25115 25116 for (var i = 0; i < strings.length; i++) { 25117 if (i < arglen - 1) { 25118 var arg = arguments[i+1] 25119 var p = parse(strings[i]) 25120 var xstate = state 25121 if (xstate === ATTR_VALUE_DQ) xstate = ATTR_VALUE 25122 if (xstate === ATTR_VALUE_SQ) xstate = ATTR_VALUE 25123 if (xstate === ATTR_VALUE_W) xstate = ATTR_VALUE 25124 if (xstate === ATTR) xstate = ATTR_KEY 25125 p.push([ VAR, xstate, arg ]) 25126 parts.push.apply(parts, p) 25127 } else parts.push.apply(parts, parse(strings[i])) 25128 } 25129 25130 var tree = [null,{},[]] 25131 var stack = [[tree,-1]] 25132 for (var i = 0; i < parts.length; i++) { 25133 var cur = stack[stack.length-1][0] 25134 var p = parts[i], s = p[0] 25135 if (s === OPEN && /^\//.test(p[1])) { 25136 var ix = stack[stack.length-1][1] 25137 if (stack.length > 1) { 25138 stack.pop() 25139 stack[stack.length-1][0][2][ix] = h( 25140 cur[0], cur[1], cur[2].length ? cur[2] : undefined 25141 ) 25142 } 25143 } else if (s === OPEN) { 25144 var c = [p[1],{},[]] 25145 cur[2].push(c) 25146 stack.push([c,cur[2].length-1]) 25147 } else if (s === ATTR_KEY || (s === VAR && p[1] === ATTR_KEY)) { 25148 var key = '' 25149 var copyKey 25150 for (; i < parts.length; i++) { 25151 if (parts[i][0] === ATTR_KEY) { 25152 key = concat(key, parts[i][1]) 25153 } else if (parts[i][0] === VAR && parts[i][1] === ATTR_KEY) { 25154 if (typeof parts[i][2] === 'object' && !key) { 25155 for (copyKey in parts[i][2]) { 25156 if (parts[i][2].hasOwnProperty(copyKey) && !cur[1][copyKey]) { 25157 cur[1][copyKey] = parts[i][2][copyKey] 25158 } 25159 } 25160 } else { 25161 key = concat(key, parts[i][2]) 25162 } 25163 } else break 25164 } 25165 if (parts[i][0] === ATTR_EQ) i++ 25166 var j = i 25167 for (; i < parts.length; i++) { 25168 if (parts[i][0] === ATTR_VALUE || parts[i][0] === ATTR_KEY) {
25169 if (!cur[1][key]) cur[1][key] = strfn(parts[i][1]) 25170 else cur[1][key] = concat(cur[1][key], parts[i][1]) 25171 } else if (parts[i][0] === VAR 25172 && (parts[i][1] === ATTR_VALUE || parts[i][1] === ATTR_KEY)) { 25173 if (!cur[1][key]) cur[1][key] = strfn(parts[i][2]) 25174 else cur[1][key] = concat(cur[1][key], parts[i][2]) 25175 } else { 25176 if (key.length && !cur[1][key] && i === j 25177 && (parts[i][0] === CLOSE || parts[i][0] === ATTR_BREAK)) { 25178 // https://html.spec.whatwg.org/multipage/infrastructure.html#boolean-attributes 25179 // empty string is falsy, not well behaved value in browser 25180 cur[1][key] = key.toLowerCase() 25181 } 25182 break 25183 } 25184 } 25185 } else if (s === ATTR_KEY) { 25186 cur[1][p[1]] = true 25187 } else if (s === VAR && p[1] === ATTR_KEY) { 25188 cur[1][p[2]] = true 25189 } else if (s === CLOSE) { 25190 if (selfClosing(cur[0]) && stack.length) { 25191 var ix = stack[stack.length-1][1] 25192 stack.pop() 25193 stack[stack.length-1][0][2][ix] = h( 25194 cur[0], cur[1], cur[2].length ? cur[2] : undefined 25195 ) 25196 } 25197 } else if (s === VAR && p[1] === TEXT) { 25198 if (p[2] === undefined || p[2] === null) p[2] = '' 25199 else if (!p[2]) p[2] = concat('', p[2]) 25200 if (Array.isArray(p[2][0])) { 25201 cur[2].push.apply(cur[2], p[2]) 25202 } else { 25203 cur[2].push(p[2]) 25204 } 25205 } else if (s === TEXT) { 25206 cur[2].push(p[1]) 25207 } else if (s === ATTR_EQ || s === ATTR_BREAK) { 25208 // no-op 25209 } else { 25210 throw new Error('unhandled: ' + s) 25211 } 25212 } 25213 25214 if (tree[2].length > 1 && /^\s*$/.test(tree[2][0])) { 25215 tree[2].shift() 25216 } 25217 25218 if (tree[2].length > 2 25219 || (tree[2].length === 2 && /\S/.test(tree[2][1]))) { 25220 throw new Error( 25221 'multiple root elements must be wrapped in an enclosing tag' 25222 ) 25223 } 25224 if (Array.isArray(tree[2][0]) && typeof tree[2][0][0] === 'string' 25225 && Array.isArray(tree[2][0][2])) { 25226 tree[2][0] = h(tree[2][0][0], tree[2][0][1], tree[2][0][2]) 25227 } 25228 return tree[2][0] 25229 25230 function parse (str) { 25231 var res = [] 25232 if (state === ATTR_VALUE_W) state = ATTR 25233 for (var i = 0; i < str.length; i++) { 25234 var c = str.charAt(i) 25235 if (state === TEXT && c === '<') { 25236 if (reg.length) res.push([TEXT, reg]) 25237 reg = '' 25238 state = OPEN 25239 } else if (c === '>' && !quot(state) && state !== COMMENT) { 25240 if (state === OPEN) { 25241 res.push([OPEN,reg]) 25242 } else if (state === ATTR_KEY) { 25243 res.push([ATTR_KEY,reg]) 25244 } else if (state === ATTR_VALUE && reg.length) { 25245 res.push([ATTR_VALUE,reg]) 25246 } 25247 res.push([CLOSE]) 25248 reg = '' 25249 state = TEXT 25250 } else if (state === COMMENT && /-$/.test(reg) && c === '-') { 25251 if (opts.comments) { 25252 res.push([ATTR_VALUE,reg.substr(0, reg.length - 1)],[CLOSE]) 25253 } 25254 reg = '' 25255 state = TEXT 25256 } else if (state === OPEN && /^!--$/.test(reg)) { 25257 if (opts.comments) { 25258 res.push([OPEN, reg],[ATTR_KEY,'comment'],[ATTR_EQ]) 25259 } 25260 reg = c 25261 state = COMMENT 25262 } else if (state === TEXT || state === COMMENT) { 25263 reg += c 25264 } else if (state === OPEN && /\s/.test(c)) { 25265 res.push([OPEN, reg]) 25266 reg = '' 25267 state = ATTR 25268 } else if (state === OPEN) { 25269 reg += c 25270 } else if (state === ATTR && /[^\s"'=/]/.test(c)) { 25271 state = ATTR_KEY 25272 reg = c 25273 } else if (state === ATTR && /\s/.test(c)) { 25274 if (reg.length) res.push([ATTR_KEY,reg]) 25275 res.push([ATTR_BREAK]) 25276 } else if (state === ATTR_KEY && /\s/.test(c)) { 25277 res.push([ATTR_KEY,reg]) 25278 reg = '' 25279 state = ATTR_KEY_W 25280 } else if (state === ATTR_KEY && c === '=') { 25281 res.push([ATTR_KEY,reg],[ATTR_EQ]) 25282 reg = '' 25283 state = ATTR_VALUE_W 25284 } else if (state === ATTR_KEY) { 25285 reg += c 25286 } else if ((state === ATTR_KEY_W || state === ATTR) && c === '=') { 25287 res.push([ATTR_EQ]) 25288 state = ATTR_VALUE_W 25289 } else if ((state === ATTR_KEY_W || state === ATTR) && !/\s/.test(c)) { 25290 res.push([ATTR_BREAK]) 25291 if (/[\w-]/.test(c)) { 25292 reg += c 25293 state = ATTR_KEY 25294 } else state = ATTR 25295 } else if (state === ATTR_VALUE_W && c === '"') { 25296 state = ATTR_VALUE_DQ 25297 } else if (state === ATTR_VALUE_W && c === "'") { 25298 state = ATTR_VALUE_SQ 25299 } else if (state === ATTR_VALUE_DQ && c === '"') { 25300 res.push([ATTR_VALUE,reg],[ATTR_BREAK]) 25301 reg = '' 25302 state = ATTR 25303 } else if (state === ATTR_VALUE_SQ && c === "'") { 25304 res.push([ATTR_VALUE,reg],[ATTR_BREAK]) 25305 reg = '' 25306 state = ATTR 25307 } else if (state === ATTR_VALUE_W && !/\s/.test(c)) { 25308 state = ATTR_VALUE 25309 i-- 25310 } else if (state === ATTR_VALUE && /\s/.test(c)) { 25311 res.push([ATTR_VALUE,reg],[ATTR_BREAK]) 25312 reg = '' 25313 state = ATTR 25314 } else if (state === ATTR_VALUE || state === ATTR_VALUE_SQ 25315 || state === ATTR_VALUE_DQ) { 25316 reg += c 25317 } 25318 } 25319 if (state === TEXT && reg.length) { 25320 res.push([TEXT,reg]) 25321 reg = '' 25322 } else if (state === ATTR_VALUE && reg.length) { 25323 res.push([ATTR_VALUE,reg]) 25324 reg = '' 25325 } else if (state === ATTR_VALUE_DQ && reg.length) { 25326 res.push([ATTR_VALUE,reg]) 25327 reg = '' 25328 } else if (state === ATTR_VALUE_SQ && reg.length) { 25329 res.push([ATTR_VALUE,reg]) 25330 reg = '' 25331 } else if (state === ATTR_KEY) { 25332 res.push([ATTR_KEY,reg]) 25333 reg = '' 25334 } 25335 return res 25336 } 25337 } 25338 25339 function strfn (x) { 25340 if (typeof x === 'function') return x 25341 else if (typeof x === 'string') return x 25342 else if (x && typeof x === 'object') return x 25343 else return concat('', x) 25344 } 25345} 25346 25347function quot (state) { 25348 return state === ATTR_VALUE_SQ || state === ATTR_VALUE_DQ 25349} 25350 25351var hasOwn = Object.prototype.hasOwnProperty 25352function has (obj, key) { return hasOwn.call(obj, key) } 25353
25354var closeRE = RegExp('^(' + [ 25355 'area', 'base', 'basefont', 'bgsound', 'br', 'col', 'command', 'embed', 25356 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param', 25357 'source', 'track', 'wbr', '!--', 25358 // SVG TAGS 25359 'animate', 'animateTransform', 'circle', 'cursor', 'desc', 'ellipse', 25360 'feBlend', 'feColorMatrix', 'feComposite', 25361 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 25362 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 25363 'feGaussianBlur', 'feImage', 'feMergeNode', 'feMorphology', 25364 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 25365 'feTurbulence', 'font-face-format', 'font-face-name', 'font-face-uri', 25366 'glyph', 'glyphRef', 'hkern', 'image', 'line', 'missing-glyph', 'mpath', 25367 'path', 'polygon', 'polyline', 'rect', 'set', 'stop', 'tref', 'use', 'view', 25368 'vkern' 25369].join('|') + ')(?:[\.#][a-zA-Z0-9\u007F-\uFFFF_:-]+)*$') 25370function selfClosing (tag) { return closeRE.test(tag) } 25371 25372},{"hyperscript-attribute-to-property":161}],163:[function(require,module,exports){ 25373exports.read = function (buffer, offset, isLE, mLen, nBytes) { 25374 var e, m 25375 var eLen = nBytes * 8 - mLen - 1 25376 var eMax = (1 << eLen) - 1 25377 var eBias = eMax >> 1 25378 var nBits = -7 25379 var i = isLE ? (nBytes - 1) : 0 25380 var d = isLE ? -1 : 1 25381 var s = buffer[offset + i] 25382 25383 i += d 25384 25385 e = s & ((1 << (-nBits)) - 1) 25386 s >>= (-nBits) 25387 nBits += eLen 25388 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} 25389 25390 m = e & ((1 << (-nBits)) - 1) 25391 e >>= (-nBits) 25392 nBits += mLen 25393 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} 25394 25395 if (e === 0) { 25396 e = 1 - eBias 25397 } else if (e === eMax) { 25398 return m ? NaN : ((s ? -1 : 1) * Infinity) 25399 } else { 25400 m = m + Math.pow(2, mLen) 25401 e = e - eBias 25402 } 25403 return (s ? -1 : 1) * m * Math.pow(2, e - mLen) 25404} 25405 25406exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { 25407 var e, m, c 25408 var eLen = nBytes * 8 - mLen - 1 25409 var eMax = (1 << eLen) - 1 25410 var eBias = eMax >> 1 25411 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) 25412 var i = isLE ? 0 : (nBytes - 1) 25413 var d = isLE ? 1 : -1 25414 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 25415 25416 value = Math.abs(value) 25417 25418 if (isNaN(value) || value === Infinity) { 25419 m = isNaN(value) ? 1 : 0 25420 e = eMax 25421 } else { 25422 e = Math.floor(Math.log(value) / Math.LN2) 25423 if (value * (c = Math.pow(2, -e)) < 1) { 25424 e-- 25425 c *= 2 25426 } 25427 if (e + eBias >= 1) { 25428 value += rt / c 25429 } else { 25430 value += rt * Math.pow(2, 1 - eBias) 25431 } 25432 if (value * c >= 2) { 25433 e++ 25434 c /= 2 25435 } 25436 25437 if (e + eBias >= eMax) { 25438 m = 0 25439 e = eMax 25440 } else if (e + eBias >= 1) { 25441 m = (value * c - 1) * Math.pow(2, mLen) 25442 e = e + eBias 25443 } else { 25444 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) 25445 e = 0 25446 } 25447 } 25448 25449 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} 25450 25451 e = (e << mLen) | m 25452 eLen += mLen 25453 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} 25454 25455 buffer[offset + i - d] |= s * 128 25456} 25457 25458},{}],164:[function(require,module,exports){ 25459var invariant = require('invariant'); 25460 25461var hasOwnProperty = Object.prototype.hasOwnProperty; 25462var splice = Array.prototype.splice; 25463 25464var toString = Object.prototype.toString 25465var type = function(obj) { 25466 return toString.call(obj).slice(8, -1); 25467} 25468 25469var assign = Object.assign || /* istanbul ignore next */ function assign(target, source) { 25470 getAllKeys(source).forEach(function(key) { 25471 if (hasOwnProperty.call(source, key)) { 25472 target[key] = source[key]; 25473 } 25474 }); 25475 return target; 25476}; 25477 25478var getAllKeys = typeof Object.getOwnPropertySymbols === 'function' ? 25479 function(obj) { return Object.keys(obj).concat(Object.getOwnPropertySymbols(obj)) } : 25480 /* istanbul ignore next */ function(obj) { return Object.keys(obj) }; 25481 25482/* istanbul ignore next */ 25483function copy(object) { 25484 if (Array.isArray(object)) { 25485 return assign(object.constructor(object.length), object) 25486 } else if (type(object) === 'Map') { 25487 return new Map(object) 25488 } else if (type(object) === 'Set') { 25489 return new Set(object) 25490 } else if (object && typeof object === 'object') { 25491 var prototype = object.constructor && object.constructor.prototype 25492 return assign(Object.create(prototype || null), object); 25493 } else { 25494 return object; 25495 } 25496} 25497 25498function newContext() { 25499 var commands = assign({}, defaultCommands); 25500 update.extend = function(directive, fn) { 25501 commands[directive] = fn; 25502 }; 25503 update.isEquals = function(a, b) { return a === b; }; 25504 25505 return update; 25506 25507 function update(object, spec) { 25508 if (!(Array.isArray(object) && Array.isArray(spec))) { 25509 invariant( 25510 !Array.isArray(spec),
25511 'update(): You provided an invalid spec to update(). The spec may ' + 25512 'not contain an array except as the value of $set, $push, $unshift, ' + 25513 '$splice or any custom command allowing an array value.' 25514 ); 25515 } 25516 25517 invariant( 25518 typeof spec === 'object' && spec !== null, 25519 'update(): You provided an invalid spec to update(). The spec and ' + 25520 'every included key path must be plain objects containing one of the ' + 25521 'following commands: %s.', 25522 Object.keys(commands).join(', ') 25523 ); 25524 25525 var nextObject = object; 25526 var index, key; 25527 getAllKeys(spec).forEach(function(key) { 25528 if (hasOwnProperty.call(commands, key)) { 25529 var objectWasNextObject = object === nextObject; 25530 nextObject = commands[key](spec[key], nextObject, spec, object); 25531 if (objectWasNextObject && update.isEquals(nextObject, object)) { 25532 nextObject = object; 25533 } 25534 } else { 25535 var nextValueForKey = update(object[key], spec[key]); 25536 if (!update.isEquals(nextValueForKey, nextObject[key]) || typeof nextValueForKey === 'undefined' && !hasOwnProperty.call(object, key)) { 25537 if (nextObject === object) { 25538 nextObject = copy(object); 25539 } 25540 nextObject[key] = nextValueForKey; 25541 } 25542 } 25543 }) 25544 return nextObject; 25545 } 25546 25547} 25548 25549var defaultCommands = { 25550 $push: function(value, nextObject, spec) { 25551 invariantPushAndUnshift(nextObject, spec, '$push'); 25552 return value.length ? nextObject.concat(value) : nextObject; 25553 }, 25554 $unshift: function(value, nextObject, spec) { 25555 invariantPushAndUnshift(nextObject, spec, '$unshift'); 25556 return value.length ? value.concat(nextObject) : nextObject; 25557 }, 25558 $splice: function(value, nextObject, spec, originalObject) { 25559 invariantSplices(nextObject, spec); 25560 value.forEach(function(args) { 25561 invariantSplice(args); 25562 if (nextObject === originalObject && args.length) nextObject = copy(originalObject); 25563 splice.apply(nextObject, args); 25564 }); 25565 return nextObject; 25566 }, 25567 $set: function(value, nextObject, spec) { 25568 invariantSet(spec); 25569 return value; 25570 }, 25571 $toggle: function(targets, nextObject) { 25572 invariantSpecArray(targets, '$toggle'); 25573 var nextObjectCopy = targets.length ? copy(nextObject) : nextObject; 25574 25575 targets.forEach(function(target) { 25576 nextObjectCopy[target] = !nextObject[target]; 25577 }); 25578 25579 return nextObjectCopy; 25580 }, 25581 $unset: function(value, nextObject, spec, originalObject) { 25582 invariantSpecArray(value, '$unset'); 25583 value.forEach(function(key) { 25584 if (Object.hasOwnProperty.call(nextObject, key)) { 25585 if (nextObject === originalObject) nextObject = copy(originalObject); 25586 delete nextObject[key]; 25587 } 25588 }); 25589 return nextObject; 25590 }, 25591 $add: function(value, nextObject, spec, originalObject) { 25592 invariantMapOrSet(nextObject, '$add'); 25593 invariantSpecArray(value, '$add'); 25594 if (type(nextObject) === 'Map') { 25595 value.forEach(function(pair) { 25596 var key = pair[0]; 25597 var value = pair[1]; 25598 if (nextObject === originalObject && nextObject.get(key) !== value) nextObject = copy(originalObject); 25599 nextObject.set(key, value); 25600 }); 25601 } else { 25602 value.forEach(function(value) { 25603 if (nextObject === originalObject && !nextObject.has(value)) nextObject = copy(originalObject); 25604 nextObject.add(value); 25605 }); 25606 } 25607 return nextObject; 25608 }, 25609 $remove: function(value, nextObject, spec, originalObject) { 25610 invariantMapOrSet(nextObject, '$remove'); 25611 invariantSpecArray(value, '$remove'); 25612 value.forEach(function(key) { 25613 if (nextObject === originalObject && nextObject.has(key)) nextObject = copy(originalObject); 25614 nextObject.delete(key); 25615 }); 25616 return nextObject; 25617 }, 25618 $merge: function(value, nextObject, spec, originalObject) { 25619 invariantMerge(nextObject, value); 25620 getAllKeys(value).forEach(function(key) { 25621 if (value[key] !== nextObject[key]) { 25622 if (nextObject === originalObject) nextObject = copy(originalObject); 25623 nextObject[key] = value[key]; 25624 } 25625 }); 25626 return nextObject; 25627 }, 25628 $apply: function(value, original) { 25629 invariantApply(value); 25630 return value(original); 25631 } 25632}; 25633 25634module.exports = newContext(); 25635module.exports.newContext = newContext; 25636 25637// invariants 25638 25639function invariantPushAndUnshift(value, spec, command) { 25640 invariant( 25641 Array.isArray(value),
25642 'update(): expected target of %s to be an array; got %s.', 25643 command, 25644 value 25645 ); 25646 invariantSpecArray(spec[command], command) 25647} 25648 25649function invariantSpecArray(spec, command) { 25650 invariant( 25651 Array.isArray(spec), 25652 'update(): expected spec of %s to be an array; got %s. ' + 25653 'Did you forget to wrap your parameter in an array?', 25654 command, 25655 spec 25656 ); 25657} 25658 25659function invariantSplices(value, spec) { 25660 invariant( 25661 Array.isArray(value), 25662 'Expected $splice target to be an array; got %s', 25663 value 25664 ); 25665 invariantSplice(spec['$splice']); 25666} 25667 25668function invariantSplice(value) { 25669 invariant( 25670 Array.isArray(value), 25671 'update(): expected spec of $splice to be an array of arrays; got %s. ' + 25672 'Did you forget to wrap your parameters in an array?', 25673 value 25674 ); 25675} 25676 25677function invariantApply(fn) { 25678 invariant( 25679 typeof fn === 'function', 25680 'update(): expected spec of $apply to be a function; got %s.', 25681 fn 25682 ); 25683} 25684 25685function invariantSet(spec) { 25686 invariant( 25687 Object.keys(spec).length === 1, 25688 'Cannot have more than one key in an object with $set' 25689 ); 25690} 25691 25692function invariantMerge(target, specValue) { 25693 invariant( 25694 specValue && typeof specValue === 'object', 25695 'update(): $merge expects a spec of type \'object\'; got %s', 25696 specValue 25697 ); 25698 invariant( 25699 target && typeof target === 'object', 25700 'update(): $merge expects a target of type \'object\'; got %s', 25701 target 25702 ); 25703} 25704 25705function invariantMapOrSet(target, command) { 25706 var typeOfTarget = type(target); 25707 invariant( 25708 typeOfTarget === 'Map' || typeOfTarget === 'Set', 25709 'update(): %s expects a target of type Set or Map; got %s', 25710 command, 25711 typeOfTarget 25712 ); 25713} 25714 25715},{"invariant":167}],165:[function(require,module,exports){ 25716if (typeof Object.create === 'function') { 25717 // implementation from standard node.js 'util' module 25718 module.exports = function inherits(ctor, superCtor) { 25719 ctor.super_ = superCtor 25720 ctor.prototype = Object.create(superCtor.prototype, { 25721 constructor: { 25722 value: ctor, 25723 enumerable: false, 25724 writable: true, 25725 configurable: true 25726 } 25727 }); 25728 }; 25729} else { 25730 // old school shim for old browsers 25731 module.exports = function inherits(ctor, superCtor) { 25732 ctor.super_ = superCtor 25733 var TempCtor = function () {} 25734 TempCtor.prototype = superCtor.prototype 25735 ctor.prototype = new TempCtor() 25736 ctor.prototype.constructor = ctor 25737 } 25738} 25739 25740},{}],166:[function(require,module,exports){ 25741var containers = []; // will store container HTMLElement references 25742var styleElements = []; // will store {prepend: HTMLElement, append: HTMLElement} 25743 25744function insertCss(css, options) { 25745 options = options || {}; 25746 25747 var position = options.prepend === true ? 'prepend' : 'append'; 25748 var container = options.container !== undefined ? options.container : document.querySelector('head'); 25749 var containerId = containers.indexOf(container); 25750 25751 // first time we see this container, create the necessary entries 25752 if (containerId === -1) { 25753 containerId = containers.push(container) - 1; 25754 styleElements[containerId] = {}; 25755 } 25756 25757 // try to get the correponding container + position styleElement, create it otherwise 25758 var styleElement; 25759 25760 if (styleElements[containerId] !== undefined && styleElements[containerId][position] !== undefined) { 25761 styleElement = styleElements[containerId][position]; 25762 } else { 25763 styleElement = styleElements[containerId][position] = createStyleElement(); 25764 25765 if (position === 'prepend') { 25766 container.insertBefore(styleElement, container.childNodes[0]); 25767 } else { 25768 container.appendChild(styleElement); 25769 } 25770 } 25771 25772 // strip potential UTF-8 BOM if css was read from a file 25773 if (css.charCodeAt(0) === 0xFEFF) { css = css.substr(1, css.length); } 25774 25775 // actually add the stylesheet 25776 if (styleElement.styleSheet) { 25777 styleElement.styleSheet.cssText += css 25778 } else { 25779 styleElement.textContent += css; 25780 } 25781 25782 return styleElement; 25783}; 25784 25785function createStyleElement() { 25786 var styleElement = document.createElement('style'); 25787 styleElement.setAttribute('type', 'text/css'); 25788 return styleElement; 25789} 25790 25791module.exports = insertCss; 25792module.exports.insertCss = insertCss; 25793 25794},{}],167:[function(require,module,exports){ 25795(function (process){ 25796/** 25797 * Copyright 2013-2015, Facebook, Inc. 25798 * All rights reserved. 25799 * 25800 * This source code is licensed under the BSD-style license found in the 25801 * LICENSE file in the root directory of this source tree. An additional grant 25802 * of patent rights can be found in the PATENTS file in the same directory. 25803 */ 25804 25805'use strict'; 25806 25807/** 25808 * Use invariant() to assert state which your program assumes to be true. 25809 * 25810 * Provide sprintf-style format (only %s is supported) and arguments 25811 * to provide information about what broke and what you were 25812 * expecting. 25813 * 25814 * The invariant message will be stripped in production, but the invariant 25815 * will remain to ensure logic does not differ in production. 25816 */ 25817 25818var invariant = function(condition, format, a, b, c, d, e, f) { 25819 if (process.env.NODE_ENV !== 'production') { 25820 if (format === undefined) { 25821 throw new Error('invariant requires an error message argument'); 25822 } 25823 } 25824 25825 if (!condition) { 25826 var error; 25827 if (format === undefined) { 25828 error = new Error( 25829 'Minified exception occurred; use the non-minified dev environment ' + 25830 'for the full error message and additional helpful warnings.' 25831 ); 25832 } else { 25833 var args = [a, b, c, d, e, f]; 25834 var argIndex = 0; 25835 error = new Error( 25836 format.replace(/%s/g, function() { return args[argIndex++]; }) 25837 );
25838 error.name = 'Invariant Violation'; 25839 } 25840 25841 error.framesToPop = 1; // we don't care about invariant's own frame 25842 throw error; 25843 } 25844}; 25845 25846module.exports = invariant; 25847 25848}).call(this,require('_process')) 25849},{"_process":84}],168:[function(require,module,exports){ 25850/*! 25851 * Determine if an object is a Buffer 25852 * 25853 * @author Feross Aboukhadijeh <https://feross.org> 25854 * @license MIT 25855 */ 25856 25857// The _isBuffer check is for Safari 5-7 support, because it's missing 25858// Object.prototype.constructor. Remove this eventually 25859module.exports = function (obj) { 25860 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) 25861} 25862 25863function isBuffer (obj) { 25864 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) 25865} 25866 25867// For Node v0.10 support. Remove this eventually. 25868function isSlowBuffer (obj) { 25869 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) 25870} 25871 25872},{}],169:[function(require,module,exports){ 25873module.exports = isFunction 25874 25875var toString = Object.prototype.toString 25876 25877function isFunction (fn) { 25878 var string = toString.call(fn) 25879 return string === '[object Function]' || 25880 (typeof fn === 'function' && string !== '[object RegExp]') || 25881 (typeof window !== 'undefined' && 25882 // IE8 and below 25883 (fn === window.setTimeout || 25884 fn === window.alert || 25885 fn === window.confirm || 25886 fn === window.prompt)) 25887}; 25888 25889},{}],170:[function(require,module,exports){ 25890module.exports = Array.isArray || function (arr) { 25891 return Object.prototype.toString.call(arr) == '[object Array]'; 25892}; 25893 25894},{}],171:[function(require,module,exports){ 25895(function (global){ 25896/** 25897 * @license 25898 * Lodash <https://lodash.com/> 25899 * Copyright JS Foundation and other contributors <https://js.foundation/> 25900 * Released under MIT license <https://lodash.com/license> 25901 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> 25902 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors 25903 */ 25904;(function() { 25905 25906 /** Used as a safe reference for `undefined` in pre-ES5 environments. */ 25907 var undefined; 25908 25909 /** Used as the semantic version number. */ 25910 var VERSION = '4.17.4'; 25911 25912 /** Used as the size to enable large array optimizations. */ 25913 var LARGE_ARRAY_SIZE = 200; 25914 25915 /** Error message constants. */ 25916 var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', 25917 FUNC_ERROR_TEXT = 'Expected a function'; 25918 25919 /** Used to stand-in for `undefined` hash values. */ 25920 var HASH_UNDEFINED = '__lodash_hash_undefined__'; 25921 25922 /** Used as the maximum memoize cache size. */ 25923 var MAX_MEMOIZE_SIZE = 500; 25924 25925 /** Used as the internal argument placeholder. */ 25926 var PLACEHOLDER = '__lodash_placeholder__'; 25927 25928 /** Used to compose bitmasks for cloning. */ 25929 var CLONE_DEEP_FLAG = 1, 25930 CLONE_FLAT_FLAG = 2, 25931 CLONE_SYMBOLS_FLAG = 4; 25932 25933 /** Used to compose bitmasks for value comparisons. */ 25934 var COMPARE_PARTIAL_FLAG = 1, 25935 COMPARE_UNORDERED_FLAG = 2; 25936 25937 /** Used to compose bitmasks for function metadata. */ 25938 var WRAP_BIND_FLAG = 1, 25939 WRAP_BIND_KEY_FLAG = 2, 25940 WRAP_CURRY_BOUND_FLAG = 4, 25941 WRAP_CURRY_FLAG = 8, 25942 WRAP_CURRY_RIGHT_FLAG = 16, 25943 WRAP_PARTIAL_FLAG = 32, 25944 WRAP_PARTIAL_RIGHT_FLAG = 64, 25945 WRAP_ARY_FLAG = 128, 25946 WRAP_REARG_FLAG = 256, 25947 WRAP_FLIP_FLAG = 512; 25948 25949 /** Used as default options for `_.truncate`. */ 25950 var DEFAULT_TRUNC_LENGTH = 30, 25951 DEFAULT_TRUNC_OMISSION = '...'; 25952 25953 /** Used to detect hot functions by number of calls within a span of milliseconds. */ 25954 var HOT_COUNT = 800, 25955 HOT_SPAN = 16; 25956 25957 /** Used to indicate the type of lazy iteratees. */ 25958 var LAZY_FILTER_FLAG = 1, 25959 LAZY_MAP_FLAG = 2, 25960 LAZY_WHILE_FLAG = 3; 25961 25962 /** Used as references for various `Number` constants. */ 25963 var INFINITY = 1 / 0, 25964 MAX_SAFE_INTEGER = 9007199254740991, 25965 MAX_INTEGER = 1.7976931348623157e+308, 25966 NAN = 0 / 0; 25967 25968 /** Used as references for the maximum length and index of an array. */ 25969 var MAX_ARRAY_LENGTH = 4294967295, 25970 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, 25971 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; 25972 25973 /** Used to associate wrap methods with their bit flags. */ 25974 var wrapFlags = [ 25975 ['ary', WRAP_ARY_FLAG], 25976 ['bind', WRAP_BIND_FLAG], 25977 ['bindKey', WRAP_BIND_KEY_FLAG], 25978 ['curry', WRAP_CURRY_FLAG], 25979 ['curryRight', WRAP_CURRY_RIGHT_FLAG], 25980 ['flip', WRAP_FLIP_FLAG], 25981 ['partial', WRAP_PARTIAL_FLAG], 25982 ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], 25983 ['rearg', WRAP_REARG_FLAG] 25984 ]; 25985 25986 /** `Object#toString` result references. */ 25987 var argsTag = '[object Arguments]', 25988 arrayTag = '[object Array]', 25989 asyncTag = '[object AsyncFunction]', 25990 boolTag = '[object Boolean]', 25991 dateTag = '[object Date]', 25992 domExcTag = '[object DOMException]', 25993 errorTag = '[object Error]', 25994 funcTag = '[object Function]', 25995 genTag = '[object GeneratorFunction]', 25996 mapTag = '[object Map]', 25997 numberTag = '[object Number]', 25998 nullTag = '[object Null]', 25999 objectTag = '[object Object]', 26000 promiseTag = '[object Promise]', 26001 proxyTag = '[object Proxy]', 26002 regexpTag = '[object RegExp]', 26003 setTag = '[object Set]',
26004 stringTag = '[object String]', 26005 symbolTag = '[object Symbol]', 26006 undefinedTag = '[object Undefined]', 26007 weakMapTag = '[object WeakMap]', 26008 weakSetTag = '[object WeakSet]'; 26009 26010 var arrayBufferTag = '[object ArrayBuffer]', 26011 dataViewTag = '[object DataView]', 26012 float32Tag = '[object Float32Array]', 26013 float64Tag = '[object Float64Array]', 26014 int8Tag = '[object Int8Array]', 26015 int16Tag = '[object Int16Array]', 26016 int32Tag = '[object Int32Array]', 26017 uint8Tag = '[object Uint8Array]', 26018 uint8ClampedTag = '[object Uint8ClampedArray]', 26019 uint16Tag = '[object Uint16Array]', 26020 uint32Tag = '[object Uint32Array]'; 26021 26022 /** Used to match empty string literals in compiled template source. */ 26023 var reEmptyStringLeading = /\b__p \+= '';/g, 26024 reEmptyStringMiddle = /\b(__p \+=) '' \+/g, 26025 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; 26026 26027 /** Used to match HTML entities and HTML characters. */ 26028 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, 26029 reUnescapedHtml = /[&<>"']/g, 26030 reHasEscapedHtml = RegExp(reEscapedHtml.source), 26031 reHasUnescapedHtml = RegExp(reUnescapedHtml.source); 26032 26033 /** Used to match template delimiters. */ 26034 var reEscape = /<%-([\s\S]+?)%>/g, 26035 reEvaluate = /<%([\s\S]+?)%>/g, 26036 reInterpolate = /<%=([\s\S]+?)%>/g; 26037 26038 /** Used to match property names within property paths. */ 26039 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, 26040 reIsPlainProp = /^\w*$/, 26041 reLeadingDot = /^\./, 26042 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; 26043 26044 /** 26045 * Used to match `RegExp` 26046 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). 26047 */ 26048 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, 26049 reHasRegExpChar = RegExp(reRegExpChar.source); 26050 26051 /** Used to match leading and trailing whitespace. */ 26052 var reTrim = /^\s+|\s+$/g, 26053 reTrimStart = /^\s+/, 26054 reTrimEnd = /\s+$/; 26055 26056 /** Used to match wrap detail comments. */ 26057 var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, 26058 reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, 26059 reSplitDetails = /,? & /; 26060 26061 /** Used to match words composed of alphanumeric characters. */ 26062 var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; 26063 26064 /** Used to match backslashes in property paths. */ 26065 var reEscapeChar = /\\(\\)?/g; 26066 26067 /** 26068 * Used to match 26069 * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). 26070 */ 26071 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; 26072 26073 /** Used to match `RegExp` flags from their coerced string values. */ 26074 var reFlags = /\w*$/; 26075 26076 /** Used to detect bad signed hexadecimal string values. */ 26077 var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; 26078 26079 /** Used to detect binary string values. */ 26080 var reIsBinary = /^0b[01]+$/i; 26081 26082 /** Used to detect host constructors (Safari). */ 26083 var reIsHostCtor = /^\[object .+?Constructor\]$/; 26084 26085 /** Used to detect octal string values. */ 26086 var reIsOctal = /^0o[0-7]+$/i; 26087 26088 /** Used to detect unsigned integer values. */ 26089 var reIsUint = /^(?:0|[1-9]\d*)$/; 26090 26091 /** Used to match Latin Unicode letters (excluding mathematical operators). */
vendor: 4,214 bytes, lines 26092-26175
26092 var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; 26093 26094 /** Used to ensure capturing order of template delimiters. */ 26095 var reNoMatch = /($^)/; 26096 26097 /** Used to match unescaped characters in compiled string literals. */ 26098 var reUnescapedString = /['\n\r\u2028\u2029\\]/g; 26099 26100 /** Used to compose unicode character classes. */ 26101 var rsAstralRange = '\\ud800-\\udfff', 26102 rsComboMarksRange = '\\u0300-\\u036f', 26103 reComboHalfMarksRange = '\\ufe20-\\ufe2f', 26104 rsComboSymbolsRange = '\\u20d0-\\u20ff', 26105 rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, 26106 rsDingbatRange = '\\u2700-\\u27bf', 26107 rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', 26108 rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', 26109 rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', 26110 rsPunctuationRange = '\\u2000-\\u206f', 26111 rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', 26112 rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', 26113 rsVarRange = '\\ufe0e\\ufe0f', 26114 rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; 26115 26116 /** Used to compose unicode capture groups. */ 26117 var rsApos = "['\u2019]", 26118 rsAstral = '[' + rsAstralRange + ']', 26119 rsBreak = '[' + rsBreakRange + ']', 26120 rsCombo = '[' + rsComboRange + ']', 26121 rsDigits = '\\d+', 26122 rsDingbat = '[' + rsDingbatRange + ']', 26123 rsLower = '[' + rsLowerRange + ']', 26124 rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', 26125 rsFitz = '\\ud83c[\\udffb-\\udfff]', 26126 rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', 26127 rsNonAstral = '[^' + rsAstralRange + ']', 26128 rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', 26129 rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', 26130 rsUpper = '[' + rsUpperRange + ']', 26131 rsZWJ = '\\u200d'; 26132 26133 /** Used to compose unicode regexes. */ 26134 var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', 26135 rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', 26136 rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', 26137 rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', 26138 reOptMod = rsModifier + '?', 26139 rsOptVar = '[' + rsVarRange + ']?', 26140 rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', 26141 rsOrdLower = '\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)', 26142 rsOrdUpper = '\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)', 26143 rsSeq = rsOptVar + reOptMod + rsOptJoin, 26144 rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, 26145 rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; 26146 26147 /** Used to match apostrophes. */ 26148 var reApos = RegExp(rsApos, 'g'); 26149 26150 /** 26151 * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and 26152 * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). 26153 */ 26154 var reComboMark = RegExp(rsCombo, 'g'); 26155 26156 /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ 26157 var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); 26158 26159 /** Used to match complex or compound words. */ 26160 var reUnicodeWord = RegExp([ 26161 rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', 26162 rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', 26163 rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, 26164 rsUpper + '+' + rsOptContrUpper, 26165 rsOrdUpper, 26166 rsOrdLower, 26167 rsDigits, 26168 rsEmoji 26169 ].join('|'), 'g'); 26170 26171 /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ 26172 var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); 26173 26174 /** Used to detect strings that need a more robust regexp to match words. */ 26175 var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,
vendor: 7,054 bytes, lines 26175-26335
26175}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; 26176 26177 /** Used to assign default `context` object properties. */ 26178 var contextProps = [ 26179 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 26180 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 26181 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 26182 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', 26183 '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' 26184 ]; 26185 26186 /** Used to make template sourceURLs easier to identify. */ 26187 var templateCounter = -1; 26188 26189 /** Used to identify `toStringTag` values of typed arrays. */ 26190 var typedArrayTags = {}; 26191 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = 26192 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = 26193 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = 26194 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = 26195 typedArrayTags[uint32Tag] = true; 26196 typedArrayTags[argsTag] = typedArrayTags[arrayTag] = 26197 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = 26198 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = 26199 typedArrayTags[errorTag] = typedArrayTags[funcTag] = 26200 typedArrayTags[mapTag] = typedArrayTags[numberTag] = 26201 typedArrayTags[objectTag] = typedArrayTags[regexpTag] = 26202 typedArrayTags[setTag] = typedArrayTags[stringTag] = 26203 typedArrayTags[weakMapTag] = false; 26204 26205 /** Used to identify `toStringTag` values supported by `_.clone`. */ 26206 var cloneableTags = {}; 26207 cloneableTags[argsTag] = cloneableTags[arrayTag] = 26208 cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = 26209 cloneableTags[boolTag] = cloneableTags[dateTag] = 26210 cloneableTags[float32Tag] = cloneableTags[float64Tag] = 26211 cloneableTags[int8Tag] = cloneableTags[int16Tag] = 26212 cloneableTags[int32Tag] = cloneableTags[mapTag] = 26213 cloneableTags[numberTag] = cloneableTags[objectTag] = 26214 cloneableTags[regexpTag] = cloneableTags[setTag] = 26215 cloneableTags[stringTag] = cloneableTags[symbolTag] = 26216 cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = 26217 cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; 26218 cloneableTags[errorTag] = cloneableTags[funcTag] = 26219 cloneableTags[weakMapTag] = false; 26220 26221 /** Used to map Latin Unicode letters to basic Latin letters. */ 26222 var deburredLetters = { 26223 // Latin-1 Supplement block. 26224 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', 26225 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', 26226 '\xc7': 'C', '\xe7': 'c', 26227 '\xd0': 'D', '\xf0': 'd', 26228 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', 26229 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', 26230 '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', 26231 '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', 26232 '\xd1': 'N', '\xf1': 'n', 26233 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', 26234 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', 26235 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', 26236 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', 26237 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', 26238 '\xc6': 'Ae', '\xe6': 'ae', 26239 '\xde': 'Th', '\xfe': 'th', 26240 '\xdf': 'ss', 26241 // Latin Extended-A block. 26242 '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', 26243 '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', 26244 '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', 26245 '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', 26246 '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', 26247 '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', 26248 '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', 26249 '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', 26250 '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', 26251 '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', 26252 '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', 26253 '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', 26254 '\u0134': 'J', '\u0135': 'j', 26255 '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', 26256 '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', 26257 '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', 26258 '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', 26259 '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', 26260 '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', 26261 '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', 26262 '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', 26263 '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', 26264 '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', 26265 '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', 26266 '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', 26267 '\u0163': 't', '\u0165': 't', '\u0167': 't', 26268 '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', 26269 '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', 26270 '\u0174': 'W', '\u0175': 'w', 26271 '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', 26272 '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', 26273 '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', 26274 '\u0132': 'IJ', '\u0133': 'ij', 26275 '\u0152': 'Oe', '\u0153': 'oe', 26276 '\u0149': "'n", '\u017f': 's' 26277 }; 26278 26279 /** Used to map characters to HTML entities. */ 26280 var htmlEscapes = { 26281 '&': '&', 26282 '<': '<', 26283 '>': '>', 26284 '"': '"', 26285 "'": ''' 26286 }; 26287 26288 /** Used to map HTML entities to characters. */ 26289 var htmlUnescapes = { 26290 '&': '&', 26291 '<': '<', 26292 '>': '>', 26293 '"': '"', 26294 ''': "'" 26295 }; 26296 26297 /** Used to escape characters for inclusion in compiled string literals. */ 26298 var stringEscapes = { 26299 '\\': '\\', 26300 "'": "'", 26301 '\n': 'n', 26302 '\r': 'r', 26303 '\u2028': 'u2028', 26304 '\u2029': 'u2029' 26305 }; 26306 26307 /** Built-in method references without a dependency on `root`. */ 26308 var freeParseFloat = parseFloat, 26309 freeParseInt = parseInt; 26310 26311 /** Detect free variable `global` from Node.js. */ 26312 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; 26313 26314 /** Detect free variable `self`. */ 26315 var freeSelf = typeof self == 'object' && self && self.Object === Object && self; 26316 26317 /** Used as a reference to the global object. */ 26318 var root = freeGlobal || freeSelf || Function('return this')(); 26319 26320 /** Detect free variable `exports`. */ 26321 var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; 26322 26323 /** Detect free variable `module`. */ 26324 var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; 26325 26326 /** Detect the popular CommonJS extension `module.exports`. */ 26327 var moduleExports = freeModule && freeModule.exports === freeExports; 26328 26329 /** Detect free variable `process` from Node.js. */ 26330 var freeProcess = moduleExports && freeGlobal.process; 26331 26332 /** Used to access faster Node.js helpers. */ 26333 var nodeUtil = (function() { 26334 try { 26335
26335return freeProcess && freeProcess.binding && freeProcess.binding('util'); 26336 } catch (e) {} 26337 }()); 26338 26339 /* Node.js helper references. */ 26340 var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, 26341 nodeIsDate = nodeUtil && nodeUtil.isDate, 26342 nodeIsMap = nodeUtil && nodeUtil.isMap, 26343 nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, 26344 nodeIsSet = nodeUtil && nodeUtil.isSet, 26345 nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; 26346 26347 /*--------------------------------------------------------------------------*/ 26348 26349 /** 26350 * Adds the key-value `pair` to `map`. 26351 * 26352 * @private 26353 * @param {Object} map The map to modify. 26354 * @param {Array} pair The key-value pair to add. 26355 * @returns {Object} Returns `map`. 26356 */ 26357 function addMapEntry(map, pair) { 26358 // Don't return `map.set` because it's not chainable in IE 11. 26359 map.set(pair[0], pair[1]); 26360 return map; 26361 } 26362 26363 /** 26364 * Adds `value` to `set`. 26365 * 26366 * @private 26367 * @param {Object} set The set to modify. 26368 * @param {*} value The value to add. 26369 * @returns {Object} Returns `set`. 26370 */ 26371 function addSetEntry(set, value) { 26372 // Don't return `set.add` because it's not chainable in IE 11. 26373 set.add(value); 26374 return set; 26375 }
vendor: 15,023 bytes, lines 26375-26878
26375 26376 26377 /** 26378 * A faster alternative to `Function#apply`, this function invokes `func` 26379 * with the `this` binding of `thisArg` and the arguments of `args`. 26380 * 26381 * @private 26382 * @param {Function} func The function to invoke. 26383 * @param {*} thisArg The `this` binding of `func`. 26384 * @param {Array} args The arguments to invoke `func` with. 26385 * @returns {*} Returns the result of `func`. 26386 */ 26387 function apply(func, thisArg, args) { 26388 switch (args.length) { 26389 case 0: return func.call(thisArg); 26390 case 1: return func.call(thisArg, args[0]); 26391 case 2: return func.call(thisArg, args[0], args[1]); 26392 case 3: return func.call(thisArg, args[0], args[1], args[2]); 26393 } 26394 return func.apply(thisArg, args); 26395 } 26396 26397 /** 26398 * A specialized version of `baseAggregator` for arrays. 26399 * 26400 * @private 26401 * @param {Array} [array] The array to iterate over. 26402 * @param {Function} setter The function to set `accumulator` values. 26403 * @param {Function} iteratee The iteratee to transform keys. 26404 * @param {Object} accumulator The initial aggregated object. 26405 * @returns {Function} Returns `accumulator`. 26406 */ 26407 function arrayAggregator(array, setter, iteratee, accumulator) { 26408 var index = -1, 26409 length = array == null ? 0 : array.length; 26410 26411 while (++index < length) { 26412 var value = array[index]; 26413 setter(accumulator, value, iteratee(value), array); 26414 } 26415 return accumulator; 26416 } 26417 26418 /** 26419 * A specialized version of `_.forEach` for arrays without support for 26420 * iteratee shorthands. 26421 * 26422 * @private 26423 * @param {Array} [array] The array to iterate over. 26424 * @param {Function} iteratee The function invoked per iteration. 26425 * @returns {Array} Returns `array`. 26426 */ 26427 function arrayEach(array, iteratee) { 26428 var index = -1, 26429 length = array == null ? 0 : array.length; 26430 26431 while (++index < length) { 26432 if (iteratee(array[index], index, array) === false) { 26433 break; 26434 } 26435 } 26436 return array; 26437 } 26438 26439 /** 26440 * A specialized version of `_.forEachRight` for arrays without support for 26441 * iteratee shorthands. 26442 * 26443 * @private 26444 * @param {Array} [array] The array to iterate over. 26445 * @param {Function} iteratee The function invoked per iteration. 26446 * @returns {Array} Returns `array`. 26447 */ 26448 function arrayEachRight(array, iteratee) { 26449 var length = array == null ? 0 : array.length; 26450 26451 while (length--) { 26452 if (iteratee(array[length], length, array) === false) { 26453 break; 26454 } 26455 } 26456 return array; 26457 } 26458 26459 /** 26460 * A specialized version of `_.every` for arrays without support for 26461 * iteratee shorthands. 26462 * 26463 * @private 26464 * @param {Array} [array] The array to iterate over. 26465 * @param {Function} predicate The function invoked per iteration. 26466 * @returns {boolean} Returns `true` if all elements pass the predicate check, 26467 * else `false`. 26468 */ 26469 function arrayEvery(array, predicate) { 26470 var index = -1, 26471 length = array == null ? 0 : array.length; 26472 26473 while (++index < length) { 26474 if (!predicate(array[index], index, array)) { 26475 return false; 26476 } 26477 } 26478 return true; 26479 } 26480 26481 /** 26482 * A specialized version of `_.filter` for arrays without support for 26483 * iteratee shorthands. 26484 * 26485 * @private 26486 * @param {Array} [array] The array to iterate over. 26487 * @param {Function} predicate The function invoked per iteration. 26488 * @returns {Array} Returns the new filtered array. 26489 */ 26490 function arrayFilter(array, predicate) { 26491 var index = -1, 26492 length = array == null ? 0 : array.length, 26493 resIndex = 0, 26494 result = []; 26495 26496 while (++index < length) { 26497 var value = array[index]; 26498 if (predicate(value, index, array)) { 26499 result[resIndex++] = value; 26500 } 26501 } 26502 return result; 26503 } 26504 26505 /** 26506 * A specialized version of `_.includes` for arrays without support for 26507 * specifying an index to search from. 26508 * 26509 * @private 26510 * @param {Array} [array] The array to inspect. 26511 * @param {*} target The value to search for. 26512 * @returns {boolean} Returns `true` if `target` is found, else `false`. 26513 */ 26514 function arrayIncludes(array, value) { 26515 var length = array == null ? 0 : array.length; 26516 return !!length && baseIndexOf(array, value, 0) > -1; 26517 } 26518 26519 /** 26520 * This function is like `arrayIncludes` except that it accepts a comparator. 26521 * 26522 * @private 26523 * @param {Array} [array] The array to inspect. 26524 * @param {*} target The value to search for. 26525 * @param {Function} comparator The comparator invoked per element. 26526 * @returns {boolean} Returns `true` if `target` is found, else `false`. 26527 */ 26528 function arrayIncludesWith(array, value, comparator) { 26529 var index = -1, 26530 length = array == null ? 0 : array.length; 26531 26532 while (++index < length) { 26533 if (comparator(value, array[index])) { 26534 return true; 26535 } 26536 } 26537 return false; 26538 } 26539 26540 /** 26541 * A specialized version of `_.map` for arrays without support for iteratee 26542 * shorthands. 26543 * 26544 * @private 26545 * @param {Array} [array] The array to iterate over. 26546 * @param {Function} iteratee The function invoked per iteration. 26547 * @returns {Array} Returns the new mapped array. 26548 */ 26549 function arrayMap(array, iteratee) { 26550 var index = -1, 26551 length = array == null ? 0 : array.length, 26552 result = Array(length); 26553 26554 while (++index < length) { 26555 result[index] = iteratee(array[index], index, array); 26556 } 26557 return result; 26558 } 26559 26560 /** 26561 * Appends the elements of `values` to `array`. 26562 * 26563 * @private 26564 * @param {Array} array The array to modify. 26565 * @param {Array} values The values to append. 26566 * @returns {Array} Returns `array`. 26567 */ 26568 function arrayPush(array, values) { 26569 var index = -1, 26570 length = values.length, 26571 offset = array.length; 26572 26573 while (++index < length) { 26574 array[offset + index] = values[index]; 26575 } 26576 return array; 26577 } 26578 26579 /** 26580 * A specialized version of `_.reduce` for arrays without support for 26581 * iteratee shorthands. 26582 * 26583 * @private 26584 * @param {Array} [array] The array to iterate over. 26585 * @param {Function} iteratee The function invoked per iteration. 26586 * @param {*} [accumulator] The initial value. 26587 * @param {boolean} [initAccum] Specify using the first element of `array` as 26588 * the initial value. 26589 * @returns {*} Returns the accumulated value. 26590 */ 26591 function arrayReduce(array, iteratee, accumulator, initAccum) { 26592 var index = -1, 26593 length = array == null ? 0 : array.length; 26594 26595 if (initAccum && length) { 26596 accumulator = array[++index]; 26597 } 26598 while (++index < length) { 26599 accumulator = iteratee(accumulator, array[index], index, array); 26600 } 26601 return accumulator; 26602 } 26603 26604 /** 26605 * A specialized version of `_.reduceRight` for arrays without support for 26606 * iteratee shorthands. 26607 * 26608 * @private 26609 * @param {Array} [array] The array to iterate over. 26610 * @param {Function} iteratee The function invoked per iteration. 26611 * @param {*} [accumulator] The initial value. 26612 * @param {boolean} [initAccum] Specify using the last element of `array` as 26613 * the initial value. 26614 * @returns {*} Returns the accumulated value. 26615 */ 26616 function arrayReduceRight(array, iteratee, accumulator, initAccum) { 26617 var length = array == null ? 0 : array.length; 26618 if (initAccum && length) { 26619 accumulator = array[--length]; 26620 } 26621 while (length--) { 26622 accumulator = iteratee(accumulator, array[length], length, array); 26623 } 26624 return accumulator; 26625 } 26626 26627 /** 26628 * A specialized version of `_.some` for arrays without support for iteratee 26629 * shorthands. 26630 * 26631 * @private 26632 * @param {Array} [array] The array to iterate over. 26633 * @param {Function} predicate The function invoked per iteration. 26634 * @returns {boolean} Returns `true` if any element passes the predicate check, 26635 * else `false`. 26636 */ 26637 function arraySome(array, predicate) { 26638 var index = -1, 26639 length = array == null ? 0 : array.length; 26640 26641 while (++index < length) { 26642 if (predicate(array[index], index, array)) { 26643 return true; 26644 } 26645 } 26646 return false; 26647 } 26648 26649 /** 26650 * Gets the size of an ASCII `string`. 26651 * 26652 * @private 26653 * @param {string} string The string inspect. 26654 * @returns {number} Returns the string size. 26655 */ 26656 var asciiSize = baseProperty('length'); 26657 26658 /** 26659 * Converts an ASCII `string` to an array. 26660 * 26661 * @private 26662 * @param {string} string The string to convert. 26663 * @returns {Array} Returns the converted array. 26664 */ 26665 function asciiToArray(string) { 26666 return string.split(''); 26667 } 26668 26669 /** 26670 * Splits an ASCII `string` into an array of its words. 26671 * 26672 * @private 26673 * @param {string} The string to inspect. 26674 * @returns {Array} Returns the words of `string`. 26675 */ 26676 function asciiWords(string) { 26677 return string.match(reAsciiWord) || []; 26678 } 26679 26680 /** 26681 * The base implementation of methods like `_.findKey` and `_.findLastKey`, 26682 * without support for iteratee shorthands, which iterates over `collection` 26683 * using `eachFunc`. 26684 * 26685 * @private 26686 * @param {Array|Object} collection The collection to inspect. 26687 * @param {Function} predicate The function invoked per iteration. 26688 * @param {Function} eachFunc The function to iterate over `collection`. 26689 * @returns {*} Returns the found element or its key, else `undefined`. 26690 */ 26691 function baseFindKey(collection, predicate, eachFunc) { 26692 var result; 26693 eachFunc(collection, function(value, key, collection) { 26694 if (predicate(value, key, collection)) { 26695 result = key; 26696 return false; 26697 } 26698 }); 26699 return result; 26700 } 26701 26702 /** 26703 * The base implementation of `_.findIndex` and `_.findLastIndex` without 26704 * support for iteratee shorthands. 26705 * 26706 * @private 26707 * @param {Array} array The array to inspect. 26708 * @param {Function} predicate The function invoked per iteration. 26709 * @param {number} fromIndex The index to search from. 26710 * @param {boolean} [fromRight] Specify iterating from right to left. 26711 * @returns {number} Returns the index of the matched value, else `-1`. 26712 */ 26713 function baseFindIndex(array, predicate, fromIndex, fromRight) { 26714 var length = array.length, 26715 index = fromIndex + (fromRight ? 1 : -1); 26716 26717 while ((fromRight ? index-- : ++index < length)) { 26718 if (predicate(array[index], index, array)) { 26719 return index; 26720 } 26721 } 26722 return -1; 26723 } 26724 26725 /** 26726 * The base implementation of `_.indexOf` without `fromIndex` bounds checks. 26727 * 26728 * @private 26729 * @param {Array} array The array to inspect. 26730 * @param {*} value The value to search for. 26731 * @param {number} fromIndex The index to search from. 26732 * @returns {number} Returns the index of the matched value, else `-1`. 26733 */ 26734 function baseIndexOf(array, value, fromIndex) { 26735 return value === value 26736 ? strictIndexOf(array, value, fromIndex) 26737 : baseFindIndex(array, baseIsNaN, fromIndex); 26738 } 26739 26740 /** 26741 * This function is like `baseIndexOf` except that it accepts a comparator. 26742 * 26743 * @private 26744 * @param {Array} array The array to inspect. 26745 * @param {*} value The value to search for. 26746 * @param {number} fromIndex The index to search from. 26747 * @param {Function} comparator The comparator invoked per element. 26748 * @returns {number} Returns the index of the matched value, else `-1`. 26749 */ 26750 function baseIndexOfWith(array, value, fromIndex, comparator) { 26751 var index = fromIndex - 1, 26752 length = array.length; 26753 26754 while (++index < length) { 26755 if (comparator(array[index], value)) { 26756 return index; 26757 } 26758 } 26759 return -1; 26760 } 26761 26762 /** 26763 * The base implementation of `_.isNaN` without support for number objects. 26764 * 26765 * @private 26766 * @param {*} value The value to check. 26767 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. 26768 */ 26769 function baseIsNaN(value) { 26770 return value !== value; 26771 } 26772 26773 /** 26774 * The base implementation of `_.mean` and `_.meanBy` without support for 26775 * iteratee shorthands. 26776 * 26777 * @private 26778 * @param {Array} array The array to iterate over. 26779 * @param {Function} iteratee The function invoked per iteration. 26780 * @returns {number} Returns the mean. 26781 */ 26782 function baseMean(array, iteratee) { 26783 var length = array == null ? 0 : array.length; 26784 return length ? (baseSum(array, iteratee) / length) : NAN; 26785 } 26786 26787 /** 26788 * The base implementation of `_.property` without support for deep paths. 26789 * 26790 * @private 26791 * @param {string} key The key of the property to get. 26792 * @returns {Function} Returns the new accessor function. 26793 */ 26794 function baseProperty(key) { 26795 return function(object) { 26796 return object == null ? undefined : object[key]; 26797 }; 26798 } 26799 26800 /** 26801 * The base implementation of `_.propertyOf` without support for deep paths. 26802 * 26803 * @private 26804 * @param {Object} object The object to query. 26805 * @returns {Function} Returns the new accessor function. 26806 */ 26807 function basePropertyOf(object) { 26808 return function(key) { 26809 return object == null ? undefined : object[key]; 26810 }; 26811 } 26812 26813 /** 26814 * The base implementation of `_.reduce` and `_.reduceRight`, without support 26815 * for iteratee shorthands, which iterates over `collection` using `eachFunc`. 26816 * 26817 * @private 26818 * @param {Array|Object} collection The collection to iterate over. 26819 * @param {Function} iteratee The function invoked per iteration. 26820 * @param {*} accumulator The initial value. 26821 * @param {boolean} initAccum Specify using the first or last element of 26822 * `collection` as the initial value. 26823 * @param {Function} eachFunc The function to iterate over `collection`. 26824 * @returns {*} Returns the accumulated value. 26825 */ 26826 function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { 26827 eachFunc(collection, function(value, index, collection) { 26828 accumulator = initAccum 26829 ? (initAccum = false, value) 26830 : iteratee(accumulator, value, index, collection); 26831 }); 26832 return accumulator; 26833 } 26834 26835 /** 26836 * The base implementation of `_.sortBy` which uses `comparer` to define the 26837 * sort order of `array` and replaces criteria objects with their corresponding 26838 * values. 26839 * 26840 * @private 26841 * @param {Array} array The array to sort. 26842 * @param {Function} comparer The function to define sort order. 26843 * @returns {Array} Returns `array`. 26844 */ 26845 function baseSortBy(array, comparer) { 26846 var length = array.length; 26847 26848 array.sort(comparer); 26849 while (length--) { 26850 array[length] = array[length].value; 26851 } 26852 return array; 26853 } 26854 26855 /** 26856 * The base implementation of `_.sum` and `_.sumBy` without support for 26857 * iteratee shorthands. 26858 * 26859 * @private 26860 * @param {Array} array The array to iterate over. 26861 * @param {Function} iteratee The function invoked per iteration. 26862 * @returns {number} Returns the sum. 26863 */ 26864 function baseSum(array, iteratee) { 26865 var result, 26866 index = -1, 26867 length = array.length; 26868 26869 while (++index < length) { 26870 var current = iteratee(array[index]); 26871 if (current !== undefined) { 26872 result = result === undefined ? current : (result + current); 26873 } 26874 } 26875 return result; 26876 } 26877 26878 /**
vendor: 5,596 bytes, lines 26879-27071
26879 * The base implementation of `_.times` without support for iteratee shorthands 26880 * or max array length checks. 26881 * 26882 * @private 26883 * @param {number} n The number of times to invoke `iteratee`. 26884 * @param {Function} iteratee The function invoked per iteration. 26885 * @returns {Array} Returns the array of results. 26886 */ 26887 function baseTimes(n, iteratee) { 26888 var index = -1, 26889 result = Array(n); 26890 26891 while (++index < n) { 26892 result[index] = iteratee(index); 26893 } 26894 return result; 26895 } 26896 26897 /** 26898 * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array 26899 * of key-value pairs for `object` corresponding to the property names of `props`. 26900 * 26901 * @private 26902 * @param {Object} object The object to query. 26903 * @param {Array} props The property names to get values for. 26904 * @returns {Object} Returns the key-value pairs. 26905 */ 26906 function baseToPairs(object, props) { 26907 return arrayMap(props, function(key) { 26908 return [key, object[key]]; 26909 }); 26910 } 26911 26912 /** 26913 * The base implementation of `_.unary` without support for storing metadata. 26914 * 26915 * @private 26916 * @param {Function} func The function to cap arguments for. 26917 * @returns {Function} Returns the new capped function. 26918 */ 26919 function baseUnary(func) { 26920 return function(value) { 26921 return func(value); 26922 }; 26923 } 26924 26925 /** 26926 * The base implementation of `_.values` and `_.valuesIn` which creates an 26927 * array of `object` property values corresponding to the property names 26928 * of `props`. 26929 * 26930 * @private 26931 * @param {Object} object The object to query. 26932 * @param {Array} props The property names to get values for. 26933 * @returns {Object} Returns the array of property values. 26934 */ 26935 function baseValues(object, props) { 26936 return arrayMap(props, function(key) { 26937 return object[key]; 26938 }); 26939 } 26940 26941 /** 26942 * Checks if a `cache` value for `key` exists. 26943 * 26944 * @private 26945 * @param {Object} cache The cache to query. 26946 * @param {string} key The key of the entry to check. 26947 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. 26948 */ 26949 function cacheHas(cache, key) { 26950 return cache.has(key); 26951 } 26952 26953 /** 26954 * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol 26955 * that is not found in the character symbols. 26956 * 26957 * @private 26958 * @param {Array} strSymbols The string symbols to inspect. 26959 * @param {Array} chrSymbols The character symbols to find. 26960 * @returns {number} Returns the index of the first unmatched string symbol. 26961 */ 26962 function charsStartIndex(strSymbols, chrSymbols) { 26963 var index = -1, 26964 length = strSymbols.length; 26965 26966 while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} 26967 return index; 26968 } 26969 26970 /** 26971 * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol 26972 * that is not found in the character symbols. 26973 * 26974 * @private 26975 * @param {Array} strSymbols The string symbols to inspect. 26976 * @param {Array} chrSymbols The character symbols to find. 26977 * @returns {number} Returns the index of the last unmatched string symbol. 26978 */ 26979 function charsEndIndex(strSymbols, chrSymbols) { 26980 var index = strSymbols.length; 26981 26982 while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} 26983 return index; 26984 } 26985 26986 /** 26987 * Gets the number of `placeholder` occurrences in `array`. 26988 * 26989 * @private 26990 * @param {Array} array The array to inspect. 26991 * @param {*} placeholder The placeholder to search for. 26992 * @returns {number} Returns the placeholder count. 26993 */ 26994 function countHolders(array, placeholder) { 26995 var length = array.length, 26996 result = 0; 26997 26998 while (length--) { 26999 if (array[length] === placeholder) { 27000 ++result; 27001 } 27002 } 27003 return result; 27004 } 27005 27006 /** 27007 * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A 27008 * letters to basic Latin letters. 27009 * 27010 * @private 27011 * @param {string} letter The matched letter to deburr. 27012 * @returns {string} Returns the deburred letter. 27013 */ 27014 var deburrLetter = basePropertyOf(deburredLetters); 27015 27016 /** 27017 * Used by `_.escape` to convert characters to HTML entities. 27018 * 27019 * @private 27020 * @param {string} chr The matched character to escape. 27021 * @returns {string} Returns the escaped character. 27022 */ 27023 var escapeHtmlChar = basePropertyOf(htmlEscapes); 27024 27025 /** 27026 * Used by `_.template` to escape characters for inclusion in compiled string literals. 27027 * 27028 * @private 27029 * @param {string} chr The matched character to escape. 27030 * @returns {string} Returns the escaped character. 27031 */ 27032 function escapeStringChar(chr) { 27033 return '\\' + stringEscapes[chr]; 27034 } 27035 27036 /** 27037 * Gets the value at `key` of `object`. 27038 * 27039 * @private 27040 * @param {Object} [object] The object to query. 27041 * @param {string} key The key of the property to get. 27042 * @returns {*} Returns the property value. 27043 */ 27044 function getValue(object, key) { 27045 return object == null ? undefined : object[key]; 27046 } 27047 27048 /** 27049 * Checks if `string` contains Unicode symbols. 27050 * 27051 * @private 27052 * @param {string} string The string to inspect. 27053 * @returns {boolean} Returns `true` if a symbol is found, else `false`. 27054 */ 27055 function hasUnicode(string) { 27056 return reHasUnicode.test(string); 27057 } 27058 27059 /** 27060 * Checks if `string` contains a word composed of Unicode symbols. 27061 * 27062 * @private 27063 * @param {string} string The string to inspect. 27064 * @returns {boolean} Returns `true` if a word is found, else `false`. 27065 */ 27066 function hasUnicodeWord(string) { 27067 return reHasUnicodeWord.test(string); 27068 } 27069 27070 /** 27071 * Converts `iterator` to an array.
vendor: 4,118 bytes, lines 27072-27237
27072 * 27073 * @private 27074 * @param {Object} iterator The iterator to convert. 27075 * @returns {Array} Returns the converted array. 27076 */ 27077 function iteratorToArray(iterator) { 27078 var data, 27079 result = []; 27080 27081 while (!(data = iterator.next()).done) { 27082 result.push(data.value); 27083 } 27084 return result; 27085 } 27086 27087 /** 27088 * Converts `map` to its key-value pairs. 27089 * 27090 * @private 27091 * @param {Object} map The map to convert. 27092 * @returns {Array} Returns the key-value pairs. 27093 */ 27094 function mapToArray(map) { 27095 var index = -1, 27096 result = Array(map.size); 27097 27098 map.forEach(function(value, key) { 27099 result[++index] = [key, value]; 27100 }); 27101 return result; 27102 } 27103 27104 /** 27105 * Creates a unary function that invokes `func` with its argument transformed. 27106 * 27107 * @private 27108 * @param {Function} func The function to wrap. 27109 * @param {Function} transform The argument transform. 27110 * @returns {Function} Returns the new function. 27111 */ 27112 function overArg(func, transform) { 27113 return function(arg) { 27114 return func(transform(arg)); 27115 }; 27116 } 27117 27118 /** 27119 * Replaces all `placeholder` elements in `array` with an internal placeholder 27120 * and returns an array of their indexes. 27121 * 27122 * @private 27123 * @param {Array} array The array to modify. 27124 * @param {*} placeholder The placeholder to replace. 27125 * @returns {Array} Returns the new array of placeholder indexes. 27126 */ 27127 function replaceHolders(array, placeholder) { 27128 var index = -1, 27129 length = array.length, 27130 resIndex = 0, 27131 result = []; 27132 27133 while (++index < length) { 27134 var value = array[index]; 27135 if (value === placeholder || value === PLACEHOLDER) { 27136 array[index] = PLACEHOLDER; 27137 result[resIndex++] = index; 27138 } 27139 } 27140 return result; 27141 } 27142 27143 /** 27144 * Converts `set` to an array of its values. 27145 * 27146 * @private 27147 * @param {Object} set The set to convert. 27148 * @returns {Array} Returns the values. 27149 */ 27150 function setToArray(set) { 27151 var index = -1, 27152 result = Array(set.size); 27153 27154 set.forEach(function(value) { 27155 result[++index] = value; 27156 }); 27157 return result; 27158 } 27159 27160 /** 27161 * Converts `set` to its value-value pairs. 27162 * 27163 * @private 27164 * @param {Object} set The set to convert. 27165 * @returns {Array} Returns the value-value pairs. 27166 */ 27167 function setToPairs(set) { 27168 var index = -1, 27169 result = Array(set.size); 27170 27171 set.forEach(function(value) { 27172 result[++index] = [value, value]; 27173 }); 27174 return result; 27175 } 27176 27177 /** 27178 * A specialized version of `_.indexOf` which performs strict equality 27179 * comparisons of values, i.e. `===`. 27180 * 27181 * @private 27182 * @param {Array} array The array to inspect. 27183 * @param {*} value The value to search for. 27184 * @param {number} fromIndex The index to search from. 27185 * @returns {number} Returns the index of the matched value, else `-1`. 27186 */ 27187 function strictIndexOf(array, value, fromIndex) { 27188 var index = fromIndex - 1, 27189 length = array.length; 27190 27191 while (++index < length) { 27192 if (array[index] === value) { 27193 return index; 27194 } 27195 } 27196 return -1; 27197 } 27198 27199 /** 27200 * A specialized version of `_.lastIndexOf` which performs strict equality 27201 * comparisons of values, i.e. `===`. 27202 * 27203 * @private 27204 * @param {Array} array The array to inspect. 27205 * @param {*} value The value to search for. 27206 * @param {number} fromIndex The index to search from. 27207 * @returns {number} Returns the index of the matched value, else `-1`. 27208 */ 27209 function strictLastIndexOf(array, value, fromIndex) { 27210 var index = fromIndex + 1; 27211 while (index--) { 27212 if (array[index] === value) { 27213 return index; 27214 } 27215 } 27216 return index; 27217 } 27218 27219 /** 27220 * Gets the number of symbols in `string`. 27221 * 27222 * @private 27223 * @param {string} string The string to inspect. 27224 * @returns {number} Returns the string size. 27225 */ 27226 function stringSize(string) { 27227 return hasUnicode(string) 27228 ? unicodeSize(string) 27229 : asciiSize(string); 27230 } 27231 27232 /** 27233 * Converts `string` to an array. 27234 * 27235 * @private 27236 * @param {string} string The string to convert. 27237 * @returns {Array} Returns the converted array.
vendor: 10,876 bytes, lines 27238-27511
27238 */ 27239 function stringToArray(string) { 27240 return hasUnicode(string) 27241 ? unicodeToArray(string) 27242 : asciiToArray(string); 27243 } 27244 27245 /** 27246 * Used by `_.unescape` to convert HTML entities to characters. 27247 * 27248 * @private 27249 * @param {string} chr The matched character to unescape. 27250 * @returns {string} Returns the unescaped character. 27251 */ 27252 var unescapeHtmlChar = basePropertyOf(htmlUnescapes); 27253 27254 /** 27255 * Gets the size of a Unicode `string`. 27256 * 27257 * @private 27258 * @param {string} string The string inspect. 27259 * @returns {number} Returns the string size. 27260 */ 27261 function unicodeSize(string) { 27262 var result = reUnicode.lastIndex = 0; 27263 while (reUnicode.test(string)) { 27264 ++result; 27265 } 27266 return result; 27267 } 27268 27269 /** 27270 * Converts a Unicode `string` to an array. 27271 * 27272 * @private 27273 * @param {string} string The string to convert. 27274 * @returns {Array} Returns the converted array. 27275 */ 27276 function unicodeToArray(string) { 27277 return string.match(reUnicode) || []; 27278 } 27279 27280 /** 27281 * Splits a Unicode `string` into an array of its words. 27282 * 27283 * @private 27284 * @param {string} The string to inspect. 27285 * @returns {Array} Returns the words of `string`. 27286 */ 27287 function unicodeWords(string) { 27288 return string.match(reUnicodeWord) || []; 27289 } 27290 27291 /*--------------------------------------------------------------------------*/ 27292 27293 /** 27294 * Create a new pristine `lodash` function using the `context` object. 27295 * 27296 * @static 27297 * @memberOf _ 27298 * @since 1.1.0 27299 * @category Util 27300 * @param {Object} [context=root] The context object. 27301 * @returns {Function} Returns a new `lodash` function. 27302 * @example 27303 * 27304 * _.mixin({ 'foo': _.constant('foo') }); 27305 * 27306 * var lodash = _.runInContext(); 27307 * lodash.mixin({ 'bar': lodash.constant('bar') }); 27308 * 27309 * _.isFunction(_.foo); 27310 * // => true 27311 * _.isFunction(_.bar); 27312 * // => false 27313 * 27314 * lodash.isFunction(lodash.foo); 27315 * // => false 27316 * lodash.isFunction(lodash.bar); 27317 * // => true 27318 * 27319 * // Create a suped-up `defer` in Node.js. 27320 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; 27321 */ 27322 var runInContext = (function runInContext(context) { 27323 context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); 27324 27325 /** Built-in constructor references. */ 27326 var Array = context.Array, 27327 Date = context.Date, 27328 Error = context.Error, 27329 Function = context.Function, 27330 Math = context.Math, 27331 Object = context.Object, 27332 RegExp = context.RegExp, 27333 String = context.String, 27334 TypeError = context.TypeError; 27335 27336 /** Used for built-in method references. */ 27337 var arrayProto = Array.prototype, 27338 funcProto = Function.prototype, 27339 objectProto = Object.prototype; 27340 27341 /** Used to detect overreaching core-js shims. */ 27342 var coreJsData = context['__core-js_shared__']; 27343 27344 /** Used to resolve the decompiled source of functions. */ 27345 var funcToString = funcProto.toString; 27346 27347 /** Used to check objects for own properties. */ 27348 var hasOwnProperty = objectProto.hasOwnProperty; 27349 27350 /** Used to generate unique IDs. */ 27351 var idCounter = 0; 27352 27353 /** Used to detect methods masquerading as native. */ 27354 var maskSrcKey = (function() { 27355 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); 27356 return uid ? ('Symbol(src)_1.' + uid) : ''; 27357 }()); 27358 27359 /** 27360 * Used to resolve the 27361 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) 27362 * of values. 27363 */ 27364 var nativeObjectToString = objectProto.toString; 27365 27366 /** Used to infer the `Object` constructor. */ 27367 var objectCtorString = funcToString.call(Object); 27368 27369 /** Used to restore the original `_` reference in `_.noConflict`. */ 27370 var oldDash = root._; 27371 27372 /** Used to detect if a method is native. */ 27373 var reIsNative = RegExp('^' + 27374 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') 27375 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' 27376 ); 27377 27378 /** Built-in value references. */ 27379 var Buffer = moduleExports ? context.Buffer : undefined, 27380 Symbol = context.Symbol, 27381 Uint8Array = context.Uint8Array, 27382 allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, 27383 getPrototype = overArg(Object.getPrototypeOf, Object), 27384 objectCreate = Object.create, 27385 propertyIsEnumerable = objectProto.propertyIsEnumerable, 27386 splice = arrayProto.splice, 27387 spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, 27388 symIterator = Symbol ? Symbol.iterator : undefined, 27389 symToStringTag = Symbol ? Symbol.toStringTag : undefined; 27390 27391 var defineProperty = (function() { 27392 try { 27393 var func = getNative(Object, 'defineProperty'); 27394 func({}, '', {}); 27395 return func; 27396 } catch (e) {} 27397 }()); 27398 27399 /** Mocked built-ins. */ 27400 var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, 27401 ctxNow = Date && Date.now !== root.Date.now && Date.now, 27402 ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; 27403 27404 /* Built-in method references for those with the same name as other `lodash` methods. */ 27405 var nativeCeil = Math.ceil, 27406 nativeFloor = Math.floor, 27407 nativeGetSymbols = Object.getOwnPropertySymbols, 27408 nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, 27409 nativeIsFinite = context.isFinite, 27410 nativeJoin = arrayProto.join, 27411 nativeKeys = overArg(Object.keys, Object), 27412 nativeMax = Math.max, 27413 nativeMin = Math.min, 27414 nativeNow = Date.now, 27415 nativeParseInt = context.parseInt, 27416 nativeRandom = Math.random, 27417 nativeReverse = arrayProto.reverse; 27418 27419 /* Built-in method references that are verified to be native. */ 27420 var DataView = getNative(context, 'DataView'), 27421 Map = getNative(context, 'Map'), 27422 Promise = getNative(context, 'Promise'), 27423 Set = getNative(context, 'Set'), 27424 WeakMap = getNative(context, 'WeakMap'), 27425 nativeCreate = getNative(Object, 'create'); 27426 27427 /** Used to store function metadata. */ 27428 var metaMap = WeakMap && new WeakMap; 27429 27430 /** Used to lookup unminified function names. */ 27431 var realNames = {}; 27432 27433 /** Used to detect maps, sets, and weakmaps. */ 27434 var dataViewCtorString = toSource(DataView), 27435 mapCtorString = toSource(Map), 27436 promiseCtorString = toSource(Promise), 27437 setCtorString = toSource(Set), 27438 weakMapCtorString = toSource(WeakMap); 27439 27440 /** Used to convert symbols to primitives and strings. */ 27441 var symbolProto = Symbol ? Symbol.prototype : undefined, 27442 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, 27443 symbolToString = symbolProto ? symbolProto.toString : undefined; 27444 27445 /*------------------------------------------------------------------------*/ 27446 27447 /** 27448 * Creates a `lodash` object which wraps `value` to enable implicit method 27449 * chain sequences. Methods that operate on and return arrays, collections, 27450 * and functions can be chained together. Methods that retrieve a single value 27451 * or may return a primitive value will automatically end the chain sequence 27452 * and return the unwrapped value. Otherwise, the value must be unwrapped 27453 * with `_#value`. 27454 * 27455 * Explicit chain sequences, which must be unwrapped with `_#value`, may be 27456 * enabled using `_.chain`. 27457 * 27458 * The execution of chained methods is lazy, that is, it's deferred until 27459 * `_#value` is implicitly or explicitly called. 27460 * 27461 * Lazy evaluation allows several methods to support shortcut fusion. 27462 * Shortcut fusion is an optimization to merge iteratee calls; this avoids 27463 * the creation of intermediate arrays and can greatly reduce the number of 27464 * iteratee executions. Sections of a chain sequence qualify for shortcut 27465 * fusion if the section is applied to an array and iteratees accept only 27466 * one argument. The heuristic for whether a section qualifies for shortcut 27467 * fusion is subject to change. 27468 * 27469 * Chaining is supported in custom builds as long as the `_#value` method is 27470 * directly or indirectly included in the build. 27471 * 27472 * In addition to lodash methods, wrappers have `Array` and `String` methods. 27473 * 27474 * The wrapper `Array` methods are: 27475 * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` 27476 * 27477 * The wrapper `String` methods are: 27478 * `replace` and `split` 27479 * 27480 * The wrapper methods that support shortcut fusion are: 27481 * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, 27482 * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, 27483 * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` 27484 * 27485 * The chainable wrapper methods are: 27486 * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, 27487 * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, 27488 * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, 27489 * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, 27490 * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, 27491 * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, 27492 * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, 27493 * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, 27494 * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, 27495 * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, 27496 * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, 27497 * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, 27498 * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, 27499 * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, 27500 * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, 27501 * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, 27502 * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, 27503 * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, 27504 * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, 27505 * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, 27506 * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, 27507 * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, 27508 * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, 27509 * `zipObject`, `zipObjectDeep`, and `zipWith` 27510 * 27511 * The wrapper methods that are **not** chainable by default are:
vendor: 18,450 bytes, lines 27512-28164
27512 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, 27513 * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, 27514 * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, 27515 * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, 27516 * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, 27517 * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, 27518 * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, 27519 * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, 27520 * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, 27521 * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, 27522 * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, 27523 * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, 27524 * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, 27525 * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, 27526 * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, 27527 * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, 27528 * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, 27529 * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, 27530 * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, 27531 * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, 27532 * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, 27533 * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, 27534 * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, 27535 * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, 27536 * `upperFirst`, `value`, and `words` 27537 * 27538 * @name _ 27539 * @constructor 27540 * @category Seq 27541 * @param {*} value The value to wrap in a `lodash` instance. 27542 * @returns {Object} Returns the new `lodash` wrapper instance. 27543 * @example 27544 * 27545 * function square(n) { 27546 * return n * n; 27547 * } 27548 * 27549 * var wrapped = _([1, 2, 3]); 27550 * 27551 * // Returns an unwrapped value. 27552 * wrapped.reduce(_.add); 27553 * // => 6 27554 * 27555 * // Returns a wrapped value. 27556 * var squares = wrapped.map(square); 27557 * 27558 * _.isArray(squares); 27559 * // => false 27560 * 27561 * _.isArray(squares.value()); 27562 * // => true 27563 */ 27564 function lodash(value) { 27565 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { 27566 if (value instanceof LodashWrapper) { 27567 return value; 27568 } 27569 if (hasOwnProperty.call(value, '__wrapped__')) { 27570 return wrapperClone(value); 27571 } 27572 } 27573 return new LodashWrapper(value); 27574 } 27575 27576 /** 27577 * The base implementation of `_.create` without support for assigning 27578 * properties to the created object. 27579 * 27580 * @private 27581 * @param {Object} proto The object to inherit from. 27582 * @returns {Object} Returns the new object. 27583 */ 27584 var baseCreate = (function() { 27585 function object() {} 27586 return function(proto) { 27587 if (!isObject(proto)) { 27588 return {}; 27589 } 27590 if (objectCreate) { 27591 return objectCreate(proto); 27592 } 27593 object.prototype = proto; 27594 var result = new object; 27595 object.prototype = undefined; 27596 return result; 27597 }; 27598 }()); 27599 27600 /** 27601 * The function whose prototype chain sequence wrappers inherit from. 27602 * 27603 * @private 27604 */ 27605 function baseLodash() { 27606 // No operation performed. 27607 } 27608 27609 /** 27610 * The base constructor for creating `lodash` wrapper objects. 27611 * 27612 * @private 27613 * @param {*} value The value to wrap. 27614 * @param {boolean} [chainAll] Enable explicit method chain sequences. 27615 */ 27616 function LodashWrapper(value, chainAll) { 27617 this.__wrapped__ = value; 27618 this.__actions__ = []; 27619 this.__chain__ = !!chainAll; 27620 this.__index__ = 0; 27621 this.__values__ = undefined; 27622 } 27623 27624 /** 27625 * By default, the template delimiters used by lodash are like those in 27626 * embedded Ruby (ERB) as well as ES2015 template strings. Change the 27627 * following template settings to use alternative delimiters. 27628 * 27629 * @static 27630 * @memberOf _ 27631 * @type {Object} 27632 */ 27633 lodash.templateSettings = { 27634 27635 /** 27636 * Used to detect `data` property values to be HTML-escaped. 27637 * 27638 * @memberOf _.templateSettings 27639 * @type {RegExp} 27640 */ 27641 'escape': reEscape, 27642 27643 /** 27644 * Used to detect code to be evaluated. 27645 * 27646 * @memberOf _.templateSettings 27647 * @type {RegExp} 27648 */ 27649 'evaluate': reEvaluate, 27650 27651 /** 27652 * Used to detect `data` property values to inject. 27653 * 27654 * @memberOf _.templateSettings 27655 * @type {RegExp} 27656 */ 27657 'interpolate': reInterpolate, 27658 27659 /** 27660 * Used to reference the data object in the template text. 27661 * 27662 * @memberOf _.templateSettings 27663 * @type {string} 27664 */ 27665 'variable': '', 27666 27667 /** 27668 * Used to import variables into the compiled template. 27669 * 27670 * @memberOf _.templateSettings 27671 * @type {Object} 27672 */ 27673 'imports': { 27674 27675 /** 27676 * A reference to the `lodash` function. 27677 * 27678 * @memberOf _.templateSettings.imports 27679 * @type {Function} 27680 */ 27681 '_': lodash 27682 } 27683 }; 27684 27685 // Ensure wrappers are instances of `baseLodash`. 27686 lodash.prototype = baseLodash.prototype; 27687 lodash.prototype.constructor = lodash; 27688 27689 LodashWrapper.prototype = baseCreate(baseLodash.prototype); 27690 LodashWrapper.prototype.constructor = LodashWrapper; 27691 27692 /*------------------------------------------------------------------------*/ 27693 27694 /** 27695 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. 27696 * 27697 * @private 27698 * @constructor 27699 * @param {*} value The value to wrap. 27700 */ 27701 function LazyWrapper(value) { 27702 this.__wrapped__ = value; 27703 this.__actions__ = []; 27704 this.__dir__ = 1; 27705 this.__filtered__ = false; 27706 this.__iteratees__ = []; 27707 this.__takeCount__ = MAX_ARRAY_LENGTH; 27708 this.__views__ = []; 27709 } 27710 27711 /** 27712 * Creates a clone of the lazy wrapper object. 27713 * 27714 * @private 27715 * @name clone 27716 * @memberOf LazyWrapper 27717 * @returns {Object} Returns the cloned `LazyWrapper` object. 27718 */ 27719 function lazyClone() { 27720 var result = new LazyWrapper(this.__wrapped__); 27721 result.__actions__ = copyArray(this.__actions__); 27722 result.__dir__ = this.__dir__; 27723 result.__filtered__ = this.__filtered__; 27724 result.__iteratees__ = copyArray(this.__iteratees__); 27725 result.__takeCount__ = this.__takeCount__; 27726 result.__views__ = copyArray(this.__views__); 27727 return result; 27728 } 27729 27730 /** 27731 * Reverses the direction of lazy iteration. 27732 * 27733 * @private 27734 * @name reverse 27735 * @memberOf LazyWrapper 27736 * @returns {Object} Returns the new reversed `LazyWrapper` object. 27737 */ 27738 function lazyReverse() { 27739 if (this.__filtered__) { 27740 var result = new LazyWrapper(this); 27741 result.__dir__ = -1; 27742 result.__filtered__ = true; 27743 } else { 27744 result = this.clone(); 27745 result.__dir__ *= -1; 27746 } 27747 return result; 27748 } 27749 27750 /** 27751 * Extracts the unwrapped value from its lazy wrapper. 27752 * 27753 * @private 27754 * @name value 27755 * @memberOf LazyWrapper 27756 * @returns {*} Returns the unwrapped value. 27757 */ 27758 function lazyValue() { 27759 var array = this.__wrapped__.value(), 27760 dir = this.__dir__, 27761 isArr = isArray(array), 27762 isRight = dir < 0, 27763 arrLength = isArr ? array.length : 0, 27764 view = getView(0, arrLength, this.__views__), 27765 start = view.start, 27766 end = view.end, 27767 length = end - start, 27768 index = isRight ? end : (start - 1), 27769 iteratees = this.__iteratees__, 27770 iterLength = iteratees.length, 27771 resIndex = 0, 27772 takeCount = nativeMin(length, this.__takeCount__); 27773 27774 if (!isArr || (!isRight && arrLength == length && takeCount == length)) { 27775 return baseWrapperValue(array, this.__actions__); 27776 } 27777 var result = []; 27778 27779 outer: 27780 while (length-- && resIndex < takeCount) { 27781 index += dir; 27782 27783 var iterIndex = -1, 27784 value = array[index]; 27785 27786 while (++iterIndex < iterLength) { 27787 var data = iteratees[iterIndex], 27788 iteratee = data.iteratee, 27789 type = data.type, 27790 computed = iteratee(value); 27791 27792 if (type == LAZY_MAP_FLAG) { 27793 value = computed; 27794 } else if (!computed) { 27795 if (type == LAZY_FILTER_FLAG) { 27796 continue outer; 27797 } else { 27798 break outer; 27799 } 27800 } 27801 } 27802 result[resIndex++] = value; 27803 } 27804 return result; 27805 } 27806 27807 // Ensure `LazyWrapper` is an instance of `baseLodash`. 27808 LazyWrapper.prototype = baseCreate(baseLodash.prototype); 27809 LazyWrapper.prototype.constructor = LazyWrapper; 27810 27811 /*------------------------------------------------------------------------*/ 27812 27813 /** 27814 * Creates a hash object. 27815 * 27816 * @private 27817 * @constructor 27818 * @param {Array} [entries] The key-value pairs to cache. 27819 */ 27820 function Hash(entries) { 27821 var index = -1, 27822 length = entries == null ? 0 : entries.length; 27823 27824 this.clear(); 27825 while (++index < length) { 27826 var entry = entries[index]; 27827 this.set(entry[0], entry[1]); 27828 } 27829 } 27830 27831 /** 27832 * Removes all key-value entries from the hash. 27833 * 27834 * @private 27835 * @name clear 27836 * @memberOf Hash 27837 */ 27838 function hashClear() { 27839 this.__data__ = nativeCreate ? nativeCreate(null) : {}; 27840 this.size = 0; 27841 } 27842 27843 /** 27844 * Removes `key` and its value from the hash. 27845 * 27846 * @private 27847 * @name delete 27848 * @memberOf Hash 27849 * @param {Object} hash The hash to modify. 27850 * @param {string} key The key of the value to remove. 27851 * @returns {boolean} Returns `true` if the entry was removed, else `false`. 27852 */ 27853 function hashDelete(key) { 27854 var result = this.has(key) && delete this.__data__[key]; 27855 this.size -= result ? 1 : 0; 27856 return result; 27857 } 27858 27859 /** 27860 * Gets the hash value for `key`. 27861 * 27862 * @private 27863 * @name get 27864 * @memberOf Hash 27865 * @param {string} key The key of the value to get. 27866 * @returns {*} Returns the entry value. 27867 */ 27868 function hashGet(key) { 27869 var data = this.__data__; 27870 if (nativeCreate) { 27871 var result = data[key]; 27872 return result === HASH_UNDEFINED ? undefined : result; 27873 } 27874 return hasOwnProperty.call(data, key) ? data[key] : undefined; 27875 } 27876 27877 /** 27878 * Checks if a hash value for `key` exists. 27879 * 27880 * @private 27881 * @name has 27882 * @memberOf Hash 27883 * @param {string} key The key of the entry to check. 27884 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. 27885 */ 27886 function hashHas(key) { 27887 var data = this.__data__; 27888 return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); 27889 } 27890 27891 /** 27892 * Sets the hash `key` to `value`. 27893 * 27894 * @private 27895 * @name set 27896 * @memberOf Hash 27897 * @param {string} key The key of the value to set. 27898 * @param {*} value The value to set. 27899 * @returns {Object} Returns the hash instance. 27900 */ 27901 function hashSet(key, value) { 27902 var data = this.__data__; 27903 this.size += this.has(key) ? 0 : 1; 27904 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; 27905 return this; 27906 } 27907 27908 // Add methods to `Hash`. 27909 Hash.prototype.clear = hashClear; 27910 Hash.prototype['delete'] = hashDelete; 27911 Hash.prototype.get = hashGet; 27912 Hash.prototype.has = hashHas; 27913 Hash.prototype.set = hashSet; 27914 27915 /*------------------------------------------------------------------------*/ 27916 27917 /** 27918 * Creates an list cache object. 27919 * 27920 * @private 27921 * @constructor 27922 * @param {Array} [entries] The key-value pairs to cache. 27923 */ 27924 function ListCache(entries) { 27925 var index = -1, 27926 length = entries == null ? 0 : entries.length; 27927 27928 this.clear(); 27929 while (++index < length) { 27930 var entry = entries[index]; 27931 this.set(entry[0], entry[1]); 27932 } 27933 } 27934 27935 /** 27936 * Removes all key-value entries from the list cache. 27937 * 27938 * @private 27939 * @name clear 27940 * @memberOf ListCache 27941 */ 27942 function listCacheClear() { 27943 this.__data__ = []; 27944 this.size = 0; 27945 } 27946 27947 /** 27948 * Removes `key` and its value from the list cache. 27949 * 27950 * @private 27951 * @name delete 27952 * @memberOf ListCache 27953 * @param {string} key The key of the value to remove. 27954 * @returns {boolean} Returns `true` if the entry was removed, else `false`. 27955 */ 27956 function listCacheDelete(key) { 27957 var data = this.__data__, 27958 index = assocIndexOf(data, key); 27959 27960 if (index < 0) { 27961 return false; 27962 } 27963 var lastIndex = data.length - 1; 27964 if (index == lastIndex) { 27965 data.pop(); 27966 } else { 27967 splice.call(data, index, 1); 27968 } 27969 --this.size; 27970 return true; 27971 } 27972 27973 /** 27974 * Gets the list cache value for `key`. 27975 * 27976 * @private 27977 * @name get 27978 * @memberOf ListCache 27979 * @param {string} key The key of the value to get. 27980 * @returns {*} Returns the entry value. 27981 */ 27982 function listCacheGet(key) { 27983 var data = this.__data__, 27984 index = assocIndexOf(data, key); 27985 27986 return index < 0 ? undefined : data[index][1]; 27987 } 27988 27989 /** 27990 * Checks if a list cache value for `key` exists. 27991 * 27992 * @private 27993 * @name has 27994 * @memberOf ListCache 27995 * @param {string} key The key of the entry to check. 27996 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. 27997 */ 27998 function listCacheHas(key) { 27999 return assocIndexOf(this.__data__, key) > -1; 28000 } 28001 28002 /** 28003 * Sets the list cache `key` to `value`. 28004 * 28005 * @private 28006 * @name set 28007 * @memberOf ListCache 28008 * @param {string} key The key of the value to set. 28009 * @param {*} value The value to set. 28010 * @returns {Object} Returns the list cache instance. 28011 */ 28012 function listCacheSet(key, value) { 28013 var data = this.__data__, 28014 index = assocIndexOf(data, key); 28015 28016 if (index < 0) { 28017 ++this.size; 28018 data.push([key, value]); 28019 } else { 28020 data[index][1] = value; 28021 } 28022 return this; 28023 } 28024 28025 // Add methods to `ListCache`. 28026 ListCache.prototype.clear = listCacheClear; 28027 ListCache.prototype['delete'] = listCacheDelete; 28028 ListCache.prototype.get = listCacheGet; 28029 ListCache.prototype.has = listCacheHas; 28030 ListCache.prototype.set = listCacheSet; 28031 28032 /*------------------------------------------------------------------------*/ 28033 28034 /** 28035 * Creates a map cache object to store key-value pairs. 28036 * 28037 * @private 28038 * @constructor 28039 * @param {Array} [entries] The key-value pairs to cache. 28040 */ 28041 function MapCache(entries) { 28042 var index = -1, 28043 length = entries == null ? 0 : entries.length; 28044 28045 this.clear(); 28046 while (++index < length) { 28047 var entry = entries[index]; 28048 this.set(entry[0], entry[1]); 28049 } 28050 } 28051 28052 /** 28053 * Removes all key-value entries from the map. 28054 * 28055 * @private 28056 * @name clear 28057 * @memberOf MapCache 28058 */ 28059 function mapCacheClear() { 28060 this.size = 0; 28061 this.__data__ = { 28062 'hash': new Hash, 28063 'map': new (Map || ListCache), 28064 'string': new Hash 28065 }; 28066 } 28067 28068 /** 28069 * Removes `key` and its value from the map. 28070 * 28071 * @private 28072 * @name delete 28073 * @memberOf MapCache 28074 * @param {string} key The key of the value to remove. 28075 * @returns {boolean} Returns `true` if the entry was removed, else `false`. 28076 */ 28077 function mapCacheDelete(key) { 28078 var result = getMapData(this, key)['delete'](key); 28079 this.size -= result ? 1 : 0; 28080 return result; 28081 } 28082 28083 /** 28084 * Gets the map value for `key`. 28085 * 28086 * @private 28087 * @name get 28088 * @memberOf MapCache 28089 * @param {string} key The key of the value to get. 28090 * @returns {*} Returns the entry value. 28091 */ 28092 function mapCacheGet(key) { 28093 return getMapData(this, key).get(key); 28094 } 28095 28096 /** 28097 * Checks if a map value for `key` exists. 28098 * 28099 * @private 28100 * @name has 28101 * @memberOf MapCache 28102 * @param {string} key The key of the entry to check. 28103 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. 28104 */ 28105 function mapCacheHas(key) { 28106 return getMapData(this, key).has(key); 28107 } 28108 28109 /** 28110 * Sets the map `key` to `value`. 28111 * 28112 * @private 28113 * @name set 28114 * @memberOf MapCache 28115 * @param {string} key The key of the value to set. 28116 * @param {*} value The value to set. 28117 * @returns {Object} Returns the map cache instance. 28118 */ 28119 function mapCacheSet(key, value) { 28120 var data = getMapData(this, key), 28121 size = data.size; 28122 28123 data.set(key, value); 28124 this.size += data.size == size ? 0 : 1; 28125 return this; 28126 } 28127 28128 // Add methods to `MapCache`. 28129 MapCache.prototype.clear = mapCacheClear; 28130 MapCache.prototype['delete'] = mapCacheDelete; 28131 MapCache.prototype.get = mapCacheGet; 28132 MapCache.prototype.has = mapCacheHas; 28133 MapCache.prototype.set = mapCacheSet; 28134 28135 /*------------------------------------------------------------------------*/ 28136 28137 /** 28138 * 28139 * Creates an array cache object to store unique values. 28140 * 28141 * @private 28142 * @constructor 28143 * @param {Array} [values] The values to cache. 28144 */ 28145 function SetCache(values) { 28146 var index = -1, 28147 length = values == null ? 0 : values.length; 28148 28149 this.__data__ = new MapCache; 28150 while (++index < length) { 28151 this.add(values[index]); 28152 } 28153 } 28154 28155 /** 28156 * Adds `value` to the array cache. 28157 * 28158 * @private 28159 * @name add 28160 * @memberOf SetCache 28161 * @alias push 28162 * @param {*} value The value to cache. 28163 * @returns {Object} Returns the cache instance. 28164 */
vendor: 3,741 bytes, lines 28165-28301
28165 function setCacheAdd(value) { 28166 this.__data__.set(value, HASH_UNDEFINED); 28167 return this; 28168 } 28169 28170 /** 28171 * Checks if `value` is in the array cache. 28172 * 28173 * @private 28174 * @name has 28175 * @memberOf SetCache 28176 * @param {*} value The value to search for. 28177 * @returns {number} Returns `true` if `value` is found, else `false`. 28178 */ 28179 function setCacheHas(value) { 28180 return this.__data__.has(value); 28181 } 28182 28183 // Add methods to `SetCache`. 28184 SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; 28185 SetCache.prototype.has = setCacheHas; 28186 28187 /*------------------------------------------------------------------------*/ 28188 28189 /** 28190 * Creates a stack cache object to store key-value pairs. 28191 * 28192 * @private 28193 * @constructor 28194 * @param {Array} [entries] The key-value pairs to cache. 28195 */ 28196 function Stack(entries) { 28197 var data = this.__data__ = new ListCache(entries); 28198 this.size = data.size; 28199 } 28200 28201 /** 28202 * Removes all key-value entries from the stack. 28203 * 28204 * @private 28205 * @name clear 28206 * @memberOf Stack 28207 */ 28208 function stackClear() { 28209 this.__data__ = new ListCache; 28210 this.size = 0; 28211 } 28212 28213 /** 28214 * Removes `key` and its value from the stack. 28215 * 28216 * @private 28217 * @name delete 28218 * @memberOf Stack 28219 * @param {string} key The key of the value to remove. 28220 * @returns {boolean} Returns `true` if the entry was removed, else `false`. 28221 */ 28222 function stackDelete(key) { 28223 var data = this.__data__, 28224 result = data['delete'](key); 28225 28226 this.size = data.size; 28227 return result; 28228 } 28229 28230 /** 28231 * Gets the stack value for `key`. 28232 * 28233 * @private 28234 * @name get 28235 * @memberOf Stack 28236 * @param {string} key The key of the value to get. 28237 * @returns {*} Returns the entry value. 28238 */ 28239 function stackGet(key) { 28240 return this.__data__.get(key); 28241 } 28242 28243 /** 28244 * Checks if a stack value for `key` exists. 28245 * 28246 * @private 28247 * @name has 28248 * @memberOf Stack 28249 * @param {string} key The key of the entry to check. 28250 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. 28251 */ 28252 function stackHas(key) { 28253 return this.__data__.has(key); 28254 } 28255 28256 /** 28257 * Sets the stack `key` to `value`. 28258 * 28259 * @private 28260 * @name set 28261 * @memberOf Stack 28262 * @param {string} key The key of the value to set. 28263 * @param {*} value The value to set. 28264 * @returns {Object} Returns the stack cache instance. 28265 */ 28266 function stackSet(key, value) { 28267 var data = this.__data__; 28268 if (data instanceof ListCache) { 28269 var pairs = data.__data__; 28270 if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { 28271 pairs.push([key, value]); 28272 this.size = ++data.size; 28273 return this; 28274 } 28275 data = this.__data__ = new MapCache(pairs); 28276 } 28277 data.set(key, value); 28278 this.size = data.size; 28279 return this; 28280 } 28281 28282 // Add methods to `Stack`. 28283 Stack.prototype.clear = stackClear; 28284 Stack.prototype['delete'] = stackDelete; 28285 Stack.prototype.get = stackGet; 28286 Stack.prototype.has = stackHas; 28287 Stack.prototype.set = stackSet; 28288 28289 /*------------------------------------------------------------------------*/ 28290 28291 /** 28292 * Creates an array of the enumerable property names of the array-like `value`. 28293 * 28294 * @private 28295 * @param {*} value The value to query. 28296 * @param {boolean} inherited Specify returning inherited property names. 28297 * @returns {Array} Returns the array of property names. 28298 */ 28299 function arrayLikeKeys(value, inherited) { 28300 var isArr = isArray(value), 28301 isArg = !isArr && isArguments(value),
vendor: 9,093 bytes, lines 28302-28575
28302 isBuff = !isArr && !isArg && isBuffer(value), 28303 isType = !isArr && !isArg && !isBuff && isTypedArray(value), 28304 skipIndexes = isArr || isArg || isBuff || isType, 28305 result = skipIndexes ? baseTimes(value.length, String) : [], 28306 length = result.length; 28307 28308 for (var key in value) { 28309 if ((inherited || hasOwnProperty.call(value, key)) && 28310 !(skipIndexes && ( 28311 // Safari 9 has enumerable `arguments.length` in strict mode. 28312 key == 'length' || 28313 // Node.js 0.10 has enumerable non-index properties on buffers. 28314 (isBuff && (key == 'offset' || key == 'parent')) || 28315 // PhantomJS 2 has enumerable non-index properties on typed arrays. 28316 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || 28317 // Skip index properties. 28318 isIndex(key, length) 28319 ))) { 28320 result.push(key); 28321 } 28322 } 28323 return result; 28324 } 28325 28326 /** 28327 * A specialized version of `_.sample` for arrays. 28328 * 28329 * @private 28330 * @param {Array} array The array to sample. 28331 * @returns {*} Returns the random element. 28332 */ 28333 function arraySample(array) { 28334 var length = array.length; 28335 return length ? array[baseRandom(0, length - 1)] : undefined; 28336 } 28337 28338 /** 28339 * A specialized version of `_.sampleSize` for arrays. 28340 * 28341 * @private 28342 * @param {Array} array The array to sample. 28343 * @param {number} n The number of elements to sample. 28344 * @returns {Array} Returns the random elements. 28345 */ 28346 function arraySampleSize(array, n) { 28347 return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); 28348 } 28349 28350 /** 28351 * A specialized version of `_.shuffle` for arrays. 28352 * 28353 * @private 28354 * @param {Array} array The array to shuffle. 28355 * @returns {Array} Returns the new shuffled array. 28356 */ 28357 function arrayShuffle(array) { 28358 return shuffleSelf(copyArray(array)); 28359 } 28360 28361 /** 28362 * This function is like `assignValue` except that it doesn't assign 28363 * `undefined` values. 28364 * 28365 * @private 28366 * @param {Object} object The object to modify. 28367 * @param {string} key The key of the property to assign. 28368 * @param {*} value The value to assign. 28369 */ 28370 function assignMergeValue(object, key, value) { 28371 if ((value !== undefined && !eq(object[key], value)) || 28372 (value === undefined && !(key in object))) { 28373 baseAssignValue(object, key, value); 28374 } 28375 } 28376 28377 /** 28378 * Assigns `value` to `key` of `object` if the existing value is not equivalent 28379 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) 28380 * for equality comparisons. 28381 * 28382 * @private 28383 * @param {Object} object The object to modify. 28384 * @param {string} key The key of the property to assign. 28385 * @param {*} value The value to assign. 28386 */ 28387 function assignValue(object, key, value) { 28388 var objValue = object[key]; 28389 if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || 28390 (value === undefined && !(key in object))) { 28391 baseAssignValue(object, key, value); 28392 } 28393 } 28394 28395 /** 28396 * Gets the index at which the `key` is found in `array` of key-value pairs. 28397 * 28398 * @private 28399 * @param {Array} array The array to inspect. 28400 * @param {*} key The key to search for. 28401 * @returns {number} Returns the index of the matched value, else `-1`. 28402 */ 28403 function assocIndexOf(array, key) { 28404 var length = array.length; 28405 while (length--) { 28406 if (eq(array[length][0], key)) { 28407 return length; 28408 } 28409 } 28410 return -1; 28411 } 28412 28413 /** 28414 * Aggregates elements of `collection` on `accumulator` with keys transformed 28415 * by `iteratee` and values set by `setter`. 28416 * 28417 * @private 28418 * @param {Array|Object} collection The collection to iterate over. 28419 * @param {Function} setter The function to set `accumulator` values. 28420 * @param {Function} iteratee The iteratee to transform keys. 28421 * @param {Object} accumulator The initial aggregated object. 28422 * @returns {Function} Returns `accumulator`. 28423 */ 28424 function baseAggregator(collection, setter, iteratee, accumulator) { 28425 baseEach(collection, function(value, key, collection) { 28426 setter(accumulator, value, iteratee(value), collection); 28427 }); 28428 return accumulator; 28429 } 28430 28431 /** 28432 * The base implementation of `_.assign` without support for multiple sources 28433 * or `customizer` functions. 28434 * 28435 * @private 28436 * @param {Object} object The destination object. 28437 * @param {Object} source The source object. 28438 * @returns {Object} Returns `object`. 28439 */ 28440 function baseAssign(object, source) { 28441 return object && copyObject(source, keys(source), object); 28442 } 28443 28444 /** 28445 * The base implementation of `_.assignIn` without support for multiple sources 28446 * or `customizer` functions. 28447 * 28448 * @private 28449 * @param {Object} object The destination object. 28450 * @param {Object} source The source object. 28451 * @returns {Object} Returns `object`. 28452 */ 28453 function baseAssignIn(object, source) { 28454 return object && copyObject(source, keysIn(source), object); 28455 } 28456 28457 /** 28458 * The base implementation of `assignValue` and `assignMergeValue` without 28459 * value checks. 28460 * 28461 * @private 28462 * @param {Object} object The object to modify. 28463 * @param {string} key The key of the property to assign. 28464 * @param {*} value The value to assign. 28465 */ 28466 function baseAssignValue(object, key, value) { 28467 if (key == '__proto__' && defineProperty) { 28468 defineProperty(object, key, { 28469 'configurable': true, 28470 'enumerable': true, 28471 'value': value, 28472 'writable': true 28473 }); 28474 } else { 28475 object[key] = value; 28476 } 28477 } 28478 28479 /** 28480 * The base implementation of `_.at` without support for individual paths. 28481 * 28482 * @private 28483 * @param {Object} object The object to iterate over. 28484 * @param {string[]} paths The property paths to pick. 28485 * @returns {Array} Returns the picked elements. 28486 */ 28487 function baseAt(object, paths) { 28488 var index = -1, 28489 length = paths.length, 28490 result = Array(length), 28491 skip = object == null; 28492 28493 while (++index < length) { 28494 result[index] = skip ? undefined : get(object, paths[index]); 28495 } 28496 return result; 28497 } 28498 28499 /** 28500 * The base implementation of `_.clamp` which doesn't coerce arguments. 28501 * 28502 * @private 28503 * @param {number} number The number to clamp. 28504 * @param {number} [lower] The lower bound. 28505 * @param {number} upper The upper bound. 28506 * @returns {number} Returns the clamped number. 28507 */ 28508 function baseClamp(number, lower, upper) { 28509 if (number === number) { 28510 if (upper !== undefined) { 28511 number = number <= upper ? number : upper; 28512 } 28513 if (lower !== undefined) { 28514 number = number >= lower ? number : lower; 28515 } 28516 } 28517 return number; 28518 } 28519 28520 /** 28521 * The base implementation of `_.clone` and `_.cloneDeep` which tracks 28522 * traversed objects. 28523 * 28524 * @private 28525 * @param {*} value The value to clone. 28526 * @param {boolean} bitmask The bitmask flags. 28527 * 1 - Deep clone 28528 * 2 - Flatten inherited properties 28529 * 4 - Clone symbols 28530 * @param {Function} [customizer] The function to customize cloning. 28531 * @param {string} [key] The key of `value`. 28532 * @param {Object} [object] The parent object of `value`. 28533 * @param {Object} [stack] Tracks traversed objects and their clone counterparts. 28534 * @returns {*} Returns the cloned value. 28535 */ 28536 function baseClone(value, bitmask, customizer, key, object, stack) { 28537 var result, 28538 isDeep = bitmask & CLONE_DEEP_FLAG, 28539 isFlat = bitmask & CLONE_FLAT_FLAG, 28540 isFull = bitmask & CLONE_SYMBOLS_FLAG; 28541 28542 if (customizer) { 28543 result = object ? customizer(value, key, object, stack) : customizer(value); 28544 } 28545 if (result !== undefined) { 28546 return result; 28547 } 28548 if (!isObject(value)) { 28549 return value; 28550 } 28551 var isArr = isArray(value); 28552 if (isArr) { 28553 result = initCloneArray(value); 28554 if (!isDeep) { 28555 return copyArray(value, result); 28556 } 28557 } else { 28558 var tag = getTag(value), 28559 isFunc = tag == funcTag || tag == genTag; 28560 28561 if (isBuffer(value)) { 28562 return cloneBuffer(value, isDeep); 28563 } 28564 if (tag == objectTag || tag == argsTag || (isFunc && !object)) { 28565 result = (isFlat || isFunc) ? {} : initCloneObject(value); 28566 if (!isDeep) { 28567 return isFlat 28568 ? copySymbolsIn(value, baseAssignIn(result, value)) 28569 : copySymbols(value, baseAssign(result, value)); 28570 } 28571 } else { 28572 if (!cloneableTags[tag]) { 28573 return object ? value : {}; 28574 } 28575 result = initCloneByTag(value, tag,
28575baseClone, isDeep); 28576 } 28577 } 28578 // Check for circular references and return its corresponding clone. 28579 stack || (stack = new Stack); 28580 var stacked = stack.get(value); 28581 if (stacked) { 28582 return stacked; 28583 } 28584 stack.set(value, result);
vendor: 31,223 bytes, lines 28584-29507
28584 28585 28586 var keysFunc = isFull 28587 ? (isFlat ? getAllKeysIn : getAllKeys) 28588 : (isFlat ? keysIn : keys); 28589 28590 var props = isArr ? undefined : keysFunc(value); 28591 arrayEach(props || value, function(subValue, key) { 28592 if (props) { 28593 key = subValue; 28594 subValue = value[key]; 28595 } 28596 // Recursively populate clone (susceptible to call stack limits). 28597 assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); 28598 }); 28599 return result; 28600 } 28601 28602 /** 28603 * The base implementation of `_.conforms` which doesn't clone `source`. 28604 * 28605 * @private 28606 * @param {Object} source The object of property predicates to conform to. 28607 * @returns {Function} Returns the new spec function. 28608 */ 28609 function baseConforms(source) { 28610 var props = keys(source); 28611 return function(object) { 28612 return baseConformsTo(object, source, props); 28613 }; 28614 } 28615 28616 /** 28617 * The base implementation of `_.conformsTo` which accepts `props` to check. 28618 * 28619 * @private 28620 * @param {Object} object The object to inspect. 28621 * @param {Object} source The object of property predicates to conform to. 28622 * @returns {boolean} Returns `true` if `object` conforms, else `false`. 28623 */ 28624 function baseConformsTo(object, source, props) { 28625 var length = props.length; 28626 if (object == null) { 28627 return !length; 28628 } 28629 object = Object(object); 28630 while (length--) { 28631 var key = props[length], 28632 predicate = source[key], 28633 value = object[key]; 28634 28635 if ((value === undefined && !(key in object)) || !predicate(value)) { 28636 return false; 28637 } 28638 } 28639 return true; 28640 } 28641 28642 /** 28643 * The base implementation of `_.delay` and `_.defer` which accepts `args` 28644 * to provide to `func`. 28645 * 28646 * @private 28647 * @param {Function} func The function to delay. 28648 * @param {number} wait The number of milliseconds to delay invocation. 28649 * @param {Array} args The arguments to provide to `func`. 28650 * @returns {number|Object} Returns the timer id or timeout object. 28651 */ 28652 function baseDelay(func, wait, args) { 28653 if (typeof func != 'function') { 28654 throw new TypeError(FUNC_ERROR_TEXT); 28655 } 28656 return setTimeout(function() { func.apply(undefined, args); }, wait); 28657 } 28658 28659 /** 28660 * The base implementation of methods like `_.difference` without support 28661 * for excluding multiple arrays or iteratee shorthands. 28662 * 28663 * @private 28664 * @param {Array} array The array to inspect. 28665 * @param {Array} values The values to exclude. 28666 * @param {Function} [iteratee] The iteratee invoked per element. 28667 * @param {Function} [comparator] The comparator invoked per element. 28668 * @returns {Array} Returns the new array of filtered values. 28669 */ 28670 function baseDifference(array, values, iteratee, comparator) { 28671 var index = -1, 28672 includes = arrayIncludes, 28673 isCommon = true, 28674 length = array.length, 28675 result = [], 28676 valuesLength = values.length; 28677 28678 if (!length) { 28679 return result; 28680 } 28681 if (iteratee) { 28682 values = arrayMap(values, baseUnary(iteratee)); 28683 } 28684 if (comparator) { 28685 includes = arrayIncludesWith; 28686 isCommon = false; 28687 } 28688 else if (values.length >= LARGE_ARRAY_SIZE) { 28689 includes = cacheHas; 28690 isCommon = false; 28691 values = new SetCache(values); 28692 } 28693 outer: 28694 while (++index < length) { 28695 var value = array[index], 28696 computed = iteratee == null ? value : iteratee(value); 28697 28698 value = (comparator || value !== 0) ? value : 0; 28699 if (isCommon && computed === computed) { 28700 var valuesIndex = valuesLength; 28701 while (valuesIndex--) { 28702 if (values[valuesIndex] === computed) { 28703 continue outer; 28704 } 28705 } 28706 result.push(value); 28707 } 28708 else if (!includes(values, computed, comparator)) { 28709 result.push(value); 28710 } 28711 } 28712 return result; 28713 } 28714 28715 /** 28716 * The base implementation of `_.forEach` without support for iteratee shorthands. 28717 * 28718 * @private 28719 * @param {Array|Object} collection The collection to iterate over. 28720 * @param {Function} iteratee The function invoked per iteration. 28721 * @returns {Array|Object} Returns `collection`. 28722 */ 28723 var baseEach = createBaseEach(baseForOwn); 28724 28725 /** 28726 * The base implementation of `_.forEachRight` without support for iteratee shorthands. 28727 * 28728 * @private 28729 * @param {Array|Object} collection The collection to iterate over. 28730 * @param {Function} iteratee The function invoked per iteration. 28731 * @returns {Array|Object} Returns `collection`. 28732 */ 28733 var baseEachRight = createBaseEach(baseForOwnRight, true); 28734 28735 /** 28736 * The base implementation of `_.every` without support for iteratee shorthands. 28737 * 28738 * @private 28739 * @param {Array|Object} collection The collection to iterate over. 28740 * @param {Function} predicate The function invoked per iteration. 28741 * @returns {boolean} Returns `true` if all elements pass the predicate check, 28742 * else `false` 28743 */ 28744 function baseEvery(collection, predicate) { 28745 var result = true; 28746 baseEach(collection, function(value, index, collection) { 28747 result = !!predicate(value, index, collection); 28748 return result; 28749 }); 28750 return result; 28751 } 28752 28753 /** 28754 * The base implementation of methods like `_.max` and `_.min` which accepts a 28755 * `comparator` to determine the extremum value. 28756 * 28757 * @private 28758 * @param {Array} array The array to iterate over. 28759 * @param {Function} iteratee The iteratee invoked per iteration. 28760 * @param {Function} comparator The comparator used to compare values. 28761 * @returns {*} Returns the extremum value. 28762 */ 28763 function baseExtremum(array, iteratee, comparator) { 28764 var index = -1, 28765 length = array.length; 28766 28767 while (++index < length) { 28768 var value = array[index], 28769 current = iteratee(value); 28770 28771 if (current != null && (computed === undefined 28772 ? (current === current && !isSymbol(current)) 28773 : comparator(current, computed) 28774 )) { 28775 var computed = current, 28776 result = value; 28777 } 28778 } 28779 return result; 28780 } 28781 28782 /** 28783 * The base implementation of `_.fill` without an iteratee call guard. 28784 * 28785 * @private 28786 * @param {Array} array The array to fill. 28787 * @param {*} value The value to fill `array` with. 28788 * @param {number} [start=0] The start position. 28789 * @param {number} [end=array.length] The end position. 28790 * @returns {Array} Returns `array`. 28791 */ 28792 function baseFill(array, value, start, end) { 28793 var length = array.length; 28794 28795 start = toInteger(start); 28796 if (start < 0) { 28797 start = -start > length ? 0 : (length + start); 28798 } 28799 end = (end === undefined || end > length) ? length : toInteger(end); 28800 if (end < 0) { 28801 end += length; 28802 } 28803 end = start > end ? 0 : toLength(end); 28804 while (start < end) { 28805 array[start++] = value; 28806 } 28807 return array; 28808 } 28809 28810 /** 28811 * The base implementation of `_.filter` without support for iteratee shorthands. 28812 * 28813 * @private 28814 * @param {Array|Object} collection The collection to iterate over. 28815 * @param {Function} predicate The function invoked per iteration. 28816 * @returns {Array} Returns the new filtered array. 28817 */ 28818 function baseFilter(collection, predicate) { 28819 var result = []; 28820 baseEach(collection, function(value, index, collection) { 28821 if (predicate(value, index, collection)) { 28822 result.push(value); 28823 } 28824 }); 28825 return result; 28826 } 28827 28828 /** 28829 * The base implementation of `_.flatten` with support for restricting flattening. 28830 * 28831 * @private 28832 * @param {Array} array The array to flatten. 28833 * @param {number} depth The maximum recursion depth. 28834 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. 28835 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. 28836 * @param {Array} [result=[]] The initial result value. 28837 * @returns {Array} Returns the new flattened array. 28838 */ 28839 function baseFlatten(array, depth, predicate, isStrict, result) { 28840 var index = -1, 28841 length = array.length; 28842 28843 predicate || (predicate = isFlattenable); 28844 result || (result = []); 28845 28846 while (++index < length) { 28847 var value = array[index]; 28848 if (depth > 0 && predicate(value)) { 28849 if (depth > 1) { 28850 // Recursively flatten arrays (susceptible to call stack limits). 28851 baseFlatten(value, depth - 1, predicate, isStrict, result); 28852 } else { 28853 arrayPush(result, value); 28854 } 28855 } else if (!isStrict) { 28856 result[result.length] = value; 28857 } 28858 } 28859 return result; 28860 } 28861 28862 /** 28863 * The base implementation of `baseForOwn` which iterates over `object` 28864 * properties returned by `keysFunc` and invokes `iteratee` for each property. 28865 * Iteratee functions may exit iteration early by explicitly returning `false`. 28866 * 28867 * @private 28868 * @param {Object} object The object to iterate over. 28869 * @param {Function} iteratee The function invoked per iteration. 28870 * @param {Function} keysFunc The function to get the keys of `object`. 28871 * @returns {Object} Returns `object`. 28872 */ 28873 var baseFor = createBaseFor(); 28874 28875 /** 28876 * This function is like `baseFor` except that it iterates over properties 28877 * in the opposite order. 28878 * 28879 * @private 28880 * @param {Object} object The object to iterate over. 28881 * @param {Function} iteratee The function invoked per iteration. 28882 * @param {Function} keysFunc The function to get the keys of `object`. 28883 * @returns {Object} Returns `object`. 28884 */ 28885 var baseForRight = createBaseFor(true); 28886 28887 /** 28888 * The base implementation of `_.forOwn` without support for iteratee shorthands. 28889 * 28890 * @private 28891 * @param {Object} object The object to iterate over. 28892 * @param {Function} iteratee The function invoked per iteration. 28893 * @returns {Object} Returns `object`. 28894 */ 28895 function baseForOwn(object, iteratee) { 28896 return object && baseFor(object, iteratee, keys); 28897 } 28898 28899 /** 28900 * The base implementation of `_.forOwnRight` without support for iteratee shorthands. 28901 * 28902 * @private 28903 * @param {Object} object The object to iterate over. 28904 * @param {Function} iteratee The function invoked per iteration. 28905 * @returns {Object} Returns `object`. 28906 */ 28907 function baseForOwnRight(object, iteratee) { 28908 return object && baseForRight(object, iteratee, keys); 28909 } 28910 28911 /** 28912 * The base implementation of `_.functions` which creates an array of 28913 * `object` function property names filtered from `props`. 28914 * 28915 * @private 28916 * @param {Object} object The object to inspect. 28917 * @param {Array} props The property names to filter. 28918 * @returns {Array} Returns the function names. 28919 */ 28920 function baseFunctions(object, props) { 28921 return arrayFilter(props, function(key) { 28922 return isFunction(object[key]); 28923 }); 28924 } 28925 28926 /** 28927 * The base implementation of `_.get` without support for default values. 28928 * 28929 * @private 28930 * @param {Object} object The object to query. 28931 * @param {Array|string} path The path of the property to get. 28932 * @returns {*} Returns the resolved value. 28933 */ 28934 function baseGet(object, path) { 28935 path = castPath(path, object); 28936 28937 var index = 0, 28938 length = path.length; 28939 28940 while (object != null && index < length) { 28941 object = object[toKey(path[index++])]; 28942 } 28943 return (index && index == length) ? object : undefined; 28944 } 28945 28946 /** 28947 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses 28948 * `keysFunc` and `symbolsFunc` to get the enumerable property names and 28949 * symbols of `object`. 28950 * 28951 * @private 28952 * @param {Object} object The object to query. 28953 * @param {Function} keysFunc The function to get the keys of `object`. 28954 * @param {Function} symbolsFunc The function to get the symbols of `object`. 28955 * @returns {Array} Returns the array of property names and symbols. 28956 */ 28957 function baseGetAllKeys(object, keysFunc, symbolsFunc) { 28958 var result = keysFunc(object); 28959 return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); 28960 } 28961 28962 /** 28963 * The base implementation of `getTag` without fallbacks for buggy environments. 28964 * 28965 * @private 28966 * @param {*} value The value to query. 28967 * @returns {string} Returns the `toStringTag`. 28968 */ 28969 function baseGetTag(value) { 28970 if (value == null) { 28971 return value === undefined ? undefinedTag : nullTag; 28972 } 28973 return (symToStringTag && symToStringTag in Object(value)) 28974 ? getRawTag(value) 28975 : objectToString(value); 28976 } 28977 28978 /** 28979 * The base implementation of `_.gt` which doesn't coerce arguments. 28980 * 28981 * @private 28982 * @param {*} value The value to compare. 28983 * @param {*} other The other value to compare. 28984 * @returns {boolean} Returns `true` if `value` is greater than `other`, 28985 * else `false`. 28986 */ 28987 function baseGt(value, other) { 28988 return value > other; 28989 } 28990 28991 /** 28992 * The base implementation of `_.has` without support for deep paths. 28993 * 28994 * @private 28995 * @param {Object} [object] The object to query. 28996 * @param {Array|string} key The key to check. 28997 * @returns {boolean} Returns `true` if `key` exists, else `false`. 28998 */ 28999 function baseHas(object, key) { 29000 return object != null && hasOwnProperty.call(object, key); 29001 } 29002 29003 /** 29004 * The base implementation of `_.hasIn` without support for deep paths. 29005 * 29006 * @private 29007 * @param {Object} [object] The object to query. 29008 * @param {Array|string} key The key to check. 29009 * @returns {boolean} Returns `true` if `key` exists, else `false`. 29010 */ 29011 function baseHasIn(object, key) { 29012 return object != null && key in Object(object); 29013 } 29014 29015 /** 29016 * The base implementation of `_.inRange` which doesn't coerce arguments. 29017 * 29018 * @private 29019 * @param {number} number The number to check. 29020 * @param {number} start The start of the range. 29021 * @param {number} end The end of the range. 29022 * @returns {boolean} Returns `true` if `number` is in the range, else `false`. 29023 */ 29024 function baseInRange(number, start, end) { 29025 return number >= nativeMin(start, end) && number < nativeMax(start, end); 29026 } 29027 29028 /** 29029 * The base implementation of methods like `_.intersection`, without support 29030 * for iteratee shorthands, that accepts an array of arrays to inspect. 29031 * 29032 * @private 29033 * @param {Array} arrays The arrays to inspect. 29034 * @param {Function} [iteratee] The iteratee invoked per element. 29035 * @param {Function} [comparator] The comparator invoked per element. 29036 * @returns {Array} Returns the new array of shared values. 29037 */ 29038 function baseIntersection(arrays, iteratee, comparator) { 29039 var includes = comparator ? arrayIncludesWith : arrayIncludes, 29040 length = arrays[0].length, 29041 othLength = arrays.length, 29042 othIndex = othLength, 29043 caches = Array(othLength), 29044 maxLength = Infinity, 29045 result = []; 29046 29047 while (othIndex--) { 29048 var array = arrays[othIndex]; 29049 if (othIndex && iteratee) { 29050 array = arrayMap(array, baseUnary(iteratee)); 29051 } 29052 maxLength = nativeMin(array.length, maxLength); 29053 caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) 29054 ? new SetCache(othIndex && array) 29055 : undefined; 29056 } 29057 array = arrays[0]; 29058 29059 var index = -1, 29060 seen = caches[0]; 29061 29062 outer: 29063 while (++index < length && result.length < maxLength) { 29064 var value = array[index], 29065 computed = iteratee ? iteratee(value) : value; 29066 29067 value = (comparator || value !== 0) ? value : 0; 29068 if (!(seen 29069 ? cacheHas(seen, computed) 29070 : includes(result, computed, comparator) 29071 )) { 29072 othIndex = othLength; 29073 while (--othIndex) { 29074 var cache = caches[othIndex]; 29075 if (!(cache 29076 ? cacheHas(cache, computed) 29077 : includes(arrays[othIndex], computed, comparator)) 29078 ) { 29079 continue outer; 29080 } 29081 } 29082 if (seen) { 29083 seen.push(computed); 29084 } 29085 result.push(value); 29086 } 29087 } 29088 return result; 29089 } 29090 29091 /** 29092 * The base implementation of `_.invert` and `_.invertBy` which inverts 29093 * `object` with values transformed by `iteratee` and set by `setter`. 29094 * 29095 * @private 29096 * @param {Object} object The object to iterate over. 29097 * @param {Function} setter The function to set `accumulator` values. 29098 * @param {Function} iteratee The iteratee to transform values. 29099 * @param {Object} accumulator The initial inverted object. 29100 * @returns {Function} Returns `accumulator`. 29101 */ 29102 function baseInverter(object, setter, iteratee, accumulator) { 29103 baseForOwn(object, function(value, key, object) { 29104 setter(accumulator, iteratee(value), key, object); 29105 }); 29106 return accumulator; 29107 } 29108 29109 /** 29110 * The base implementation of `_.invoke` without support for individual 29111 * method arguments. 29112 * 29113 * @private 29114 * @param {Object} object The object to query. 29115 * @param {Array|string} path The path of the method to invoke. 29116 * @param {Array} args The arguments to invoke the method with. 29117 * @returns {*} Returns the result of the invoked method. 29118 */ 29119 function baseInvoke(object, path, args) { 29120 path = castPath(path, object); 29121 object = parent(object, path); 29122 var func = object == null ? object : object[toKey(last(path))]; 29123 return func == null ? undefined : apply(func, object, args); 29124 } 29125 29126 /** 29127 * The base implementation of `_.isArguments`. 29128 * 29129 * @private 29130 * @param {*} value The value to check. 29131 * @returns {boolean} Returns `true` if `value` is an `arguments` object, 29132 */ 29133 function baseIsArguments(value) { 29134 return isObjectLike(value) && baseGetTag(value) == argsTag; 29135 } 29136 29137 /** 29138 * The base implementation of `_.isArrayBuffer` without Node.js optimizations. 29139 * 29140 * @private 29141 * @param {*} value The value to check. 29142 * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. 29143 */ 29144 function baseIsArrayBuffer(value) { 29145 return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; 29146 } 29147 29148 /** 29149 * The base implementation of `_.isDate` without Node.js optimizations. 29150 * 29151 * @private 29152 * @param {*} value The value to check. 29153 * @returns {boolean} Returns `true` if `value` is a date object, else `false`. 29154 */ 29155 function baseIsDate(value) { 29156 return isObjectLike(value) && baseGetTag(value) == dateTag; 29157 } 29158 29159 /** 29160 * The base implementation of `_.isEqual` which supports partial comparisons 29161 * and tracks traversed objects. 29162 * 29163 * @private 29164 * @param {*} value The value to compare. 29165 * @param {*} other The other value to compare. 29166 * @param {boolean} bitmask The bitmask flags. 29167 * 1 - Unordered comparison 29168 * 2 - Partial comparison 29169 * @param {Function} [customizer] The function to customize comparisons. 29170 * @param {Object} [stack] Tracks traversed `value` and `other` objects. 29171 * @returns {boolean} Returns `true` if the values are equivalent, else `false`. 29172 */ 29173 function baseIsEqual(value, other, bitmask, customizer, stack) { 29174 if (value === other) { 29175 return true; 29176 } 29177 if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { 29178 return value !== value && other !== other; 29179 } 29180 return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); 29181 } 29182 29183 /** 29184 * A specialized version of `baseIsEqual` for arrays and objects which performs 29185 * deep comparisons and tracks traversed objects enabling objects with circular 29186 * references to be compared. 29187 * 29188 * @private 29189 * @param {Object} object The object to compare. 29190 * @param {Object} other The other object to compare. 29191 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. 29192 * @param {Function} customizer The function to customize comparisons. 29193 * @param {Function} equalFunc The function to determine equivalents of values. 29194 * @param {Object} [stack] Tracks traversed `object` and `other` objects. 29195 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. 29196 */ 29197 function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { 29198 var objIsArr = isArray(object), 29199 othIsArr = isArray(other), 29200 objTag = objIsArr ? arrayTag : getTag(object), 29201 othTag = othIsArr ? arrayTag : getTag(other); 29202 29203 objTag = objTag == argsTag ? objectTag : objTag; 29204 othTag = othTag == argsTag ? objectTag : othTag; 29205 29206 var objIsObj = objTag == objectTag, 29207 othIsObj = othTag == objectTag, 29208 isSameTag = objTag == othTag; 29209 29210 if (isSameTag && isBuffer(object)) { 29211 if (!isBuffer(other)) { 29212 return false; 29213 } 29214 objIsArr = true; 29215 objIsObj = false; 29216 } 29217 if (isSameTag && !objIsObj) { 29218 stack || (stack = new Stack); 29219 return (objIsArr || isTypedArray(object)) 29220 ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) 29221 : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); 29222 } 29223 if (!(bitmask & COMPARE_PARTIAL_FLAG)) { 29224 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), 29225 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); 29226 29227 if (objIsWrapped || othIsWrapped) { 29228 var objUnwrapped = objIsWrapped ? object.value() : object, 29229 othUnwrapped = othIsWrapped ? other.value() : other; 29230 29231 stack || (stack = new Stack); 29232 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); 29233 } 29234 } 29235 if (!isSameTag) { 29236 return false; 29237 } 29238 stack || (stack = new Stack); 29239 return equalObjects(object, other, bitmask, customizer, equalFunc, stack); 29240 } 29241 29242 /** 29243 * The base implementation of `_.isMap` without Node.js optimizations. 29244 * 29245 * @private 29246 * @param {*} value The value to check. 29247 * @returns {boolean} Returns `true` if `value` is a map, else `false`. 29248 */ 29249 function baseIsMap(value) { 29250 return isObjectLike(value) && getTag(value) == mapTag; 29251 } 29252 29253 /** 29254 * The base implementation of `_.isMatch` without support for iteratee shorthands. 29255 * 29256 * @private 29257 * @param {Object} object The object to inspect. 29258 * @param {Object} source The object of property values to match. 29259 * @param {Array} matchData The property names, values, and compare flags to match. 29260 * @param {Function} [customizer] The function to customize comparisons. 29261 * @returns {boolean} Returns `true` if `object` is a match, else `false`. 29262 */ 29263 function baseIsMatch(object, source, matchData, customizer) { 29264 var index = matchData.length, 29265 length = index, 29266 noCustomizer = !customizer; 29267 29268 if (object == null) { 29269 return !length; 29270 } 29271 object = Object(object); 29272 while (index--) { 29273 var data = matchData[index]; 29274 if ((noCustomizer && data[2]) 29275 ? data[1] !== object[data[0]] 29276 : !(data[0] in object) 29277 ) { 29278 return false; 29279 } 29280 } 29281 while (++index < length) { 29282 data = matchData[index]; 29283 var key = data[0], 29284 objValue = object[key], 29285 srcValue = data[1]; 29286 29287 if (noCustomizer && data[2]) { 29288 if (objValue === undefined && !(key in object)) { 29289 return false; 29290 } 29291 } else { 29292 var stack = new Stack; 29293 if (customizer) { 29294 var result = customizer(objValue, srcValue, key, object, source, stack); 29295 } 29296 if (!(result === undefined 29297 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) 29298 : result 29299 )) { 29300 return false; 29301 } 29302 } 29303 } 29304 return true; 29305 } 29306 29307 /** 29308 * The base implementation of `_.isNative` without bad shim checks. 29309 * 29310 * @private 29311 * @param {*} value The value to check. 29312 * @returns {boolean} Returns `true` if `value` is a native function, 29313 * else `false`. 29314 */ 29315 function baseIsNative(value) { 29316 if (!isObject(value) || isMasked(value)) { 29317 return false; 29318 } 29319 var pattern = isFunction(value) ? reIsNative : reIsHostCtor; 29320 return pattern.test(toSource(value)); 29321 } 29322 29323 /** 29324 * The base implementation of `_.isRegExp` without Node.js optimizations. 29325 * 29326 * @private 29327 * @param {*} value The value to check. 29328 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. 29329 */ 29330 function baseIsRegExp(value) { 29331 return isObjectLike(value) && baseGetTag(value) == regexpTag; 29332 } 29333 29334 /** 29335 * The base implementation of `_.isSet` without Node.js optimizations. 29336 * 29337 * @private 29338 * @param {*} value The value to check. 29339 * @returns {boolean} Returns `true` if `value` is a set, else `false`. 29340 */ 29341 function baseIsSet(value) { 29342 return isObjectLike(value) && getTag(value) == setTag; 29343 } 29344 29345 /** 29346 * The base implementation of `_.isTypedArray` without Node.js optimizations. 29347 * 29348 * @private 29349 * @param {*} value The value to check. 29350 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. 29351 */ 29352 function baseIsTypedArray(value) { 29353 return isObjectLike(value) && 29354 isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; 29355 } 29356 29357 /** 29358 * The base implementation of `_.iteratee`. 29359 * 29360 * @private 29361 * @param {*} [value=_.identity] The value to convert to an iteratee. 29362 * @returns {Function} Returns the iteratee. 29363 */ 29364 function baseIteratee(value) { 29365 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. 29366 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. 29367 if (typeof value == 'function') { 29368 return value; 29369 } 29370 if (value == null) { 29371 return identity; 29372 } 29373 if (typeof value == 'object') { 29374 return isArray(value) 29375 ? baseMatchesProperty(value[0], value[1]) 29376 : baseMatches(value); 29377 } 29378 return property(value); 29379 } 29380 29381 /** 29382 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. 29383 * 29384 * @private 29385 * @param {Object} object The object to query. 29386 * @returns {Array} Returns the array of property names. 29387 */ 29388 function baseKeys(object) { 29389 if (!isPrototype(object)) { 29390 return nativeKeys(object); 29391 } 29392 var result = []; 29393 for (var key in Object(object)) { 29394 if (hasOwnProperty.call(object, key) && key != 'constructor') { 29395 result.push(key); 29396 } 29397 } 29398 return result; 29399 } 29400 29401 /** 29402 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. 29403 * 29404 * @private 29405 * @param {Object} object The object to query. 29406 * @returns {Array} Returns the array of property names. 29407 */ 29408 function baseKeysIn(object) { 29409 if (!isObject(object)) { 29410 return nativeKeysIn(object); 29411 } 29412 var isProto = isPrototype(object), 29413 result = []; 29414 29415 for (var key in object) { 29416 if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { 29417 result.push(key); 29418 } 29419 } 29420 return result; 29421 } 29422 29423 /** 29424 * The base implementation of `_.lt` which doesn't coerce arguments. 29425 * 29426 * @private 29427 * @param {*} value The value to compare. 29428 * @param {*} other The other value to compare. 29429 * @returns {boolean} Returns `true` if `value` is less than `other`, 29430 * else `false`. 29431 */ 29432 function baseLt(value, other) { 29433 return value < other; 29434 } 29435 29436 /** 29437 * The base implementation of `_.map` without support for iteratee shorthands. 29438 * 29439 * @private 29440 * @param {Array|Object} collection The collection to iterate over. 29441 * @param {Function} iteratee The function invoked per iteration. 29442 * @returns {Array} Returns the new mapped array. 29443 */ 29444 function baseMap(collection, iteratee) { 29445 var index = -1, 29446 result = isArrayLike(collection) ? Array(collection.length) : []; 29447 29448 baseEach(collection, function(value, key, collection) { 29449 result[++index] = iteratee(value, key, collection); 29450 }); 29451 return result; 29452 } 29453 29454 /** 29455 * The base implementation of `_.matches` which doesn't clone `source`. 29456 * 29457 * @private 29458 * @param {Object} source The object of property values to match. 29459 * @returns {Function} Returns the new spec function. 29460 */ 29461 function baseMatches(source) { 29462 var matchData = getMatchData(source); 29463 if (matchData.length == 1 && matchData[0][2]) { 29464 return matchesStrictComparable(matchData[0][0], matchData[0][1]); 29465 } 29466 return function(object) { 29467 return object === source || baseIsMatch(object, source, matchData); 29468 }; 29469 } 29470 29471 /** 29472 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. 29473 * 29474 * @private 29475 * @param {string} path The path of the property to get. 29476 * @param {*} srcValue The value to match. 29477 * @returns {Function} Returns the new spec function. 29478 */ 29479 function baseMatchesProperty(path, srcValue) { 29480 if (isKey(path) && isStrictComparable(srcValue)) { 29481 return matchesStrictComparable(toKey(path), srcValue); 29482 } 29483 return function(object) { 29484 var objValue = get(object, path); 29485 return (objValue === undefined && objValue === srcValue) 29486 ? hasIn(object, path) 29487 : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); 29488 }; 29489 } 29490 29491 /** 29492 * The base implementation of `_.merge` without support for multiple sources. 29493 * 29494 * @private 29495 * @param {Object} object The destination object. 29496 * @param {Object} source The source object. 29497 * @param {number} srcIndex The index of `source`. 29498 * @param {Function} [customizer] The function to customize merged values. 29499 * @param {Object} [stack] Tracks traversed source values and their merged 29500 * counterparts. 29501 */ 29502 function baseMerge(object, source, srcIndex, customizer, stack) { 29503 if (object === source) { 29504 return; 29505 } 29506 baseFor(source, function(srcValue, key) { 29507
vendor: 2,153 bytes, lines 29507-29568
29507if (isObject(srcValue)) { 29508 stack || (stack = new Stack); 29509 baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); 29510 } 29511 else { 29512 var newValue = customizer 29513 ? customizer(object[key], srcValue, (key + ''), object, source, stack) 29514 : undefined; 29515 29516 if (newValue === undefined) { 29517 newValue = srcValue; 29518 } 29519 assignMergeValue(object, key, newValue); 29520 } 29521 }, keysIn); 29522 } 29523 29524 /** 29525 * A specialized version of `baseMerge` for arrays and objects which performs 29526 * deep merges and tracks traversed objects enabling objects with circular 29527 * references to be merged. 29528 * 29529 * @private 29530 * @param {Object} object The destination object. 29531 * @param {Object} source The source object. 29532 * @param {string} key The key of the value to merge. 29533 * @param {number} srcIndex The index of `source`. 29534 * @param {Function} mergeFunc The function to merge values. 29535 * @param {Function} [customizer] The function to customize assigned values. 29536 * @param {Object} [stack] Tracks traversed source values and their merged 29537 * counterparts. 29538 */ 29539 function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { 29540 var objValue = object[key], 29541 srcValue = source[key], 29542 stacked = stack.get(srcValue); 29543 29544 if (stacked) { 29545 assignMergeValue(object, key, stacked); 29546 return; 29547 } 29548 var newValue = customizer 29549 ? customizer(objValue, srcValue, (key + ''), object, source, stack) 29550 : undefined; 29551 29552 var isCommon = newValue === undefined; 29553 29554 if (isCommon) { 29555 var isArr = isArray(srcValue), 29556 isBuff = !isArr && isBuffer(srcValue), 29557 isTyped = !isArr && !isBuff && isTypedArray(srcValue); 29558 29559 newValue = srcValue; 29560 if (isArr || isBuff || isTyped) { 29561 if (isArray(objValue)) { 29562 newValue = objValue; 29563 } 29564 else if (isArrayLikeObject(objValue)) { 29565 newValue = copyArray(objValue); 29566 } 29567 else if (isBuff) { 29568 isCommon = false;
29569 newValue = cloneBuffer(srcValue, true); 29570 } 29571 else if (isTyped) { 29572 isCommon = false; 29573 newValue = cloneTypedArray(srcValue, true); 29574 } 29575 else { 29576 newValue = []; 29577 } 29578 } 29579 else if (isPlainObject(srcValue) || isArguments(srcValue)) { 29580 newValue = objValue; 29581 if (isArguments(objValue)) { 29582 newValue = toPlainObject(objValue); 29583 } 29584 else if (!isObject(objValue) || (srcIndex && isFunction(objValue)
vendor: 14,715 bytes, lines 29584-30047
29584)) { 29585 newValue = initCloneObject(srcValue); 29586 } 29587 } 29588 else { 29589 isCommon = false; 29590 } 29591 } 29592 if (isCommon) { 29593 // Recursively merge objects and arrays (susceptible to call stack limits). 29594 stack.set(srcValue, newValue); 29595 mergeFunc(newValue, srcValue, srcIndex, customizer, stack); 29596 stack['delete'](srcValue); 29597 } 29598 assignMergeValue(object, key, newValue); 29599 } 29600 29601 /** 29602 * The base implementation of `_.nth` which doesn't coerce arguments. 29603 * 29604 * @private 29605 * @param {Array} array The array to query. 29606 * @param {number} n The index of the element to return. 29607 * @returns {*} Returns the nth element of `array`. 29608 */ 29609 function baseNth(array, n) { 29610 var length = array.length; 29611 if (!length) { 29612 return; 29613 } 29614 n += n < 0 ? length : 0; 29615 return isIndex(n, length) ? array[n] : undefined; 29616 } 29617 29618 /** 29619 * The base implementation of `_.orderBy` without param guards. 29620 * 29621 * @private 29622 * @param {Array|Object} collection The collection to iterate over. 29623 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. 29624 * @param {string[]} orders The sort orders of `iteratees`. 29625 * @returns {Array} Returns the new sorted array. 29626 */ 29627 function baseOrderBy(collection, iteratees, orders) { 29628 var index = -1; 29629 iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); 29630 29631 var result = baseMap(collection, function(value, key, collection) { 29632 var criteria = arrayMap(iteratees, function(iteratee) { 29633 return iteratee(value); 29634 }); 29635 return { 'criteria': criteria, 'index': ++index, 'value': value }; 29636 }); 29637 29638 return baseSortBy(result, function(object, other) { 29639 return compareMultiple(object, other, orders); 29640 }); 29641 } 29642 29643 /** 29644 * The base implementation of `_.pick` without support for individual 29645 * property identifiers. 29646 * 29647 * @private 29648 * @param {Object} object The source object. 29649 * @param {string[]} paths The property paths to pick. 29650 * @returns {Object} Returns the new object. 29651 */ 29652 function basePick(object, paths) { 29653 return basePickBy(object, paths, function(value, path) { 29654 return hasIn(object, path); 29655 }); 29656 } 29657 29658 /** 29659 * The base implementation of `_.pickBy` without support for iteratee shorthands. 29660 * 29661 * @private 29662 * @param {Object} object The source object. 29663 * @param {string[]} paths The property paths to pick. 29664 * @param {Function} predicate The function invoked per property. 29665 * @returns {Object} Returns the new object. 29666 */ 29667 function basePickBy(object, paths, predicate) { 29668 var index = -1, 29669 length = paths.length, 29670 result = {}; 29671 29672 while (++index < length) { 29673 var path = paths[index], 29674 value = baseGet(object, path); 29675 29676 if (predicate(value, path)) { 29677 baseSet(result, castPath(path, object), value); 29678 } 29679 } 29680 return result; 29681 } 29682 29683 /** 29684 * A specialized version of `baseProperty` which supports deep paths. 29685 * 29686 * @private 29687 * @param {Array|string} path The path of the property to get. 29688 * @returns {Function} Returns the new accessor function. 29689 */ 29690 function basePropertyDeep(path) { 29691 return function(object) { 29692 return baseGet(object, path); 29693 }; 29694 } 29695 29696 /** 29697 * The base implementation of `_.pullAllBy` without support for iteratee 29698 * shorthands. 29699 * 29700 * @private 29701 * @param {Array} array The array to modify. 29702 * @param {Array} values The values to remove. 29703 * @param {Function} [iteratee] The iteratee invoked per element. 29704 * @param {Function} [comparator] The comparator invoked per element. 29705 * @returns {Array} Returns `array`. 29706 */ 29707 function basePullAll(array, values, iteratee, comparator) { 29708 var indexOf = comparator ? baseIndexOfWith : baseIndexOf, 29709 index = -1, 29710 length = values.length, 29711 seen = array; 29712 29713 if (array === values) { 29714 values = copyArray(values); 29715 } 29716 if (iteratee) { 29717 seen = arrayMap(array, baseUnary(iteratee)); 29718 } 29719 while (++index < length) { 29720 var fromIndex = 0, 29721 value = values[index], 29722 computed = iteratee ? iteratee(value) : value; 29723 29724 while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { 29725 if (seen !== array) { 29726 splice.call(seen, fromIndex, 1); 29727 } 29728 splice.call(array, fromIndex, 1); 29729 } 29730 } 29731 return array; 29732 } 29733 29734 /** 29735 * The base implementation of `_.pullAt` without support for individual 29736 * indexes or capturing the removed elements. 29737 * 29738 * @private 29739 * @param {Array} array The array to modify. 29740 * @param {number[]} indexes The indexes of elements to remove. 29741 * @returns {Array} Returns `array`. 29742 */ 29743 function basePullAt(array, indexes) { 29744 var length = array ? indexes.length : 0, 29745 lastIndex = length - 1; 29746 29747 while (length--) { 29748 var index = indexes[length]; 29749 if (length == lastIndex || index !== previous) { 29750 var previous = index; 29751 if (isIndex(index)) { 29752 splice.call(array, index, 1); 29753 } else { 29754 baseUnset(array, index); 29755 } 29756 } 29757 } 29758 return array; 29759 } 29760 29761 /** 29762 * The base implementation of `_.random` without support for returning 29763 * floating-point numbers. 29764 * 29765 * @private 29766 * @param {number} lower The lower bound. 29767 * @param {number} upper The upper bound. 29768 * @returns {number} Returns the random number. 29769 */ 29770 function baseRandom(lower, upper) { 29771 return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); 29772 } 29773 29774 /** 29775 * The base implementation of `_.range` and `_.rangeRight` which doesn't 29776 * coerce arguments. 29777 * 29778 * @private 29779 * @param {number} start The start of the range. 29780 * @param {number} end The end of the range. 29781 * @param {number} step The value to increment or decrement by. 29782 * @param {boolean} [fromRight] Specify iterating from right to left. 29783 * @returns {Array} Returns the range of numbers. 29784 */ 29785 function baseRange(start, end, step, fromRight) { 29786 var index = -1, 29787 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), 29788 result = Array(length); 29789 29790 while (length--) { 29791 result[fromRight ? length : ++index] = start; 29792 start += step; 29793 } 29794 return result; 29795 } 29796 29797 /** 29798 * The base implementation of `_.repeat` which doesn't coerce arguments. 29799 * 29800 * @private 29801 * @param {string} string The string to repeat. 29802 * @param {number} n The number of times to repeat the string. 29803 * @returns {string} Returns the repeated string. 29804 */ 29805 function baseRepeat(string, n) { 29806 var result = ''; 29807 if (!string || n < 1 || n > MAX_SAFE_INTEGER) { 29808 return result; 29809 } 29810 // Leverage the exponentiation by squaring algorithm for a faster repeat. 29811 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. 29812 do { 29813 if (n % 2) { 29814 result += string; 29815 } 29816 n = nativeFloor(n / 2); 29817 if (n) { 29818 string += string; 29819 } 29820 } while (n); 29821 29822 return result; 29823 } 29824 29825 /** 29826 * The base implementation of `_.rest` which doesn't validate or coerce arguments. 29827 * 29828 * @private 29829 * @param {Function} func The function to apply a rest parameter to. 29830 * @param {number} [start=func.length-1] The start position of the rest parameter. 29831 * @returns {Function} Returns the new function. 29832 */ 29833 function baseRest(func, start) { 29834 return setToString(overRest(func, start, identity), func + ''); 29835 } 29836 29837 /** 29838 * The base implementation of `_.sample`. 29839 * 29840 * @private 29841 * @param {Array|Object} collection The collection to sample. 29842 * @returns {*} Returns the random element. 29843 */ 29844 function baseSample(collection) { 29845 return arraySample(values(collection)); 29846 } 29847 29848 /** 29849 * The base implementation of `_.sampleSize` without param guards. 29850 * 29851 * @private 29852 * @param {Array|Object} collection The collection to sample. 29853 * @param {number} n The number of elements to sample. 29854 * @returns {Array} Returns the random elements. 29855 */ 29856 function baseSampleSize(collection, n) { 29857 var array = values(collection); 29858 return shuffleSelf(array, baseClamp(n, 0, array.length)); 29859 } 29860 29861 /** 29862 * The base implementation of `_.set`. 29863 * 29864 * @private 29865 * @param {Object} object The object to modify. 29866 * @param {Array|string} path The path of the property to set. 29867 * @param {*} value The value to set. 29868 * @param {Function} [customizer] The function to customize path creation. 29869 * @returns {Object} Returns `object`. 29870 */ 29871 function baseSet(object, path, value, customizer) { 29872 if (!isObject(object)) { 29873 return object; 29874 } 29875 path = castPath(path, object); 29876 29877 var index = -1, 29878 length = path.length, 29879 lastIndex = length - 1, 29880 nested = object; 29881 29882 while (nested != null && ++index < length) { 29883 var key = toKey(path[index]), 29884 newValue = value; 29885 29886 if (index != lastIndex) { 29887 var objValue = nested[key]; 29888 newValue = customizer ? customizer(objValue, key, nested) : undefined; 29889 if (newValue === undefined) { 29890 newValue = isObject(objValue) 29891 ? objValue 29892 : (isIndex(path[index + 1]) ? [] : {}); 29893 } 29894 } 29895 assignValue(nested, key, newValue); 29896 nested = nested[key]; 29897 } 29898 return object; 29899 } 29900 29901 /** 29902 * The base implementation of `setData` without support for hot loop shorting. 29903 * 29904 * @private 29905 * @param {Function} func The function to associate metadata with. 29906 * @param {*} data The metadata. 29907 * @returns {Function} Returns `func`. 29908 */ 29909 var baseSetData = !metaMap ? identity : function(func, data) { 29910 metaMap.set(func, data); 29911 return func; 29912 }; 29913 29914 /** 29915 * The base implementation of `setToString` without support for hot loop shorting. 29916 * 29917 * @private 29918 * @param {Function} func The function to modify. 29919 * @param {Function} string The `toString` result. 29920 * @returns {Function} Returns `func`. 29921 */ 29922 var baseSetToString = !defineProperty ? identity : function(func, string) { 29923 return defineProperty(func, 'toString', { 29924 'configurable': true, 29925 'enumerable': false, 29926 'value': constant(string), 29927 'writable': true 29928 }); 29929 }; 29930 29931 /** 29932 * The base implementation of `_.shuffle`. 29933 * 29934 * @private 29935 * @param {Array|Object} collection The collection to shuffle. 29936 * @returns {Array} Returns the new shuffled array. 29937 */ 29938 function baseShuffle(collection) { 29939 return shuffleSelf(values(collection)); 29940 } 29941 29942 /** 29943 * The base implementation of `_.slice` without an iteratee call guard. 29944 * 29945 * @private 29946 * @param {Array} array The array to slice. 29947 * @param {number} [start=0] The start position. 29948 * @param {number} [end=array.length] The end position. 29949 * @returns {Array} Returns the slice of `array`. 29950 */ 29951 function baseSlice(array, start, end) { 29952 var index = -1, 29953 length = array.length; 29954 29955 if (start < 0) { 29956 start = -start > length ? 0 : (length + start); 29957 } 29958 end = end > length ? length : end; 29959 if (end < 0) { 29960 end += length; 29961 } 29962 length = start > end ? 0 : ((end - start) >>> 0); 29963 start >>>= 0; 29964 29965 var result = Array(length); 29966 while (++index < length) { 29967 result[index] = array[index + start]; 29968 } 29969 return result; 29970 } 29971 29972 /** 29973 * The base implementation of `_.some` without support for iteratee shorthands. 29974 * 29975 * @private 29976 * @param {Array|Object} collection The collection to iterate over. 29977 * @param {Function} predicate The function invoked per iteration. 29978 * @returns {boolean} Returns `true` if any element passes the predicate check, 29979 * else `false`. 29980 */ 29981 function baseSome(collection, predicate) { 29982 var result; 29983 29984 baseEach(collection, function(value, index, collection) { 29985 result = predicate(value, index, collection); 29986 return !result; 29987 }); 29988 return !!result; 29989 } 29990 29991 /** 29992 * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which 29993 * performs a binary search of `array` to determine the index at which `value` 29994 * should be inserted into `array` in order to maintain its sort order. 29995 * 29996 * @private 29997 * @param {Array} array The sorted array to inspect. 29998 * @param {*} value The value to evaluate. 29999 * @param {boolean} [retHighest] Specify returning the highest qualified index. 30000 * @returns {number} Returns the index at which `value` should be inserted 30001 * into `array`. 30002 */ 30003 function baseSortedIndex(array, value, retHighest) { 30004 var low = 0, 30005 high = array == null ? low : array.length; 30006 30007 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { 30008 while (low < high) { 30009 var mid = (low + high) >>> 1, 30010 computed = array[mid]; 30011 30012 if (computed !== null && !isSymbol(computed) && 30013 (retHighest ? (computed <= value) : (computed < value))) { 30014 low = mid + 1; 30015 } else { 30016 high = mid; 30017 } 30018 } 30019 return high; 30020 } 30021 return baseSortedIndexBy(array, value, identity, retHighest); 30022 } 30023 30024 /** 30025 * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` 30026 * which invokes `iteratee` for `value` and each element of `array` to compute 30027 * their sort ranking. The iteratee is invoked with one argument; (value). 30028 * 30029 * @private 30030 * @param {Array} array The sorted array to inspect. 30031 * @param {*} value The value to evaluate. 30032 * @param {Function} iteratee The iteratee invoked per element. 30033 * @param {boolean} [retHighest] Specify returning the highest qualified index. 30034 * @returns {number} Returns the index at which `value` should be inserted 30035 * into `array`. 30036 */ 30037 function baseSortedIndexBy(array, value, iteratee, retHighest) { 30038 value = iteratee(value); 30039 30040 var low = 0, 30041 high = array == null ? 0 : array.length, 30042 valIsNaN = value !== value, 30043 valIsNull = value === null, 30044 valIsSymbol = isSymbol(value), 30045 valIsUndefined = value === undefined; 30046 30047 while (low < high) {
vendor: 12,977 bytes, lines 30048-30450
30048 var mid = nativeFloor((low + high) / 2), 30049 computed = iteratee(array[mid]), 30050 othIsDefined = computed !== undefined, 30051 othIsNull = computed === null, 30052 othIsReflexive = computed === computed, 30053 othIsSymbol = isSymbol(computed); 30054 30055 if (valIsNaN) { 30056 var setLow = retHighest || othIsReflexive; 30057 } else if (valIsUndefined) { 30058 setLow = othIsReflexive && (retHighest || othIsDefined); 30059 } else if (valIsNull) { 30060 setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); 30061 } else if (valIsSymbol) { 30062 setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); 30063 } else if (othIsNull || othIsSymbol) { 30064 setLow = false; 30065 } else { 30066 setLow = retHighest ? (computed <= value) : (computed < value); 30067 } 30068 if (setLow) { 30069 low = mid + 1; 30070 } else { 30071 high = mid; 30072 } 30073 } 30074 return nativeMin(high, MAX_ARRAY_INDEX); 30075 } 30076 30077 /** 30078 * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without 30079 * support for iteratee shorthands. 30080 * 30081 * @private 30082 * @param {Array} array The array to inspect. 30083 * @param {Function} [iteratee] The iteratee invoked per element. 30084 * @returns {Array} Returns the new duplicate free array. 30085 */ 30086 function baseSortedUniq(array, iteratee) { 30087 var index = -1, 30088 length = array.length, 30089 resIndex = 0, 30090 result = []; 30091 30092 while (++index < length) { 30093 var value = array[index], 30094 computed = iteratee ? iteratee(value) : value; 30095 30096 if (!index || !eq(computed, seen)) { 30097 var seen = computed; 30098 result[resIndex++] = value === 0 ? 0 : value; 30099 } 30100 } 30101 return result; 30102 } 30103 30104 /** 30105 * The base implementation of `_.toNumber` which doesn't ensure correct 30106 * conversions of binary, hexadecimal, or octal string values. 30107 * 30108 * @private 30109 * @param {*} value The value to process. 30110 * @returns {number} Returns the number. 30111 */ 30112 function baseToNumber(value) { 30113 if (typeof value == 'number') { 30114 return value; 30115 } 30116 if (isSymbol(value)) { 30117 return NAN; 30118 } 30119 return +value; 30120 } 30121 30122 /** 30123 * The base implementation of `_.toString` which doesn't convert nullish 30124 * values to empty strings. 30125 * 30126 * @private 30127 * @param {*} value The value to process. 30128 * @returns {string} Returns the string. 30129 */ 30130 function baseToString(value) { 30131 // Exit early for strings to avoid a performance hit in some environments. 30132 if (typeof value == 'string') { 30133 return value; 30134 } 30135 if (isArray(value)) { 30136 // Recursively convert values (susceptible to call stack limits). 30137 return arrayMap(value, baseToString) + ''; 30138 } 30139 if (isSymbol(value)) { 30140 return symbolToString ? symbolToString.call(value) : ''; 30141 } 30142 var result = (value + ''); 30143 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; 30144 } 30145 30146 /** 30147 * The base implementation of `_.uniqBy` without support for iteratee shorthands. 30148 * 30149 * @private 30150 * @param {Array} array The array to inspect. 30151 * @param {Function} [iteratee] The iteratee invoked per element. 30152 * @param {Function} [comparator] The comparator invoked per element. 30153 * @returns {Array} Returns the new duplicate free array. 30154 */ 30155 function baseUniq(array, iteratee, comparator) { 30156 var index = -1, 30157 includes = arrayIncludes, 30158 length = array.length, 30159 isCommon = true, 30160 result = [], 30161 seen = result; 30162 30163 if (comparator) { 30164 isCommon = false; 30165 includes = arrayIncludesWith; 30166 } 30167 else if (length >= LARGE_ARRAY_SIZE) { 30168 var set = iteratee ? null : createSet(array); 30169 if (set) { 30170 return setToArray(set); 30171 } 30172 isCommon = false; 30173 includes = cacheHas; 30174 seen = new SetCache; 30175 } 30176 else { 30177 seen = iteratee ? [] : result; 30178 } 30179 outer: 30180 while (++index < length) { 30181 var value = array[index], 30182 computed = iteratee ? iteratee(value) : value; 30183 30184 value = (comparator || value !== 0) ? value : 0; 30185 if (isCommon && computed === computed) { 30186 var seenIndex = seen.length; 30187 while (seenIndex--) { 30188 if (seen[seenIndex] === computed) { 30189 continue outer; 30190 } 30191 } 30192 if (iteratee) { 30193 seen.push(computed); 30194 } 30195 result.push(value); 30196 } 30197 else if (!includes(seen, computed, comparator)) { 30198 if (seen !== result) { 30199 seen.push(computed); 30200 } 30201 result.push(value); 30202 } 30203 } 30204 return result; 30205 } 30206 30207 /** 30208 * The base implementation of `_.unset`. 30209 * 30210 * @private 30211 * @param {Object} object The object to modify. 30212 * @param {Array|string} path The property path to unset. 30213 * @returns {boolean} Returns `true` if the property is deleted, else `false`. 30214 */ 30215 function baseUnset(object, path) { 30216 path = castPath(path, object); 30217 object = parent(object, path); 30218 return object == null || delete object[toKey(last(path))]; 30219 } 30220 30221 /** 30222 * The base implementation of `_.update`. 30223 * 30224 * @private 30225 * @param {Object} object The object to modify. 30226 * @param {Array|string} path The path of the property to update. 30227 * @param {Function} updater The function to produce the updated value. 30228 * @param {Function} [customizer] The function to customize path creation. 30229 * @returns {Object} Returns `object`. 30230 */ 30231 function baseUpdate(object, path, updater, customizer) { 30232 return baseSet(object, path, updater(baseGet(object, path)), customizer); 30233 } 30234 30235 /** 30236 * The base implementation of methods like `_.dropWhile` and `_.takeWhile` 30237 * without support for iteratee shorthands. 30238 * 30239 * @private 30240 * @param {Array} array The array to query. 30241 * @param {Function} predicate The function invoked per iteration. 30242 * @param {boolean} [isDrop] Specify dropping elements instead of taking them. 30243 * @param {boolean} [fromRight] Specify iterating from right to left. 30244 * @returns {Array} Returns the slice of `array`. 30245 */ 30246 function baseWhile(array, predicate, isDrop, fromRight) { 30247 var length = array.length, 30248 index = fromRight ? length : -1; 30249 30250 while ((fromRight ? index-- : ++index < length) && 30251 predicate(array[index], index, array)) {} 30252 30253 return isDrop 30254 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) 30255 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); 30256 } 30257 30258 /** 30259 * The base implementation of `wrapperValue` which returns the result of 30260 * performing a sequence of actions on the unwrapped `value`, where each 30261 * successive action is supplied the return value of the previous. 30262 * 30263 * @private 30264 * @param {*} value The unwrapped value. 30265 * @param {Array} actions Actions to perform to resolve the unwrapped value. 30266 * @returns {*} Returns the resolved value. 30267 */ 30268 function baseWrapperValue(value, actions) { 30269 var result = value; 30270 if (result instanceof LazyWrapper) { 30271 result = result.value(); 30272 } 30273 return arrayReduce(actions, function(result, action) { 30274 return action.func.apply(action.thisArg, arrayPush([result], action.args)); 30275 }, result); 30276 } 30277 30278 /** 30279 * The base implementation of methods like `_.xor`, without support for 30280 * iteratee shorthands, that accepts an array of arrays to inspect. 30281 * 30282 * @private 30283 * @param {Array} arrays The arrays to inspect. 30284 * @param {Function} [iteratee] The iteratee invoked per element. 30285 * @param {Function} [comparator] The comparator invoked per element. 30286 * @returns {Array} Returns the new array of values. 30287 */ 30288 function baseXor(arrays, iteratee, comparator) { 30289 var length = arrays.length; 30290 if (length < 2) { 30291 return length ? baseUniq(arrays[0]) : []; 30292 } 30293 var index = -1, 30294 result = Array(length); 30295 30296 while (++index < length) { 30297 var array = arrays[index], 30298 othIndex = -1; 30299 30300 while (++othIndex < length) { 30301 if (othIndex != index) { 30302 result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); 30303 } 30304 } 30305 } 30306 return baseUniq(baseFlatten(result, 1), iteratee, comparator); 30307 } 30308 30309 /** 30310 * This base implementation of `_.zipObject` which assigns values using `assignFunc`. 30311 * 30312 * @private 30313 * @param {Array} props The property identifiers. 30314 * @param {Array} values The property values. 30315 * @param {Function} assignFunc The function to assign values. 30316 * @returns {Object} Returns the new object. 30317 */ 30318 function baseZipObject(props, values, assignFunc) { 30319 var index = -1, 30320 length = props.length, 30321 valsLength = values.length, 30322 result = {}; 30323 30324 while (++index < length) { 30325 var value = index < valsLength ? values[index] : undefined; 30326 assignFunc(result, props[index], value); 30327 } 30328 return result; 30329 } 30330 30331 /** 30332 * Casts `value` to an empty array if it's not an array like object. 30333 * 30334 * @private 30335 * @param {*} value The value to inspect. 30336 * @returns {Array|Object} Returns the cast array-like object. 30337 */ 30338 function castArrayLikeObject(value) { 30339 return isArrayLikeObject(value) ? value : []; 30340 } 30341 30342 /** 30343 * Casts `value` to `identity` if it's not a function. 30344 * 30345 * @private 30346 * @param {*} value The value to inspect. 30347 * @returns {Function} Returns cast function. 30348 */ 30349 function castFunction(value) { 30350 return typeof value == 'function' ? value : identity; 30351 } 30352 30353 /** 30354 * Casts `value` to a path array if it's not one. 30355 * 30356 * @private 30357 * @param {*} value The value to inspect. 30358 * @param {Object} [object] The object to query keys on. 30359 * @returns {Array} Returns the cast property path array. 30360 */ 30361 function castPath(value, object) { 30362 if (isArray(value)) { 30363 return value; 30364 } 30365 return isKey(value, object) ? [value] : stringToPath(toString(value)); 30366 } 30367 30368 /** 30369 * A `baseRest` alias which can be replaced with `identity` by module 30370 * replacement plugins. 30371 * 30372 * @private 30373 * @type {Function} 30374 * @param {Function} func The function to apply a rest parameter to. 30375 * @returns {Function} Returns the new function. 30376 */ 30377 var castRest = baseRest; 30378 30379 /** 30380 * Casts `array` to a slice if it's needed. 30381 * 30382 * @private 30383 * @param {Array} array The array to inspect. 30384 * @param {number} start The start position. 30385 * @param {number} [end=array.length] The end position. 30386 * @returns {Array} Returns the cast slice. 30387 */ 30388 function castSlice(array, start, end) { 30389 var length = array.length; 30390 end = end === undefined ? length : end; 30391 return (!start && end >= length) ? array : baseSlice(array, start, end); 30392 } 30393 30394 /** 30395 * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). 30396 * 30397 * @private 30398 * @param {number|Object} id The timer id or timeout object of the timer to clear. 30399 */ 30400 var clearTimeout = ctxClearTimeout || function(id) { 30401 return root.clearTimeout(id); 30402 }; 30403 30404 /** 30405 * Creates a clone of `buffer`. 30406 * 30407 * @private 30408 * @param {Buffer} buffer The buffer to clone. 30409 * @param {boolean} [isDeep] Specify a deep clone. 30410 * @returns {Buffer} Returns the cloned buffer. 30411 */ 30412 function cloneBuffer(buffer, isDeep) { 30413 if (isDeep) { 30414 return buffer.slice(); 30415 } 30416 var length = buffer.length, 30417 result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); 30418 30419 buffer.copy(result); 30420 return result; 30421 } 30422 30423 /** 30424 * Creates a clone of `arrayBuffer`. 30425 * 30426 * @private 30427 * @param {ArrayBuffer} arrayBuffer The array buffer to clone. 30428 * @returns {ArrayBuffer} Returns the cloned array buffer. 30429 */ 30430 function cloneArrayBuffer(arrayBuffer) { 30431 var result = new arrayBuffer.constructor(arrayBuffer.byteLength); 30432 new Uint8Array(result).set(new Uint8Array(arrayBuffer)); 30433 return result; 30434 } 30435 30436 /** 30437 * Creates a clone of `dataView`. 30438 * 30439 * @private 30440 * @param {Object} dataView The data view to clone. 30441 * @param {boolean} [isDeep] Specify a deep clone. 30442 * @returns {Object} Returns the cloned data view. 30443 */ 30444 function cloneDataView(dataView, isDeep) { 30445 var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; 30446 return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); 30447 } 30448 30449 /** 30450 * Creates a clone of `
30450map`. 30451 * 30452 * @private 30453 * @param {Object} map The map to clone. 30454 * @param {Function} cloneFunc The function to clone values. 30455 * @param {boolean} [isDeep] Specify a deep clone. 30456 * @returns {Object} Returns the cloned map. 30457 */ 30458 function cloneMap(map, isDeep, cloneFunc) { 30459 var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); 30460 return arrayReduce(array, addMapEntry, new map.constructor); 30461 } 30462 30463 /** 30464 * Creates a clone of `regexp`. 30465 * 30466 * @private 30467 * @param {Object} regexp The regexp to clone. 30468 * @returns {Object} Returns the cloned regexp. 30469 */ 30470 function cloneRegExp(regexp) { 30471 var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); 30472 result.lastIndex = regexp.lastIndex; 30473 return result; 30474 } 30475 30476 /** 30477 * Creates a clone of `set`. 30478 * 30479 * @private 30480 * @param {Object} set The set to clone. 30481 * @param {Function} cloneFunc The function to clone values. 30482 * @param {boolean} [isDeep] Specify a deep clone. 30483 * @returns {Object} Returns the cloned set. 30484 */ 30485 function cloneSet(set, isDeep, cloneFunc) { 30486 var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); 30487 return arrayReduce(array, addSetEntry, new set.constructor)
vendor: 37,974 bytes, lines 30487-31553
30487; 30488 } 30489 30490 /** 30491 * Creates a clone of the `symbol` object. 30492 * 30493 * @private 30494 * @param {Object} symbol The symbol object to clone. 30495 * @returns {Object} Returns the cloned symbol object. 30496 */ 30497 function cloneSymbol(symbol) { 30498 return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; 30499 } 30500 30501 /** 30502 * Creates a clone of `typedArray`. 30503 * 30504 * @private 30505 * @param {Object} typedArray The typed array to clone. 30506 * @param {boolean} [isDeep] Specify a deep clone. 30507 * @returns {Object} Returns the cloned typed array. 30508 */ 30509 function cloneTypedArray(typedArray, isDeep) { 30510 var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; 30511 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); 30512 } 30513 30514 /** 30515 * Compares values to sort them in ascending order. 30516 * 30517 * @private 30518 * @param {*} value The value to compare. 30519 * @param {*} other The other value to compare. 30520 * @returns {number} Returns the sort order indicator for `value`. 30521 */ 30522 function compareAscending(value, other) { 30523 if (value !== other) { 30524 var valIsDefined = value !== undefined, 30525 valIsNull = value === null, 30526 valIsReflexive = value === value, 30527 valIsSymbol = isSymbol(value); 30528 30529 var othIsDefined = other !== undefined, 30530 othIsNull = other === null, 30531 othIsReflexive = other === other, 30532 othIsSymbol = isSymbol(other); 30533 30534 if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || 30535 (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || 30536 (valIsNull && othIsDefined && othIsReflexive) || 30537 (!valIsDefined && othIsReflexive) || 30538 !valIsReflexive) { 30539 return 1; 30540 } 30541 if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || 30542 (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || 30543 (othIsNull && valIsDefined && valIsReflexive) || 30544 (!othIsDefined && valIsReflexive) || 30545 !othIsReflexive) { 30546 return -1; 30547 } 30548 } 30549 return 0; 30550 } 30551 30552 /** 30553 * Used by `_.orderBy` to compare multiple properties of a value to another 30554 * and stable sort them. 30555 * 30556 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, 30557 * specify an order of "desc" for descending or "asc" for ascending sort order 30558 * of corresponding values. 30559 * 30560 * @private 30561 * @param {Object} object The object to compare. 30562 * @param {Object} other The other object to compare. 30563 * @param {boolean[]|string[]} orders The order to sort by for each property. 30564 * @returns {number} Returns the sort order indicator for `object`. 30565 */ 30566 function compareMultiple(object, other, orders) { 30567 var index = -1, 30568 objCriteria = object.criteria, 30569 othCriteria = other.criteria, 30570 length = objCriteria.length, 30571 ordersLength = orders.length; 30572 30573 while (++index < length) { 30574 var result = compareAscending(objCriteria[index], othCriteria[index]); 30575 if (result) { 30576 if (index >= ordersLength) { 30577 return result; 30578 } 30579 var order = orders[index]; 30580 return result * (order == 'desc' ? -1 : 1); 30581 } 30582 } 30583 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications 30584 // that causes it, under certain circumstances, to provide the same value for 30585 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 30586 // for more details. 30587 // 30588 // This also ensures a stable sort in V8 and other engines. 30589 // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. 30590 return object.index - other.index; 30591 } 30592 30593 /** 30594 * Creates an array that is the composition of partially applied arguments, 30595 * placeholders, and provided arguments into a single array of arguments. 30596 * 30597 * @private 30598 * @param {Array} args The provided arguments. 30599 * @param {Array} partials The arguments to prepend to those provided. 30600 * @param {Array} holders The `partials` placeholder indexes. 30601 * @params {boolean} [isCurried] Specify composing for a curried function. 30602 * @returns {Array} Returns the new array of composed arguments. 30603 */ 30604 function composeArgs(args, partials, holders, isCurried) { 30605 var argsIndex = -1, 30606 argsLength = args.length, 30607 holdersLength = holders.length, 30608 leftIndex = -1, 30609 leftLength = partials.length, 30610 rangeLength = nativeMax(argsLength - holdersLength, 0), 30611 result = Array(leftLength + rangeLength), 30612 isUncurried = !isCurried; 30613 30614 while (++leftIndex < leftLength) { 30615 result[leftIndex] = partials[leftIndex]; 30616 } 30617 while (++argsIndex < holdersLength) { 30618 if (isUncurried || argsIndex < argsLength) { 30619 result[holders[argsIndex]] = args[argsIndex]; 30620 } 30621 } 30622 while (rangeLength--) { 30623 result[leftIndex++] = args[argsIndex++]; 30624 } 30625 return result; 30626 } 30627 30628 /** 30629 * This function is like `composeArgs` except that the arguments composition 30630 * is tailored for `_.partialRight`. 30631 * 30632 * @private 30633 * @param {Array} args The provided arguments. 30634 * @param {Array} partials The arguments to append to those provided. 30635 * @param {Array} holders The `partials` placeholder indexes. 30636 * @params {boolean} [isCurried] Specify composing for a curried function. 30637 * @returns {Array} Returns the new array of composed arguments. 30638 */ 30639 function composeArgsRight(args, partials, holders, isCurried) { 30640 var argsIndex = -1, 30641 argsLength = args.length, 30642 holdersIndex = -1, 30643 holdersLength = holders.length, 30644 rightIndex = -1, 30645 rightLength = partials.length, 30646 rangeLength = nativeMax(argsLength - holdersLength, 0), 30647 result = Array(rangeLength + rightLength), 30648 isUncurried = !isCurried; 30649 30650 while (++argsIndex < rangeLength) { 30651 result[argsIndex] = args[argsIndex]; 30652 } 30653 var offset = argsIndex; 30654 while (++rightIndex < rightLength) { 30655 result[offset + rightIndex] = partials[rightIndex]; 30656 } 30657 while (++holdersIndex < holdersLength) { 30658 if (isUncurried || argsIndex < argsLength) { 30659 result[offset + holders[holdersIndex]] = args[argsIndex++]; 30660 } 30661 } 30662 return result; 30663 } 30664 30665 /** 30666 * Copies the values of `source` to `array`. 30667 * 30668 * @private 30669 * @param {Array} source The array to copy values from. 30670 * @param {Array} [array=[]] The array to copy values to. 30671 * @returns {Array} Returns `array`. 30672 */ 30673 function copyArray(source, array) { 30674 var index = -1, 30675 length = source.length; 30676 30677 array || (array = Array(length)); 30678 while (++index < length) { 30679 array[index] = source[index]; 30680 } 30681 return array; 30682 } 30683 30684 /** 30685 * Copies properties of `source` to `object`. 30686 * 30687 * @private 30688 * @param {Object} source The object to copy properties from. 30689 * @param {Array} props The property identifiers to copy. 30690 * @param {Object} [object={}] The object to copy properties to. 30691 * @param {Function} [customizer] The function to customize copied values. 30692 * @returns {Object} Returns `object`. 30693 */ 30694 function copyObject(source, props, object, customizer) { 30695 var isNew = !object; 30696 object || (object = {}); 30697 30698 var index = -1, 30699 length = props.length; 30700 30701 while (++index < length) { 30702 var key = props[index]; 30703 30704 var newValue = customizer 30705 ? customizer(object[key], source[key], key, object, source) 30706 : undefined; 30707 30708 if (newValue === undefined) { 30709 newValue = source[key]; 30710 } 30711 if (isNew) { 30712 baseAssignValue(object, key, newValue); 30713 } else { 30714 assignValue(object, key, newValue); 30715 } 30716 } 30717 return object; 30718 } 30719 30720 /** 30721 * Copies own symbols of `source` to `object`. 30722 * 30723 * @private 30724 * @param {Object} source The object to copy symbols from. 30725 * @param {Object} [object={}] The object to copy symbols to. 30726 * @returns {Object} Returns `object`. 30727 */ 30728 function copySymbols(source, object) { 30729 return copyObject(source, getSymbols(source), object); 30730 } 30731 30732 /** 30733 * Copies own and inherited symbols of `source` to `object`. 30734 * 30735 * @private 30736 * @param {Object} source The object to copy symbols from. 30737 * @param {Object} [object={}] The object to copy symbols to. 30738 * @returns {Object} Returns `object`. 30739 */ 30740 function copySymbolsIn(source, object) { 30741 return copyObject(source, getSymbolsIn(source), object); 30742 } 30743 30744 /** 30745 * Creates a function like `_.groupBy`. 30746 * 30747 * @private 30748 * @param {Function} setter The function to set accumulator values. 30749 * @param {Function} [initializer] The accumulator object initializer. 30750 * @returns {Function} Returns the new aggregator function. 30751 */ 30752 function createAggregator(setter, initializer) { 30753 return function(collection, iteratee) { 30754 var func = isArray(collection) ? arrayAggregator : baseAggregator, 30755 accumulator = initializer ? initializer() : {}; 30756 30757 return func(collection, setter, getIteratee(iteratee, 2), accumulator); 30758 }; 30759 } 30760 30761 /** 30762 * Creates a function like `_.assign`. 30763 * 30764 * @private 30765 * @param {Function} assigner The function to assign values. 30766 * @returns {Function} Returns the new assigner function. 30767 */ 30768 function createAssigner(assigner) { 30769 return baseRest(function(object, sources) { 30770 var index = -1, 30771 length = sources.length, 30772 customizer = length > 1 ? sources[length - 1] : undefined, 30773 guard = length > 2 ? sources[2] : undefined; 30774 30775 customizer = (assigner.length > 3 && typeof customizer == 'function') 30776 ? (length--, customizer) 30777 : undefined; 30778 30779 if (guard && isIterateeCall(sources[0], sources[1], guard)) { 30780 customizer = length < 3 ? undefined : customizer; 30781 length = 1; 30782 } 30783 object = Object(object); 30784 while (++index < length) { 30785 var source = sources[index]; 30786 if (source) { 30787 assigner(object, source, index, customizer); 30788 } 30789 } 30790 return object; 30791 }); 30792 } 30793 30794 /** 30795 * Creates a `baseEach` or `baseEachRight` function. 30796 * 30797 * @private 30798 * @param {Function} eachFunc The function to iterate over a collection. 30799 * @param {boolean} [fromRight] Specify iterating from right to left. 30800 * @returns {Function} Returns the new base function. 30801 */ 30802 function createBaseEach(eachFunc, fromRight) { 30803 return function(collection, iteratee) { 30804 if (collection == null) { 30805 return collection; 30806 } 30807 if (!isArrayLike(collection)) { 30808 return eachFunc(collection, iteratee); 30809 } 30810 var length = collection.length, 30811 index = fromRight ? length : -1, 30812 iterable = Object(collection); 30813 30814 while ((fromRight ? index-- : ++index < length)) { 30815 if (iteratee(iterable[index], index, iterable) === false) { 30816 break; 30817 } 30818 } 30819 return collection; 30820 }; 30821 } 30822 30823 /** 30824 * Creates a base function for methods like `_.forIn` and `_.forOwn`. 30825 * 30826 * @private 30827 * @param {boolean} [fromRight] Specify iterating from right to left. 30828 * @returns {Function} Returns the new base function. 30829 */ 30830 function createBaseFor(fromRight) { 30831 return function(object, iteratee, keysFunc) { 30832 var index = -1, 30833 iterable = Object(object), 30834 props = keysFunc(object), 30835 length = props.length; 30836 30837 while (length--) { 30838 var key = props[fromRight ? length : ++index]; 30839 if (iteratee(iterable[key], key, iterable) === false) { 30840 break; 30841 } 30842 } 30843 return object; 30844 }; 30845 } 30846 30847 /** 30848 * Creates a function that wraps `func` to invoke it with the optional `this` 30849 * binding of `thisArg`. 30850 * 30851 * @private 30852 * @param {Function} func The function to wrap. 30853 * @param {number} bitmask The bitmask flags. See `createWrap` for more details. 30854 * @param {*} [thisArg] The `this` binding of `func`. 30855 * @returns {Function} Returns the new wrapped function. 30856 */ 30857 function createBind(func, bitmask, thisArg) { 30858 var isBind = bitmask & WRAP_BIND_FLAG, 30859 Ctor = createCtor(func); 30860 30861 function wrapper() { 30862 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; 30863 return fn.apply(isBind ? thisArg : this, arguments); 30864 } 30865 return wrapper; 30866 } 30867 30868 /** 30869 * Creates a function like `_.lowerFirst`. 30870 * 30871 * @private 30872 * @param {string} methodName The name of the `String` case method to use. 30873 * @returns {Function} Returns the new case function. 30874 */ 30875 function createCaseFirst(methodName) { 30876 return function(string) { 30877 string = toString(string); 30878 30879 var strSymbols = hasUnicode(string) 30880 ? stringToArray(string) 30881 : undefined; 30882 30883 var chr = strSymbols 30884 ? strSymbols[0] 30885 : string.charAt(0); 30886 30887 var trailing = strSymbols 30888 ? castSlice(strSymbols, 1).join('') 30889 : string.slice(1); 30890 30891 return chr[methodName]() + trailing; 30892 }; 30893 } 30894 30895 /** 30896 * Creates a function like `_.camelCase`. 30897 * 30898 * @private 30899 * @param {Function} callback The function to combine each word. 30900 * @returns {Function} Returns the new compounder function. 30901 */ 30902 function createCompounder(callback) { 30903 return function(string) { 30904 return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); 30905 }; 30906 } 30907 30908 /** 30909 * Creates a function that produces an instance of `Ctor` regardless of 30910 * whether it was invoked as part of a `new` expression or by `call` or `apply`. 30911 * 30912 * @private 30913 * @param {Function} Ctor The constructor to wrap. 30914 * @returns {Function} Returns the new wrapped function. 30915 */ 30916 function createCtor(Ctor) { 30917 return function() { 30918 // Use a `switch` statement to work with class constructors. See 30919 // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist 30920 // for more details. 30921 var args = arguments; 30922 switch (args.length) { 30923 case 0: return new Ctor; 30924 case 1: return new Ctor(args[0]); 30925 case 2: return new Ctor(args[0], args[1]); 30926 case 3: return new Ctor(args[0], args[1], args[2]); 30927 case 4: return new Ctor(args[0], args[1], args[2], args[3]); 30928 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); 30929 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); 30930 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); 30931 } 30932 var thisBinding = baseCreate(Ctor.prototype), 30933 result = Ctor.apply(thisBinding, args); 30934 30935 // Mimic the constructor's `return` behavior. 30936 // See https://es5.github.io/#x13.2.2 for more details. 30937 return isObject(result) ? result : thisBinding; 30938 }; 30939 } 30940 30941 /** 30942 * Creates a function that wraps `func` to enable currying. 30943 * 30944 * @private 30945 * @param {Function} func The function to wrap. 30946 * @param {number} bitmask The bitmask flags. See `createWrap` for more details. 30947 * @param {number} arity The arity of `func`. 30948 * @returns {Function} Returns the new wrapped function. 30949 */ 30950 function createCurry(func, bitmask, arity) { 30951 var Ctor = createCtor(func); 30952 30953 function wrapper() { 30954 var length = arguments.length, 30955 args = Array(length), 30956 index = length, 30957 placeholder = getHolder(wrapper); 30958 30959 while (index--) { 30960 args[index] = arguments[index]; 30961 } 30962 var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) 30963 ? [] 30964 : replaceHolders(args, placeholder); 30965 30966 length -= holders.length; 30967 if (length < arity) { 30968 return createRecurry( 30969 func, bitmask, createHybrid, wrapper.placeholder, undefined, 30970 args, holders, undefined, undefined, arity - length); 30971 } 30972 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; 30973 return apply(fn, this, args); 30974 } 30975 return wrapper; 30976 } 30977 30978 /** 30979 * Creates a `_.find` or `_.findLast` function. 30980 * 30981 * @private 30982 * @param {Function} findIndexFunc The function to find the collection index. 30983 * @returns {Function} Returns the new find function. 30984 */ 30985 function createFind(findIndexFunc) { 30986 return function(collection, predicate, fromIndex) { 30987 var iterable = Object(collection); 30988 if (!isArrayLike(collection)) { 30989 var iteratee = getIteratee(predicate, 3); 30990 collection = keys(collection); 30991 predicate = function(key) { return iteratee(iterable[key], key, iterable); }; 30992 } 30993 var index = findIndexFunc(collection, predicate, fromIndex); 30994 return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; 30995 }; 30996 } 30997 30998 /** 30999 * Creates a `_.flow` or `_.flowRight` function. 31000 * 31001 * @private 31002 * @param {boolean} [fromRight] Specify iterating from right to left. 31003 * @returns {Function} Returns the new flow function. 31004 */ 31005 function createFlow(fromRight) { 31006 return flatRest(function(funcs) { 31007 var length = funcs.length, 31008 index = length, 31009 prereq = LodashWrapper.prototype.thru; 31010 31011 if (fromRight) { 31012 funcs.reverse(); 31013 } 31014 while (index--) { 31015 var func = funcs[index]; 31016 if (typeof func != 'function') { 31017 throw new TypeError(FUNC_ERROR_TEXT); 31018 } 31019 if (prereq && !wrapper && getFuncName(func) == 'wrapper') { 31020 var wrapper = new LodashWrapper([], true); 31021 } 31022 } 31023 index = wrapper ? index : length; 31024 while (++index < length) { 31025 func = funcs[index]; 31026 31027 var funcName = getFuncName(func), 31028 data = funcName == 'wrapper' ? getData(func) : undefined; 31029 31030 if (data && isLaziable(data[0]) && 31031 data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && 31032 !data[4].length && data[9] == 1 31033 ) { 31034 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); 31035 } else { 31036 wrapper = (func.length == 1 && isLaziable(func)) 31037 ? wrapper[funcName]() 31038 : wrapper.thru(func); 31039 } 31040 } 31041 return function() { 31042 var args = arguments, 31043 value = args[0]; 31044 31045 if (wrapper && args.length == 1 && isArray(value)) { 31046 return wrapper.plant(value).value(); 31047 } 31048 var index = 0, 31049 result = length ? funcs[index].apply(this, args) : value; 31050 31051 while (++index < length) { 31052 result = funcs[index].call(this, result); 31053 } 31054 return result; 31055 }; 31056 }); 31057 } 31058 31059 /** 31060 * Creates a function that wraps `func` to invoke it with optional `this` 31061 * binding of `thisArg`, partial application, and currying. 31062 * 31063 * @private 31064 * @param {Function|string} func The function or method name to wrap. 31065 * @param {number} bitmask The bitmask flags. See `createWrap` for more details. 31066 * @param {*} [thisArg] The `this` binding of `func`. 31067 * @param {Array} [partials] The arguments to prepend to those provided to 31068 * the new function. 31069 * @param {Array} [holders] The `partials` placeholder indexes. 31070 * @param {Array} [partialsRight] The arguments to append to those provided 31071 * to the new function. 31072 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. 31073 * @param {Array} [argPos] The argument positions of the new function. 31074 * @param {number} [ary] The arity cap of `func`. 31075 * @param {number} [arity] The arity of `func`. 31076 * @returns {Function} Returns the new wrapped function. 31077 */ 31078 function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { 31079 var isAry = bitmask & WRAP_ARY_FLAG, 31080 isBind = bitmask & WRAP_BIND_FLAG, 31081 isBindKey = bitmask & WRAP_BIND_KEY_FLAG, 31082 isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), 31083 isFlip = bitmask & WRAP_FLIP_FLAG, 31084 Ctor = isBindKey ? undefined : createCtor(func); 31085 31086 function wrapper() { 31087 var length = arguments.length, 31088 args = Array(length), 31089 index = length; 31090 31091 while (index--) { 31092 args[index] = arguments[index]; 31093 } 31094 if (isCurried) { 31095 var placeholder = getHolder(wrapper), 31096 holdersCount = countHolders(args, placeholder); 31097 } 31098 if (partials) { 31099 args = composeArgs(args, partials, holders, isCurried); 31100 } 31101 if (partialsRight) { 31102 args = composeArgsRight(args, partialsRight, holdersRight, isCurried); 31103 } 31104 length -= holdersCount; 31105 if (isCurried && length < arity) { 31106 var newHolders = replaceHolders(args, placeholder); 31107 return createRecurry( 31108 func, bitmask, createHybrid, wrapper.placeholder, thisArg, 31109 args, newHolders, argPos, ary, arity - length 31110 ); 31111 } 31112 var thisBinding = isBind ? thisArg : this, 31113 fn = isBindKey ? thisBinding[func] : func; 31114 31115 length = args.length; 31116 if (argPos) { 31117 args = reorder(args, argPos); 31118 } else if (isFlip && length > 1) { 31119 args.reverse(); 31120 } 31121 if (isAry && ary < length) { 31122 args.length = ary; 31123 } 31124 if (this && this !== root && this instanceof wrapper) { 31125 fn = Ctor || createCtor(fn); 31126 } 31127 return fn.apply(thisBinding, args); 31128 } 31129 return wrapper; 31130 } 31131 31132 /** 31133 * Creates a function like `_.invertBy`. 31134 * 31135 * @private 31136 * @param {Function} setter The function to set accumulator values. 31137 * @param {Function} toIteratee The function to resolve iteratees. 31138 * @returns {Function} Returns the new inverter function. 31139 */ 31140 function createInverter(setter, toIteratee) { 31141 return function(object, iteratee) { 31142 return baseInverter(object, setter, toIteratee(iteratee), {}); 31143 }; 31144 } 31145 31146 /** 31147 * Creates a function that performs a mathematical operation on two values. 31148 * 31149 * @private 31150 * @param {Function} operator The function to perform the operation. 31151 * @param {number} [defaultValue] The value used for `undefined` arguments. 31152 * @returns {Function} Returns the new mathematical operation function. 31153 */ 31154 function createMathOperation(operator, defaultValue) { 31155 return function(value, other) { 31156 var result; 31157 if (value === undefined && other === undefined) { 31158 return defaultValue; 31159 } 31160 if (value !== undefined) { 31161 result = value; 31162 } 31163 if (other !== undefined) { 31164 if (result === undefined) { 31165 return other; 31166 } 31167 if (typeof value == 'string' || typeof other == 'string') { 31168 value = baseToString(value); 31169 other = baseToString(other); 31170 } else { 31171 value = baseToNumber(value); 31172 other = baseToNumber(other); 31173 } 31174 result = operator(value, other); 31175 } 31176 return result; 31177 }; 31178 } 31179 31180 /** 31181 * Creates a function like `_.over`. 31182 * 31183 * @private 31184 * @param {Function} arrayFunc The function to iterate over iteratees. 31185 * @returns {Function} Returns the new over function. 31186 */ 31187 function createOver(arrayFunc) { 31188 return flatRest(function(iteratees) { 31189 iteratees = arrayMap(iteratees, baseUnary(getIteratee())); 31190 return baseRest(function(args) { 31191 var thisArg = this; 31192 return arrayFunc(iteratees, function(iteratee) { 31193 return apply(iteratee, thisArg, args); 31194 }); 31195 }); 31196 }); 31197 } 31198 31199 /** 31200 * Creates the padding for `string` based on `length`. The `chars` string 31201 * is truncated if the number of characters exceeds `length`. 31202 * 31203 * @private 31204 * @param {number} length The padding length. 31205 * @param {string} [chars=' '] The string used as padding. 31206 * @returns {string} Returns the padding for `string`. 31207 */ 31208 function createPadding(length, chars) { 31209 chars = chars === undefined ? ' ' : baseToString(chars); 31210 31211 var charsLength = chars.length; 31212 if (charsLength < 2) { 31213 return charsLength ? baseRepeat(chars, length) : chars; 31214 } 31215 var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); 31216 return hasUnicode(chars) 31217 ? castSlice(stringToArray(result), 0, length).join('') 31218 : result.slice(0, length); 31219 } 31220 31221 /** 31222 * Creates a function that wraps `func` to invoke it with the `this` binding 31223 * of `thisArg` and `partials` prepended to the arguments it receives. 31224 * 31225 * @private 31226 * @param {Function} func The function to wrap. 31227 * @param {number} bitmask The bitmask flags. See `createWrap` for more details. 31228 * @param {*} thisArg The `this` binding of `func`. 31229 * @param {Array} partials The arguments to prepend to those provided to 31230 * the new function. 31231 * @returns {Function} Returns the new wrapped function. 31232 */ 31233 function createPartial(func, bitmask, thisArg, partials) { 31234 var isBind = bitmask & WRAP_BIND_FLAG, 31235 Ctor = createCtor(func); 31236 31237 function wrapper() { 31238 var argsIndex = -1, 31239 argsLength = arguments.length, 31240 leftIndex = -1, 31241 leftLength = partials.length, 31242 args = Array(leftLength + argsLength), 31243 fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; 31244 31245 while (++leftIndex < leftLength) { 31246 args[leftIndex] = partials[leftIndex]; 31247 } 31248 while (argsLength--) { 31249 args[leftIndex++] = arguments[++argsIndex]; 31250 } 31251 return apply(fn, isBind ? thisArg : this, args); 31252 } 31253 return wrapper; 31254 } 31255 31256 /** 31257 * Creates a `_.range` or `_.rangeRight` function. 31258 * 31259 * @private 31260 * @param {boolean} [fromRight] Specify iterating from right to left. 31261 * @returns {Function} Returns the new range function. 31262 */ 31263 function createRange(fromRight) { 31264 return function(start, end, step) { 31265 if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { 31266 end = step = undefined; 31267 } 31268 // Ensure the sign of `-0` is preserved. 31269 start = toFinite(start); 31270 if (end === undefined) { 31271 end = start; 31272 start = 0; 31273 } else { 31274 end = toFinite(end); 31275 } 31276 step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); 31277 return baseRange(start, end, step, fromRight); 31278 }; 31279 } 31280 31281 /** 31282 * Creates a function that performs a relational operation on two values. 31283 * 31284 * @private 31285 * @param {Function} operator The function to perform the operation. 31286 * @returns {Function} Returns the new relational operation function. 31287 */ 31288 function createRelationalOperation(operator) { 31289 return function(value, other) { 31290 if (!(typeof value == 'string' && typeof other == 'string')) { 31291 value = toNumber(value); 31292 other = toNumber(other); 31293 } 31294 return operator(value, other); 31295 }; 31296 } 31297 31298 /** 31299 * Creates a function that wraps `func` to continue currying. 31300 * 31301 * @private 31302 * @param {Function} func The function to wrap. 31303 * @param {number} bitmask The bitmask flags. See `createWrap` for more details. 31304 * @param {Function} wrapFunc The function to create the `func` wrapper. 31305 * @param {*} placeholder The placeholder value. 31306 * @param {*} [thisArg] The `this` binding of `func`. 31307 * @param {Array} [partials] The arguments to prepend to those provided to 31308 * the new function. 31309 * @param {Array} [holders] The `partials` placeholder indexes. 31310 * @param {Array} [argPos] The argument positions of the new function. 31311 * @param {number} [ary] The arity cap of `func`. 31312 * @param {number} [arity] The arity of `func`. 31313 * @returns {Function} Returns the new wrapped function. 31314 */ 31315 function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { 31316 var isCurry = bitmask & WRAP_CURRY_FLAG, 31317 newHolders = isCurry ? holders : undefined, 31318 newHoldersRight = isCurry ? undefined : holders, 31319 newPartials = isCurry ? partials : undefined, 31320 newPartialsRight = isCurry ? undefined : partials; 31321 31322 bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); 31323 bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); 31324 31325 if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { 31326 bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); 31327 } 31328 var newData = [ 31329 func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, 31330 newHoldersRight, argPos, ary, arity 31331 ]; 31332 31333 var result = wrapFunc.apply(undefined, newData); 31334 if (isLaziable(func)) { 31335 setData(result, newData); 31336 } 31337 result.placeholder = placeholder; 31338 return setWrapToString(result, func, bitmask); 31339 } 31340 31341 /** 31342 * Creates a function like `_.round`. 31343 * 31344 * @private 31345 * @param {string} methodName The name of the `Math` method to use when rounding. 31346 * @returns {Function} Returns the new round function. 31347 */ 31348 function createRound(methodName) { 31349 var func = Math[methodName]; 31350 return function(number, precision) { 31351 number = toNumber(number); 31352 precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); 31353 if (precision) { 31354 // Shift with exponential notation to avoid floating-point issues. 31355 // See [MDN](https://mdn.io/round#Examples) for more details. 31356 var pair = (toString(number) + 'e').split('e'), 31357 value = func(pair[0] + 'e' + (+pair[1] + precision)); 31358 31359 pair = (toString(value) + 'e').split('e'); 31360 return +(pair[0] + 'e' + (+pair[1] - precision)); 31361 } 31362 return func(number); 31363 }; 31364 } 31365 31366 /** 31367 * Creates a set object of `values`. 31368 * 31369 * @private 31370 * @param {Array} values The values to add to the set. 31371 * @returns {Object} Returns the new set. 31372 */ 31373 var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { 31374 return new Set(values); 31375 }; 31376 31377 /** 31378 * Creates a `_.toPairs` or `_.toPairsIn` function. 31379 * 31380 * @private 31381 * @param {Function} keysFunc The function to get the keys of a given object. 31382 * @returns {Function} Returns the new pairs function. 31383 */ 31384 function createToPairs(keysFunc) { 31385 return function(object) { 31386 var tag = getTag(object); 31387 if (tag == mapTag) { 31388 return mapToArray(object); 31389 } 31390 if (tag == setTag) { 31391 return setToPairs(object); 31392 } 31393 return baseToPairs(object, keysFunc(object)); 31394 }; 31395 } 31396 31397 /** 31398 * Creates a function that either curries or invokes `func` with optional 31399 * `this` binding and partially applied arguments. 31400 * 31401 * @private 31402 * @param {Function|string} func The function or method name to wrap. 31403 * @param {number} bitmask The bitmask flags. 31404 * 1 - `_.bind` 31405 * 2 - `_.bindKey` 31406 * 4 - `_.curry` or `_.curryRight` of a bound function 31407 * 8 - `_.curry` 31408 * 16 - `_.curryRight` 31409 * 32 - `_.partial` 31410 * 64 - `_.partialRight` 31411 * 128 - `_.rearg` 31412 * 256 - `_.ary` 31413 * 512 - `_.flip` 31414 * @param {*} [thisArg] The `this` binding of `func`. 31415 * @param {Array} [partials] The arguments to be partially applied. 31416 * @param {Array} [holders] The `partials` placeholder indexes. 31417 * @param {Array} [argPos] The argument positions of the new function. 31418 * @param {number} [ary] The arity cap of `func`. 31419 * @param {number} [arity] The arity of `func`. 31420 * @returns {Function} Returns the new wrapped function. 31421 */ 31422 function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { 31423 var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; 31424 if (!isBindKey && typeof func != 'function') { 31425 throw new TypeError(FUNC_ERROR_TEXT); 31426 } 31427 var length = partials ? partials.length : 0; 31428 if (!length) { 31429 bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); 31430 partials = holders = undefined; 31431 } 31432 ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); 31433 arity = arity === undefined ? arity : toInteger(arity); 31434 length -= holders ? holders.length : 0; 31435 31436 if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { 31437 var partialsRight = partials, 31438 holdersRight = holders; 31439 31440 partials = holders = undefined; 31441 } 31442 var data = isBindKey ? undefined : getData(func); 31443 31444 var newData = [ 31445 func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, 31446 argPos, ary, arity 31447 ]; 31448 31449 if (data) { 31450 mergeData(newData, data); 31451 } 31452 func = newData[0]; 31453 bitmask = newData[1]; 31454 thisArg = newData[2]; 31455 partials = newData[3]; 31456 holders = newData[4]; 31457 arity = newData[9] = newData[9] === undefined 31458 ? (isBindKey ? 0 : func.length) 31459 : nativeMax(newData[9] - length, 0); 31460 31461 if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { 31462 bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); 31463 } 31464 if (!bitmask || bitmask == WRAP_BIND_FLAG) { 31465 var result = createBind(func, bitmask, thisArg); 31466 } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { 31467 result = createCurry(func, bitmask, arity); 31468 } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { 31469 result = createPartial(func, bitmask, thisArg, partials); 31470 } else { 31471 result = createHybrid.apply(undefined, newData); 31472 } 31473 var setter = data ? baseSetData : setData; 31474 return setWrapToString(setter(result, newData), func, bitmask); 31475 } 31476 31477 /** 31478 * Used by `_.defaults` to customize its `_.assignIn` use to assign properties 31479 * of source objects to the destination object for all destination properties 31480 * that resolve to `undefined`. 31481 * 31482 * @private 31483 * @param {*} objValue The destination value. 31484 * @param {*} srcValue The source value. 31485 * @param {string} key The key of the property to assign. 31486 * @param {Object} object The parent object of `objValue`. 31487 * @returns {*} Returns the value to assign. 31488 */ 31489 function customDefaultsAssignIn(objValue, srcValue, key, object) { 31490 if (objValue === undefined || 31491 (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { 31492 return srcValue; 31493 } 31494 return objValue; 31495 } 31496 31497 /** 31498 * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source 31499 * objects into destination objects that are passed thru. 31500 * 31501 * @private 31502 * @param {*} objValue The destination value. 31503 * @param {*} srcValue The source value. 31504 * @param {string} key The key of the property to merge. 31505 * @param {Object} object The parent object of `objValue`. 31506 * @param {Object} source The parent object of `srcValue`. 31507 * @param {Object} [stack] Tracks traversed source values and their merged 31508 * counterparts. 31509 * @returns {*} Returns the value to assign. 31510 */ 31511 function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { 31512 if (isObject(objValue) && isObject(srcValue)) { 31513 // Recursively merge objects and arrays (susceptible to call stack limits). 31514 stack.set(srcValue, objValue); 31515 baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); 31516 stack['delete'](srcValue); 31517 } 31518 return objValue; 31519 } 31520 31521 /** 31522 * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain 31523 * objects. 31524 * 31525 * @private 31526 * @param {*} value The value to inspect. 31527 * @param {string} key The key of the property to inspect. 31528 * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. 31529 */ 31530 function customOmitClone(value) { 31531 return isPlainObject(value) ? undefined : value; 31532 } 31533 31534 /** 31535 * A specialized version of `baseIsEqualDeep` for arrays with support for 31536 * partial deep comparisons. 31537 * 31538 * @private 31539 * @param {Array} array The array to compare. 31540 * @param {Array} other The other array to compare. 31541 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. 31542 * @param {Function} customizer The function to customize comparisons. 31543 * @param {Function} equalFunc The function to determine equivalents of values. 31544 * @param {Object} stack Tracks traversed `array` and `other` objects. 31545 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. 31546 */ 31547 function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { 31548 var isPartial = bitmask & COMPARE_PARTIAL_FLAG, 31549 arrLength = array.length, 31550 othLength = other.length; 31551 31552 if (arrLength != othLength && !(isPartial && othLength > arrLength)) { 31553 return false;
vendor: 1,304 bytes, lines 31554-31592
31554 } 31555 // Assume cyclic values are equal. 31556 var stacked = stack.get(array); 31557 if (stacked && stack.get(other)) { 31558 return stacked == other; 31559 } 31560 var index = -1, 31561 result = true, 31562 seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; 31563 31564 stack.set(array, other); 31565 stack.set(other, array); 31566 31567 // Ignore non-index properties. 31568 while (++index < arrLength) { 31569 var arrValue = array[index], 31570 othValue = other[index]; 31571 31572 if (customizer) { 31573 var compared = isPartial 31574 ? customizer(othValue, arrValue, index, other, array, stack) 31575 : customizer(arrValue, othValue, index, array, other, stack); 31576 } 31577 if (compared !== undefined) { 31578 if (compared) { 31579 continue; 31580 } 31581 result = false; 31582 break; 31583 } 31584 // Recursively compare arrays (susceptible to call stack limits). 31585 if (seen) { 31586 if (!arraySome(other, function(othValue, othIndex) { 31587 if (!cacheHas(seen, othIndex) && 31588 (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { 31589 return seen.push(othIndex); 31590 } 31591 })) { 31592 result = false;
vendor: 4,179 bytes, lines 31593-31704
31593 break; 31594 } 31595 } else if (!( 31596 arrValue === othValue || 31597 equalFunc(arrValue, othValue, bitmask, customizer, stack) 31598 )) { 31599 result = false; 31600 break; 31601 } 31602 } 31603 stack['delete'](array); 31604 stack['delete'](other); 31605 return result; 31606 } 31607 31608 /** 31609 * A specialized version of `baseIsEqualDeep` for comparing objects of 31610 * the same `toStringTag`. 31611 * 31612 * **Note:** This function only supports comparing values with tags of 31613 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. 31614 * 31615 * @private 31616 * @param {Object} object The object to compare. 31617 * @param {Object} other The other object to compare. 31618 * @param {string} tag The `toStringTag` of the objects to compare. 31619 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. 31620 * @param {Function} customizer The function to customize comparisons. 31621 * @param {Function} equalFunc The function to determine equivalents of values. 31622 * @param {Object} stack Tracks traversed `object` and `other` objects. 31623 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. 31624 */ 31625 function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { 31626 switch (tag) { 31627 case dataViewTag: 31628 if ((object.byteLength != other.byteLength) || 31629 (object.byteOffset != other.byteOffset)) { 31630 return false; 31631 } 31632 object = object.buffer; 31633 other = other.buffer; 31634 31635 case arrayBufferTag: 31636 if ((object.byteLength != other.byteLength) || 31637 !equalFunc(new Uint8Array(object), new Uint8Array(other))) { 31638 return false; 31639 } 31640 return true; 31641 31642 case boolTag: 31643 case dateTag: 31644 case numberTag: 31645 // Coerce booleans to `1` or `0` and dates to milliseconds. 31646 // Invalid dates are coerced to `NaN`. 31647 return eq(+object, +other); 31648 31649 case errorTag: 31650 return object.name == other.name && object.message == other.message; 31651 31652 case regexpTag: 31653 case stringTag: 31654 // Coerce regexes to strings and treat strings, primitives and objects, 31655 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring 31656 // for more details. 31657 return object == (other + ''); 31658 31659 case mapTag: 31660 var convert = mapToArray; 31661 31662 case setTag: 31663 var isPartial = bitmask & COMPARE_PARTIAL_FLAG; 31664 convert || (convert = setToArray); 31665 31666 if (object.size != other.size && !isPartial) { 31667 return false; 31668 } 31669 // Assume cyclic values are equal. 31670 var stacked = stack.get(object); 31671 if (stacked) { 31672 return stacked == other; 31673 } 31674 bitmask |= COMPARE_UNORDERED_FLAG; 31675 31676 // Recursively compare objects (susceptible to call stack limits). 31677 stack.set(object, other); 31678 var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); 31679 stack['delete'](object); 31680 return result; 31681 31682 case symbolTag: 31683 if (symbolValueOf) { 31684 return symbolValueOf.call(object) == symbolValueOf.call(other); 31685 } 31686 } 31687 return false; 31688 } 31689 31690 /** 31691 * A specialized version of `baseIsEqualDeep` for objects with support for 31692 * partial deep comparisons. 31693 * 31694 * @private 31695 * @param {Object} object The object to compare. 31696 * @param {Object} other The other object to compare. 31697 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. 31698 * @param {Function} customizer The function to customize comparisons. 31699 * @param {Function} equalFunc The function to determine equivalents of values. 31700 * @param {Object} stack Tracks traversed `object` and `other` objects. 31701 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. 31702 */ 31703 function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { 31704 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
vendor: 1,367 bytes, lines 31705-31745
31705 objProps = getAllKeys(object), 31706 objLength = objProps.length, 31707 othProps = getAllKeys(other), 31708 othLength = othProps.length; 31709 31710 if (objLength != othLength && !isPartial) { 31711 return false; 31712 } 31713 var index = objLength; 31714 while (index--) { 31715 var key = objProps[index]; 31716 if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { 31717 return false; 31718 } 31719 } 31720 // Assume cyclic values are equal. 31721 var stacked = stack.get(object); 31722 if (stacked && stack.get(other)) { 31723 return stacked == other; 31724 } 31725 var result = true; 31726 stack.set(object, other); 31727 stack.set(other, object); 31728 31729 var skipCtor = isPartial; 31730 while (++index < objLength) { 31731 key = objProps[index]; 31732 var objValue = object[key], 31733 othValue = other[key]; 31734 31735 if (customizer) { 31736 var compared = isPartial 31737 ? customizer(othValue, objValue, key, other, object, stack) 31738 : customizer(objValue, othValue, key, object, other, stack); 31739 } 31740 // Recursively compare objects (susceptible to call stack limits). 31741 if (!(compared === undefined 31742 ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) 31743 : compared 31744 )) { 31745 result = false;
vendor: 8,175 bytes, lines 31746-32011
31746 break; 31747 } 31748 skipCtor || (skipCtor = key == 'constructor'); 31749 } 31750 if (result && !skipCtor) { 31751 var objCtor = object.constructor, 31752 othCtor = other.constructor; 31753 31754 // Non `Object` object instances with different constructors are not equal. 31755 if (objCtor != othCtor && 31756 ('constructor' in object && 'constructor' in other) && 31757 !(typeof objCtor == 'function' && objCtor instanceof objCtor && 31758 typeof othCtor == 'function' && othCtor instanceof othCtor)) { 31759 result = false; 31760 } 31761 } 31762 stack['delete'](object); 31763 stack['delete'](other); 31764 return result; 31765 } 31766 31767 /** 31768 * A specialized version of `baseRest` which flattens the rest array. 31769 * 31770 * @private 31771 * @param {Function} func The function to apply a rest parameter to. 31772 * @returns {Function} Returns the new function. 31773 */ 31774 function flatRest(func) { 31775 return setToString(overRest(func, undefined, flatten), func + ''); 31776 } 31777 31778 /** 31779 * Creates an array of own enumerable property names and symbols of `object`. 31780 * 31781 * @private 31782 * @param {Object} object The object to query. 31783 * @returns {Array} Returns the array of property names and symbols. 31784 */ 31785 function getAllKeys(object) { 31786 return baseGetAllKeys(object, keys, getSymbols); 31787 } 31788 31789 /** 31790 * Creates an array of own and inherited enumerable property names and 31791 * symbols of `object`. 31792 * 31793 * @private 31794 * @param {Object} object The object to query. 31795 * @returns {Array} Returns the array of property names and symbols. 31796 */ 31797 function getAllKeysIn(object) { 31798 return baseGetAllKeys(object, keysIn, getSymbolsIn); 31799 } 31800 31801 /** 31802 * Gets metadata for `func`. 31803 * 31804 * @private 31805 * @param {Function} func The function to query. 31806 * @returns {*} Returns the metadata for `func`. 31807 */ 31808 var getData = !metaMap ? noop : function(func) { 31809 return metaMap.get(func); 31810 }; 31811 31812 /** 31813 * Gets the name of `func`. 31814 * 31815 * @private 31816 * @param {Function} func The function to query. 31817 * @returns {string} Returns the function name. 31818 */ 31819 function getFuncName(func) { 31820 var result = (func.name + ''), 31821 array = realNames[result], 31822 length = hasOwnProperty.call(realNames, result) ? array.length : 0; 31823 31824 while (length--) { 31825 var data = array[length], 31826 otherFunc = data.func; 31827 if (otherFunc == null || otherFunc == func) { 31828 return data.name; 31829 } 31830 } 31831 return result; 31832 } 31833 31834 /** 31835 * Gets the argument placeholder value for `func`. 31836 * 31837 * @private 31838 * @param {Function} func The function to inspect. 31839 * @returns {*} Returns the placeholder value. 31840 */ 31841 function getHolder(func) { 31842 var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; 31843 return object.placeholder; 31844 } 31845 31846 /** 31847 * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, 31848 * this function returns the custom method, otherwise it returns `baseIteratee`. 31849 * If arguments are provided, the chosen function is invoked with them and 31850 * its result is returned. 31851 * 31852 * @private 31853 * @param {*} [value] The value to convert to an iteratee. 31854 * @param {number} [arity] The arity of the created iteratee. 31855 * @returns {Function} Returns the chosen function or its result. 31856 */ 31857 function getIteratee() { 31858 var result = lodash.iteratee || iteratee; 31859 result = result === iteratee ? baseIteratee : result; 31860 return arguments.length ? result(arguments[0], arguments[1]) : result; 31861 } 31862 31863 /** 31864 * Gets the data for `map`. 31865 * 31866 * @private 31867 * @param {Object} map The map to query. 31868 * @param {string} key The reference key. 31869 * @returns {*} Returns the map data. 31870 */ 31871 function getMapData(map, key) { 31872 var data = map.__data__; 31873 return isKeyable(key) 31874 ? data[typeof key == 'string' ? 'string' : 'hash'] 31875 : data.map; 31876 } 31877 31878 /** 31879 * Gets the property names, values, and compare flags of `object`. 31880 * 31881 * @private 31882 * @param {Object} object The object to query. 31883 * @returns {Array} Returns the match data of `object`. 31884 */ 31885 function getMatchData(object) { 31886 var result = keys(object), 31887 length = result.length; 31888 31889 while (length--) { 31890 var key = result[length], 31891 value = object[key]; 31892 31893 result[length] = [key, value, isStrictComparable(value)]; 31894 } 31895 return result; 31896 } 31897 31898 /** 31899 * Gets the native function at `key` of `object`. 31900 * 31901 * @private 31902 * @param {Object} object The object to query. 31903 * @param {string} key The key of the method to get. 31904 * @returns {*} Returns the function if it's native, else `undefined`. 31905 */ 31906 function getNative(object, key) { 31907 var value = getValue(object, key); 31908 return baseIsNative(value) ? value : undefined; 31909 } 31910 31911 /** 31912 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. 31913 * 31914 * @private 31915 * @param {*} value The value to query. 31916 * @returns {string} Returns the raw `toStringTag`. 31917 */ 31918 function getRawTag(value) { 31919 var isOwn = hasOwnProperty.call(value, symToStringTag), 31920 tag = value[symToStringTag]; 31921 31922 try { 31923 value[symToStringTag] = undefined; 31924 var unmasked = true; 31925 } catch (e) {} 31926 31927 var result = nativeObjectToString.call(value); 31928 if (unmasked) { 31929 if (isOwn) { 31930 value[symToStringTag] = tag; 31931 } else { 31932 delete value[symToStringTag]; 31933 } 31934 } 31935 return result; 31936 } 31937 31938 /** 31939 * Creates an array of the own enumerable symbols of `object`. 31940 * 31941 * @private 31942 * @param {Object} object The object to query. 31943 * @returns {Array} Returns the array of symbols. 31944 */ 31945 var getSymbols = !nativeGetSymbols ? stubArray : function(object) { 31946 if (object == null) { 31947 return []; 31948 } 31949 object = Object(object); 31950 return arrayFilter(nativeGetSymbols(object), function(symbol) { 31951 return propertyIsEnumerable.call(object, symbol); 31952 }); 31953 }; 31954 31955 /** 31956 * Creates an array of the own and inherited enumerable symbols of `object`. 31957 * 31958 * @private 31959 * @param {Object} object The object to query. 31960 * @returns {Array} Returns the array of symbols. 31961 */ 31962 var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { 31963 var result = []; 31964 while (object) { 31965 arrayPush(result, getSymbols(object)); 31966 object = getPrototype(object); 31967 } 31968 return result; 31969 }; 31970 31971 /** 31972 * Gets the `toStringTag` of `value`. 31973 * 31974 * @private 31975 * @param {*} value The value to query. 31976 * @returns {string} Returns the `toStringTag`. 31977 */ 31978 var getTag = baseGetTag; 31979 31980 // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. 31981 if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || 31982 (Map && getTag(new Map) != mapTag) || 31983 (Promise && getTag(Promise.resolve()) != promiseTag) || 31984 (Set && getTag(new Set) != setTag) || 31985 (WeakMap && getTag(new WeakMap) != weakMapTag)) { 31986 getTag = function(value) { 31987 var result = baseGetTag(value), 31988 Ctor = result == objectTag ? value.constructor : undefined, 31989 ctorString = Ctor ? toSource(Ctor) : ''; 31990 31991 if (ctorString) { 31992 switch (ctorString) { 31993 case dataViewCtorString: return dataViewTag; 31994 case mapCtorString: return mapTag; 31995 case promiseCtorString: return promiseTag; 31996 case setCtorString: return setTag; 31997 case weakMapCtorString: return weakMapTag; 31998 } 31999 } 32000 return result; 32001 }; 32002 } 32003 32004 /** 32005 * Gets the view, applying any `transforms` to the `start` and `end` positions. 32006 * 32007 * @private 32008 * @param {number} start The start of the view. 32009 * @param {number} end The end of the view. 32010 * @param {Array} transforms The transformations to apply to the view. 32011 * @returns {Object}
vendor: 2,210 bytes, lines 32011-32084
32011 Returns an object containing the `start` and `end` 32012 * positions of the view. 32013 */ 32014 function getView(start, end, transforms) { 32015 var index = -1, 32016 length = transforms.length; 32017 32018 while (++index < length) { 32019 var data = transforms[index], 32020 size = data.size; 32021 32022 switch (data.type) { 32023 case 'drop': start += size; break; 32024 case 'dropRight': end -= size; break; 32025 case 'take': end = nativeMin(end, start + size); break; 32026 case 'takeRight': start = nativeMax(start, end - size); break; 32027 } 32028 } 32029 return { 'start': start, 'end': end }; 32030 } 32031 32032 /** 32033 * Extracts wrapper details from the `source` body comment. 32034 * 32035 * @private 32036 * @param {string} source The source to inspect. 32037 * @returns {Array} Returns the wrapper details. 32038 */ 32039 function getWrapDetails(source) { 32040 var match = source.match(reWrapDetails); 32041 return match ? match[1].split(reSplitDetails) : []; 32042 } 32043 32044 /** 32045 * Checks if `path` exists on `object`. 32046 * 32047 * @private 32048 * @param {Object} object The object to query. 32049 * @param {Array|string} path The path to check. 32050 * @param {Function} hasFunc The function to check properties. 32051 * @returns {boolean} Returns `true` if `path` exists, else `false`. 32052 */ 32053 function hasPath(object, path, hasFunc) { 32054 path = castPath(path, object); 32055 32056 var index = -1, 32057 length = path.length, 32058 result = false; 32059 32060 while (++index < length) { 32061 var key = toKey(path[index]); 32062 if (!(result = object != null && hasFunc(object, key))) { 32063 break; 32064 } 32065 object = object[key]; 32066 } 32067 if (result || ++index != length) { 32068 return result; 32069 } 32070 length = object == null ? 0 : object.length; 32071 return !!length && isLength(length) && isIndex(key, length) && 32072 (isArray(object) || isArguments(object)); 32073 } 32074 32075 /** 32076 * Initializes an array clone. 32077 * 32078 * @private 32079 * @param {Array} array The array to clone. 32080 * @returns {Array} Returns the initialized clone. 32081 */ 32082 function initCloneArray(array) { 32083 var length = array.length, 32084 result =
vendor: 3,696 bytes, lines 32084-32198
32084array.constructor(length); 32085 32086 // Add properties assigned by `RegExp#exec`. 32087 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { 32088 result.index = array.index; 32089 result.input = array.input; 32090 } 32091 return result; 32092 } 32093 32094 /** 32095 * Initializes an object clone. 32096 * 32097 * @private 32098 * @param {Object} object The object to clone. 32099 * @returns {Object} Returns the initialized clone. 32100 */ 32101 function initCloneObject(object) { 32102 return (typeof object.constructor == 'function' && !isPrototype(object)) 32103 ? baseCreate(getPrototype(object)) 32104 : {}; 32105 } 32106 32107 /** 32108 * Initializes an object clone based on its `toStringTag`. 32109 * 32110 * **Note:** This function only supports cloning values with tags of 32111 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. 32112 * 32113 * @private 32114 * @param {Object} object The object to clone. 32115 * @param {string} tag The `toStringTag` of the object to clone. 32116 * @param {Function} cloneFunc The function to clone values. 32117 * @param {boolean} [isDeep] Specify a deep clone. 32118 * @returns {Object} Returns the initialized clone. 32119 */ 32120 function initCloneByTag(object, tag, cloneFunc, isDeep) { 32121 var Ctor = object.constructor; 32122 switch (tag) { 32123 case arrayBufferTag: 32124 return cloneArrayBuffer(object); 32125 32126 case boolTag: 32127 case dateTag: 32128 return new Ctor(+object); 32129 32130 case dataViewTag: 32131 return cloneDataView(object, isDeep); 32132 32133 case float32Tag: case float64Tag: 32134 case int8Tag: case int16Tag: case int32Tag: 32135 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: 32136 return cloneTypedArray(object, isDeep); 32137 32138 case mapTag: 32139 return cloneMap(object, isDeep, cloneFunc); 32140 32141 case numberTag: 32142 case stringTag: 32143 return new Ctor(object); 32144 32145 case regexpTag: 32146 return cloneRegExp(object); 32147 32148 case setTag: 32149 return cloneSet(object, isDeep, cloneFunc); 32150 32151 case symbolTag: 32152 return cloneSymbol(object); 32153 } 32154 } 32155 32156 /** 32157 * Inserts wrapper `details` in a comment at the top of the `source` body. 32158 * 32159 * @private 32160 * @param {string} source The source to modify. 32161 * @returns {Array} details The details to insert. 32162 * @returns {string} Returns the modified source. 32163 */ 32164 function insertWrapDetails(source, details) { 32165 var length = details.length; 32166 if (!length) { 32167 return source; 32168 } 32169 var lastIndex = length - 1; 32170 details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; 32171 details = details.join(length > 2 ? ', ' : ' '); 32172 return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); 32173 } 32174 32175 /** 32176 * Checks if `value` is a flattenable `arguments` object or array. 32177 * 32178 * @private 32179 * @param {*} value The value to check. 32180 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. 32181 */ 32182 function isFlattenable(value) { 32183 return isArray(value) || isArguments(value) || 32184 !!(spreadableSymbol && value && value[spreadableSymbol]); 32185 } 32186 32187 /** 32188 * Checks if `value` is a valid array-like index. 32189 * 32190 * @private 32191 * @param {*} value The value to check. 32192 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. 32193 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. 32194 */ 32195 function isIndex(value, length) { 32196 length = length == null ? MAX_SAFE_INTEGER : length; 32197 return !!length && 32198 (typeof value == 'number' || reIsUint.test(value)) &&
vendor: 10,952 bytes, lines 32199-32534
32199 (value > -1 && value % 1 == 0 && value < length); 32200 } 32201 32202 /** 32203 * Checks if the given arguments are from an iteratee call. 32204 * 32205 * @private 32206 * @param {*} value The potential iteratee value argument. 32207 * @param {*} index The potential iteratee index or key argument. 32208 * @param {*} object The potential iteratee object argument. 32209 * @returns {boolean} Returns `true` if the arguments are from an iteratee call, 32210 * else `false`. 32211 */ 32212 function isIterateeCall(value, index, object) { 32213 if (!isObject(object)) { 32214 return false; 32215 } 32216 var type = typeof index; 32217 if (type == 'number' 32218 ? (isArrayLike(object) && isIndex(index, object.length)) 32219 : (type == 'string' && index in object) 32220 ) { 32221 return eq(object[index], value); 32222 } 32223 return false; 32224 } 32225 32226 /** 32227 * Checks if `value` is a property name and not a property path. 32228 * 32229 * @private 32230 * @param {*} value The value to check. 32231 * @param {Object} [object] The object to query keys on. 32232 * @returns {boolean} Returns `true` if `value` is a property name, else `false`. 32233 */ 32234 function isKey(value, object) { 32235 if (isArray(value)) { 32236 return false; 32237 } 32238 var type = typeof value; 32239 if (type == 'number' || type == 'symbol' || type == 'boolean' || 32240 value == null || isSymbol(value)) { 32241 return true; 32242 } 32243 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || 32244 (object != null && value in Object(object)); 32245 } 32246 32247 /** 32248 * Checks if `value` is suitable for use as unique object key. 32249 * 32250 * @private 32251 * @param {*} value The value to check. 32252 * @returns {boolean} Returns `true` if `value` is suitable, else `false`. 32253 */ 32254 function isKeyable(value) { 32255 var type = typeof value; 32256 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') 32257 ? (value !== '__proto__') 32258 : (value === null); 32259 } 32260 32261 /** 32262 * Checks if `func` has a lazy counterpart. 32263 * 32264 * @private 32265 * @param {Function} func The function to check. 32266 * @returns {boolean} Returns `true` if `func` has a lazy counterpart, 32267 * else `false`. 32268 */ 32269 function isLaziable(func) { 32270 var funcName = getFuncName(func), 32271 other = lodash[funcName]; 32272 32273 if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { 32274 return false; 32275 } 32276 if (func === other) { 32277 return true; 32278 } 32279 var data = getData(other); 32280 return !!data && func === data[0]; 32281 } 32282 32283 /** 32284 * Checks if `func` has its source masked. 32285 * 32286 * @private 32287 * @param {Function} func The function to check. 32288 * @returns {boolean} Returns `true` if `func` is masked, else `false`. 32289 */ 32290 function isMasked(func) { 32291 return !!maskSrcKey && (maskSrcKey in func); 32292 } 32293 32294 /** 32295 * Checks if `func` is capable of being masked. 32296 * 32297 * @private 32298 * @param {*} value The value to check. 32299 * @returns {boolean} Returns `true` if `func` is maskable, else `false`. 32300 */ 32301 var isMaskable = coreJsData ? isFunction : stubFalse; 32302 32303 /** 32304 * Checks if `value` is likely a prototype object. 32305 * 32306 * @private 32307 * @param {*} value The value to check. 32308 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. 32309 */ 32310 function isPrototype(value) { 32311 var Ctor = value && value.constructor, 32312 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; 32313 32314 return value === proto; 32315 } 32316 32317 /** 32318 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. 32319 * 32320 * @private 32321 * @param {*} value The value to check. 32322 * @returns {boolean} Returns `true` if `value` if suitable for strict 32323 * equality comparisons, else `false`. 32324 */ 32325 function isStrictComparable(value) { 32326 return value === value && !isObject(value); 32327 } 32328 32329 /** 32330 * A specialized version of `matchesProperty` for source values suitable 32331 * for strict equality comparisons, i.e. `===`. 32332 * 32333 * @private 32334 * @param {string} key The key of the property to get. 32335 * @param {*} srcValue The value to match. 32336 * @returns {Function} Returns the new spec function. 32337 */ 32338 function matchesStrictComparable(key, srcValue) { 32339 return function(object) { 32340 if (object == null) { 32341 return false; 32342 } 32343 return object[key] === srcValue && 32344 (srcValue !== undefined || (key in Object(object))); 32345 }; 32346 } 32347 32348 /** 32349 * A specialized version of `_.memoize` which clears the memoized function's 32350 * cache when it exceeds `MAX_MEMOIZE_SIZE`. 32351 * 32352 * @private 32353 * @param {Function} func The function to have its output memoized. 32354 * @returns {Function} Returns the new memoized function. 32355 */ 32356 function memoizeCapped(func) { 32357 var result = memoize(func, function(key) { 32358 if (cache.size === MAX_MEMOIZE_SIZE) { 32359 cache.clear(); 32360 } 32361 return key; 32362 }); 32363 32364 var cache = result.cache; 32365 return result; 32366 } 32367 32368 /** 32369 * Merges the function metadata of `source` into `data`. 32370 * 32371 * Merging metadata reduces the number of wrappers used to invoke a function. 32372 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` 32373 * may be applied regardless of execution order. Methods like `_.ary` and 32374 * `_.rearg` modify function arguments, making the order in which they are 32375 * executed important, preventing the merging of metadata. However, we make 32376 * an exception for a safe combined case where curried functions have `_.ary` 32377 * and or `_.rearg` applied. 32378 * 32379 * @private 32380 * @param {Array} data The destination metadata. 32381 * @param {Array} source The source metadata. 32382 * @returns {Array} Returns `data`. 32383 */ 32384 function mergeData(data, source) { 32385 var bitmask = data[1], 32386 srcBitmask = source[1], 32387 newBitmask = bitmask | srcBitmask, 32388 isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); 32389 32390 var isCombo = 32391 ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || 32392 ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || 32393 ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); 32394 32395 // Exit early if metadata can't be merged. 32396 if (!(isCommon || isCombo)) { 32397 return data; 32398 } 32399 // Use source `thisArg` if available. 32400 if (srcBitmask & WRAP_BIND_FLAG) { 32401 data[2] = source[2]; 32402 // Set when currying a bound function. 32403 newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; 32404 } 32405 // Compose partial arguments. 32406 var value = source[3]; 32407 if (value) { 32408 var partials = data[3]; 32409 data[3] = partials ? composeArgs(partials, value, source[4]) : value; 32410 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; 32411 } 32412 // Compose partial right arguments. 32413 value = source[5]; 32414 if (value) { 32415 partials = data[5]; 32416 data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; 32417 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; 32418 } 32419 // Use source `argPos` if available. 32420 value = source[7]; 32421 if (value) { 32422 data[7] = value; 32423 } 32424 // Use source `ary` if it's smaller. 32425 if (srcBitmask & WRAP_ARY_FLAG) { 32426 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); 32427 } 32428 // Use source `arity` if one is not provided. 32429 if (data[9] == null) { 32430 data[9] = source[9]; 32431 } 32432 // Use source `func` and merge bitmasks. 32433 data[0] = source[0]; 32434 data[1] = newBitmask; 32435 32436 return data; 32437 } 32438 32439 /** 32440 * This function is like 32441 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) 32442 * except that it includes inherited enumerable properties. 32443 * 32444 * @private 32445 * @param {Object} object The object to query. 32446 * @returns {Array} Returns the array of property names. 32447 */ 32448 function nativeKeysIn(object) { 32449 var result = []; 32450 if (object != null) { 32451 for (var key in Object(object)) { 32452 result.push(key); 32453 } 32454 } 32455 return result; 32456 } 32457 32458 /** 32459 * Converts `value` to a string using `Object.prototype.toString`. 32460 * 32461 * @private 32462 * @param {*} value The value to convert. 32463 * @returns {string} Returns the converted string. 32464 */ 32465 function objectToString(value) { 32466 return nativeObjectToString.call(value); 32467 } 32468 32469 /** 32470 * A specialized version of `baseRest` which transforms the rest array. 32471 * 32472 * @private 32473 * @param {Function} func The function to apply a rest parameter to. 32474 * @param {number} [start=func.length-1] The start position of the rest parameter. 32475 * @param {Function} transform The rest array transform. 32476 * @returns {Function} Returns the new function. 32477 */ 32478 function overRest(func, start, transform) { 32479 start = nativeMax(start === undefined ? (func.length - 1) : start, 0); 32480 return function() { 32481 var args = arguments, 32482 index = -1, 32483 length = nativeMax(args.length - start, 0), 32484 array = Array(length); 32485 32486 while (++index < length) { 32487 array[index] = args[start + index]; 32488 } 32489 index = -1; 32490 var otherArgs = Array(start + 1); 32491 while (++index < start) { 32492 otherArgs[index] = args[index]; 32493 } 32494 otherArgs[start] = transform(array); 32495 return apply(func, this, otherArgs); 32496 }; 32497 } 32498 32499 /** 32500 * Gets the parent value at `path` of `object`. 32501 * 32502 * @private 32503 * @param {Object} object The object to query. 32504 * @param {Array} path The path to get the parent value of. 32505 * @returns {*} Returns the parent value. 32506 */ 32507 function parent(object, path) { 32508 return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); 32509 } 32510 32511 /** 32512 * Reorder `array` according to the specified indexes where the element at 32513 * the first index is assigned as the first element, the element at 32514 * the second index is assigned as the second element, and so on. 32515 * 32516 * @private 32517 * @param {Array} array The array to reorder. 32518 * @param {Array} indexes The arranged array indexes. 32519 * @returns {Array} Returns `array`. 32520 */ 32521 function reorder(array, indexes) { 32522 var arrLength = array.length, 32523 length = nativeMin(indexes.length, arrLength), 32524 oldArray = copyArray(array); 32525 32526 while (length--) { 32527 var index = indexes[length]; 32528 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; 32529 } 32530 return array; 32531 } 32532 32533 /** 32534 *
32534Sets metadata for `func`. 32535 * 32536 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short 32537 * period of time, it will trip its breaker and transition to an identity 32538 * function to avoid garbage collection pauses in V8. See 32539 * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) 32540 * for more details. 32541 * 32542 * @private 32543 * @param {Function} func The function to associate metadata with. 32544 * @param {*} data The metadata. 32545 * @returns {Function} Returns `func`. 32546 */ 32547 var setData = shortOut(baseSetData); 32548 32549 /** 32550 * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). 32551 * 32552 * @private 32553 * @param {Function} func The function to delay. 32554 * @param {number} wait The number of milliseconds to delay invocation. 32555 * @returns {number|Object} Returns the timer id or timeout object. 32556 */ 32557 var setTimeout = ctxSetTimeout || function(func, wait) { 32558 return root.setTimeout(func, wait); 32559 }; 32560 32561 /** 32562 * Sets the `toString` method of `func` to return `string`. 32563 * 32564 * @private 32565 * @param {Function} func The function to modify. 32566 * @param {Function} string The `toString` result. 32567 * @returns {Function} Returns `func`. 32568 */ 32569 var setToString = shortOut(baseSetToString); 32570 32571 /** 32572 * Sets the `toString` method of `wrapper` to mimic the source of `reference` 32573 * with wrapper details in a comment at the top of the source body. 32574 * 32575 * @private 32576 * @param {Function} wrapper The function to modify. 32577 * @param {Function} reference The reference function. 32578 * @param {number} bitmask The bitmask flags. See `createWrap` for more details. 32579 * @returns {Function} Returns `wrapper`. 32580 */ 32581 function setWrapToString(wrapper, reference, bitmask) { 32582 var source = (reference + ''); 32583 return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); 32584 } 32585 32586 /** 32587 * Creates a function that'll short out and invoke `identity` instead 32588 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` 32589 * milliseconds. 32590 * 32591 * @private 32592 * @param {Function} func The function to restrict. 32593 * @returns {Function} Returns the new shortable function. 32594 */ 32595 function shortOut(func) { 32596 var count = 0, 32597 lastCalled = 0; 32598 32599 return function() { 32600 var stamp = nativeNow(), 32601 remaining = HOT_SPAN - (stamp - lastCalled); 32602 32603 lastCalled = stamp; 32604 if (remaining > 0) { 32605 if (++count >= HOT_COUNT) { 32606 return arguments[0]; 32607 } 32608 } else { 32609 count = 0; 32610 } 32611 return func.apply(undefined, arguments); 32612 }; 32613 } 32614 32615 /** 32616 * A specialized version of `_.shuffle` which mutates and sets the size of `array`. 32617 * 32618 * @private 32619 * @param {Array} array The array to shuffle. 32620 * @param {number} [size=array.length] The size of `array`. 32621 * @returns {Array} Returns `array`. 32622 */ 32623 function shuffleSelf(array, size) { 32624 var index = -1, 32625 length = array.length, 32626 lastIndex = length - 1; 32627 32628 size = size === undefined ? length : size; 32629 while (++index < size) { 32630 var rand = baseRandom(index, lastIndex), 32631 value = array[rand]; 32632 32633 array[rand] = array[index]; 32634 array[index] = value; 32635 } 32636 array.length = size; 32637 return array; 32638 } 32639 32640 /** 32641 * Converts `string` to a property path array. 32642 * 32643 * @private 32644 * @param {string} string The string to convert. 32645 * @returns {Array} Returns the property path array. 32646 */ 32647 var stringToPath = memoizeCapped(function(string) { 32648 var result = []; 32649 if (reLeadingDot.test(string)) { 32650 result.push(''); 32651 }
32652 string.replace(rePropName, function(match, number, quote, string) { 32653 result.push(quote ? s
vendor: 70,687 bytes, lines 32653-34967
32653tring.replace(reEscapeChar, '$1') : (number || match)); 32654 }); 32655 return result; 32656 }); 32657 32658 /** 32659 * Converts `value` to a string key if it's not a string or symbol. 32660 * 32661 * @private 32662 * @param {*} value The value to inspect. 32663 * @returns {string|symbol} Returns the key. 32664 */ 32665 function toKey(value) { 32666 if (typeof value == 'string' || isSymbol(value)) { 32667 return value; 32668 } 32669 var result = (value + ''); 32670 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; 32671 } 32672 32673 /** 32674 * Converts `func` to its source code. 32675 * 32676 * @private 32677 * @param {Function} func The function to convert. 32678 * @returns {string} Returns the source code. 32679 */ 32680 function toSource(func) { 32681 if (func != null) { 32682 try { 32683 return funcToString.call(func); 32684 } catch (e) {} 32685 try { 32686 return (func + ''); 32687 } catch (e) {} 32688 } 32689 return ''; 32690 } 32691 32692 /** 32693 * Updates wrapper `details` based on `bitmask` flags. 32694 * 32695 * @private 32696 * @returns {Array} details The details to modify. 32697 * @param {number} bitmask The bitmask flags. See `createWrap` for more details. 32698 * @returns {Array} Returns `details`. 32699 */ 32700 function updateWrapDetails(details, bitmask) { 32701 arrayEach(wrapFlags, function(pair) { 32702 var value = '_.' + pair[0]; 32703 if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { 32704 details.push(value); 32705 } 32706 }); 32707 return details.sort(); 32708 } 32709 32710 /** 32711 * Creates a clone of `wrapper`. 32712 * 32713 * @private 32714 * @param {Object} wrapper The wrapper to clone. 32715 * @returns {Object} Returns the cloned wrapper. 32716 */ 32717 function wrapperClone(wrapper) { 32718 if (wrapper instanceof LazyWrapper) { 32719 return wrapper.clone(); 32720 } 32721 var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); 32722 result.__actions__ = copyArray(wrapper.__actions__); 32723 result.__index__ = wrapper.__index__; 32724 result.__values__ = wrapper.__values__; 32725 return result; 32726 } 32727 32728 /*------------------------------------------------------------------------*/ 32729 32730 /** 32731 * Creates an array of elements split into groups the length of `size`. 32732 * If `array` can't be split evenly, the final chunk will be the remaining 32733 * elements. 32734 * 32735 * @static 32736 * @memberOf _ 32737 * @since 3.0.0 32738 * @category Array 32739 * @param {Array} array The array to process. 32740 * @param {number} [size=1] The length of each chunk 32741 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 32742 * @returns {Array} Returns the new array of chunks. 32743 * @example 32744 * 32745 * _.chunk(['a', 'b', 'c', 'd'], 2); 32746 * // => [['a', 'b'], ['c', 'd']] 32747 * 32748 * _.chunk(['a', 'b', 'c', 'd'], 3); 32749 * // => [['a', 'b', 'c'], ['d']] 32750 */ 32751 function chunk(array, size, guard) { 32752 if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { 32753 size = 1; 32754 } else { 32755 size = nativeMax(toInteger(size), 0); 32756 } 32757 var length = array == null ? 0 : array.length; 32758 if (!length || size < 1) { 32759 return []; 32760 } 32761 var index = 0, 32762 resIndex = 0, 32763 result = Array(nativeCeil(length / size)); 32764 32765 while (index < length) { 32766 result[resIndex++] = baseSlice(array, index, (index += size)); 32767 } 32768 return result; 32769 } 32770 32771 /** 32772 * Creates an array with all falsey values removed. The values `false`, `null`, 32773 * `0`, `""`, `undefined`, and `NaN` are falsey. 32774 * 32775 * @static 32776 * @memberOf _ 32777 * @since 0.1.0 32778 * @category Array 32779 * @param {Array} array The array to compact. 32780 * @returns {Array} Returns the new array of filtered values. 32781 * @example 32782 * 32783 * _.compact([0, 1, false, 2, '', 3]); 32784 * // => [1, 2, 3] 32785 */ 32786 function compact(array) { 32787 var index = -1, 32788 length = array == null ? 0 : array.length, 32789 resIndex = 0, 32790 result = []; 32791 32792 while (++index < length) { 32793 var value = array[index]; 32794 if (value) { 32795 result[resIndex++] = value; 32796 } 32797 } 32798 return result; 32799 } 32800 32801 /** 32802 * Creates a new array concatenating `array` with any additional arrays 32803 * and/or values. 32804 * 32805 * @static 32806 * @memberOf _ 32807 * @since 4.0.0 32808 * @category Array 32809 * @param {Array} array The array to concatenate. 32810 * @param {...*} [values] The values to concatenate. 32811 * @returns {Array} Returns the new concatenated array. 32812 * @example 32813 * 32814 * var array = [1]; 32815 * var other = _.concat(array, 2, [3], [[4]]); 32816 * 32817 * console.log(other); 32818 * // => [1, 2, 3, [4]] 32819 * 32820 * console.log(array); 32821 * // => [1] 32822 */ 32823 function concat() { 32824 var length = arguments.length; 32825 if (!length) { 32826 return []; 32827 } 32828 var args = Array(length - 1), 32829 array = arguments[0], 32830 index = length; 32831 32832 while (index--) { 32833 args[index - 1] = arguments[index]; 32834 } 32835 return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); 32836 } 32837 32838 /** 32839 * Creates an array of `array` values not included in the other given arrays 32840 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) 32841 * for equality comparisons. The order and references of result values are 32842 * determined by the first array. 32843 * 32844 * **Note:** Unlike `_.pullAll`, this method returns a new array. 32845 * 32846 * @static 32847 * @memberOf _ 32848 * @since 0.1.0 32849 * @category Array 32850 * @param {Array} array The array to inspect. 32851 * @param {...Array} [values] The values to exclude. 32852 * @returns {Array} Returns the new array of filtered values. 32853 * @see _.without, _.xor 32854 * @example 32855 * 32856 * _.difference([2, 1], [2, 3]); 32857 * // => [1] 32858 */ 32859 var difference = baseRest(function(array, values) { 32860 return isArrayLikeObject(array) 32861 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) 32862 : []; 32863 }); 32864 32865 /** 32866 * This method is like `_.difference` except that it accepts `iteratee` which 32867 * is invoked for each element of `array` and `values` to generate the criterion 32868 * by which they're compared. The order and references of result values are 32869 * determined by the first array. The iteratee is invoked with one argument: 32870 * (value). 32871 * 32872 * **Note:** Unlike `_.pullAllBy`, this method returns a new array. 32873 * 32874 * @static 32875 * @memberOf _ 32876 * @since 4.0.0 32877 * @category Array 32878 * @param {Array} array The array to inspect. 32879 * @param {...Array} [values] The values to exclude. 32880 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 32881 * @returns {Array} Returns the new array of filtered values. 32882 * @example 32883 * 32884 * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); 32885 * // => [1.2] 32886 * 32887 * // The `_.property` iteratee shorthand. 32888 * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); 32889 * // => [{ 'x': 2 }] 32890 */ 32891 var differenceBy = baseRest(function(array, values) { 32892 var iteratee = last(values); 32893 if (isArrayLikeObject(iteratee)) { 32894 iteratee = undefined; 32895 } 32896 return isArrayLikeObject(array) 32897 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) 32898 : []; 32899 }); 32900 32901 /** 32902 * This method is like `_.difference` except that it accepts `comparator` 32903 * which is invoked to compare elements of `array` to `values`. The order and 32904 * references of result values are determined by the first array. The comparator 32905 * is invoked with two arguments: (arrVal, othVal). 32906 * 32907 * **Note:** Unlike `_.pullAllWith`, this method returns a new array. 32908 * 32909 * @static 32910 * @memberOf _ 32911 * @since 4.0.0 32912 * @category Array 32913 * @param {Array} array The array to inspect. 32914 * @param {...Array} [values] The values to exclude. 32915 * @param {Function} [comparator] The comparator invoked per element. 32916 * @returns {Array} Returns the new array of filtered values. 32917 * @example 32918 * 32919 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; 32920 * 32921 * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); 32922 * // => [{ 'x': 2, 'y': 1 }] 32923 */ 32924 var differenceWith = baseRest(function(array, values) { 32925 var comparator = last(values); 32926 if (isArrayLikeObject(comparator)) { 32927 comparator = undefined; 32928 } 32929 return isArrayLikeObject(array) 32930 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) 32931 : []; 32932 }); 32933 32934 /** 32935 * Creates a slice of `array` with `n` elements dropped from the beginning. 32936 * 32937 * @static 32938 * @memberOf _ 32939 * @since 0.5.0 32940 * @category Array 32941 * @param {Array} array The array to query. 32942 * @param {number} [n=1] The number of elements to drop. 32943 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 32944 * @returns {Array} Returns the slice of `array`. 32945 * @example 32946 * 32947 * _.drop([1, 2, 3]); 32948 * // => [2, 3] 32949 * 32950 * _.drop([1, 2, 3], 2); 32951 * // => [3] 32952 * 32953 * _.drop([1, 2, 3], 5); 32954 * // => [] 32955 * 32956 * _.drop([1, 2, 3], 0); 32957 * // => [1, 2, 3] 32958 */ 32959 function drop(array, n, guard) { 32960 var length = array == null ? 0 : array.length; 32961 if (!length) { 32962 return []; 32963 } 32964 n = (guard || n === undefined) ? 1 : toInteger(n); 32965 return baseSlice(array, n < 0 ? 0 : n, length); 32966 } 32967 32968 /** 32969 * Creates a slice of `array` with `n` elements dropped from the end. 32970 * 32971 * @static 32972 * @memberOf _ 32973 * @since 3.0.0 32974 * @category Array 32975 * @param {Array} array The array to query. 32976 * @param {number} [n=1] The number of elements to drop. 32977 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 32978 * @returns {Array} Returns the slice of `array`. 32979 * @example 32980 * 32981 * _.dropRight([1, 2, 3]); 32982 * // => [1, 2] 32983 * 32984 * _.dropRight([1, 2, 3], 2); 32985 * // => [1] 32986 * 32987 * _.dropRight([1, 2, 3], 5); 32988 * // => [] 32989 * 32990 * _.dropRight([1, 2, 3], 0); 32991 * // => [1, 2, 3] 32992 */ 32993 function dropRight(array, n, guard) { 32994 var length = array == null ? 0 : array.length; 32995 if (!length) { 32996 return []; 32997 } 32998 n = (guard || n === undefined) ? 1 : toInteger(n); 32999 n = length - n; 33000 return baseSlice(array, 0, n < 0 ? 0 : n); 33001 } 33002 33003 /** 33004 * Creates a slice of `array` excluding elements dropped from the end. 33005 * Elements are dropped until `predicate` returns falsey. The predicate is 33006 * invoked with three arguments: (value, index, array). 33007 * 33008 * @static 33009 * @memberOf _ 33010 * @since 3.0.0 33011 * @category Array 33012 * @param {Array} array The array to query. 33013 * @param {Function} [predicate=_.identity] The function invoked per iteration. 33014 * @returns {Array} Returns the slice of `array`. 33015 * @example 33016 * 33017 * var users = [ 33018 * { 'user': 'barney', 'active': true }, 33019 * { 'user': 'fred', 'active': false }, 33020 * { 'user': 'pebbles', 'active': false } 33021 * ]; 33022 * 33023 * _.dropRightWhile(users, function(o) { return !o.active; }); 33024 * // => objects for ['barney'] 33025 * 33026 * // The `_.matches` iteratee shorthand. 33027 * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); 33028 * // => objects for ['barney', 'fred'] 33029 * 33030 * // The `_.matchesProperty` iteratee shorthand. 33031 * _.dropRightWhile(users, ['active', false]); 33032 * // => objects for ['barney'] 33033 * 33034 * // The `_.property` iteratee shorthand. 33035 * _.dropRightWhile(users, 'active'); 33036 * // => objects for ['barney', 'fred', 'pebbles'] 33037 */ 33038 function dropRightWhile(array, predicate) { 33039 return (array && array.length) 33040 ? baseWhile(array, getIteratee(predicate, 3), true, true) 33041 : []; 33042 } 33043 33044 /** 33045 * Creates a slice of `array` excluding elements dropped from the beginning. 33046 * Elements are dropped until `predicate` returns falsey. The predicate is 33047 * invoked with three arguments: (value, index, array). 33048 * 33049 * @static 33050 * @memberOf _ 33051 * @since 3.0.0 33052 * @category Array 33053 * @param {Array} array The array to query. 33054 * @param {Function} [predicate=_.identity] The function invoked per iteration. 33055 * @returns {Array} Returns the slice of `array`. 33056 * @example 33057 * 33058 * var users = [ 33059 * { 'user': 'barney', 'active': false }, 33060 * { 'user': 'fred', 'active': false }, 33061 * { 'user': 'pebbles', 'active': true } 33062 * ]; 33063 * 33064 * _.dropWhile(users, function(o) { return !o.active; }); 33065 * // => objects for ['pebbles'] 33066 * 33067 * // The `_.matches` iteratee shorthand. 33068 * _.dropWhile(users, { 'user': 'barney', 'active': false }); 33069 * // => objects for ['fred', 'pebbles'] 33070 * 33071 * // The `_.matchesProperty` iteratee shorthand. 33072 * _.dropWhile(users, ['active', false]); 33073 * // => objects for ['pebbles'] 33074 * 33075 * // The `_.property` iteratee shorthand. 33076 * _.dropWhile(users, 'active'); 33077 * // => objects for ['barney', 'fred', 'pebbles'] 33078 */ 33079 function dropWhile(array, predicate) { 33080 return (array && array.length) 33081 ? baseWhile(array, getIteratee(predicate, 3), true) 33082 : []; 33083 } 33084 33085 /** 33086 * Fills elements of `array` with `value` from `start` up to, but not 33087 * including, `end`. 33088 * 33089 * **Note:** This method mutates `array`. 33090 * 33091 * @static 33092 * @memberOf _ 33093 * @since 3.2.0 33094 * @category Array 33095 * @param {Array} array The array to fill. 33096 * @param {*} value The value to fill `array` with. 33097 * @param {number} [start=0] The start position. 33098 * @param {number} [end=array.length] The end position. 33099 * @returns {Array} Returns `array`. 33100 * @example 33101 * 33102 * var array = [1, 2, 3]; 33103 * 33104 * _.fill(array, 'a'); 33105 * console.log(array); 33106 * // => ['a', 'a', 'a'] 33107 * 33108 * _.fill(Array(3), 2); 33109 * // => [2, 2, 2] 33110 * 33111 * _.fill([4, 6, 8, 10], '*', 1, 3); 33112 * // => [4, '*', '*', 10] 33113 */ 33114 function fill(array, value, start, end) { 33115 var length = array == null ? 0 : array.length; 33116 if (!length) { 33117 return []; 33118 } 33119 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { 33120 start = 0; 33121 end = length; 33122 } 33123 return baseFill(array, value, start, end); 33124 } 33125 33126 /** 33127 * This method is like `_.find` except that it returns the index of the first 33128 * element `predicate` returns truthy for instead of the element itself. 33129 * 33130 * @static 33131 * @memberOf _ 33132 * @since 1.1.0 33133 * @category Array 33134 * @param {Array} array The array to inspect. 33135 * @param {Function} [predicate=_.identity] The function invoked per iteration. 33136 * @param {number} [fromIndex=0] The index to search from. 33137 * @returns {number} Returns the index of the found element, else `-1`. 33138 * @example 33139 * 33140 * var users = [ 33141 * { 'user': 'barney', 'active': false }, 33142 * { 'user': 'fred', 'active': false }, 33143 * { 'user': 'pebbles', 'active': true } 33144 * ]; 33145 * 33146 * _.findIndex(users, function(o) { return o.user == 'barney'; }); 33147 * // => 0 33148 * 33149 * // The `_.matches` iteratee shorthand. 33150 * _.findIndex(users, { 'user': 'fred', 'active': false }); 33151 * // => 1 33152 * 33153 * // The `_.matchesProperty` iteratee shorthand. 33154 * _.findIndex(users, ['active', false]); 33155 * // => 0 33156 * 33157 * // The `_.property` iteratee shorthand. 33158 * _.findIndex(users, 'active'); 33159 * // => 2 33160 */ 33161 function findIndex(array, predicate, fromIndex) { 33162 var length = array == null ? 0 : array.length; 33163 if (!length) { 33164 return -1; 33165 } 33166 var index = fromIndex == null ? 0 : toInteger(fromIndex); 33167 if (index < 0) { 33168 index = nativeMax(length + index, 0); 33169 } 33170 return baseFindIndex(array, getIteratee(predicate, 3), index); 33171 } 33172 33173 /** 33174 * This method is like `_.findIndex` except that it iterates over elements 33175 * of `collection` from right to left. 33176 * 33177 * @static 33178 * @memberOf _ 33179 * @since 2.0.0 33180 * @category Array 33181 * @param {Array} array The array to inspect. 33182 * @param {Function} [predicate=_.identity] The function invoked per iteration. 33183 * @param {number} [fromIndex=array.length-1] The index to search from. 33184 * @returns {number} Returns the index of the found element, else `-1`. 33185 * @example 33186 * 33187 * var users = [ 33188 * { 'user': 'barney', 'active': true }, 33189 * { 'user': 'fred', 'active': false }, 33190 * { 'user': 'pebbles', 'active': false } 33191 * ]; 33192 * 33193 * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); 33194 * // => 2 33195 * 33196 * // The `_.matches` iteratee shorthand. 33197 * _.findLastIndex(users, { 'user': 'barney', 'active': true }); 33198 * // => 0 33199 * 33200 * // The `_.matchesProperty` iteratee shorthand. 33201 * _.findLastIndex(users, ['active', false]); 33202 * // => 2 33203 * 33204 * // The `_.property` iteratee shorthand. 33205 * _.findLastIndex(users, 'active'); 33206 * // => 0 33207 */ 33208 function findLastIndex(array, predicate, fromIndex) { 33209 var length = array == null ? 0 : array.length; 33210 if (!length) { 33211 return -1; 33212 } 33213 var index = length - 1; 33214 if (fromIndex !== undefined) { 33215 index = toInteger(fromIndex); 33216 index = fromIndex < 0 33217 ? nativeMax(length + index, 0) 33218 : nativeMin(index, length - 1); 33219 } 33220 return baseFindIndex(array, getIteratee(predicate, 3), index, true); 33221 } 33222 33223 /** 33224 * Flattens `array` a single level deep. 33225 * 33226 * @static 33227 * @memberOf _ 33228 * @since 0.1.0 33229 * @category Array 33230 * @param {Array} array The array to flatten. 33231 * @returns {Array} Returns the new flattened array. 33232 * @example 33233 * 33234 * _.flatten([1, [2, [3, [4]], 5]]); 33235 * // => [1, 2, [3, [4]], 5] 33236 */ 33237 function flatten(array) { 33238 var length = array == null ? 0 : array.length; 33239 return length ? baseFlatten(array, 1) : []; 33240 } 33241 33242 /** 33243 * Recursively flattens `array`. 33244 * 33245 * @static 33246 * @memberOf _ 33247 * @since 3.0.0 33248 * @category Array 33249 * @param {Array} array The array to flatten. 33250 * @returns {Array} Returns the new flattened array. 33251 * @example 33252 * 33253 * _.flattenDeep([1, [2, [3, [4]], 5]]); 33254 * // => [1, 2, 3, 4, 5] 33255 */ 33256 function flattenDeep(array) { 33257 var length = array == null ? 0 : array.length; 33258 return length ? baseFlatten(array, INFINITY) : []; 33259 } 33260 33261 /** 33262 * Recursively flatten `array` up to `depth` times. 33263 * 33264 * @static 33265 * @memberOf _ 33266 * @since 4.4.0 33267 * @category Array 33268 * @param {Array} array The array to flatten. 33269 * @param {number} [depth=1] The maximum recursion depth. 33270 * @returns {Array} Returns the new flattened array. 33271 * @example 33272 * 33273 * var array = [1, [2, [3, [4]], 5]]; 33274 * 33275 * _.flattenDepth(array, 1); 33276 * // => [1, 2, [3, [4]], 5] 33277 * 33278 * _.flattenDepth(array, 2); 33279 * // => [1, 2, 3, [4], 5] 33280 */ 33281 function flattenDepth(array, depth) { 33282 var length = array == null ? 0 : array.length; 33283 if (!length) { 33284 return []; 33285 } 33286 depth = depth === undefined ? 1 : toInteger(depth); 33287 return baseFlatten(array, depth); 33288 } 33289 33290 /** 33291 * The inverse of `_.toPairs`; this method returns an object composed 33292 * from key-value `pairs`. 33293 * 33294 * @static 33295 * @memberOf _ 33296 * @since 4.0.0 33297 * @category Array 33298 * @param {Array} pairs The key-value pairs. 33299 * @returns {Object} Returns the new object. 33300 * @example 33301 * 33302 * _.fromPairs([['a', 1], ['b', 2]]); 33303 * // => { 'a': 1, 'b': 2 } 33304 */ 33305 function fromPairs(pairs) { 33306 var index = -1, 33307 length = pairs == null ? 0 : pairs.length, 33308 result = {}; 33309 33310 while (++index < length) { 33311 var pair = pairs[index]; 33312 result[pair[0]] = pair[1]; 33313 } 33314 return result; 33315 } 33316 33317 /** 33318 * Gets the first element of `array`. 33319 * 33320 * @static 33321 * @memberOf _ 33322 * @since 0.1.0 33323 * @alias first 33324 * @category Array 33325 * @param {Array} array The array to query. 33326 * @returns {*} Returns the first element of `array`. 33327 * @example 33328 * 33329 * _.head([1, 2, 3]); 33330 * // => 1 33331 * 33332 * _.head([]); 33333 * // => undefined 33334 */ 33335 function head(array) { 33336 return (array && array.length) ? array[0] : undefined; 33337 } 33338 33339 /** 33340 * Gets the index at which the first occurrence of `value` is found in `array` 33341 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) 33342 * for equality comparisons. If `fromIndex` is negative, it's used as the 33343 * offset from the end of `array`. 33344 * 33345 * @static 33346 * @memberOf _ 33347 * @since 0.1.0 33348 * @category Array 33349 * @param {Array} array The array to inspect. 33350 * @param {*} value The value to search for. 33351 * @param {number} [fromIndex=0] The index to search from. 33352 * @returns {number} Returns the index of the matched value, else `-1`. 33353 * @example 33354 * 33355 * _.indexOf([1, 2, 1, 2], 2); 33356 * // => 1 33357 * 33358 * // Search from the `fromIndex`. 33359 * _.indexOf([1, 2, 1, 2], 2, 2); 33360 * // => 3 33361 */ 33362 function indexOf(array, value, fromIndex) { 33363 var length = array == null ? 0 : array.length; 33364 if (!length) { 33365 return -1; 33366 } 33367 var index = fromIndex == null ? 0 : toInteger(fromIndex); 33368 if (index < 0) { 33369 index = nativeMax(length + index, 0); 33370 } 33371 return baseIndexOf(array, value, index); 33372 } 33373 33374 /** 33375 * Gets all but the last element of `array`. 33376 * 33377 * @static 33378 * @memberOf _ 33379 * @since 0.1.0 33380 * @category Array 33381 * @param {Array} array The array to query. 33382 * @returns {Array} Returns the slice of `array`. 33383 * @example 33384 * 33385 * _.initial([1, 2, 3]); 33386 * // => [1, 2] 33387 */ 33388 function initial(array) { 33389 var length = array == null ? 0 : array.length; 33390 return length ? baseSlice(array, 0, -1) : []; 33391 } 33392 33393 /** 33394 * Creates an array of unique values that are included in all given arrays 33395 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) 33396 * for equality comparisons. The order and references of result values are 33397 * determined by the first array. 33398 * 33399 * @static 33400 * @memberOf _ 33401 * @since 0.1.0 33402 * @category Array 33403 * @param {...Array} [arrays] The arrays to inspect. 33404 * @returns {Array} Returns the new array of intersecting values. 33405 * @example 33406 * 33407 * _.intersection([2, 1], [2, 3]); 33408 * // => [2] 33409 */ 33410 var intersection = baseRest(function(arrays) { 33411 var mapped = arrayMap(arrays, castArrayLikeObject); 33412 return (mapped.length && mapped[0] === arrays[0]) 33413 ? baseIntersection(mapped) 33414 : []; 33415 }); 33416 33417 /** 33418 * This method is like `_.intersection` except that it accepts `iteratee` 33419 * which is invoked for each element of each `arrays` to generate the criterion 33420 * by which they're compared. The order and references of result values are 33421 * determined by the first array. The iteratee is invoked with one argument: 33422 * (value). 33423 * 33424 * @static 33425 * @memberOf _ 33426 * @since 4.0.0 33427 * @category Array 33428 * @param {...Array} [arrays] The arrays to inspect. 33429 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 33430 * @returns {Array} Returns the new array of intersecting values. 33431 * @example 33432 * 33433 * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); 33434 * // => [2.1] 33435 * 33436 * // The `_.property` iteratee shorthand. 33437 * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); 33438 * // => [{ 'x': 1 }] 33439 */ 33440 var intersectionBy = baseRest(function(arrays) { 33441 var iteratee = last(arrays), 33442 mapped = arrayMap(arrays, castArrayLikeObject); 33443 33444 if (iteratee === last(mapped)) { 33445 iteratee = undefined; 33446 } else { 33447 mapped.pop(); 33448 } 33449 return (mapped.length && mapped[0] === arrays[0]) 33450 ? baseIntersection(mapped, getIteratee(iteratee, 2)) 33451 : []; 33452 }); 33453 33454 /** 33455 * This method is like `_.intersection` except that it accepts `comparator` 33456 * which is invoked to compare elements of `arrays`. The order and references 33457 * of result values are determined by the first array. The comparator is 33458 * invoked with two arguments: (arrVal, othVal). 33459 * 33460 * @static 33461 * @memberOf _ 33462 * @since 4.0.0 33463 * @category Array 33464 * @param {...Array} [arrays] The arrays to inspect. 33465 * @param {Function} [comparator] The comparator invoked per element. 33466 * @returns {Array} Returns the new array of intersecting values. 33467 * @example 33468 * 33469 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; 33470 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; 33471 * 33472 * _.intersectionWith(objects, others, _.isEqual); 33473 * // => [{ 'x': 1, 'y': 2 }] 33474 */ 33475 var intersectionWith = baseRest(function(arrays) { 33476 var comparator = last(arrays), 33477 mapped = arrayMap(arrays, castArrayLikeObject); 33478 33479 comparator = typeof comparator == 'function' ? comparator : undefined; 33480 if (comparator) { 33481 mapped.pop(); 33482 } 33483 return (mapped.length && mapped[0] === arrays[0]) 33484 ? baseIntersection(mapped, undefined, comparator) 33485 : []; 33486 }); 33487 33488 /** 33489 * Converts all elements in `array` into a string separated by `separator`. 33490 * 33491 * @static 33492 * @memberOf _ 33493 * @since 4.0.0 33494 * @category Array 33495 * @param {Array} array The array to convert. 33496 * @param {string} [separator=','] The element separator. 33497 * @returns {string} Returns the joined string. 33498 * @example 33499 * 33500 * _.join(['a', 'b', 'c'], '~'); 33501 * // => 'a~b~c' 33502 */ 33503 function join(array, separator) { 33504 return array == null ? '' : nativeJoin.call(array, separator); 33505 } 33506 33507 /** 33508 * Gets the last element of `array`. 33509 * 33510 * @static 33511 * @memberOf _ 33512 * @since 0.1.0 33513 * @category Array 33514 * @param {Array} array The array to query. 33515 * @returns {*} Returns the last element of `array`. 33516 * @example 33517 * 33518 * _.last([1, 2, 3]); 33519 * // => 3 33520 */ 33521 function last(array) { 33522 var length = array == null ? 0 : array.length; 33523 return length ? array[length - 1] : undefined; 33524 } 33525 33526 /** 33527 * This method is like `_.indexOf` except that it iterates over elements of 33528 * `array` from right to left. 33529 * 33530 * @static 33531 * @memberOf _ 33532 * @since 0.1.0 33533 * @category Array 33534 * @param {Array} array The array to inspect. 33535 * @param {*} value The value to search for. 33536 * @param {number} [fromIndex=array.length-1] The index to search from. 33537 * @returns {number} Returns the index of the matched value, else `-1`. 33538 * @example 33539 * 33540 * _.lastIndexOf([1, 2, 1, 2], 2); 33541 * // => 3 33542 * 33543 * // Search from the `fromIndex`. 33544 * _.lastIndexOf([1, 2, 1, 2], 2, 2); 33545 * // => 1 33546 */ 33547 function lastIndexOf(array, value, fromIndex) { 33548 var length = array == null ? 0 : array.length; 33549 if (!length) { 33550 return -1; 33551 } 33552 var index = length; 33553 if (fromIndex !== undefined) { 33554 index = toInteger(fromIndex); 33555 index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); 33556 } 33557 return value === value 33558 ? strictLastIndexOf(array, value, index) 33559 : baseFindIndex(array, baseIsNaN, index, true); 33560 } 33561 33562 /** 33563 * Gets the element at index `n` of `array`. If `n` is negative, the nth 33564 * element from the end is returned. 33565 * 33566 * @static 33567 * @memberOf _ 33568 * @since 4.11.0 33569 * @category Array 33570 * @param {Array} array The array to query. 33571 * @param {number} [n=0] The index of the element to return. 33572 * @returns {*} Returns the nth element of `array`. 33573 * @example 33574 * 33575 * var array = ['a', 'b', 'c', 'd']; 33576 * 33577 * _.nth(array, 1); 33578 * // => 'b' 33579 * 33580 * _.nth(array, -2); 33581 * // => 'c'; 33582 */ 33583 function nth(array, n) { 33584 return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; 33585 } 33586 33587 /** 33588 * Removes all given values from `array` using 33589 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) 33590 * for equality comparisons. 33591 * 33592 * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` 33593 * to remove elements from an array by predicate. 33594 * 33595 * @static 33596 * @memberOf _ 33597 * @since 2.0.0 33598 * @category Array 33599 * @param {Array} array The array to modify. 33600 * @param {...*} [values] The values to remove. 33601 * @returns {Array} Returns `array`. 33602 * @example 33603 * 33604 * var array = ['a', 'b', 'c', 'a', 'b', 'c']; 33605 * 33606 * _.pull(array, 'a', 'c'); 33607 * console.log(array); 33608 * // => ['b', 'b'] 33609 */ 33610 var pull = baseRest(pullAll); 33611 33612 /** 33613 * This method is like `_.pull` except that it accepts an array of values to remove. 33614 * 33615 * **Note:** Unlike `_.difference`, this method mutates `array`. 33616 * 33617 * @static 33618 * @memberOf _ 33619 * @since 4.0.0 33620 * @category Array 33621 * @param {Array} array The array to modify. 33622 * @param {Array} values The values to remove. 33623 * @returns {Array} Returns `array`. 33624 * @example 33625 * 33626 * var array = ['a', 'b', 'c', 'a', 'b', 'c']; 33627 * 33628 * _.pullAll(array, ['a', 'c']); 33629 * console.log(array); 33630 * // => ['b', 'b'] 33631 */ 33632 function pullAll(array, values) { 33633 return (array && array.length && values && values.length) 33634 ? basePullAll(array, values) 33635 : array; 33636 } 33637 33638 /** 33639 * This method is like `_.pullAll` except that it accepts `iteratee` which is 33640 * invoked for each element of `array` and `values` to generate the criterion 33641 * by which they're compared. The iteratee is invoked with one argument: (value). 33642 * 33643 * **Note:** Unlike `_.differenceBy`, this method mutates `array`. 33644 * 33645 * @static 33646 * @memberOf _ 33647 * @since 4.0.0 33648 * @category Array 33649 * @param {Array} array The array to modify. 33650 * @param {Array} values The values to remove. 33651 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 33652 * @returns {Array} Returns `array`. 33653 * @example 33654 * 33655 * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; 33656 * 33657 * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); 33658 * console.log(array); 33659 * // => [{ 'x': 2 }] 33660 */ 33661 function pullAllBy(array, values, iteratee) { 33662 return (array && array.length && values && values.length) 33663 ? basePullAll(array, values, getIteratee(iteratee, 2)) 33664 : array; 33665 } 33666 33667 /** 33668 * This method is like `_.pullAll` except that it accepts `comparator` which 33669 * is invoked to compare elements of `array` to `values`. The comparator is 33670 * invoked with two arguments: (arrVal, othVal). 33671 * 33672 * **Note:** Unlike `_.differenceWith`, this method mutates `array`. 33673 * 33674 * @static 33675 * @memberOf _ 33676 * @since 4.6.0 33677 * @category Array 33678 * @param {Array} array The array to modify. 33679 * @param {Array} values The values to remove. 33680 * @param {Function} [comparator] The comparator invoked per element. 33681 * @returns {Array} Returns `array`. 33682 * @example 33683 * 33684 * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; 33685 * 33686 * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); 33687 * console.log(array); 33688 * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] 33689 */ 33690 function pullAllWith(array, values, comparator) { 33691 return (array && array.length && values && values.length) 33692 ? basePullAll(array, values, undefined, comparator) 33693 : array; 33694 } 33695 33696 /** 33697 * Removes elements from `array` corresponding to `indexes` and returns an 33698 * array of removed elements. 33699 * 33700 * **Note:** Unlike `_.at`, this method mutates `array`. 33701 * 33702 * @static 33703 * @memberOf _ 33704 * @since 3.0.0 33705 * @category Array 33706 * @param {Array} array The array to modify. 33707 * @param {...(number|number[])} [indexes] The indexes of elements to remove. 33708 * @returns {Array} Returns the new array of removed elements. 33709 * @example 33710 * 33711 * var array = ['a', 'b', 'c', 'd']; 33712 * var pulled = _.pullAt(array, [1, 3]); 33713 * 33714 * console.log(array); 33715 * // => ['a', 'c'] 33716 * 33717 * console.log(pulled); 33718 * // => ['b', 'd'] 33719 */ 33720 var pullAt = flatRest(function(array, indexes) { 33721 var length = array == null ? 0 : array.length, 33722 result = baseAt(array, indexes); 33723 33724 basePullAt(array, arrayMap(indexes, function(index) { 33725 return isIndex(index, length) ? +index : index; 33726 }).sort(compareAscending)); 33727 33728 return result; 33729 }); 33730 33731 /** 33732 * Removes all elements from `array` that `predicate` returns truthy for 33733 * and returns an array of the removed elements. The predicate is invoked 33734 * with three arguments: (value, index, array). 33735 * 33736 * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` 33737 * to pull elements from an array by value. 33738 * 33739 * @static 33740 * @memberOf _ 33741 * @since 2.0.0 33742 * @category Array 33743 * @param {Array} array The array to modify. 33744 * @param {Function} [predicate=_.identity] The function invoked per iteration. 33745 * @returns {Array} Returns the new array of removed elements. 33746 * @example 33747 * 33748 * var array = [1, 2, 3, 4]; 33749 * var evens = _.remove(array, function(n) { 33750 * return n % 2 == 0; 33751 * }); 33752 * 33753 * console.log(array); 33754 * // => [1, 3] 33755 * 33756 * console.log(evens); 33757 * // => [2, 4] 33758 */ 33759 function remove(array, predicate) { 33760 var result = []; 33761 if (!(array && array.length)) { 33762 return result; 33763 } 33764 var index = -1, 33765 indexes = [], 33766 length = array.length; 33767 33768 predicate = getIteratee(predicate, 3); 33769 while (++index < length) { 33770 var value = array[index]; 33771 if (predicate(value, index, array)) { 33772 result.push(value); 33773 indexes.push(index); 33774 } 33775 } 33776 basePullAt(array, indexes); 33777 return result; 33778 } 33779 33780 /** 33781 * Reverses `array` so that the first element becomes the last, the second 33782 * element becomes the second to last, and so on. 33783 * 33784 * **Note:** This method mutates `array` and is based on 33785 * [`Array#reverse`](https://mdn.io/Array/reverse). 33786 * 33787 * @static 33788 * @memberOf _ 33789 * @since 4.0.0 33790 * @category Array 33791 * @param {Array} array The array to modify. 33792 * @returns {Array} Returns `array`. 33793 * @example 33794 * 33795 * var array = [1, 2, 3]; 33796 * 33797 * _.reverse(array); 33798 * // => [3, 2, 1] 33799 * 33800 * console.log(array); 33801 * // => [3, 2, 1] 33802 */ 33803 function reverse(array) { 33804 return array == null ? array : nativeReverse.call(array); 33805 } 33806 33807 /** 33808 * Creates a slice of `array` from `start` up to, but not including, `end`. 33809 * 33810 * **Note:** This method is used instead of 33811 * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are 33812 * returned. 33813 * 33814 * @static 33815 * @memberOf _ 33816 * @since 3.0.0 33817 * @category Array 33818 * @param {Array} array The array to slice. 33819 * @param {number} [start=0] The start position. 33820 * @param {number} [end=array.length] The end position. 33821 * @returns {Array} Returns the slice of `array`. 33822 */ 33823 function slice(array, start, end) { 33824 var length = array == null ? 0 : array.length; 33825 if (!length) { 33826 return []; 33827 } 33828 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { 33829 start = 0; 33830 end = length; 33831 } 33832 else { 33833 start = start == null ? 0 : toInteger(start); 33834 end = end === undefined ? length : toInteger(end); 33835 } 33836 return baseSlice(array, start, end); 33837 } 33838 33839 /** 33840 * Uses a binary search to determine the lowest index at which `value` 33841 * should be inserted into `array` in order to maintain its sort order. 33842 * 33843 * @static 33844 * @memberOf _ 33845 * @since 0.1.0 33846 * @category Array 33847 * @param {Array} array The sorted array to inspect. 33848 * @param {*} value The value to evaluate. 33849 * @returns {number} Returns the index at which `value` should be inserted 33850 * into `array`. 33851 * @example 33852 * 33853 * _.sortedIndex([30, 50], 40); 33854 * // => 1 33855 */ 33856 function sortedIndex(array, value) { 33857 return baseSortedIndex(array, value); 33858 } 33859 33860 /** 33861 * This method is like `_.sortedIndex` except that it accepts `iteratee` 33862 * which is invoked for `value` and each element of `array` to compute their 33863 * sort ranking. The iteratee is invoked with one argument: (value). 33864 * 33865 * @static 33866 * @memberOf _ 33867 * @since 4.0.0 33868 * @category Array 33869 * @param {Array} array The sorted array to inspect. 33870 * @param {*} value The value to evaluate. 33871 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 33872 * @returns {number} Returns the index at which `value` should be inserted 33873 * into `array`. 33874 * @example 33875 * 33876 * var objects = [{ 'x': 4 }, { 'x': 5 }]; 33877 * 33878 * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); 33879 * // => 0 33880 * 33881 * // The `_.property` iteratee shorthand. 33882 * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); 33883 * // => 0 33884 */ 33885 function sortedIndexBy(array, value, iteratee) { 33886 return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); 33887 } 33888 33889 /** 33890 * This method is like `_.indexOf` except that it performs a binary 33891 * search on a sorted `array`. 33892 * 33893 * @static 33894 * @memberOf _ 33895 * @since 4.0.0 33896 * @category Array 33897 * @param {Array} array The array to inspect. 33898 * @param {*} value The value to search for. 33899 * @returns {number} Returns the index of the matched value, else `-1`. 33900 * @example 33901 * 33902 * _.sortedIndexOf([4, 5, 5, 5, 6], 5); 33903 * // => 1 33904 */ 33905 function sortedIndexOf(array, value) { 33906 var length = array == null ? 0 : array.length; 33907 if (length) { 33908 var index = baseSortedIndex(array, value); 33909 if (index < length && eq(array[index], value)) { 33910 return index; 33911 } 33912 } 33913 return -1; 33914 } 33915 33916 /** 33917 * This method is like `_.sortedIndex` except that it returns the highest 33918 * index at which `value` should be inserted into `array` in order to 33919 * maintain its sort order. 33920 * 33921 * @static 33922 * @memberOf _ 33923 * @since 3.0.0 33924 * @category Array 33925 * @param {Array} array The sorted array to inspect. 33926 * @param {*} value The value to evaluate. 33927 * @returns {number} Returns the index at which `value` should be inserted 33928 * into `array`. 33929 * @example 33930 * 33931 * _.sortedLastIndex([4, 5, 5, 5, 6], 5); 33932 * // => 4 33933 */ 33934 function sortedLastIndex(array, value) { 33935 return baseSortedIndex(array, value, true); 33936 } 33937 33938 /** 33939 * This method is like `_.sortedLastIndex` except that it accepts `iteratee` 33940 * which is invoked for `value` and each element of `array` to compute their 33941 * sort ranking. The iteratee is invoked with one argument: (value). 33942 * 33943 * @static 33944 * @memberOf _ 33945 * @since 4.0.0 33946 * @category Array 33947 * @param {Array} array The sorted array to inspect. 33948 * @param {*} value The value to evaluate. 33949 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 33950 * @returns {number} Returns the index at which `value` should be inserted 33951 * into `array`. 33952 * @example 33953 * 33954 * var objects = [{ 'x': 4 }, { 'x': 5 }]; 33955 * 33956 * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); 33957 * // => 1 33958 * 33959 * // The `_.property` iteratee shorthand. 33960 * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); 33961 * // => 1 33962 */ 33963 function sortedLastIndexBy(array, value, iteratee) { 33964 return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); 33965 } 33966 33967 /** 33968 * This method is like `_.lastIndexOf` except that it performs a binary 33969 * search on a sorted `array`. 33970 * 33971 * @static 33972 * @memberOf _ 33973 * @since 4.0.0 33974 * @category Array 33975 * @param {Array} array The array to inspect. 33976 * @param {*} value The value to search for. 33977 * @returns {number} Returns the index of the matched value, else `-1`. 33978 * @example 33979 * 33980 * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); 33981 * // => 3 33982 */ 33983 function sortedLastIndexOf(array, value) { 33984 var length = array == null ? 0 : array.length; 33985 if (length) { 33986 var index = baseSortedIndex(array, value, true) - 1; 33987 if (eq(array[index], value)) { 33988 return index; 33989 } 33990 } 33991 return -1; 33992 } 33993 33994 /** 33995 * This method is like `_.uniq` except that it's designed and optimized 33996 * for sorted arrays. 33997 * 33998 * @static 33999 * @memberOf _ 34000 * @since 4.0.0 34001 * @category Array 34002 * @param {Array} array The array to inspect. 34003 * @returns {Array} Returns the new duplicate free array. 34004 * @example 34005 * 34006 * _.sortedUniq([1, 1, 2]); 34007 * // => [1, 2] 34008 */ 34009 function sortedUniq(array) { 34010 return (array && array.length) 34011 ? baseSortedUniq(array) 34012 : []; 34013 } 34014 34015 /** 34016 * This method is like `_.uniqBy` except that it's designed and optimized 34017 * for sorted arrays. 34018 * 34019 * @static 34020 * @memberOf _ 34021 * @since 4.0.0 34022 * @category Array 34023 * @param {Array} array The array to inspect. 34024 * @param {Function} [iteratee] The iteratee invoked per element. 34025 * @returns {Array} Returns the new duplicate free array. 34026 * @example 34027 * 34028 * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); 34029 * // => [1.1, 2.3] 34030 */ 34031 function sortedUniqBy(array, iteratee) { 34032 return (array && array.length) 34033 ? baseSortedUniq(array, getIteratee(iteratee, 2)) 34034 : []; 34035 } 34036 34037 /** 34038 * Gets all but the first element of `array`. 34039 * 34040 * @static 34041 * @memberOf _ 34042 * @since 4.0.0 34043 * @category Array 34044 * @param {Array} array The array to query. 34045 * @returns {Array} Returns the slice of `array`. 34046 * @example 34047 * 34048 * _.tail([1, 2, 3]); 34049 * // => [2, 3] 34050 */ 34051 function tail(array) { 34052 var length = array == null ? 0 : array.length; 34053 return length ? baseSlice(array, 1, length) : []; 34054 } 34055 34056 /** 34057 * Creates a slice of `array` with `n` elements taken from the beginning. 34058 * 34059 * @static 34060 * @memberOf _ 34061 * @since 0.1.0 34062 * @category Array 34063 * @param {Array} array The array to query. 34064 * @param {number} [n=1] The number of elements to take. 34065 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 34066 * @returns {Array} Returns the slice of `array`. 34067 * @example 34068 * 34069 * _.take([1, 2, 3]); 34070 * // => [1] 34071 * 34072 * _.take([1, 2, 3], 2); 34073 * // => [1, 2] 34074 * 34075 * _.take([1, 2, 3], 5); 34076 * // => [1, 2, 3] 34077 * 34078 * _.take([1, 2, 3], 0); 34079 * // => [] 34080 */ 34081 function take(array, n, guard) { 34082 if (!(array && array.length)) { 34083 return []; 34084 } 34085 n = (guard || n === undefined) ? 1 : toInteger(n); 34086 return baseSlice(array, 0, n < 0 ? 0 : n); 34087 } 34088 34089 /** 34090 * Creates a slice of `array` with `n` elements taken from the end. 34091 * 34092 * @static 34093 * @memberOf _ 34094 * @since 3.0.0 34095 * @category Array 34096 * @param {Array} array The array to query. 34097 * @param {number} [n=1] The number of elements to take. 34098 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 34099 * @returns {Array} Returns the slice of `array`. 34100 * @example 34101 * 34102 * _.takeRight([1, 2, 3]); 34103 * // => [3] 34104 * 34105 * _.takeRight([1, 2, 3], 2); 34106 * // => [2, 3] 34107 * 34108 * _.takeRight([1, 2, 3], 5); 34109 * // => [1, 2, 3] 34110 * 34111 * _.takeRight([1, 2, 3], 0); 34112 * // => [] 34113 */ 34114 function takeRight(array, n, guard) { 34115 var length = array == null ? 0 : array.length; 34116 if (!length) { 34117 return []; 34118 } 34119 n = (guard || n === undefined) ? 1 : toInteger(n); 34120 n = length - n; 34121 return baseSlice(array, n < 0 ? 0 : n, length); 34122 } 34123 34124 /** 34125 * Creates a slice of `array` with elements taken from the end. Elements are 34126 * taken until `predicate` returns falsey. The predicate is invoked with 34127 * three arguments: (value, index, array). 34128 * 34129 * @static 34130 * @memberOf _ 34131 * @since 3.0.0 34132 * @category Array 34133 * @param {Array} array The array to query. 34134 * @param {Function} [predicate=_.identity] The function invoked per iteration. 34135 * @returns {Array} Returns the slice of `array`. 34136 * @example 34137 * 34138 * var users = [ 34139 * { 'user': 'barney', 'active': true }, 34140 * { 'user': 'fred', 'active': false }, 34141 * { 'user': 'pebbles', 'active': false } 34142 * ]; 34143 * 34144 * _.takeRightWhile(users, function(o) { return !o.active; }); 34145 * // => objects for ['fred', 'pebbles'] 34146 * 34147 * // The `_.matches` iteratee shorthand. 34148 * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); 34149 * // => objects for ['pebbles'] 34150 * 34151 * // The `_.matchesProperty` iteratee shorthand. 34152 * _.takeRightWhile(users, ['active', false]); 34153 * // => objects for ['fred', 'pebbles'] 34154 * 34155 * // The `_.property` iteratee shorthand. 34156 * _.takeRightWhile(users, 'active'); 34157 * // => [] 34158 */ 34159 function takeRightWhile(array, predicate) { 34160 return (array && array.length) 34161 ? baseWhile(array, getIteratee(predicate, 3), false, true) 34162 : []; 34163 } 34164 34165 /** 34166 * Creates a slice of `array` with elements taken from the beginning. Elements 34167 * are taken until `predicate` returns falsey. The predicate is invoked with 34168 * three arguments: (value, index, array). 34169 * 34170 * @static 34171 * @memberOf _ 34172 * @since 3.0.0 34173 * @category Array 34174 * @param {Array} array The array to query. 34175 * @param {Function} [predicate=_.identity] The function invoked per iteration. 34176 * @returns {Array} Returns the slice of `array`. 34177 * @example 34178 * 34179 * var users = [ 34180 * { 'user': 'barney', 'active': false }, 34181 * { 'user': 'fred', 'active': false }, 34182 * { 'user': 'pebbles', 'active': true } 34183 * ]; 34184 * 34185 * _.takeWhile(users, function(o) { return !o.active; }); 34186 * // => objects for ['barney', 'fred'] 34187 * 34188 * // The `_.matches` iteratee shorthand. 34189 * _.takeWhile(users, { 'user': 'barney', 'active': false }); 34190 * // => objects for ['barney'] 34191 * 34192 * // The `_.matchesProperty` iteratee shorthand. 34193 * _.takeWhile(users, ['active', false]); 34194 * // => objects for ['barney', 'fred'] 34195 * 34196 * // The `_.property` iteratee shorthand. 34197 * _.takeWhile(users, 'active'); 34198 * // => [] 34199 */ 34200 function takeWhile(array, predicate) { 34201 return (array && array.length) 34202 ? baseWhile(array, getIteratee(predicate, 3)) 34203 : []; 34204 } 34205 34206 /** 34207 * Creates an array of unique values, in order, from all given arrays using 34208 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) 34209 * for equality comparisons. 34210 * 34211 * @static 34212 * @memberOf _ 34213 * @since 0.1.0 34214 * @category Array 34215 * @param {...Array} [arrays] The arrays to inspect. 34216 * @returns {Array} Returns the new array of combined values. 34217 * @example 34218 * 34219 * _.union([2], [1, 2]); 34220 * // => [2, 1] 34221 */ 34222 var union = baseRest(function(arrays) { 34223 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); 34224 }); 34225 34226 /** 34227 * This method is like `_.union` except that it accepts `iteratee` which is 34228 * invoked for each element of each `arrays` to generate the criterion by 34229 * which uniqueness is computed. Result values are chosen from the first 34230 * array in which the value occurs. The iteratee is invoked with one argument: 34231 * (value). 34232 * 34233 * @static 34234 * @memberOf _ 34235 * @since 4.0.0 34236 * @category Array 34237 * @param {...Array} [arrays] The arrays to inspect. 34238 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 34239 * @returns {Array} Returns the new array of combined values. 34240 * @example 34241 * 34242 * _.unionBy([2.1], [1.2, 2.3], Math.floor); 34243 * // => [2.1, 1.2] 34244 * 34245 * // The `_.property` iteratee shorthand. 34246 * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); 34247 * // => [{ 'x': 1 }, { 'x': 2 }] 34248 */ 34249 var unionBy = baseRest(function(arrays) { 34250 var iteratee = last(arrays); 34251 if (isArrayLikeObject(iteratee)) { 34252 iteratee = undefined; 34253 } 34254 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); 34255 }); 34256 34257 /** 34258 * This method is like `_.union` except that it accepts `comparator` which 34259 * is invoked to compare elements of `arrays`. Result values are chosen from 34260 * the first array in which the value occurs. The comparator is invoked 34261 * with two arguments: (arrVal, othVal). 34262 * 34263 * @static 34264 * @memberOf _ 34265 * @since 4.0.0 34266 * @category Array 34267 * @param {...Array} [arrays] The arrays to inspect. 34268 * @param {Function} [comparator] The comparator invoked per element. 34269 * @returns {Array} Returns the new array of combined values. 34270 * @example 34271 * 34272 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; 34273 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; 34274 * 34275 * _.unionWith(objects, others, _.isEqual); 34276 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] 34277 */ 34278 var unionWith = baseRest(function(arrays) { 34279 var comparator = last(arrays); 34280 comparator = typeof comparator == 'function' ? comparator : undefined; 34281 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); 34282 }); 34283 34284 /** 34285 * Creates a duplicate-free version of an array, using 34286 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) 34287 * for equality comparisons, in which only the first occurrence of each element 34288 * is kept. The order of result values is determined by the order they occur 34289 * in the array. 34290 * 34291 * @static 34292 * @memberOf _ 34293 * @since 0.1.0 34294 * @category Array 34295 * @param {Array} array The array to inspect. 34296 * @returns {Array} Returns the new duplicate free array. 34297 * @example 34298 * 34299 * _.uniq([2, 1, 2]); 34300 * // => [2, 1] 34301 */ 34302 function uniq(array) { 34303 return (array && array.length) ? baseUniq(array) : []; 34304 } 34305 34306 /** 34307 * This method is like `_.uniq` except that it accepts `iteratee` which is 34308 * invoked for each element in `array` to generate the criterion by which 34309 * uniqueness is computed. The order of result values is determined by the 34310 * order they occur in the array. The iteratee is invoked with one argument: 34311 * (value). 34312 * 34313 * @static 34314 * @memberOf _ 34315 * @since 4.0.0 34316 * @category Array 34317 * @param {Array} array The array to inspect. 34318 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 34319 * @returns {Array} Returns the new duplicate free array. 34320 * @example 34321 * 34322 * _.uniqBy([2.1, 1.2, 2.3], Math.floor); 34323 * // => [2.1, 1.2] 34324 * 34325 * // The `_.property` iteratee shorthand. 34326 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); 34327 * // => [{ 'x': 1 }, { 'x': 2 }] 34328 */ 34329 function uniqBy(array, iteratee) { 34330 return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; 34331 } 34332 34333 /** 34334 * This method is like `_.uniq` except that it accepts `comparator` which 34335 * is invoked to compare elements of `array`. The order of result values is 34336 * determined by the order they occur in the array.The comparator is invoked 34337 * with two arguments: (arrVal, othVal). 34338 * 34339 * @static 34340 * @memberOf _ 34341 * @since 4.0.0 34342 * @category Array 34343 * @param {Array} array The array to inspect. 34344 * @param {Function} [comparator] The comparator invoked per element. 34345 * @returns {Array} Returns the new duplicate free array. 34346 * @example 34347 * 34348 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; 34349 * 34350 * _.uniqWith(objects, _.isEqual); 34351 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] 34352 */ 34353 function uniqWith(array, comparator) { 34354 comparator = typeof comparator == 'function' ? comparator : undefined; 34355 return (array && array.length) ? baseUniq(array, undefined, comparator) : []; 34356 } 34357 34358 /** 34359 * This method is like `_.zip` except that it accepts an array of grouped 34360 * elements and creates an array regrouping the elements to their pre-zip 34361 * configuration. 34362 * 34363 * @static 34364 * @memberOf _ 34365 * @since 1.2.0 34366 * @category Array 34367 * @param {Array} array The array of grouped elements to process. 34368 * @returns {Array} Returns the new array of regrouped elements. 34369 * @example 34370 * 34371 * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); 34372 * // => [['a', 1, true], ['b', 2, false]] 34373 * 34374 * _.unzip(zipped); 34375 * // => [['a', 'b'], [1, 2], [true, false]] 34376 */ 34377 function unzip(array) { 34378 if (!(array && array.length)) { 34379 return []; 34380 } 34381 var length = 0; 34382 array = arrayFilter(array, function(group) { 34383 if (isArrayLikeObject(group)) { 34384 length = nativeMax(group.length, length); 34385 return true; 34386 } 34387 }); 34388 return baseTimes(length, function(index) { 34389 return arrayMap(array, baseProperty(index)); 34390 }); 34391 } 34392 34393 /** 34394 * This method is like `_.unzip` except that it accepts `iteratee` to specify 34395 * how regrouped values should be combined. The iteratee is invoked with the 34396 * elements of each group: (...group). 34397 * 34398 * @static 34399 * @memberOf _ 34400 * @since 3.8.0 34401 * @category Array 34402 * @param {Array} array The array of grouped elements to process. 34403 * @param {Function} [iteratee=_.identity] The function to combine 34404 * regrouped values. 34405 * @returns {Array} Returns the new array of regrouped elements. 34406 * @example 34407 * 34408 * var zipped = _.zip([1, 2], [10, 20], [100, 200]); 34409 * // => [[1, 10, 100], [2, 20, 200]] 34410 * 34411 * _.unzipWith(zipped, _.add); 34412 * // => [3, 30, 300] 34413 */ 34414 function unzipWith(array, iteratee) { 34415 if (!(array && array.length)) { 34416 return []; 34417 } 34418 var result = unzip(array); 34419 if (iteratee == null) { 34420 return result; 34421 } 34422 return arrayMap(result, function(group) { 34423 return apply(iteratee, undefined, group); 34424 }); 34425 } 34426 34427 /** 34428 * Creates an array excluding all given values using 34429 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) 34430 * for equality comparisons. 34431 * 34432 * **Note:** Unlike `_.pull`, this method returns a new array. 34433 * 34434 * @static 34435 * @memberOf _ 34436 * @since 0.1.0 34437 * @category Array 34438 * @param {Array} array The array to inspect. 34439 * @param {...*} [values] The values to exclude. 34440 * @returns {Array} Returns the new array of filtered values. 34441 * @see _.difference, _.xor 34442 * @example 34443 * 34444 * _.without([2, 1, 2, 3], 1, 2); 34445 * // => [3] 34446 */ 34447 var without = baseRest(function(array, values) { 34448 return isArrayLikeObject(array) 34449 ? baseDifference(array, values) 34450 : []; 34451 }); 34452 34453 /** 34454 * Creates an array of unique values that is the 34455 * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) 34456 * of the given arrays. The order of result values is determined by the order 34457 * they occur in the arrays. 34458 * 34459 * @static 34460 * @memberOf _ 34461 * @since 2.4.0 34462 * @category Array 34463 * @param {...Array} [arrays] The arrays to inspect. 34464 * @returns {Array} Returns the new array of filtered values. 34465 * @see _.difference, _.without 34466 * @example 34467 * 34468 * _.xor([2, 1], [2, 3]); 34469 * // => [1, 3] 34470 */ 34471 var xor = baseRest(function(arrays) { 34472 return baseXor(arrayFilter(arrays, isArrayLikeObject)); 34473 }); 34474 34475 /** 34476 * This method is like `_.xor` except that it accepts `iteratee` which is 34477 * invoked for each element of each `arrays` to generate the criterion by 34478 * which by which they're compared. The order of result values is determined 34479 * by the order they occur in the arrays. The iteratee is invoked with one 34480 * argument: (value). 34481 * 34482 * @static 34483 * @memberOf _ 34484 * @since 4.0.0 34485 * @category Array 34486 * @param {...Array} [arrays] The arrays to inspect. 34487 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 34488 * @returns {Array} Returns the new array of filtered values. 34489 * @example 34490 * 34491 * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); 34492 * // => [1.2, 3.4] 34493 * 34494 * // The `_.property` iteratee shorthand. 34495 * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); 34496 * // => [{ 'x': 2 }] 34497 */ 34498 var xorBy = baseRest(function(arrays) { 34499 var iteratee = last(arrays); 34500 if (isArrayLikeObject(iteratee)) { 34501 iteratee = undefined; 34502 } 34503 return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); 34504 }); 34505 34506 /** 34507 * This method is like `_.xor` except that it accepts `comparator` which is 34508 * invoked to compare elements of `arrays`. The order of result values is 34509 * determined by the order they occur in the arrays. The comparator is invoked 34510 * with two arguments: (arrVal, othVal). 34511 * 34512 * @static 34513 * @memberOf _ 34514 * @since 4.0.0 34515 * @category Array 34516 * @param {...Array} [arrays] The arrays to inspect. 34517 * @param {Function} [comparator] The comparator invoked per element. 34518 * @returns {Array} Returns the new array of filtered values. 34519 * @example 34520 * 34521 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; 34522 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; 34523 * 34524 * _.xorWith(objects, others, _.isEqual); 34525 * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] 34526 */ 34527 var xorWith = baseRest(function(arrays) { 34528 var comparator = last(arrays); 34529 comparator = typeof comparator == 'function' ? comparator : undefined; 34530 return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); 34531 }); 34532 34533 /** 34534 * Creates an array of grouped elements, the first of which contains the 34535 * first elements of the given arrays, the second of which contains the 34536 * second elements of the given arrays, and so on. 34537 * 34538 * @static 34539 * @memberOf _ 34540 * @since 0.1.0 34541 * @category Array 34542 * @param {...Array} [arrays] The arrays to process. 34543 * @returns {Array} Returns the new array of grouped elements. 34544 * @example 34545 * 34546 * _.zip(['a', 'b'], [1, 2], [true, false]); 34547 * // => [['a', 1, true], ['b', 2, false]] 34548 */ 34549 var zip = baseRest(unzip); 34550 34551 /** 34552 * This method is like `_.fromPairs` except that it accepts two arrays, 34553 * one of property identifiers and one of corresponding values. 34554 * 34555 * @static 34556 * @memberOf _ 34557 * @since 0.4.0 34558 * @category Array 34559 * @param {Array} [props=[]] The property identifiers. 34560 * @param {Array} [values=[]] The property values. 34561 * @returns {Object} Returns the new object. 34562 * @example 34563 * 34564 * _.zipObject(['a', 'b'], [1, 2]); 34565 * // => { 'a': 1, 'b': 2 } 34566 */ 34567 function zipObject(props, values) { 34568 return baseZipObject(props || [], values || [], assignValue); 34569 } 34570 34571 /** 34572 * This method is like `_.zipObject` except that it supports property paths. 34573 * 34574 * @static 34575 * @memberOf _ 34576 * @since 4.1.0 34577 * @category Array 34578 * @param {Array} [props=[]] The property identifiers. 34579 * @param {Array} [values=[]] The property values. 34580 * @returns {Object} Returns the new object. 34581 * @example 34582 * 34583 * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); 34584 * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } 34585 */ 34586 function zipObjectDeep(props, values) { 34587 return baseZipObject(props || [], values || [], baseSet); 34588 } 34589 34590 /** 34591 * This method is like `_.zip` except that it accepts `iteratee` to specify 34592 * how grouped values should be combined. The iteratee is invoked with the 34593 * elements of each group: (...group). 34594 * 34595 * @static 34596 * @memberOf _ 34597 * @since 3.8.0 34598 * @category Array 34599 * @param {...Array} [arrays] The arrays to process. 34600 * @param {Function} [iteratee=_.identity] The function to combine 34601 * grouped values. 34602 * @returns {Array} Returns the new array of grouped elements. 34603 * @example 34604 * 34605 * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { 34606 * return a + b + c; 34607 * }); 34608 * // => [111, 222] 34609 */ 34610 var zipWith = baseRest(function(arrays) { 34611 var length = arrays.length, 34612 iteratee = length > 1 ? arrays[length - 1] : undefined; 34613 34614 iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; 34615 return unzipWith(arrays, iteratee); 34616 }); 34617 34618 /*------------------------------------------------------------------------*/ 34619 34620 /** 34621 * Creates a `lodash` wrapper instance that wraps `value` with explicit method 34622 * chain sequences enabled. The result of such sequences must be unwrapped 34623 * with `_#value`. 34624 * 34625 * @static 34626 * @memberOf _ 34627 * @since 1.3.0 34628 * @category Seq 34629 * @param {*} value The value to wrap. 34630 * @returns {Object} Returns the new `lodash` wrapper instance. 34631 * @example 34632 * 34633 * var users = [ 34634 * { 'user': 'barney', 'age': 36 }, 34635 * { 'user': 'fred', 'age': 40 }, 34636 * { 'user': 'pebbles', 'age': 1 } 34637 * ]; 34638 * 34639 * var youngest = _ 34640 * .chain(users) 34641 * .sortBy('age') 34642 * .map(function(o) { 34643 * return o.user + ' is ' + o.age; 34644 * }) 34645 * .head() 34646 * .value(); 34647 * // => 'pebbles is 1' 34648 */ 34649 function chain(value) { 34650 var result = lodash(value); 34651 result.__chain__ = true; 34652 return result; 34653 } 34654 34655 /** 34656 * This method invokes `interceptor` and returns `value`. The interceptor 34657 * is invoked with one argument; (value). The purpose of this method is to 34658 * "tap into" a method chain sequence in order to modify intermediate results. 34659 * 34660 * @static 34661 * @memberOf _ 34662 * @since 0.1.0 34663 * @category Seq 34664 * @param {*} value The value to provide to `interceptor`. 34665 * @param {Function} interceptor The function to invoke. 34666 * @returns {*} Returns `value`. 34667 * @example 34668 * 34669 * _([1, 2, 3]) 34670 * .tap(function(array) { 34671 * // Mutate input array. 34672 * array.pop(); 34673 * }) 34674 * .reverse() 34675 * .value(); 34676 * // => [2, 1] 34677 */ 34678 function tap(value, interceptor) { 34679 interceptor(value); 34680 return value; 34681 } 34682 34683 /** 34684 * This method is like `_.tap` except that it returns the result of `interceptor`. 34685 * The purpose of this method is to "pass thru" values replacing intermediate 34686 * results in a method chain sequence. 34687 * 34688 * @static 34689 * @memberOf _ 34690 * @since 3.0.0 34691 * @category Seq 34692 * @param {*} value The value to provide to `interceptor`. 34693 * @param {Function} interceptor The function to invoke. 34694 * @returns {*} Returns the result of `interceptor`. 34695 * @example 34696 * 34697 * _(' abc ') 34698 * .chain() 34699 * .trim() 34700 * .thru(function(value) { 34701 * return [value]; 34702 * }) 34703 * .value(); 34704 * // => ['abc'] 34705 */ 34706 function thru(value, interceptor) { 34707 return interceptor(value); 34708 } 34709 34710 /** 34711 * This method is the wrapper version of `_.at`. 34712 * 34713 * @name at 34714 * @memberOf _ 34715 * @since 1.0.0 34716 * @category Seq 34717 * @param {...(string|string[])} [paths] The property paths to pick. 34718 * @returns {Object} Returns the new `lodash` wrapper instance. 34719 * @example 34720 * 34721 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; 34722 * 34723 * _(object).at(['a[0].b.c', 'a[1]']).value(); 34724 * // => [3, 4] 34725 */ 34726 var wrapperAt = flatRest(function(paths) { 34727 var length = paths.length, 34728 start = length ? paths[0] : 0, 34729 value = this.__wrapped__, 34730 interceptor = function(object) { return baseAt(object, paths); }; 34731 34732 if (length > 1 || this.__actions__.length || 34733 !(value instanceof LazyWrapper) || !isIndex(start)) { 34734 return this.thru(interceptor); 34735 } 34736 value = value.slice(start, +start + (length ? 1 : 0)); 34737 value.__actions__.push({ 34738 'func': thru, 34739 'args': [interceptor], 34740 'thisArg': undefined 34741 }); 34742 return new LodashWrapper(value, this.__chain__).thru(function(array) { 34743 if (length && !array.length) { 34744 array.push(undefined); 34745 } 34746 return array; 34747 }); 34748 }); 34749 34750 /** 34751 * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. 34752 * 34753 * @name chain 34754 * @memberOf _ 34755 * @since 0.1.0 34756 * @category Seq 34757 * @returns {Object} Returns the new `lodash` wrapper instance. 34758 * @example 34759 * 34760 * var users = [ 34761 * { 'user': 'barney', 'age': 36 }, 34762 * { 'user': 'fred', 'age': 40 } 34763 * ]; 34764 * 34765 * // A sequence without explicit chaining. 34766 * _(users).head(); 34767 * // => { 'user': 'barney', 'age': 36 } 34768 * 34769 * // A sequence with explicit chaining. 34770 * _(users) 34771 * .chain() 34772 * .head() 34773 * .pick('user') 34774 * .value(); 34775 * // => { 'user': 'barney' } 34776 */ 34777 function wrapperChain() { 34778 return chain(this); 34779 } 34780 34781 /** 34782 * Executes the chain sequence and returns the wrapped result. 34783 * 34784 * @name commit 34785 * @memberOf _ 34786 * @since 3.2.0 34787 * @category Seq 34788 * @returns {Object} Returns the new `lodash` wrapper instance. 34789 * @example 34790 * 34791 * var array = [1, 2]; 34792 * var wrapped = _(array).push(3); 34793 * 34794 * console.log(array); 34795 * // => [1, 2] 34796 * 34797 * wrapped = wrapped.commit(); 34798 * console.log(array); 34799 * // => [1, 2, 3] 34800 * 34801 * wrapped.last(); 34802 * // => 3 34803 * 34804 * console.log(array); 34805 * // => [1, 2, 3] 34806 */ 34807 function wrapperCommit() { 34808 return new LodashWrapper(this.value(), this.__chain__); 34809 } 34810 34811 /** 34812 * Gets the next value on a wrapped object following the 34813 * [iterator protocol](https://mdn.io/iteration_protocols#iterator). 34814 * 34815 * @name next 34816 * @memberOf _ 34817 * @since 4.0.0 34818 * @category Seq 34819 * @returns {Object} Returns the next iterator value. 34820 * @example 34821 * 34822 * var wrapped = _([1, 2]); 34823 * 34824 * wrapped.next(); 34825 * // => { 'done': false, 'value': 1 } 34826 * 34827 * wrapped.next(); 34828 * // => { 'done': false, 'value': 2 } 34829 * 34830 * wrapped.next(); 34831 * // => { 'done': true, 'value': undefined } 34832 */ 34833 function wrapperNext() { 34834 if (this.__values__ === undefined) { 34835 this.__values__ = toArray(this.value()); 34836 } 34837 var done = this.__index__ >= this.__values__.length, 34838 value = done ? undefined : this.__values__[this.__index__++]; 34839 34840 return { 'done': done, 'value': value }; 34841 } 34842 34843 /** 34844 * Enables the wrapper to be iterable. 34845 * 34846 * @name Symbol.iterator 34847 * @memberOf _ 34848 * @since 4.0.0 34849 * @category Seq 34850 * @returns {Object} Returns the wrapper object. 34851 * @example 34852 * 34853 * var wrapped = _([1, 2]); 34854 * 34855 * wrapped[Symbol.iterator]() === wrapped; 34856 * // => true 34857 * 34858 * Array.from(wrapped); 34859 * // => [1, 2] 34860 */ 34861 function wrapperToIterator() { 34862 return this; 34863 } 34864 34865 /** 34866 * Creates a clone of the chain sequence planting `value` as the wrapped value. 34867 * 34868 * @name plant 34869 * @memberOf _ 34870 * @since 3.2.0 34871 * @category Seq 34872 * @param {*} value The value to plant. 34873 * @returns {Object} Returns the new `lodash` wrapper instance. 34874 * @example 34875 * 34876 * function square(n) { 34877 * return n * n; 34878 * } 34879 * 34880 * var wrapped = _([1, 2]).map(square); 34881 * var other = wrapped.plant([3, 4]); 34882 * 34883 * other.value(); 34884 * // => [9, 16] 34885 * 34886 * wrapped.value(); 34887 * // => [1, 4] 34888 */ 34889 function wrapperPlant(value) { 34890 var result, 34891 parent = this; 34892 34893 while (parent instanceof baseLodash) { 34894 var clone = wrapperClone(parent); 34895 clone.__index__ = 0; 34896 clone.__values__ = undefined; 34897 if (result) { 34898 previous.__wrapped__ = clone; 34899 } else { 34900 result = clone; 34901 } 34902 var previous = clone; 34903 parent = parent.__wrapped__; 34904 } 34905 previous.__wrapped__ = value; 34906 return result; 34907 } 34908 34909 /** 34910 * This method is the wrapper version of `_.reverse`. 34911 * 34912 * **Note:** This method mutates the wrapped array. 34913 * 34914 * @name reverse 34915 * @memberOf _ 34916 * @since 0.1.0 34917 * @category Seq 34918 * @returns {Object} Returns the new `lodash` wrapper instance. 34919 * @example 34920 * 34921 * var array = [1, 2, 3]; 34922 * 34923 * _(array).reverse().value() 34924 * // => [3, 2, 1] 34925 * 34926 * console.log(array); 34927 * // => [3, 2, 1] 34928 */ 34929 function wrapperReverse() { 34930 var value = this.__wrapped__; 34931 if (value instanceof LazyWrapper) { 34932 var wrapped = value; 34933 if (this.__actions__.length) { 34934 wrapped = new LazyWrapper(this); 34935 } 34936 wrapped = wrapped.reverse(); 34937 wrapped.__actions__.push({ 34938 'func': thru, 34939 'args': [reverse], 34940 'thisArg': undefined 34941 }); 34942 return new LodashWrapper(wrapped, this.__chain__); 34943 } 34944 return this.thru(reverse); 34945 } 34946 34947 /** 34948 * Executes the chain sequence to resolve the unwrapped value. 34949 * 34950 * @name value 34951 * @memberOf _ 34952 * @since 0.1.0 34953 * @alias toJSON, valueOf 34954 * @category Seq 34955 * @returns {*} Returns the resolved unwrapped value. 34956 * @example 34957 * 34958 * _([1, 2, 3]).value(); 34959 * // => [1, 2, 3] 34960 */ 34961 function wrapperValue() { 34962 return baseWrapperValue(this.__wrapped__, this.__actions__); 34963 } 34964 34965 /*------------------------------------------------------------------------*/ 34966 34967 /**
vendor: 6,915 bytes, lines 34968-35158
34968 * Creates an object composed of keys generated from the results of running 34969 * each element of `collection` thru `iteratee`. The corresponding value of 34970 * each key is the number of times the key was returned by `iteratee`. The 34971 * iteratee is invoked with one argument: (value). 34972 * 34973 * @static 34974 * @memberOf _ 34975 * @since 0.5.0 34976 * @category Collection 34977 * @param {Array|Object} collection The collection to iterate over. 34978 * @param {Function} [iteratee=_.identity] The iteratee to transform keys. 34979 * @returns {Object} Returns the composed aggregate object. 34980 * @example 34981 * 34982 * _.countBy([6.1, 4.2, 6.3], Math.floor); 34983 * // => { '4': 1, '6': 2 } 34984 * 34985 * // The `_.property` iteratee shorthand. 34986 * _.countBy(['one', 'two', 'three'], 'length'); 34987 * // => { '3': 2, '5': 1 } 34988 */ 34989 var countBy = createAggregator(function(result, value, key) { 34990 if (hasOwnProperty.call(result, key)) { 34991 ++result[key]; 34992 } else { 34993 baseAssignValue(result, key, 1); 34994 } 34995 }); 34996 34997 /** 34998 * Checks if `predicate` returns truthy for **all** elements of `collection`. 34999 * Iteration is stopped once `predicate` returns falsey. The predicate is 35000 * invoked with three arguments: (value, index|key, collection). 35001 * 35002 * **Note:** This method returns `true` for 35003 * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because 35004 * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of 35005 * elements of empty collections. 35006 * 35007 * @static 35008 * @memberOf _ 35009 * @since 0.1.0 35010 * @category Collection 35011 * @param {Array|Object} collection The collection to iterate over. 35012 * @param {Function} [predicate=_.identity] The function invoked per iteration. 35013 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 35014 * @returns {boolean} Returns `true` if all elements pass the predicate check, 35015 * else `false`. 35016 * @example 35017 * 35018 * _.every([true, 1, null, 'yes'], Boolean); 35019 * // => false 35020 * 35021 * var users = [ 35022 * { 'user': 'barney', 'age': 36, 'active': false }, 35023 * { 'user': 'fred', 'age': 40, 'active': false } 35024 * ]; 35025 * 35026 * // The `_.matches` iteratee shorthand. 35027 * _.every(users, { 'user': 'barney', 'active': false }); 35028 * // => false 35029 * 35030 * // The `_.matchesProperty` iteratee shorthand. 35031 * _.every(users, ['active', false]); 35032 * // => true 35033 * 35034 * // The `_.property` iteratee shorthand. 35035 * _.every(users, 'active'); 35036 * // => false 35037 */ 35038 function every(collection, predicate, guard) { 35039 var func = isArray(collection) ? arrayEvery : baseEvery; 35040 if (guard && isIterateeCall(collection, predicate, guard)) { 35041 predicate = undefined; 35042 } 35043 return func(collection, getIteratee(predicate, 3)); 35044 } 35045 35046 /** 35047 * Iterates over elements of `collection`, returning an array of all elements 35048 * `predicate` returns truthy for. The predicate is invoked with three 35049 * arguments: (value, index|key, collection). 35050 * 35051 * **Note:** Unlike `_.remove`, this method returns a new array. 35052 * 35053 * @static 35054 * @memberOf _ 35055 * @since 0.1.0 35056 * @category Collection 35057 * @param {Array|Object} collection The collection to iterate over. 35058 * @param {Function} [predicate=_.identity] The function invoked per iteration. 35059 * @returns {Array} Returns the new filtered array. 35060 * @see _.reject 35061 * @example 35062 * 35063 * var users = [ 35064 * { 'user': 'barney', 'age': 36, 'active': true }, 35065 * { 'user': 'fred', 'age': 40, 'active': false } 35066 * ]; 35067 * 35068 * _.filter(users, function(o) { return !o.active; }); 35069 * // => objects for ['fred'] 35070 * 35071 * // The `_.matches` iteratee shorthand. 35072 * _.filter(users, { 'age': 36, 'active': true }); 35073 * // => objects for ['barney'] 35074 * 35075 * // The `_.matchesProperty` iteratee shorthand. 35076 * _.filter(users, ['active', false]); 35077 * // => objects for ['fred'] 35078 * 35079 * // The `_.property` iteratee shorthand. 35080 * _.filter(users, 'active'); 35081 * // => objects for ['barney'] 35082 */ 35083 function filter(collection, predicate) { 35084 var func = isArray(collection) ? arrayFilter : baseFilter; 35085 return func(collection, getIteratee(predicate, 3)); 35086 } 35087 35088 /** 35089 * Iterates over elements of `collection`, returning the first element 35090 * `predicate` returns truthy for. The predicate is invoked with three 35091 * arguments: (value, index|key, collection). 35092 * 35093 * @static 35094 * @memberOf _ 35095 * @since 0.1.0 35096 * @category Collection 35097 * @param {Array|Object} collection The collection to inspect. 35098 * @param {Function} [predicate=_.identity] The function invoked per iteration. 35099 * @param {number} [fromIndex=0] The index to search from. 35100 * @returns {*} Returns the matched element, else `undefined`. 35101 * @example 35102 * 35103 * var users = [ 35104 * { 'user': 'barney', 'age': 36, 'active': true }, 35105 * { 'user': 'fred', 'age': 40, 'active': false }, 35106 * { 'user': 'pebbles', 'age': 1, 'active': true } 35107 * ]; 35108 * 35109 * _.find(users, function(o) { return o.age < 40; }); 35110 * // => object for 'barney' 35111 * 35112 * // The `_.matches` iteratee shorthand. 35113 * _.find(users, { 'age': 1, 'active': true }); 35114 * // => object for 'pebbles' 35115 * 35116 * // The `_.matchesProperty` iteratee shorthand. 35117 * _.find(users, ['active', false]); 35118 * // => object for 'fred' 35119 * 35120 * // The `_.property` iteratee shorthand. 35121 * _.find(users, 'active'); 35122 * // => object for 'barney' 35123 */ 35124 var find = createFind(findIndex); 35125 35126 /** 35127 * This method is like `_.find` except that it iterates over elements of 35128 * `collection` from right to left. 35129 * 35130 * @static 35131 * @memberOf _ 35132 * @since 2.0.0 35133 * @category Collection 35134 * @param {Array|Object} collection The collection to inspect. 35135 * @param {Function} [predicate=_.identity] The function invoked per iteration. 35136 * @param {number} [fromIndex=collection.length-1] The index to search from. 35137 * @returns {*} Returns the matched element, else `undefined`. 35138 * @example 35139 * 35140 * _.findLast([1, 2, 3, 4], function(n) { 35141 * return n % 2 == 1; 35142 * }); 35143 * // => 3 35144 */ 35145 var findLast = createFind(findLastIndex); 35146 35147 /** 35148 * Creates a flattened array of values by running each element in `collection` 35149 * thru `iteratee` and flattening the mapped results. The iteratee is invoked 35150 * with three arguments: (value, index|key, collection). 35151 * 35152 * @static 35153 * @memberOf _ 35154 * @since 4.0.0 35155 * @category Collection 35156 * @param {Array|Object} collection The collection to iterate over. 35157 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 35158 * @returns {Array} Returns the new flattened array.
vendor: 3,950 bytes, lines 35159-35282
35159 * @example 35160 * 35161 * function duplicate(n) { 35162 * return [n, n]; 35163 * } 35164 * 35165 * _.flatMap([1, 2], duplicate); 35166 * // => [1, 1, 2, 2] 35167 */ 35168 function flatMap(collection, iteratee) { 35169 return baseFlatten(map(collection, iteratee), 1); 35170 } 35171 35172 /** 35173 * This method is like `_.flatMap` except that it recursively flattens the 35174 * mapped results. 35175 * 35176 * @static 35177 * @memberOf _ 35178 * @since 4.7.0 35179 * @category Collection 35180 * @param {Array|Object} collection The collection to iterate over. 35181 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 35182 * @returns {Array} Returns the new flattened array. 35183 * @example 35184 * 35185 * function duplicate(n) { 35186 * return [[[n, n]]]; 35187 * } 35188 * 35189 * _.flatMapDeep([1, 2], duplicate); 35190 * // => [1, 1, 2, 2] 35191 */ 35192 function flatMapDeep(collection, iteratee) { 35193 return baseFlatten(map(collection, iteratee), INFINITY); 35194 } 35195 35196 /** 35197 * This method is like `_.flatMap` except that it recursively flattens the 35198 * mapped results up to `depth` times. 35199 * 35200 * @static 35201 * @memberOf _ 35202 * @since 4.7.0 35203 * @category Collection 35204 * @param {Array|Object} collection The collection to iterate over. 35205 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 35206 * @param {number} [depth=1] The maximum recursion depth. 35207 * @returns {Array} Returns the new flattened array. 35208 * @example 35209 * 35210 * function duplicate(n) { 35211 * return [[[n, n]]]; 35212 * } 35213 * 35214 * _.flatMapDepth([1, 2], duplicate, 2); 35215 * // => [[1, 1], [2, 2]] 35216 */ 35217 function flatMapDepth(collection, iteratee, depth) { 35218 depth = depth === undefined ? 1 : toInteger(depth); 35219 return baseFlatten(map(collection, iteratee), depth); 35220 } 35221 35222 /** 35223 * Iterates over elements of `collection` and invokes `iteratee` for each element. 35224 * The iteratee is invoked with three arguments: (value, index|key, collection). 35225 * Iteratee functions may exit iteration early by explicitly returning `false`. 35226 * 35227 * **Note:** As with other "Collections" methods, objects with a "length" 35228 * property are iterated like arrays. To avoid this behavior use `_.forIn` 35229 * or `_.forOwn` for object iteration. 35230 * 35231 * @static 35232 * @memberOf _ 35233 * @since 0.1.0 35234 * @alias each 35235 * @category Collection 35236 * @param {Array|Object} collection The collection to iterate over. 35237 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 35238 * @returns {Array|Object} Returns `collection`. 35239 * @see _.forEachRight 35240 * @example 35241 * 35242 * _.forEach([1, 2], function(value) { 35243 * console.log(value); 35244 * }); 35245 * // => Logs `1` then `2`. 35246 * 35247 * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { 35248 * console.log(key); 35249 * }); 35250 * // => Logs 'a' then 'b' (iteration order is not guaranteed). 35251 */ 35252 function forEach(collection, iteratee) { 35253 var func = isArray(collection) ? arrayEach : baseEach; 35254 return func(collection, getIteratee(iteratee, 3)); 35255 } 35256 35257 /** 35258 * This method is like `_.forEach` except that it iterates over elements of 35259 * `collection` from right to left. 35260 * 35261 * @static 35262 * @memberOf _ 35263 * @since 2.0.0 35264 * @alias eachRight 35265 * @category Collection 35266 * @param {Array|Object} collection The collection to iterate over. 35267 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 35268 * @returns {Array|Object} Returns `collection`. 35269 * @see _.forEach 35270 * @example 35271 * 35272 * _.forEachRight([1, 2], function(value) { 35273 * console.log(value); 35274 * }); 35275 * // => Logs `2` then `1`. 35276 */ 35277 function forEachRight(collection, iteratee) { 35278 var func = isArray(collection) ? arrayEachRight : baseEachRight; 35279 return func(collection, getIteratee(iteratee, 3)); 35280 } 35281 35282 /**
vendor: 4,136 bytes, lines 35283-35390
35283 * Creates an object composed of keys generated from the results of running 35284 * each element of `collection` thru `iteratee`. The order of grouped values 35285 * is determined by the order they occur in `collection`. The corresponding 35286 * value of each key is an array of elements responsible for generating the 35287 * key. The iteratee is invoked with one argument: (value). 35288 * 35289 * @static 35290 * @memberOf _ 35291 * @since 0.1.0 35292 * @category Collection 35293 * @param {Array|Object} collection The collection to iterate over. 35294 * @param {Function} [iteratee=_.identity] The iteratee to transform keys. 35295 * @returns {Object} Returns the composed aggregate object. 35296 * @example 35297 * 35298 * _.groupBy([6.1, 4.2, 6.3], Math.floor); 35299 * // => { '4': [4.2], '6': [6.1, 6.3] } 35300 * 35301 * // The `_.property` iteratee shorthand. 35302 * _.groupBy(['one', 'two', 'three'], 'length'); 35303 * // => { '3': ['one', 'two'], '5': ['three'] } 35304 */ 35305 var groupBy = createAggregator(function(result, value, key) { 35306 if (hasOwnProperty.call(result, key)) { 35307 result[key].push(value); 35308 } else { 35309 baseAssignValue(result, key, [value]); 35310 } 35311 }); 35312 35313 /** 35314 * Checks if `value` is in `collection`. If `collection` is a string, it's 35315 * checked for a substring of `value`, otherwise 35316 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) 35317 * is used for equality comparisons. If `fromIndex` is negative, it's used as 35318 * the offset from the end of `collection`. 35319 * 35320 * @static 35321 * @memberOf _ 35322 * @since 0.1.0 35323 * @category Collection 35324 * @param {Array|Object|string} collection The collection to inspect. 35325 * @param {*} value The value to search for. 35326 * @param {number} [fromIndex=0] The index to search from. 35327 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. 35328 * @returns {boolean} Returns `true` if `value` is found, else `false`. 35329 * @example 35330 * 35331 * _.includes([1, 2, 3], 1); 35332 * // => true 35333 * 35334 * _.includes([1, 2, 3], 1, 2); 35335 * // => false 35336 * 35337 * _.includes({ 'a': 1, 'b': 2 }, 1); 35338 * // => true 35339 * 35340 * _.includes('abcd', 'bc'); 35341 * // => true 35342 */ 35343 function includes(collection, value, fromIndex, guard) { 35344 collection = isArrayLike(collection) ? collection : values(collection); 35345 fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; 35346 35347 var length = collection.length; 35348 if (fromIndex < 0) { 35349 fromIndex = nativeMax(length + fromIndex, 0); 35350 } 35351 return isString(collection) 35352 ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) 35353 : (!!length && baseIndexOf(collection, value, fromIndex) > -1); 35354 } 35355 35356 /** 35357 * Invokes the method at `path` of each element in `collection`, returning 35358 * an array of the results of each invoked method. Any additional arguments 35359 * are provided to each invoked method. If `path` is a function, it's invoked 35360 * for, and `this` bound to, each element in `collection`. 35361 * 35362 * @static 35363 * @memberOf _ 35364 * @since 4.0.0 35365 * @category Collection 35366 * @param {Array|Object} collection The collection to iterate over. 35367 * @param {Array|Function|string} path The path of the method to invoke or 35368 * the function invoked per iteration. 35369 * @param {...*} [args] The arguments to invoke each method with. 35370 * @returns {Array} Returns the array of results. 35371 * @example 35372 * 35373 * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); 35374 * // => [[1, 5, 7], [1, 2, 3]] 35375 * 35376 * _.invokeMap([123, 456], String.prototype.split, ''); 35377 * // => [['1', '2', '3'], ['4', '5', '6']] 35378 */ 35379 var invokeMap = baseRest(function(collection, path, args) { 35380 var index = -1, 35381 isFunc = typeof path == 'function', 35382 result = isArrayLike(collection) ? Array(collection.length) : []; 35383 35384 baseEach(collection, function(value) { 35385 result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); 35386 }); 35387 return result; 35388 }); 35389 35390 /**
vendor: 15,265 bytes, lines 35391-35825
35391 * Creates an object composed of keys generated from the results of running 35392 * each element of `collection` thru `iteratee`. The corresponding value of 35393 * each key is the last element responsible for generating the key. The 35394 * iteratee is invoked with one argument: (value). 35395 * 35396 * @static 35397 * @memberOf _ 35398 * @since 4.0.0 35399 * @category Collection 35400 * @param {Array|Object} collection The collection to iterate over. 35401 * @param {Function} [iteratee=_.identity] The iteratee to transform keys. 35402 * @returns {Object} Returns the composed aggregate object. 35403 * @example 35404 * 35405 * var array = [ 35406 * { 'dir': 'left', 'code': 97 }, 35407 * { 'dir': 'right', 'code': 100 } 35408 * ]; 35409 * 35410 * _.keyBy(array, function(o) { 35411 * return String.fromCharCode(o.code); 35412 * }); 35413 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } 35414 * 35415 * _.keyBy(array, 'dir'); 35416 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } 35417 */ 35418 var keyBy = createAggregator(function(result, value, key) { 35419 baseAssignValue(result, key, value); 35420 }); 35421 35422 /** 35423 * Creates an array of values by running each element in `collection` thru 35424 * `iteratee`. The iteratee is invoked with three arguments: 35425 * (value, index|key, collection). 35426 * 35427 * Many lodash methods are guarded to work as iteratees for methods like 35428 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. 35429 * 35430 * The guarded methods are: 35431 * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, 35432 * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, 35433 * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, 35434 * `template`, `trim`, `trimEnd`, `trimStart`, and `words` 35435 * 35436 * @static 35437 * @memberOf _ 35438 * @since 0.1.0 35439 * @category Collection 35440 * @param {Array|Object} collection The collection to iterate over. 35441 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 35442 * @returns {Array} Returns the new mapped array. 35443 * @example 35444 * 35445 * function square(n) { 35446 * return n * n; 35447 * } 35448 * 35449 * _.map([4, 8], square); 35450 * // => [16, 64] 35451 * 35452 * _.map({ 'a': 4, 'b': 8 }, square); 35453 * // => [16, 64] (iteration order is not guaranteed) 35454 * 35455 * var users = [ 35456 * { 'user': 'barney' }, 35457 * { 'user': 'fred' } 35458 * ]; 35459 * 35460 * // The `_.property` iteratee shorthand. 35461 * _.map(users, 'user'); 35462 * // => ['barney', 'fred'] 35463 */ 35464 function map(collection, iteratee) { 35465 var func = isArray(collection) ? arrayMap : baseMap; 35466 return func(collection, getIteratee(iteratee, 3)); 35467 } 35468 35469 /** 35470 * This method is like `_.sortBy` except that it allows specifying the sort 35471 * orders of the iteratees to sort by. If `orders` is unspecified, all values 35472 * are sorted in ascending order. Otherwise, specify an order of "desc" for 35473 * descending or "asc" for ascending sort order of corresponding values. 35474 * 35475 * @static 35476 * @memberOf _ 35477 * @since 4.0.0 35478 * @category Collection 35479 * @param {Array|Object} collection The collection to iterate over. 35480 * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] 35481 * The iteratees to sort by. 35482 * @param {string[]} [orders] The sort orders of `iteratees`. 35483 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. 35484 * @returns {Array} Returns the new sorted array. 35485 * @example 35486 * 35487 * var users = [ 35488 * { 'user': 'fred', 'age': 48 }, 35489 * { 'user': 'barney', 'age': 34 }, 35490 * { 'user': 'fred', 'age': 40 }, 35491 * { 'user': 'barney', 'age': 36 } 35492 * ]; 35493 * 35494 * // Sort by `user` in ascending order and by `age` in descending order. 35495 * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); 35496 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] 35497 */ 35498 function orderBy(collection, iteratees, orders, guard) { 35499 if (collection == null) { 35500 return []; 35501 } 35502 if (!isArray(iteratees)) { 35503 iteratees = iteratees == null ? [] : [iteratees]; 35504 } 35505 orders = guard ? undefined : orders; 35506 if (!isArray(orders)) { 35507 orders = orders == null ? [] : [orders]; 35508 } 35509 return baseOrderBy(collection, iteratees, orders); 35510 } 35511 35512 /** 35513 * Creates an array of elements split into two groups, the first of which 35514 * contains elements `predicate` returns truthy for, the second of which 35515 * contains elements `predicate` returns falsey for. The predicate is 35516 * invoked with one argument: (value). 35517 * 35518 * @static 35519 * @memberOf _ 35520 * @since 3.0.0 35521 * @category Collection 35522 * @param {Array|Object} collection The collection to iterate over. 35523 * @param {Function} [predicate=_.identity] The function invoked per iteration. 35524 * @returns {Array} Returns the array of grouped elements. 35525 * @example 35526 * 35527 * var users = [ 35528 * { 'user': 'barney', 'age': 36, 'active': false }, 35529 * { 'user': 'fred', 'age': 40, 'active': true }, 35530 * { 'user': 'pebbles', 'age': 1, 'active': false } 35531 * ]; 35532 * 35533 * _.partition(users, function(o) { return o.active; }); 35534 * // => objects for [['fred'], ['barney', 'pebbles']] 35535 * 35536 * // The `_.matches` iteratee shorthand. 35537 * _.partition(users, { 'age': 1, 'active': false }); 35538 * // => objects for [['pebbles'], ['barney', 'fred']] 35539 * 35540 * // The `_.matchesProperty` iteratee shorthand. 35541 * _.partition(users, ['active', false]); 35542 * // => objects for [['barney', 'pebbles'], ['fred']] 35543 * 35544 * // The `_.property` iteratee shorthand. 35545 * _.partition(users, 'active'); 35546 * // => objects for [['fred'], ['barney', 'pebbles']] 35547 */ 35548 var partition = createAggregator(function(result, value, key) { 35549 result[key ? 0 : 1].push(value); 35550 }, function() { return [[], []]; }); 35551 35552 /** 35553 * Reduces `collection` to a value which is the accumulated result of running 35554 * each element in `collection` thru `iteratee`, where each successive 35555 * invocation is supplied the return value of the previous. If `accumulator` 35556 * is not given, the first element of `collection` is used as the initial 35557 * value. The iteratee is invoked with four arguments: 35558 * (accumulator, value, index|key, collection). 35559 * 35560 * Many lodash methods are guarded to work as iteratees for methods like 35561 * `_.reduce`, `_.reduceRight`, and `_.transform`. 35562 * 35563 * The guarded methods are: 35564 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, 35565 * and `sortBy` 35566 * 35567 * @static 35568 * @memberOf _ 35569 * @since 0.1.0 35570 * @category Collection 35571 * @param {Array|Object} collection The collection to iterate over. 35572 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 35573 * @param {*} [accumulator] The initial value. 35574 * @returns {*} Returns the accumulated value. 35575 * @see _.reduceRight 35576 * @example 35577 * 35578 * _.reduce([1, 2], function(sum, n) { 35579 * return sum + n; 35580 * }, 0); 35581 * // => 3 35582 * 35583 * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { 35584 * (result[value] || (result[value] = [])).push(key); 35585 * return result; 35586 * }, {}); 35587 * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) 35588 */ 35589 function reduce(collection, iteratee, accumulator) { 35590 var func = isArray(collection) ? arrayReduce : baseReduce, 35591 initAccum = arguments.length < 3; 35592 35593 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); 35594 } 35595 35596 /** 35597 * This method is like `_.reduce` except that it iterates over elements of 35598 * `collection` from right to left. 35599 * 35600 * @static 35601 * @memberOf _ 35602 * @since 0.1.0 35603 * @category Collection 35604 * @param {Array|Object} collection The collection to iterate over. 35605 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 35606 * @param {*} [accumulator] The initial value. 35607 * @returns {*} Returns the accumulated value. 35608 * @see _.reduce 35609 * @example 35610 * 35611 * var array = [[0, 1], [2, 3], [4, 5]]; 35612 * 35613 * _.reduceRight(array, function(flattened, other) { 35614 * return flattened.concat(other); 35615 * }, []); 35616 * // => [4, 5, 2, 3, 0, 1] 35617 */ 35618 function reduceRight(collection, iteratee, accumulator) { 35619 var func = isArray(collection) ? arrayReduceRight : baseReduce, 35620 initAccum = arguments.length < 3; 35621 35622 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); 35623 } 35624 35625 /** 35626 * The opposite of `_.filter`; this method returns the elements of `collection` 35627 * that `predicate` does **not** return truthy for. 35628 * 35629 * @static 35630 * @memberOf _ 35631 * @since 0.1.0 35632 * @category Collection 35633 * @param {Array|Object} collection The collection to iterate over. 35634 * @param {Function} [predicate=_.identity] The function invoked per iteration. 35635 * @returns {Array} Returns the new filtered array. 35636 * @see _.filter 35637 * @example 35638 * 35639 * var users = [ 35640 * { 'user': 'barney', 'age': 36, 'active': false }, 35641 * { 'user': 'fred', 'age': 40, 'active': true } 35642 * ]; 35643 * 35644 * _.reject(users, function(o) { return !o.active; }); 35645 * // => objects for ['fred'] 35646 * 35647 * // The `_.matches` iteratee shorthand. 35648 * _.reject(users, { 'age': 40, 'active': true }); 35649 * // => objects for ['barney'] 35650 * 35651 * // The `_.matchesProperty` iteratee shorthand. 35652 * _.reject(users, ['active', false]); 35653 * // => objects for ['fred'] 35654 * 35655 * // The `_.property` iteratee shorthand. 35656 * _.reject(users, 'active'); 35657 * // => objects for ['barney'] 35658 */ 35659 function reject(collection, predicate) { 35660 var func = isArray(collection) ? arrayFilter : baseFilter; 35661 return func(collection, negate(getIteratee(predicate, 3))); 35662 } 35663 35664 /** 35665 * Gets a random element from `collection`. 35666 * 35667 * @static 35668 * @memberOf _ 35669 * @since 2.0.0 35670 * @category Collection 35671 * @param {Array|Object} collection The collection to sample. 35672 * @returns {*} Returns the random element. 35673 * @example 35674 * 35675 * _.sample([1, 2, 3, 4]); 35676 * // => 2 35677 */ 35678 function sample(collection) { 35679 var func = isArray(collection) ? arraySample : baseSample; 35680 return func(collection); 35681 } 35682 35683 /** 35684 * Gets `n` random elements at unique keys from `collection` up to the 35685 * size of `collection`. 35686 * 35687 * @static 35688 * @memberOf _ 35689 * @since 4.0.0 35690 * @category Collection 35691 * @param {Array|Object} collection The collection to sample. 35692 * @param {number} [n=1] The number of elements to sample. 35693 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 35694 * @returns {Array} Returns the random elements. 35695 * @example 35696 * 35697 * _.sampleSize([1, 2, 3], 2); 35698 * // => [3, 1] 35699 * 35700 * _.sampleSize([1, 2, 3], 4); 35701 * // => [2, 3, 1] 35702 */ 35703 function sampleSize(collection, n, guard) { 35704 if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { 35705 n = 1; 35706 } else { 35707 n = toInteger(n); 35708 } 35709 var func = isArray(collection) ? arraySampleSize : baseSampleSize; 35710 return func(collection, n); 35711 } 35712 35713 /** 35714 * Creates an array of shuffled values, using a version of the 35715 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). 35716 * 35717 * @static 35718 * @memberOf _ 35719 * @since 0.1.0 35720 * @category Collection 35721 * @param {Array|Object} collection The collection to shuffle. 35722 * @returns {Array} Returns the new shuffled array. 35723 * @example 35724 * 35725 * _.shuffle([1, 2, 3, 4]); 35726 * // => [4, 1, 3, 2] 35727 */ 35728 function shuffle(collection) { 35729 var func = isArray(collection) ? arrayShuffle : baseShuffle; 35730 return func(collection); 35731 } 35732 35733 /** 35734 * Gets the size of `collection` by returning its length for array-like 35735 * values or the number of own enumerable string keyed properties for objects. 35736 * 35737 * @static 35738 * @memberOf _ 35739 * @since 0.1.0 35740 * @category Collection 35741 * @param {Array|Object|string} collection The collection to inspect. 35742 * @returns {number} Returns the collection size. 35743 * @example 35744 * 35745 * _.size([1, 2, 3]); 35746 * // => 3 35747 * 35748 * _.size({ 'a': 1, 'b': 2 }); 35749 * // => 2 35750 * 35751 * _.size('pebbles'); 35752 * // => 7 35753 */ 35754 function size(collection) { 35755 if (collection == null) { 35756 return 0; 35757 } 35758 if (isArrayLike(collection)) { 35759 return isString(collection) ? stringSize(collection) : collection.length; 35760 } 35761 var tag = getTag(collection); 35762 if (tag == mapTag || tag == setTag) { 35763 return collection.size; 35764 } 35765 return baseKeys(collection).length; 35766 } 35767 35768 /** 35769 * Checks if `predicate` returns truthy for **any** element of `collection`. 35770 * Iteration is stopped once `predicate` returns truthy. The predicate is 35771 * invoked with three arguments: (value, index|key, collection). 35772 * 35773 * @static 35774 * @memberOf _ 35775 * @since 0.1.0 35776 * @category Collection 35777 * @param {Array|Object} collection The collection to iterate over. 35778 * @param {Function} [predicate=_.identity] The function invoked per iteration. 35779 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 35780 * @returns {boolean} Returns `true` if any element passes the predicate check, 35781 * else `false`. 35782 * @example 35783 * 35784 * _.some([null, 0, 'yes', false], Boolean); 35785 * // => true 35786 * 35787 * var users = [ 35788 * { 'user': 'barney', 'active': true }, 35789 * { 'user': 'fred', 'active': false } 35790 * ]; 35791 * 35792 * // The `_.matches` iteratee shorthand. 35793 * _.some(users, { 'user': 'barney', 'active': false }); 35794 * // => false 35795 * 35796 * // The `_.matchesProperty` iteratee shorthand. 35797 * _.some(users, ['active', false]); 35798 * // => true 35799 * 35800 * // The `_.property` iteratee shorthand. 35801 * _.some(users, 'active'); 35802 * // => true 35803 */ 35804 function some(collection, predicate, guard) { 35805 var func = isArray(collection) ? arraySome : baseSome; 35806 if (guard && isIterateeCall(collection, predicate, guard)) { 35807 predicate = undefined; 35808 } 35809 return func(collection, getIteratee(predicate, 3)); 35810 } 35811 35812 /** 35813 * Creates an array of elements, sorted in ascending order by the results of 35814 * running each element in a collection thru each iteratee. This method 35815 * performs a stable sort, that is, it preserves the original sort order of 35816 * equal elements. The iteratees are invoked with one argument: (value). 35817 * 35818 * @static 35819 * @memberOf _ 35820 * @since 0.1.0 35821 * @category Collection 35822 * @param {Array|Object} collection The collection to iterate over. 35823 * @param {...(Function|Function[])} [iteratees=[_.identity]] 35824 * The iteratees to sort by. 35825 * @returns {Array} Returns the new sorted array.
vendor: 6,758 bytes, lines 35826-36028
35826 * @example 35827 * 35828 * var users = [ 35829 * { 'user': 'fred', 'age': 48 }, 35830 * { 'user': 'barney', 'age': 36 }, 35831 * { 'user': 'fred', 'age': 40 }, 35832 * { 'user': 'barney', 'age': 34 } 35833 * ]; 35834 * 35835 * _.sortBy(users, [function(o) { return o.user; }]); 35836 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] 35837 * 35838 * _.sortBy(users, ['user', 'age']); 35839 * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] 35840 */ 35841 var sortBy = baseRest(function(collection, iteratees) { 35842 if (collection == null) { 35843 return []; 35844 } 35845 var length = iteratees.length; 35846 if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { 35847 iteratees = []; 35848 } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { 35849 iteratees = [iteratees[0]]; 35850 } 35851 return baseOrderBy(collection, baseFlatten(iteratees, 1), []); 35852 }); 35853 35854 /*------------------------------------------------------------------------*/ 35855 35856 /** 35857 * Gets the timestamp of the number of milliseconds that have elapsed since 35858 * the Unix epoch (1 January 1970 00:00:00 UTC). 35859 * 35860 * @static 35861 * @memberOf _ 35862 * @since 2.4.0 35863 * @category Date 35864 * @returns {number} Returns the timestamp. 35865 * @example 35866 * 35867 * _.defer(function(stamp) { 35868 * console.log(_.now() - stamp); 35869 * }, _.now()); 35870 * // => Logs the number of milliseconds it took for the deferred invocation. 35871 */ 35872 var now = ctxNow || function() { 35873 return root.Date.now(); 35874 }; 35875 35876 /*------------------------------------------------------------------------*/ 35877 35878 /** 35879 * The opposite of `_.before`; this method creates a function that invokes 35880 * `func` once it's called `n` or more times. 35881 * 35882 * @static 35883 * @memberOf _ 35884 * @since 0.1.0 35885 * @category Function 35886 * @param {number} n The number of calls before `func` is invoked. 35887 * @param {Function} func The function to restrict. 35888 * @returns {Function} Returns the new restricted function. 35889 * @example 35890 * 35891 * var saves = ['profile', 'settings']; 35892 * 35893 * var done = _.after(saves.length, function() { 35894 * console.log('done saving!'); 35895 * }); 35896 * 35897 * _.forEach(saves, function(type) { 35898 * asyncSave({ 'type': type, 'complete': done }); 35899 * }); 35900 * // => Logs 'done saving!' after the two async saves have completed. 35901 */ 35902 function after(n, func) { 35903 if (typeof func != 'function') { 35904 throw new TypeError(FUNC_ERROR_TEXT); 35905 } 35906 n = toInteger(n); 35907 return function() { 35908 if (--n < 1) { 35909 return func.apply(this, arguments); 35910 } 35911 }; 35912 } 35913 35914 /** 35915 * Creates a function that invokes `func`, with up to `n` arguments, 35916 * ignoring any additional arguments. 35917 * 35918 * @static 35919 * @memberOf _ 35920 * @since 3.0.0 35921 * @category Function 35922 * @param {Function} func The function to cap arguments for. 35923 * @param {number} [n=func.length] The arity cap. 35924 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 35925 * @returns {Function} Returns the new capped function. 35926 * @example 35927 * 35928 * _.map(['6', '8', '10'], _.ary(parseInt, 1)); 35929 * // => [6, 8, 10] 35930 */ 35931 function ary(func, n, guard) { 35932 n = guard ? undefined : n; 35933 n = (func && n == null) ? func.length : n; 35934 return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); 35935 } 35936 35937 /** 35938 * Creates a function that invokes `func`, with the `this` binding and arguments 35939 * of the created function, while it's called less than `n` times. Subsequent 35940 * calls to the created function return the result of the last `func` invocation. 35941 * 35942 * @static 35943 * @memberOf _ 35944 * @since 3.0.0 35945 * @category Function 35946 * @param {number} n The number of calls at which `func` is no longer invoked. 35947 * @param {Function} func The function to restrict. 35948 * @returns {Function} Returns the new restricted function. 35949 * @example 35950 * 35951 * jQuery(element).on('click', _.before(5, addContactToList)); 35952 * // => Allows adding up to 4 contacts to the list. 35953 */ 35954 function before(n, func) { 35955 var result; 35956 if (typeof func != 'function') { 35957 throw new TypeError(FUNC_ERROR_TEXT); 35958 } 35959 n = toInteger(n); 35960 return function() { 35961 if (--n > 0) { 35962 result = func.apply(this, arguments); 35963 } 35964 if (n <= 1) { 35965 func = undefined; 35966 } 35967 return result; 35968 }; 35969 } 35970 35971 /** 35972 * Creates a function that invokes `func` with the `this` binding of `thisArg` 35973 * and `partials` prepended to the arguments it receives. 35974 * 35975 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, 35976 * may be used as a placeholder for partially applied arguments. 35977 * 35978 * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" 35979 * property of bound functions. 35980 * 35981 * @static 35982 * @memberOf _ 35983 * @since 0.1.0 35984 * @category Function 35985 * @param {Function} func The function to bind. 35986 * @param {*} thisArg The `this` binding of `func`. 35987 * @param {...*} [partials] The arguments to be partially applied. 35988 * @returns {Function} Returns the new bound function. 35989 * @example 35990 * 35991 * function greet(greeting, punctuation) { 35992 * return greeting + ' ' + this.user + punctuation; 35993 * } 35994 * 35995 * var object = { 'user': 'fred' }; 35996 * 35997 * var bound = _.bind(greet, object, 'hi'); 35998 * bound('!'); 35999 * // => 'hi fred!' 36000 * 36001 * // Bound with placeholders. 36002 * var bound = _.bind(greet, object, _, '!'); 36003 * bound('hi'); 36004 * // => 'hi fred!' 36005 */ 36006 var bind = baseRest(function(func, thisArg, partials) { 36007 var bitmask = WRAP_BIND_FLAG; 36008 if (partials.length) { 36009 var holders = replaceHolders(partials, getHolder(bind)); 36010 bitmask |= WRAP_PARTIAL_FLAG; 36011 } 36012 return createWrap(func, bitmask, thisArg, partials, holders); 36013 }); 36014 36015 /** 36016 * Creates a function that invokes the method at `object[key]` with `partials` 36017 * prepended to the arguments it receives. 36018 * 36019 * This method differs from `_.bind` by allowing bound functions to reference 36020 * methods that may be redefined or don't yet exist. See 36021 * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) 36022 * for more details. 36023 * 36024 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic 36025 * builds, may be used as a placeholder for partially applied arguments. 36026 * 36027 * @static 36028 * @memberOf _
vendor: 8,388 bytes, lines 36029-36261
36029 * @since 0.10.0 36030 * @category Function 36031 * @param {Object} object The object to invoke the method on. 36032 * @param {string} key The key of the method. 36033 * @param {...*} [partials] The arguments to be partially applied. 36034 * @returns {Function} Returns the new bound function. 36035 * @example 36036 * 36037 * var object = { 36038 * 'user': 'fred', 36039 * 'greet': function(greeting, punctuation) { 36040 * return greeting + ' ' + this.user + punctuation; 36041 * } 36042 * }; 36043 * 36044 * var bound = _.bindKey(object, 'greet', 'hi'); 36045 * bound('!'); 36046 * // => 'hi fred!' 36047 * 36048 * object.greet = function(greeting, punctuation) { 36049 * return greeting + 'ya ' + this.user + punctuation; 36050 * }; 36051 * 36052 * bound('!'); 36053 * // => 'hiya fred!' 36054 * 36055 * // Bound with placeholders. 36056 * var bound = _.bindKey(object, 'greet', _, '!'); 36057 * bound('hi'); 36058 * // => 'hiya fred!' 36059 */ 36060 var bindKey = baseRest(function(object, key, partials) { 36061 var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; 36062 if (partials.length) { 36063 var holders = replaceHolders(partials, getHolder(bindKey)); 36064 bitmask |= WRAP_PARTIAL_FLAG; 36065 } 36066 return createWrap(key, bitmask, object, partials, holders); 36067 }); 36068 36069 /** 36070 * Creates a function that accepts arguments of `func` and either invokes 36071 * `func` returning its result, if at least `arity` number of arguments have 36072 * been provided, or returns a function that accepts the remaining `func` 36073 * arguments, and so on. The arity of `func` may be specified if `func.length` 36074 * is not sufficient. 36075 * 36076 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, 36077 * may be used as a placeholder for provided arguments. 36078 * 36079 * **Note:** This method doesn't set the "length" property of curried functions. 36080 * 36081 * @static 36082 * @memberOf _ 36083 * @since 2.0.0 36084 * @category Function 36085 * @param {Function} func The function to curry. 36086 * @param {number} [arity=func.length] The arity of `func`. 36087 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 36088 * @returns {Function} Returns the new curried function. 36089 * @example 36090 * 36091 * var abc = function(a, b, c) { 36092 * return [a, b, c]; 36093 * }; 36094 * 36095 * var curried = _.curry(abc); 36096 * 36097 * curried(1)(2)(3); 36098 * // => [1, 2, 3] 36099 * 36100 * curried(1, 2)(3); 36101 * // => [1, 2, 3] 36102 * 36103 * curried(1, 2, 3); 36104 * // => [1, 2, 3] 36105 * 36106 * // Curried with placeholders. 36107 * curried(1)(_, 3)(2); 36108 * // => [1, 2, 3] 36109 */ 36110 function curry(func, arity, guard) { 36111 arity = guard ? undefined : arity; 36112 var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); 36113 result.placeholder = curry.placeholder; 36114 return result; 36115 } 36116 36117 /** 36118 * This method is like `_.curry` except that arguments are applied to `func` 36119 * in the manner of `_.partialRight` instead of `_.partial`. 36120 * 36121 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic 36122 * builds, may be used as a placeholder for provided arguments. 36123 * 36124 * **Note:** This method doesn't set the "length" property of curried functions. 36125 * 36126 * @static 36127 * @memberOf _ 36128 * @since 3.0.0 36129 * @category Function 36130 * @param {Function} func The function to curry. 36131 * @param {number} [arity=func.length] The arity of `func`. 36132 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 36133 * @returns {Function} Returns the new curried function. 36134 * @example 36135 * 36136 * var abc = function(a, b, c) { 36137 * return [a, b, c]; 36138 * }; 36139 * 36140 * var curried = _.curryRight(abc); 36141 * 36142 * curried(3)(2)(1); 36143 * // => [1, 2, 3] 36144 * 36145 * curried(2, 3)(1); 36146 * // => [1, 2, 3] 36147 * 36148 * curried(1, 2, 3); 36149 * // => [1, 2, 3] 36150 * 36151 * // Curried with placeholders. 36152 * curried(3)(1, _)(2); 36153 * // => [1, 2, 3] 36154 */ 36155 function curryRight(func, arity, guard) { 36156 arity = guard ? undefined : arity; 36157 var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); 36158 result.placeholder = curryRight.placeholder; 36159 return result; 36160 } 36161 36162 /** 36163 * Creates a debounced function that delays invoking `func` until after `wait` 36164 * milliseconds have elapsed since the last time the debounced function was 36165 * invoked. The debounced function comes with a `cancel` method to cancel 36166 * delayed `func` invocations and a `flush` method to immediately invoke them. 36167 * Provide `options` to indicate whether `func` should be invoked on the 36168 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked 36169 * with the last arguments provided to the debounced function. Subsequent 36170 * calls to the debounced function return the result of the last `func` 36171 * invocation. 36172 * 36173 * **Note:** If `leading` and `trailing` options are `true`, `func` is 36174 * invoked on the trailing edge of the timeout only if the debounced function 36175 * is invoked more than once during the `wait` timeout. 36176 * 36177 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred 36178 * until to the next tick, similar to `setTimeout` with a timeout of `0`. 36179 * 36180 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) 36181 * for details over the differences between `_.debounce` and `_.throttle`. 36182 * 36183 * @static 36184 * @memberOf _ 36185 * @since 0.1.0 36186 * @category Function 36187 * @param {Function} func The function to debounce. 36188 * @param {number} [wait=0] The number of milliseconds to delay. 36189 * @param {Object} [options={}] The options object. 36190 * @param {boolean} [options.leading=false] 36191 * Specify invoking on the leading edge of the timeout. 36192 * @param {number} [options.maxWait] 36193 * The maximum time `func` is allowed to be delayed before it's invoked. 36194 * @param {boolean} [options.trailing=true] 36195 * Specify invoking on the trailing edge of the timeout. 36196 * @returns {Function} Returns the new debounced function. 36197 * @example 36198 * 36199 * // Avoid costly calculations while the window size is in flux. 36200 * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); 36201 * 36202 * // Invoke `sendMail` when clicked, debouncing subsequent calls. 36203 * jQuery(element).on('click', _.debounce(sendMail, 300, { 36204 * 'leading': true, 36205 * 'trailing': false 36206 * })); 36207 * 36208 * // Ensure `batchLog` is invoked once after 1 second of debounced calls. 36209 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); 36210 * var source = new EventSource('/stream'); 36211 * jQuery(source).on('message', debounced); 36212 * 36213 * // Cancel the trailing debounced invocation. 36214 * jQuery(window).on('popstate', debounced.cancel); 36215 */ 36216 function debounce(func, wait, options) { 36217 var lastArgs, 36218 lastThis, 36219 maxWait, 36220 result, 36221 timerId, 36222 lastCallTime, 36223 lastInvokeTime = 0, 36224 leading = false, 36225 maxing = false, 36226 trailing = true; 36227 36228 if (typeof func != 'function') { 36229 throw new TypeError(FUNC_ERROR_TEXT); 36230 } 36231 wait = toNumber(wait) || 0; 36232 if (isObject(options)) { 36233 leading = !!options.leading; 36234 maxing = 'maxWait' in options; 36235 maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; 36236 trailing = 'trailing' in options ? !!options.trailing : trailing; 36237 } 36238 36239 function invokeFunc(time) { 36240 var args = lastArgs, 36241 thisArg = lastThis; 36242 36243 lastArgs = lastThis = undefined; 36244 lastInvokeTime = time; 36245 result = func.apply(thisArg, args); 36246 return result; 36247 } 36248 36249 function leadingEdge(time) { 36250 // Reset any `maxWait` timer. 36251 lastInvokeTime = time; 36252 // Start the timer for the trailing edge. 36253 timerId = setTimeout(timerExpired, wait); 36254 // Invoke the leading edge. 36255 return leading ? invokeFunc(time) : result; 36256 } 36257 36258 function remainingWait(time) { 36259 var timeSinceLastCall = time - lastCallTime, 36260 timeSinceLastInvoke = time - lastInvokeTime, 36261
vendor: 1,940 bytes, lines 36261-36323
36261result = wait - timeSinceLastCall; 36262 36263 return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; 36264 } 36265 36266 function shouldInvoke(time) { 36267 var timeSinceLastCall = time - lastCallTime, 36268 timeSinceLastInvoke = time - lastInvokeTime; 36269 36270 // Either this is the first call, activity has stopped and we're at the 36271 // trailing edge, the system time has gone backwards and we're treating 36272 // it as the trailing edge, or we've hit the `maxWait` limit. 36273 return (lastCallTime === undefined || (timeSinceLastCall >= wait) || 36274 (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); 36275 } 36276 36277 function timerExpired() { 36278 var time = now(); 36279 if (shouldInvoke(time)) { 36280 return trailingEdge(time); 36281 } 36282 // Restart the timer. 36283 timerId = setTimeout(timerExpired, remainingWait(time)); 36284 } 36285 36286 function trailingEdge(time) { 36287 timerId = undefined; 36288 36289 // Only invoke if we have `lastArgs` which means `func` has been 36290 // debounced at least once. 36291 if (trailing && lastArgs) { 36292 return invokeFunc(time); 36293 } 36294 lastArgs = lastThis = undefined; 36295 return result; 36296 } 36297 36298 function cancel() { 36299 if (timerId !== undefined) { 36300 clearTimeout(timerId); 36301 } 36302 lastInvokeTime = 0; 36303 lastArgs = lastCallTime = lastThis = timerId = undefined; 36304 } 36305 36306 function flush() { 36307 return timerId === undefined ? result : trailingEdge(now()); 36308 } 36309 36310 function debounced() { 36311 var time = now(), 36312 isInvoking = shouldInvoke(time); 36313 36314 lastArgs = arguments; 36315 lastThis = this; 36316 lastCallTime = time; 36317 36318 if (isInvoking) { 36319 if (timerId === undefined) { 36320 return leadingEdge(lastCallTime); 36321 } 36322 if (maxing) { 36323 // Handle invocations in a tight loop.
vendor: 36,079 bytes, lines 36323-37502
36323 36324 timerId = setTimeout(timerExpired, wait); 36325 return invokeFunc(lastCallTime); 36326 } 36327 } 36328 if (timerId === undefined) { 36329 timerId = setTimeout(timerExpired, wait); 36330 } 36331 return result; 36332 } 36333 debounced.cancel = cancel; 36334 debounced.flush = flush; 36335 return debounced; 36336 } 36337 36338 /** 36339 * Defers invoking the `func` until the current call stack has cleared. Any 36340 * additional arguments are provided to `func` when it's invoked. 36341 * 36342 * @static 36343 * @memberOf _ 36344 * @since 0.1.0 36345 * @category Function 36346 * @param {Function} func The function to defer. 36347 * @param {...*} [args] The arguments to invoke `func` with. 36348 * @returns {number} Returns the timer id. 36349 * @example 36350 * 36351 * _.defer(function(text) { 36352 * console.log(text); 36353 * }, 'deferred'); 36354 * // => Logs 'deferred' after one millisecond. 36355 */ 36356 var defer = baseRest(function(func, args) { 36357 return baseDelay(func, 1, args); 36358 }); 36359 36360 /** 36361 * Invokes `func` after `wait` milliseconds. Any additional arguments are 36362 * provided to `func` when it's invoked. 36363 * 36364 * @static 36365 * @memberOf _ 36366 * @since 0.1.0 36367 * @category Function 36368 * @param {Function} func The function to delay. 36369 * @param {number} wait The number of milliseconds to delay invocation. 36370 * @param {...*} [args] The arguments to invoke `func` with. 36371 * @returns {number} Returns the timer id. 36372 * @example 36373 * 36374 * _.delay(function(text) { 36375 * console.log(text); 36376 * }, 1000, 'later'); 36377 * // => Logs 'later' after one second. 36378 */ 36379 var delay = baseRest(function(func, wait, args) { 36380 return baseDelay(func, toNumber(wait) || 0, args); 36381 }); 36382 36383 /** 36384 * Creates a function that invokes `func` with arguments reversed. 36385 * 36386 * @static 36387 * @memberOf _ 36388 * @since 4.0.0 36389 * @category Function 36390 * @param {Function} func The function to flip arguments for. 36391 * @returns {Function} Returns the new flipped function. 36392 * @example 36393 * 36394 * var flipped = _.flip(function() { 36395 * return _.toArray(arguments); 36396 * }); 36397 * 36398 * flipped('a', 'b', 'c', 'd'); 36399 * // => ['d', 'c', 'b', 'a'] 36400 */ 36401 function flip(func) { 36402 return createWrap(func, WRAP_FLIP_FLAG); 36403 } 36404 36405 /** 36406 * Creates a function that memoizes the result of `func`. If `resolver` is 36407 * provided, it determines the cache key for storing the result based on the 36408 * arguments provided to the memoized function. By default, the first argument 36409 * provided to the memoized function is used as the map cache key. The `func` 36410 * is invoked with the `this` binding of the memoized function. 36411 * 36412 * **Note:** The cache is exposed as the `cache` property on the memoized 36413 * function. Its creation may be customized by replacing the `_.memoize.Cache` 36414 * constructor with one whose instances implement the 36415 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) 36416 * method interface of `clear`, `delete`, `get`, `has`, and `set`. 36417 * 36418 * @static 36419 * @memberOf _ 36420 * @since 0.1.0 36421 * @category Function 36422 * @param {Function} func The function to have its output memoized. 36423 * @param {Function} [resolver] The function to resolve the cache key. 36424 * @returns {Function} Returns the new memoized function. 36425 * @example 36426 * 36427 * var object = { 'a': 1, 'b': 2 }; 36428 * var other = { 'c': 3, 'd': 4 }; 36429 * 36430 * var values = _.memoize(_.values); 36431 * values(object); 36432 * // => [1, 2] 36433 * 36434 * values(other); 36435 * // => [3, 4] 36436 * 36437 * object.a = 2; 36438 * values(object); 36439 * // => [1, 2] 36440 * 36441 * // Modify the result cache. 36442 * values.cache.set(object, ['a', 'b']); 36443 * values(object); 36444 * // => ['a', 'b'] 36445 * 36446 * // Replace `_.memoize.Cache`. 36447 * _.memoize.Cache = WeakMap; 36448 */ 36449 function memoize(func, resolver) { 36450 if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { 36451 throw new TypeError(FUNC_ERROR_TEXT); 36452 } 36453 var memoized = function() { 36454 var args = arguments, 36455 key = resolver ? resolver.apply(this, args) : args[0], 36456 cache = memoized.cache; 36457 36458 if (cache.has(key)) { 36459 return cache.get(key); 36460 } 36461 var result = func.apply(this, args); 36462 memoized.cache = cache.set(key, result) || cache; 36463 return result; 36464 }; 36465 memoized.cache = new (memoize.Cache || MapCache); 36466 return memoized; 36467 } 36468 36469 // Expose `MapCache`. 36470 memoize.Cache = MapCache; 36471 36472 /** 36473 * Creates a function that negates the result of the predicate `func`. The 36474 * `func` predicate is invoked with the `this` binding and arguments of the 36475 * created function. 36476 * 36477 * @static 36478 * @memberOf _ 36479 * @since 3.0.0 36480 * @category Function 36481 * @param {Function} predicate The predicate to negate. 36482 * @returns {Function} Returns the new negated function. 36483 * @example 36484 * 36485 * function isEven(n) { 36486 * return n % 2 == 0; 36487 * } 36488 * 36489 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); 36490 * // => [1, 3, 5] 36491 */ 36492 function negate(predicate) { 36493 if (typeof predicate != 'function') { 36494 throw new TypeError(FUNC_ERROR_TEXT); 36495 } 36496 return function() { 36497 var args = arguments; 36498 switch (args.length) { 36499 case 0: return !predicate.call(this); 36500 case 1: return !predicate.call(this, args[0]); 36501 case 2: return !predicate.call(this, args[0], args[1]); 36502 case 3: return !predicate.call(this, args[0], args[1], args[2]); 36503 } 36504 return !predicate.apply(this, args); 36505 }; 36506 } 36507 36508 /** 36509 * Creates a function that is restricted to invoking `func` once. Repeat calls 36510 * to the function return the value of the first invocation. The `func` is 36511 * invoked with the `this` binding and arguments of the created function. 36512 * 36513 * @static 36514 * @memberOf _ 36515 * @since 0.1.0 36516 * @category Function 36517 * @param {Function} func The function to restrict. 36518 * @returns {Function} Returns the new restricted function. 36519 * @example 36520 * 36521 * var initialize = _.once(createApplication); 36522 * initialize(); 36523 * initialize(); 36524 * // => `createApplication` is invoked once 36525 */ 36526 function once(func) { 36527 return before(2, func); 36528 } 36529 36530 /** 36531 * Creates a function that invokes `func` with its arguments transformed. 36532 * 36533 * @static 36534 * @since 4.0.0 36535 * @memberOf _ 36536 * @category Function 36537 * @param {Function} func The function to wrap. 36538 * @param {...(Function|Function[])} [transforms=[_.identity]] 36539 * The argument transforms. 36540 * @returns {Function} Returns the new function. 36541 * @example 36542 * 36543 * function doubled(n) { 36544 * return n * 2; 36545 * } 36546 * 36547 * function square(n) { 36548 * return n * n; 36549 * } 36550 * 36551 * var func = _.overArgs(function(x, y) { 36552 * return [x, y]; 36553 * }, [square, doubled]); 36554 * 36555 * func(9, 3); 36556 * // => [81, 6] 36557 * 36558 * func(10, 5); 36559 * // => [100, 10] 36560 */ 36561 var overArgs = castRest(function(func, transforms) { 36562 transforms = (transforms.length == 1 && isArray(transforms[0])) 36563 ? arrayMap(transforms[0], baseUnary(getIteratee())) 36564 : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); 36565 36566 var funcsLength = transforms.length; 36567 return baseRest(function(args) { 36568 var index = -1, 36569 length = nativeMin(args.length, funcsLength); 36570 36571 while (++index < length) { 36572 args[index] = transforms[index].call(this, args[index]); 36573 } 36574 return apply(func, this, args); 36575 }); 36576 }); 36577 36578 /** 36579 * Creates a function that invokes `func` with `partials` prepended to the 36580 * arguments it receives. This method is like `_.bind` except it does **not** 36581 * alter the `this` binding. 36582 * 36583 * The `_.partial.placeholder` value, which defaults to `_` in monolithic 36584 * builds, may be used as a placeholder for partially applied arguments. 36585 * 36586 * **Note:** This method doesn't set the "length" property of partially 36587 * applied functions. 36588 * 36589 * @static 36590 * @memberOf _ 36591 * @since 0.2.0 36592 * @category Function 36593 * @param {Function} func The function to partially apply arguments to. 36594 * @param {...*} [partials] The arguments to be partially applied. 36595 * @returns {Function} Returns the new partially applied function. 36596 * @example 36597 * 36598 * function greet(greeting, name) { 36599 * return greeting + ' ' + name; 36600 * } 36601 * 36602 * var sayHelloTo = _.partial(greet, 'hello'); 36603 * sayHelloTo('fred'); 36604 * // => 'hello fred' 36605 * 36606 * // Partially applied with placeholders. 36607 * var greetFred = _.partial(greet, _, 'fred'); 36608 * greetFred('hi'); 36609 * // => 'hi fred' 36610 */ 36611 var partial = baseRest(function(func, partials) { 36612 var holders = replaceHolders(partials, getHolder(partial)); 36613 return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); 36614 }); 36615 36616 /** 36617 * This method is like `_.partial` except that partially applied arguments 36618 * are appended to the arguments it receives. 36619 * 36620 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic 36621 * builds, may be used as a placeholder for partially applied arguments. 36622 * 36623 * **Note:** This method doesn't set the "length" property of partially 36624 * applied functions. 36625 * 36626 * @static 36627 * @memberOf _ 36628 * @since 1.0.0 36629 * @category Function 36630 * @param {Function} func The function to partially apply arguments to. 36631 * @param {...*} [partials] The arguments to be partially applied. 36632 * @returns {Function} Returns the new partially applied function. 36633 * @example 36634 * 36635 * function greet(greeting, name) { 36636 * return greeting + ' ' + name; 36637 * } 36638 * 36639 * var greetFred = _.partialRight(greet, 'fred'); 36640 * greetFred('hi'); 36641 * // => 'hi fred' 36642 * 36643 * // Partially applied with placeholders. 36644 * var sayHelloTo = _.partialRight(greet, 'hello', _); 36645 * sayHelloTo('fred'); 36646 * // => 'hello fred' 36647 */ 36648 var partialRight = baseRest(function(func, partials) { 36649 var holders = replaceHolders(partials, getHolder(partialRight)); 36650 return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); 36651 }); 36652 36653 /** 36654 * Creates a function that invokes `func` with arguments arranged according 36655 * to the specified `indexes` where the argument value at the first index is 36656 * provided as the first argument, the argument value at the second index is 36657 * provided as the second argument, and so on. 36658 * 36659 * @static 36660 * @memberOf _ 36661 * @since 3.0.0 36662 * @category Function 36663 * @param {Function} func The function to rearrange arguments for. 36664 * @param {...(number|number[])} indexes The arranged argument indexes. 36665 * @returns {Function} Returns the new function. 36666 * @example 36667 * 36668 * var rearged = _.rearg(function(a, b, c) { 36669 * return [a, b, c]; 36670 * }, [2, 0, 1]); 36671 * 36672 * rearged('b', 'c', 'a') 36673 * // => ['a', 'b', 'c'] 36674 */ 36675 var rearg = flatRest(function(func, indexes) { 36676 return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); 36677 }); 36678 36679 /** 36680 * Creates a function that invokes `func` with the `this` binding of the 36681 * created function and arguments from `start` and beyond provided as 36682 * an array. 36683 * 36684 * **Note:** This method is based on the 36685 * [rest parameter](https://mdn.io/rest_parameters). 36686 * 36687 * @static 36688 * @memberOf _ 36689 * @since 4.0.0 36690 * @category Function 36691 * @param {Function} func The function to apply a rest parameter to. 36692 * @param {number} [start=func.length-1] The start position of the rest parameter. 36693 * @returns {Function} Returns the new function. 36694 * @example 36695 * 36696 * var say = _.rest(function(what, names) { 36697 * return what + ' ' + _.initial(names).join(', ') + 36698 * (_.size(names) > 1 ? ', & ' : '') + _.last(names); 36699 * }); 36700 * 36701 * say('hello', 'fred', 'barney', 'pebbles'); 36702 * // => 'hello fred, barney, & pebbles' 36703 */ 36704 function rest(func, start) { 36705 if (typeof func != 'function') { 36706 throw new TypeError(FUNC_ERROR_TEXT); 36707 } 36708 start = start === undefined ? start : toInteger(start); 36709 return baseRest(func, start); 36710 } 36711 36712 /** 36713 * Creates a function that invokes `func` with the `this` binding of the 36714 * create function and an array of arguments much like 36715 * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). 36716 * 36717 * **Note:** This method is based on the 36718 * [spread operator](https://mdn.io/spread_operator). 36719 * 36720 * @static 36721 * @memberOf _ 36722 * @since 3.2.0 36723 * @category Function 36724 * @param {Function} func The function to spread arguments over. 36725 * @param {number} [start=0] The start position of the spread. 36726 * @returns {Function} Returns the new function. 36727 * @example 36728 * 36729 * var say = _.spread(function(who, what) { 36730 * return who + ' says ' + what; 36731 * }); 36732 * 36733 * say(['fred', 'hello']); 36734 * // => 'fred says hello' 36735 * 36736 * var numbers = Promise.all([ 36737 * Promise.resolve(40), 36738 * Promise.resolve(36) 36739 * ]); 36740 * 36741 * numbers.then(_.spread(function(x, y) { 36742 * return x + y; 36743 * })); 36744 * // => a Promise of 76 36745 */ 36746 function spread(func, start) { 36747 if (typeof func != 'function') { 36748 throw new TypeError(FUNC_ERROR_TEXT); 36749 } 36750 start = start == null ? 0 : nativeMax(toInteger(start), 0); 36751 return baseRest(function(args) { 36752 var array = args[start], 36753 otherArgs = castSlice(args, 0, start); 36754 36755 if (array) { 36756 arrayPush(otherArgs, array); 36757 } 36758 return apply(func, this, otherArgs); 36759 }); 36760 } 36761 36762 /** 36763 * Creates a throttled function that only invokes `func` at most once per 36764 * every `wait` milliseconds. The throttled function comes with a `cancel` 36765 * method to cancel delayed `func` invocations and a `flush` method to 36766 * immediately invoke them. Provide `options` to indicate whether `func` 36767 * should be invoked on the leading and/or trailing edge of the `wait` 36768 * timeout. The `func` is invoked with the last arguments provided to the 36769 * throttled function. Subsequent calls to the throttled function return the 36770 * result of the last `func` invocation. 36771 * 36772 * **Note:** If `leading` and `trailing` options are `true`, `func` is 36773 * invoked on the trailing edge of the timeout only if the throttled function 36774 * is invoked more than once during the `wait` timeout. 36775 * 36776 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred 36777 * until to the next tick, similar to `setTimeout` with a timeout of `0`. 36778 * 36779 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) 36780 * for details over the differences between `_.throttle` and `_.debounce`. 36781 * 36782 * @static 36783 * @memberOf _ 36784 * @since 0.1.0 36785 * @category Function 36786 * @param {Function} func The function to throttle. 36787 * @param {number} [wait=0] The number of milliseconds to throttle invocations to. 36788 * @param {Object} [options={}] The options object. 36789 * @param {boolean} [options.leading=true] 36790 * Specify invoking on the leading edge of the timeout. 36791 * @param {boolean} [options.trailing=true] 36792 * Specify invoking on the trailing edge of the timeout. 36793 * @returns {Function} Returns the new throttled function. 36794 * @example 36795 * 36796 * // Avoid excessively updating the position while scrolling. 36797 * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); 36798 * 36799 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. 36800 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); 36801 * jQuery(element).on('click', throttled); 36802 * 36803 * // Cancel the trailing throttled invocation. 36804 * jQuery(window).on('popstate', throttled.cancel); 36805 */ 36806 function throttle(func, wait, options) { 36807 var leading = true, 36808 trailing = true; 36809 36810 if (typeof func != 'function') { 36811 throw new TypeError(FUNC_ERROR_TEXT); 36812 } 36813 if (isObject(options)) { 36814 leading = 'leading' in options ? !!options.leading : leading; 36815 trailing = 'trailing' in options ? !!options.trailing : trailing; 36816 } 36817 return debounce(func, wait, { 36818 'leading': leading, 36819 'maxWait': wait, 36820 'trailing': trailing 36821 }); 36822 } 36823 36824 /** 36825 * Creates a function that accepts up to one argument, ignoring any 36826 * additional arguments. 36827 * 36828 * @static 36829 * @memberOf _ 36830 * @since 4.0.0 36831 * @category Function 36832 * @param {Function} func The function to cap arguments for. 36833 * @returns {Function} Returns the new capped function. 36834 * @example 36835 * 36836 * _.map(['6', '8', '10'], _.unary(parseInt)); 36837 * // => [6, 8, 10] 36838 */ 36839 function unary(func) { 36840 return ary(func, 1); 36841 } 36842 36843 /** 36844 * Creates a function that provides `value` to `wrapper` as its first 36845 * argument. Any additional arguments provided to the function are appended 36846 * to those provided to the `wrapper`. The wrapper is invoked with the `this` 36847 * binding of the created function. 36848 * 36849 * @static 36850 * @memberOf _ 36851 * @since 0.1.0 36852 * @category Function 36853 * @param {*} value The value to wrap. 36854 * @param {Function} [wrapper=identity] The wrapper function. 36855 * @returns {Function} Returns the new function. 36856 * @example 36857 * 36858 * var p = _.wrap(_.escape, function(func, text) { 36859 * return '<p>' + func(text) + '</p>'; 36860 * }); 36861 * 36862 * p('fred, barney, & pebbles'); 36863 * // => '<p>fred, barney, & pebbles</p>' 36864 */ 36865 function wrap(value, wrapper) { 36866 return partial(castFunction(wrapper), value); 36867 } 36868 36869 /*------------------------------------------------------------------------*/ 36870 36871 /** 36872 * Casts `value` as an array if it's not one. 36873 * 36874 * @static 36875 * @memberOf _ 36876 * @since 4.4.0 36877 * @category Lang 36878 * @param {*} value The value to inspect. 36879 * @returns {Array} Returns the cast array. 36880 * @example 36881 * 36882 * _.castArray(1); 36883 * // => [1] 36884 * 36885 * _.castArray({ 'a': 1 }); 36886 * // => [{ 'a': 1 }] 36887 * 36888 * _.castArray('abc'); 36889 * // => ['abc'] 36890 * 36891 * _.castArray(null); 36892 * // => [null] 36893 * 36894 * _.castArray(undefined); 36895 * // => [undefined] 36896 * 36897 * _.castArray(); 36898 * // => [] 36899 * 36900 * var array = [1, 2, 3]; 36901 * console.log(_.castArray(array) === array); 36902 * // => true 36903 */ 36904 function castArray() { 36905 if (!arguments.length) { 36906 return []; 36907 } 36908 var value = arguments[0]; 36909 return isArray(value) ? value : [value]; 36910 } 36911 36912 /** 36913 * Creates a shallow clone of `value`. 36914 * 36915 * **Note:** This method is loosely based on the 36916 * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) 36917 * and supports cloning arrays, array buffers, booleans, date objects, maps, 36918 * numbers, `Object` objects, regexes, sets, strings, symbols, and typed 36919 * arrays. The own enumerable properties of `arguments` objects are cloned 36920 * as plain objects. An empty object is returned for uncloneable values such 36921 * as error objects, functions, DOM nodes, and WeakMaps. 36922 * 36923 * @static 36924 * @memberOf _ 36925 * @since 0.1.0 36926 * @category Lang 36927 * @param {*} value The value to clone. 36928 * @returns {*} Returns the cloned value. 36929 * @see _.cloneDeep 36930 * @example 36931 * 36932 * var objects = [{ 'a': 1 }, { 'b': 2 }]; 36933 * 36934 * var shallow = _.clone(objects); 36935 * console.log(shallow[0] === objects[0]); 36936 * // => true 36937 */ 36938 function clone(value) { 36939 return baseClone(value, CLONE_SYMBOLS_FLAG); 36940 } 36941 36942 /** 36943 * This method is like `_.clone` except that it accepts `customizer` which 36944 * is invoked to produce the cloned value. If `customizer` returns `undefined`, 36945 * cloning is handled by the method instead. The `customizer` is invoked with 36946 * up to four arguments; (value [, index|key, object, stack]). 36947 * 36948 * @static 36949 * @memberOf _ 36950 * @since 4.0.0 36951 * @category Lang 36952 * @param {*} value The value to clone. 36953 * @param {Function} [customizer] The function to customize cloning. 36954 * @returns {*} Returns the cloned value. 36955 * @see _.cloneDeepWith 36956 * @example 36957 * 36958 * function customizer(value) { 36959 * if (_.isElement(value)) { 36960 * return value.cloneNode(false); 36961 * } 36962 * } 36963 * 36964 * var el = _.cloneWith(document.body, customizer); 36965 * 36966 * console.log(el === document.body); 36967 * // => false 36968 * console.log(el.nodeName); 36969 * // => 'BODY' 36970 * console.log(el.childNodes.length); 36971 * // => 0 36972 */ 36973 function cloneWith(value, customizer) { 36974 customizer = typeof customizer == 'function' ? customizer : undefined; 36975 return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); 36976 } 36977 36978 /** 36979 * This method is like `_.clone` except that it recursively clones `value`. 36980 * 36981 * @static 36982 * @memberOf _ 36983 * @since 1.0.0 36984 * @category Lang 36985 * @param {*} value The value to recursively clone. 36986 * @returns {*} Returns the deep cloned value. 36987 * @see _.clone 36988 * @example 36989 * 36990 * var objects = [{ 'a': 1 }, { 'b': 2 }]; 36991 * 36992 * var deep = _.cloneDeep(objects); 36993 * console.log(deep[0] === objects[0]); 36994 * // => false 36995 */ 36996 function cloneDeep(value) { 36997 return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); 36998 } 36999 37000 /** 37001 * This method is like `_.cloneWith` except that it recursively clones `value`. 37002 * 37003 * @static 37004 * @memberOf _ 37005 * @since 4.0.0 37006 * @category Lang 37007 * @param {*} value The value to recursively clone. 37008 * @param {Function} [customizer] The function to customize cloning. 37009 * @returns {*} Returns the deep cloned value. 37010 * @see _.cloneWith 37011 * @example 37012 * 37013 * function customizer(value) { 37014 * if (_.isElement(value)) { 37015 * return value.cloneNode(true); 37016 * } 37017 * } 37018 * 37019 * var el = _.cloneDeepWith(document.body, customizer); 37020 * 37021 * console.log(el === document.body); 37022 * // => false 37023 * console.log(el.nodeName); 37024 * // => 'BODY' 37025 * console.log(el.childNodes.length); 37026 * // => 20 37027 */ 37028 function cloneDeepWith(value, customizer) { 37029 customizer = typeof customizer == 'function' ? customizer : undefined; 37030 return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); 37031 } 37032 37033 /** 37034 * Checks if `object` conforms to `source` by invoking the predicate 37035 * properties of `source` with the corresponding property values of `object`. 37036 * 37037 * **Note:** This method is equivalent to `_.conforms` when `source` is 37038 * partially applied. 37039 * 37040 * @static 37041 * @memberOf _ 37042 * @since 4.14.0 37043 * @category Lang 37044 * @param {Object} object The object to inspect. 37045 * @param {Object} source The object of property predicates to conform to. 37046 * @returns {boolean} Returns `true` if `object` conforms, else `false`. 37047 * @example 37048 * 37049 * var object = { 'a': 1, 'b': 2 }; 37050 * 37051 * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); 37052 * // => true 37053 * 37054 * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); 37055 * // => false 37056 */ 37057 function conformsTo(object, source) { 37058 return source == null || baseConformsTo(object, source, keys(source)); 37059 } 37060 37061 /** 37062 * Performs a 37063 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) 37064 * comparison between two values to determine if they are equivalent. 37065 * 37066 * @static 37067 * @memberOf _ 37068 * @since 4.0.0 37069 * @category Lang 37070 * @param {*} value The value to compare. 37071 * @param {*} other The other value to compare. 37072 * @returns {boolean} Returns `true` if the values are equivalent, else `false`. 37073 * @example 37074 * 37075 * var object = { 'a': 1 }; 37076 * var other = { 'a': 1 }; 37077 * 37078 * _.eq(object, object); 37079 * // => true 37080 * 37081 * _.eq(object, other); 37082 * // => false 37083 * 37084 * _.eq('a', 'a'); 37085 * // => true 37086 * 37087 * _.eq('a', Object('a')); 37088 * // => false 37089 * 37090 * _.eq(NaN, NaN); 37091 * // => true 37092 */ 37093 function eq(value, other) { 37094 return value === other || (value !== value && other !== other); 37095 } 37096 37097 /** 37098 * Checks if `value` is greater than `other`. 37099 * 37100 * @static 37101 * @memberOf _ 37102 * @since 3.9.0 37103 * @category Lang 37104 * @param {*} value The value to compare. 37105 * @param {*} other The other value to compare. 37106 * @returns {boolean} Returns `true` if `value` is greater than `other`, 37107 * else `false`. 37108 * @see _.lt 37109 * @example 37110 * 37111 * _.gt(3, 1); 37112 * // => true 37113 * 37114 * _.gt(3, 3); 37115 * // => false 37116 * 37117 * _.gt(1, 3); 37118 * // => false 37119 */ 37120 var gt = createRelationalOperation(baseGt); 37121 37122 /** 37123 * Checks if `value` is greater than or equal to `other`. 37124 * 37125 * @static 37126 * @memberOf _ 37127 * @since 3.9.0 37128 * @category Lang 37129 * @param {*} value The value to compare. 37130 * @param {*} other The other value to compare. 37131 * @returns {boolean} Returns `true` if `value` is greater than or equal to 37132 * `other`, else `false`. 37133 * @see _.lte 37134 * @example 37135 * 37136 * _.gte(3, 1); 37137 * // => true 37138 * 37139 * _.gte(3, 3); 37140 * // => true 37141 * 37142 * _.gte(1, 3); 37143 * // => false 37144 */ 37145 var gte = createRelationalOperation(function(value, other) { 37146 return value >= other; 37147 }); 37148 37149 /** 37150 * Checks if `value` is likely an `arguments` object. 37151 * 37152 * @static 37153 * @memberOf _ 37154 * @since 0.1.0 37155 * @category Lang 37156 * @param {*} value The value to check. 37157 * @returns {boolean} Returns `true` if `value` is an `arguments` object, 37158 * else `false`. 37159 * @example 37160 * 37161 * _.isArguments(function() { return arguments; }()); 37162 * // => true 37163 * 37164 * _.isArguments([1, 2, 3]); 37165 * // => false 37166 */ 37167 var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { 37168 return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && 37169 !propertyIsEnumerable.call(value, 'callee'); 37170 }; 37171 37172 /** 37173 * Checks if `value` is classified as an `Array` object. 37174 * 37175 * @static 37176 * @memberOf _ 37177 * @since 0.1.0 37178 * @category Lang 37179 * @param {*} value The value to check. 37180 * @returns {boolean} Returns `true` if `value` is an array, else `false`. 37181 * @example 37182 * 37183 * _.isArray([1, 2, 3]); 37184 * // => true 37185 * 37186 * _.isArray(document.body.children); 37187 * // => false 37188 * 37189 * _.isArray('abc'); 37190 * // => false 37191 * 37192 * _.isArray(_.noop); 37193 * // => false 37194 */ 37195 var isArray = Array.isArray; 37196 37197 /** 37198 * Checks if `value` is classified as an `ArrayBuffer` object. 37199 * 37200 * @static 37201 * @memberOf _ 37202 * @since 4.3.0 37203 * @category Lang 37204 * @param {*} value The value to check. 37205 * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. 37206 * @example 37207 * 37208 * _.isArrayBuffer(new ArrayBuffer(2)); 37209 * // => true 37210 * 37211 * _.isArrayBuffer(new Array(2)); 37212 * // => false 37213 */ 37214 var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; 37215 37216 /** 37217 * Checks if `value` is array-like. A value is considered array-like if it's 37218 * not a function and has a `value.length` that's an integer greater than or 37219 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. 37220 * 37221 * @static 37222 * @memberOf _ 37223 * @since 4.0.0 37224 * @category Lang 37225 * @param {*} value The value to check. 37226 * @returns {boolean} Returns `true` if `value` is array-like, else `false`. 37227 * @example 37228 * 37229 * _.isArrayLike([1, 2, 3]); 37230 * // => true 37231 * 37232 * _.isArrayLike(document.body.children); 37233 * // => true 37234 * 37235 * _.isArrayLike('abc'); 37236 * // => true 37237 * 37238 * _.isArrayLike(_.noop); 37239 * // => false 37240 */ 37241 function isArrayLike(value) { 37242 return value != null && isLength(value.length) && !isFunction(value); 37243 } 37244 37245 /** 37246 * This method is like `_.isArrayLike` except that it also checks if `value` 37247 * is an object. 37248 * 37249 * @static 37250 * @memberOf _ 37251 * @since 4.0.0 37252 * @category Lang 37253 * @param {*} value The value to check. 37254 * @returns {boolean} Returns `true` if `value` is an array-like object, 37255 * else `false`. 37256 * @example 37257 * 37258 * _.isArrayLikeObject([1, 2, 3]); 37259 * // => true 37260 * 37261 * _.isArrayLikeObject(document.body.children); 37262 * // => true 37263 * 37264 * _.isArrayLikeObject('abc'); 37265 * // => false 37266 * 37267 * _.isArrayLikeObject(_.noop); 37268 * // => false 37269 */ 37270 function isArrayLikeObject(value) { 37271 return isObjectLike(value) && isArrayLike(value); 37272 } 37273 37274 /** 37275 * Checks if `value` is classified as a boolean primitive or object. 37276 * 37277 * @static 37278 * @memberOf _ 37279 * @since 0.1.0 37280 * @category Lang 37281 * @param {*} value The value to check. 37282 * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. 37283 * @example 37284 * 37285 * _.isBoolean(false); 37286 * // => true 37287 * 37288 * _.isBoolean(null); 37289 * // => false 37290 */ 37291 function isBoolean(value) { 37292 return value === true || value === false || 37293 (isObjectLike(value) && baseGetTag(value) == boolTag); 37294 } 37295 37296 /** 37297 * Checks if `value` is a buffer. 37298 * 37299 * @static 37300 * @memberOf _ 37301 * @since 4.3.0 37302 * @category Lang 37303 * @param {*} value The value to check. 37304 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. 37305 * @example 37306 * 37307 * _.isBuffer(new Buffer(2)); 37308 * // => true 37309 * 37310 * _.isBuffer(new Uint8Array(2)); 37311 * // => false 37312 */ 37313 var isBuffer = nativeIsBuffer || stubFalse; 37314 37315 /** 37316 * Checks if `value` is classified as a `Date` object. 37317 * 37318 * @static 37319 * @memberOf _ 37320 * @since 0.1.0 37321 * @category Lang 37322 * @param {*} value The value to check. 37323 * @returns {boolean} Returns `true` if `value` is a date object, else `false`. 37324 * @example 37325 * 37326 * _.isDate(new Date); 37327 * // => true 37328 * 37329 * _.isDate('Mon April 23 2012'); 37330 * // => false 37331 */ 37332 var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; 37333 37334 /** 37335 * Checks if `value` is likely a DOM element. 37336 * 37337 * @static 37338 * @memberOf _ 37339 * @since 0.1.0 37340 * @category Lang 37341 * @param {*} value The value to check. 37342 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. 37343 * @example 37344 * 37345 * _.isElement(document.body); 37346 * // => true 37347 * 37348 * _.isElement('<body>'); 37349 * // => false 37350 */ 37351 function isElement(value) { 37352 return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); 37353 } 37354 37355 /** 37356 * Checks if `value` is an empty object, collection, map, or set. 37357 * 37358 * Objects are considered empty if they have no own enumerable string keyed 37359 * properties. 37360 * 37361 * Array-like values such as `arguments` objects, arrays, buffers, strings, or 37362 * jQuery-like collections are considered empty if they have a `length` of `0`. 37363 * Similarly, maps and sets are considered empty if they have a `size` of `0`. 37364 * 37365 * @static 37366 * @memberOf _ 37367 * @since 0.1.0 37368 * @category Lang 37369 * @param {*} value The value to check. 37370 * @returns {boolean} Returns `true` if `value` is empty, else `false`. 37371 * @example 37372 * 37373 * _.isEmpty(null); 37374 * // => true 37375 * 37376 * _.isEmpty(true); 37377 * // => true 37378 * 37379 * _.isEmpty(1); 37380 * // => true 37381 * 37382 * _.isEmpty([1, 2, 3]); 37383 * // => false 37384 * 37385 * _.isEmpty({ 'a': 1 }); 37386 * // => false 37387 */ 37388 function isEmpty(value) { 37389 if (value == null) { 37390 return true; 37391 } 37392 if (isArrayLike(value) && 37393 (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || 37394 isBuffer(value) || isTypedArray(value) || isArguments(value))) { 37395 return !value.length; 37396 } 37397 var tag = getTag(value); 37398 if (tag == mapTag || tag == setTag) { 37399 return !value.size; 37400 } 37401 if (isPrototype(value)) { 37402 return !baseKeys(value).length; 37403 } 37404 for (var key in value) { 37405 if (hasOwnProperty.call(value, key)) { 37406 return false; 37407 } 37408 } 37409 return true; 37410 } 37411 37412 /** 37413 * Performs a deep comparison between two values to determine if they are 37414 * equivalent. 37415 * 37416 * **Note:** This method supports comparing arrays, array buffers, booleans, 37417 * date objects, error objects, maps, numbers, `Object` objects, regexes, 37418 * sets, strings, symbols, and typed arrays. `Object` objects are compared 37419 * by their own, not inherited, enumerable properties. Functions and DOM 37420 * nodes are compared by strict equality, i.e. `===`. 37421 * 37422 * @static 37423 * @memberOf _ 37424 * @since 0.1.0 37425 * @category Lang 37426 * @param {*} value The value to compare. 37427 * @param {*} other The other value to compare. 37428 * @returns {boolean} Returns `true` if the values are equivalent, else `false`. 37429 * @example 37430 * 37431 * var object = { 'a': 1 }; 37432 * var other = { 'a': 1 }; 37433 * 37434 * _.isEqual(object, other); 37435 * // => true 37436 * 37437 * object === other; 37438 * // => false 37439 */ 37440 function isEqual(value, other) { 37441 return baseIsEqual(value, other); 37442 } 37443 37444 /** 37445 * This method is like `_.isEqual` except that it accepts `customizer` which 37446 * is invoked to compare values. If `customizer` returns `undefined`, comparisons 37447 * are handled by the method instead. The `customizer` is invoked with up to 37448 * six arguments: (objValue, othValue [, index|key, object, other, stack]). 37449 * 37450 * @static 37451 * @memberOf _ 37452 * @since 4.0.0 37453 * @category Lang 37454 * @param {*} value The value to compare. 37455 * @param {*} other The other value to compare. 37456 * @param {Function} [customizer] The function to customize comparisons. 37457 * @returns {boolean} Returns `true` if the values are equivalent, else `false`. 37458 * @example 37459 * 37460 * function isGreeting(value) { 37461 * return /^h(?:i|ello)$/.test(value); 37462 * } 37463 * 37464 * function customizer(objValue, othValue) { 37465 * if (isGreeting(objValue) && isGreeting(othValue)) { 37466 * return true; 37467 * } 37468 * } 37469 * 37470 * var array = ['hello', 'goodbye']; 37471 * var other = ['hi', 'goodbye']; 37472 * 37473 * _.isEqualWith(array, other, customizer); 37474 * // => true 37475 */ 37476 function isEqualWith(value, other, customizer) { 37477 customizer = typeof customizer == 'function' ? customizer : undefined; 37478 var result = customizer ? customizer(value, other) : undefined; 37479 return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; 37480 } 37481 37482 /** 37483 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, 37484 * `SyntaxError`, `TypeError`, or `URIError` object. 37485 * 37486 * @static 37487 * @memberOf _ 37488 * @since 3.0.0 37489 * @category Lang 37490 * @param {*} value The value to check. 37491 * @returns {boolean} Returns `true` if `value` is an error object, else `false`. 37492 * @example 37493 * 37494 * _.isError(new Error); 37495 * // => true 37496 * 37497 * _.isError(Error); 37498 * // => false 37499 */ 37500 function isError(value) { 37501 if (!isObjectLike(value)) { 37502 return false;
vendor: 6,607 bytes, lines 37503-37740
37503 } 37504 var tag = baseGetTag(value); 37505 return tag == errorTag || tag == domExcTag || 37506 (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); 37507 } 37508 37509 /** 37510 * Checks if `value` is a finite primitive number. 37511 * 37512 * **Note:** This method is based on 37513 * [`Number.isFinite`](https://mdn.io/Number/isFinite). 37514 * 37515 * @static 37516 * @memberOf _ 37517 * @since 0.1.0 37518 * @category Lang 37519 * @param {*} value The value to check. 37520 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. 37521 * @example 37522 * 37523 * _.isFinite(3); 37524 * // => true 37525 * 37526 * _.isFinite(Number.MIN_VALUE); 37527 * // => true 37528 * 37529 * _.isFinite(Infinity); 37530 * // => false 37531 * 37532 * _.isFinite('3'); 37533 * // => false 37534 */ 37535 function isFinite(value) { 37536 return typeof value == 'number' && nativeIsFinite(value); 37537 } 37538 37539 /** 37540 * Checks if `value` is classified as a `Function` object. 37541 * 37542 * @static 37543 * @memberOf _ 37544 * @since 0.1.0 37545 * @category Lang 37546 * @param {*} value The value to check. 37547 * @returns {boolean} Returns `true` if `value` is a function, else `false`. 37548 * @example 37549 * 37550 * _.isFunction(_); 37551 * // => true 37552 * 37553 * _.isFunction(/abc/); 37554 * // => false 37555 */ 37556 function isFunction(value) { 37557 if (!isObject(value)) { 37558 return false; 37559 } 37560 // The use of `Object#toString` avoids issues with the `typeof` operator 37561 // in Safari 9 which returns 'object' for typed arrays and other constructors. 37562 var tag = baseGetTag(value); 37563 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; 37564 } 37565 37566 /** 37567 * Checks if `value` is an integer. 37568 * 37569 * **Note:** This method is based on 37570 * [`Number.isInteger`](https://mdn.io/Number/isInteger). 37571 * 37572 * @static 37573 * @memberOf _ 37574 * @since 4.0.0 37575 * @category Lang 37576 * @param {*} value The value to check. 37577 * @returns {boolean} Returns `true` if `value` is an integer, else `false`. 37578 * @example 37579 * 37580 * _.isInteger(3); 37581 * // => true 37582 * 37583 * _.isInteger(Number.MIN_VALUE); 37584 * // => false 37585 * 37586 * _.isInteger(Infinity); 37587 * // => false 37588 * 37589 * _.isInteger('3'); 37590 * // => false 37591 */ 37592 function isInteger(value) { 37593 return typeof value == 'number' && value == toInteger(value); 37594 } 37595 37596 /** 37597 * Checks if `value` is a valid array-like length. 37598 * 37599 * **Note:** This method is loosely based on 37600 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). 37601 * 37602 * @static 37603 * @memberOf _ 37604 * @since 4.0.0 37605 * @category Lang 37606 * @param {*} value The value to check. 37607 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. 37608 * @example 37609 * 37610 * _.isLength(3); 37611 * // => true 37612 * 37613 * _.isLength(Number.MIN_VALUE); 37614 * // => false 37615 * 37616 * _.isLength(Infinity); 37617 * // => false 37618 * 37619 * _.isLength('3'); 37620 * // => false 37621 */ 37622 function isLength(value) { 37623 return typeof value == 'number' && 37624 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; 37625 } 37626 37627 /** 37628 * Checks if `value` is the 37629 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) 37630 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) 37631 * 37632 * @static 37633 * @memberOf _ 37634 * @since 0.1.0 37635 * @category Lang 37636 * @param {*} value The value to check. 37637 * @returns {boolean} Returns `true` if `value` is an object, else `false`. 37638 * @example 37639 * 37640 * _.isObject({}); 37641 * // => true 37642 * 37643 * _.isObject([1, 2, 3]); 37644 * // => true 37645 * 37646 * _.isObject(_.noop); 37647 * // => true 37648 * 37649 * _.isObject(null); 37650 * // => false 37651 */ 37652 function isObject(value) { 37653 var type = typeof value; 37654 return value != null && (type == 'object' || type == 'function'); 37655 } 37656 37657 /** 37658 * Checks if `value` is object-like. A value is object-like if it's not `null` 37659 * and has a `typeof` result of "object". 37660 * 37661 * @static 37662 * @memberOf _ 37663 * @since 4.0.0 37664 * @category Lang 37665 * @param {*} value The value to check. 37666 * @returns {boolean} Returns `true` if `value` is object-like, else `false`. 37667 * @example 37668 * 37669 * _.isObjectLike({}); 37670 * // => true 37671 * 37672 * _.isObjectLike([1, 2, 3]); 37673 * // => true 37674 * 37675 * _.isObjectLike(_.noop); 37676 * // => false 37677 * 37678 * _.isObjectLike(null); 37679 * // => false 37680 */ 37681 function isObjectLike(value) { 37682 return value != null && typeof value == 'object'; 37683 } 37684 37685 /** 37686 * Checks if `value` is classified as a `Map` object. 37687 * 37688 * @static 37689 * @memberOf _ 37690 * @since 4.3.0 37691 * @category Lang 37692 * @param {*} value The value to check. 37693 * @returns {boolean} Returns `true` if `value` is a map, else `false`. 37694 * @example 37695 * 37696 * _.isMap(new Map); 37697 * // => true 37698 * 37699 * _.isMap(new WeakMap); 37700 * // => false 37701 */ 37702 var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; 37703 37704 /** 37705 * Performs a partial deep comparison between `object` and `source` to 37706 * determine if `object` contains equivalent property values. 37707 * 37708 * **Note:** This method is equivalent to `_.matches` when `source` is 37709 * partially applied. 37710 * 37711 * Partial comparisons will match empty array and empty object `source` 37712 * values against any array or object value, respectively. See `_.isEqual` 37713 * for a list of supported value comparisons. 37714 * 37715 * @static 37716 * @memberOf _ 37717 * @since 3.0.0 37718 * @category Lang 37719 * @param {Object} object The object to inspect. 37720 * @param {Object} source The object of property values to match. 37721 * @returns {boolean} Returns `true` if `object` is a match, else `false`. 37722 * @example 37723 * 37724 * var object = { 'a': 1, 'b': 2 }; 37725 * 37726 * _.isMatch(object, { 'b': 2 }); 37727 * // => true 37728 * 37729 * _.isMatch(object, { 'b': 1 }); 37730 * // => false 37731 */ 37732 function isMatch(object, source) { 37733 return object === source || baseIsMatch(object, source, getMatchData(source)); 37734 } 37735 37736 /** 37737 * This method is like `_.isMatch` except that it accepts `customizer` which 37738 * is invoked to compare values. If `customizer` returns `undefined`, comparisons 37739 * are handled by the method instead. The `customizer` is invoked with five 37740 * arguments: (objValue, srcValue, index|key, object, source).
vendor: 12,241 bytes, lines 37741-38206
37741 * 37742 * @static 37743 * @memberOf _ 37744 * @since 4.0.0 37745 * @category Lang 37746 * @param {Object} object The object to inspect. 37747 * @param {Object} source The object of property values to match. 37748 * @param {Function} [customizer] The function to customize comparisons. 37749 * @returns {boolean} Returns `true` if `object` is a match, else `false`. 37750 * @example 37751 * 37752 * function isGreeting(value) { 37753 * return /^h(?:i|ello)$/.test(value); 37754 * } 37755 * 37756 * function customizer(objValue, srcValue) { 37757 * if (isGreeting(objValue) && isGreeting(srcValue)) { 37758 * return true; 37759 * } 37760 * } 37761 * 37762 * var object = { 'greeting': 'hello' }; 37763 * var source = { 'greeting': 'hi' }; 37764 * 37765 * _.isMatchWith(object, source, customizer); 37766 * // => true 37767 */ 37768 function isMatchWith(object, source, customizer) { 37769 customizer = typeof customizer == 'function' ? customizer : undefined; 37770 return baseIsMatch(object, source, getMatchData(source), customizer); 37771 } 37772 37773 /** 37774 * Checks if `value` is `NaN`. 37775 * 37776 * **Note:** This method is based on 37777 * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as 37778 * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for 37779 * `undefined` and other non-number values. 37780 * 37781 * @static 37782 * @memberOf _ 37783 * @since 0.1.0 37784 * @category Lang 37785 * @param {*} value The value to check. 37786 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. 37787 * @example 37788 * 37789 * _.isNaN(NaN); 37790 * // => true 37791 * 37792 * _.isNaN(new Number(NaN)); 37793 * // => true 37794 * 37795 * isNaN(undefined); 37796 * // => true 37797 * 37798 * _.isNaN(undefined); 37799 * // => false 37800 */ 37801 function isNaN(value) { 37802 // An `NaN` primitive is the only value that is not equal to itself. 37803 // Perform the `toStringTag` check first to avoid errors with some 37804 // ActiveX objects in IE. 37805 return isNumber(value) && value != +value; 37806 } 37807 37808 /** 37809 * Checks if `value` is a pristine native function. 37810 * 37811 * **Note:** This method can't reliably detect native functions in the presence 37812 * of the core-js package because core-js circumvents this kind of detection. 37813 * Despite multiple requests, the core-js maintainer has made it clear: any 37814 * attempt to fix the detection will be obstructed. As a result, we're left 37815 * with little choice but to throw an error. Unfortunately, this also affects 37816 * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), 37817 * which rely on core-js. 37818 * 37819 * @static 37820 * @memberOf _ 37821 * @since 3.0.0 37822 * @category Lang 37823 * @param {*} value The value to check. 37824 * @returns {boolean} Returns `true` if `value` is a native function, 37825 * else `false`. 37826 * @example 37827 * 37828 * _.isNative(Array.prototype.push); 37829 * // => true 37830 * 37831 * _.isNative(_); 37832 * // => false 37833 */ 37834 function isNative(value) { 37835 if (isMaskable(value)) { 37836 throw new Error(CORE_ERROR_TEXT); 37837 } 37838 return baseIsNative(value); 37839 } 37840 37841 /** 37842 * Checks if `value` is `null`. 37843 * 37844 * @static 37845 * @memberOf _ 37846 * @since 0.1.0 37847 * @category Lang 37848 * @param {*} value The value to check. 37849 * @returns {boolean} Returns `true` if `value` is `null`, else `false`. 37850 * @example 37851 * 37852 * _.isNull(null); 37853 * // => true 37854 * 37855 * _.isNull(void 0); 37856 * // => false 37857 */ 37858 function isNull(value) { 37859 return value === null; 37860 } 37861 37862 /** 37863 * Checks if `value` is `null` or `undefined`. 37864 * 37865 * @static 37866 * @memberOf _ 37867 * @since 4.0.0 37868 * @category Lang 37869 * @param {*} value The value to check. 37870 * @returns {boolean} Returns `true` if `value` is nullish, else `false`. 37871 * @example 37872 * 37873 * _.isNil(null); 37874 * // => true 37875 * 37876 * _.isNil(void 0); 37877 * // => true 37878 * 37879 * _.isNil(NaN); 37880 * // => false 37881 */ 37882 function isNil(value) { 37883 return value == null; 37884 } 37885 37886 /** 37887 * Checks if `value` is classified as a `Number` primitive or object. 37888 * 37889 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are 37890 * classified as numbers, use the `_.isFinite` method. 37891 * 37892 * @static 37893 * @memberOf _ 37894 * @since 0.1.0 37895 * @category Lang 37896 * @param {*} value The value to check. 37897 * @returns {boolean} Returns `true` if `value` is a number, else `false`. 37898 * @example 37899 * 37900 * _.isNumber(3); 37901 * // => true 37902 * 37903 * _.isNumber(Number.MIN_VALUE); 37904 * // => true 37905 * 37906 * _.isNumber(Infinity); 37907 * // => true 37908 * 37909 * _.isNumber('3'); 37910 * // => false 37911 */ 37912 function isNumber(value) { 37913 return typeof value == 'number' || 37914 (isObjectLike(value) && baseGetTag(value) == numberTag); 37915 } 37916 37917 /** 37918 * Checks if `value` is a plain object, that is, an object created by the 37919 * `Object` constructor or one with a `[[Prototype]]` of `null`. 37920 * 37921 * @static 37922 * @memberOf _ 37923 * @since 0.8.0 37924 * @category Lang 37925 * @param {*} value The value to check. 37926 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. 37927 * @example 37928 * 37929 * function Foo() { 37930 * this.a = 1; 37931 * } 37932 * 37933 * _.isPlainObject(new Foo); 37934 * // => false 37935 * 37936 * _.isPlainObject([1, 2, 3]); 37937 * // => false 37938 * 37939 * _.isPlainObject({ 'x': 0, 'y': 0 }); 37940 * // => true 37941 * 37942 * _.isPlainObject(Object.create(null)); 37943 * // => true 37944 */ 37945 function isPlainObject(value) { 37946 if (!isObjectLike(value) || baseGetTag(value) != objectTag) { 37947 return false; 37948 } 37949 var proto = getPrototype(value); 37950 if (proto === null) { 37951 return true; 37952 } 37953 var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; 37954 return typeof Ctor == 'function' && Ctor instanceof Ctor && 37955 funcToString.call(Ctor) == objectCtorString; 37956 } 37957 37958 /** 37959 * Checks if `value` is classified as a `RegExp` object. 37960 * 37961 * @static 37962 * @memberOf _ 37963 * @since 0.1.0 37964 * @category Lang 37965 * @param {*} value The value to check. 37966 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. 37967 * @example 37968 * 37969 * _.isRegExp(/abc/); 37970 * // => true 37971 * 37972 * _.isRegExp('/abc/'); 37973 * // => false 37974 */ 37975 var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; 37976 37977 /** 37978 * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 37979 * double precision number which isn't the result of a rounded unsafe integer. 37980 * 37981 * **Note:** This method is based on 37982 * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). 37983 * 37984 * @static 37985 * @memberOf _ 37986 * @since 4.0.0 37987 * @category Lang 37988 * @param {*} value The value to check. 37989 * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. 37990 * @example 37991 * 37992 * _.isSafeInteger(3); 37993 * // => true 37994 * 37995 * _.isSafeInteger(Number.MIN_VALUE); 37996 * // => false 37997 * 37998 * _.isSafeInteger(Infinity); 37999 * // => false 38000 * 38001 * _.isSafeInteger('3'); 38002 * // => false 38003 */ 38004 function isSafeInteger(value) { 38005 return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; 38006 } 38007 38008 /** 38009 * Checks if `value` is classified as a `Set` object. 38010 * 38011 * @static 38012 * @memberOf _ 38013 * @since 4.3.0 38014 * @category Lang 38015 * @param {*} value The value to check. 38016 * @returns {boolean} Returns `true` if `value` is a set, else `false`. 38017 * @example 38018 * 38019 * _.isSet(new Set); 38020 * // => true 38021 * 38022 * _.isSet(new WeakSet); 38023 * // => false 38024 */ 38025 var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; 38026 38027 /** 38028 * Checks if `value` is classified as a `String` primitive or object. 38029 * 38030 * @static 38031 * @since 0.1.0 38032 * @memberOf _ 38033 * @category Lang 38034 * @param {*} value The value to check. 38035 * @returns {boolean} Returns `true` if `value` is a string, else `false`. 38036 * @example 38037 * 38038 * _.isString('abc'); 38039 * // => true 38040 * 38041 * _.isString(1); 38042 * // => false 38043 */ 38044 function isString(value) { 38045 return typeof value == 'string' || 38046 (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); 38047 } 38048 38049 /** 38050 * Checks if `value` is classified as a `Symbol` primitive or object. 38051 * 38052 * @static 38053 * @memberOf _ 38054 * @since 4.0.0 38055 * @category Lang 38056 * @param {*} value The value to check. 38057 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. 38058 * @example 38059 * 38060 * _.isSymbol(Symbol.iterator); 38061 * // => true 38062 * 38063 * _.isSymbol('abc'); 38064 * // => false 38065 */ 38066 function isSymbol(value) { 38067 return typeof value == 'symbol' || 38068 (isObjectLike(value) && baseGetTag(value) == symbolTag); 38069 } 38070 38071 /** 38072 * Checks if `value` is classified as a typed array. 38073 * 38074 * @static 38075 * @memberOf _ 38076 * @since 3.0.0 38077 * @category Lang 38078 * @param {*} value The value to check. 38079 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. 38080 * @example 38081 * 38082 * _.isTypedArray(new Uint8Array); 38083 * // => true 38084 * 38085 * _.isTypedArray([]); 38086 * // => false 38087 */ 38088 var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; 38089 38090 /** 38091 * Checks if `value` is `undefined`. 38092 * 38093 * @static 38094 * @since 0.1.0 38095 * @memberOf _ 38096 * @category Lang 38097 * @param {*} value The value to check. 38098 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. 38099 * @example 38100 * 38101 * _.isUndefined(void 0); 38102 * // => true 38103 * 38104 * _.isUndefined(null); 38105 * // => false 38106 */ 38107 function isUndefined(value) { 38108 return value === undefined; 38109 } 38110 38111 /** 38112 * Checks if `value` is classified as a `WeakMap` object. 38113 * 38114 * @static 38115 * @memberOf _ 38116 * @since 4.3.0 38117 * @category Lang 38118 * @param {*} value The value to check. 38119 * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. 38120 * @example 38121 * 38122 * _.isWeakMap(new WeakMap); 38123 * // => true 38124 * 38125 * _.isWeakMap(new Map); 38126 * // => false 38127 */ 38128 function isWeakMap(value) { 38129 return isObjectLike(value) && getTag(value) == weakMapTag; 38130 } 38131 38132 /** 38133 * Checks if `value` is classified as a `WeakSet` object. 38134 * 38135 * @static 38136 * @memberOf _ 38137 * @since 4.3.0 38138 * @category Lang 38139 * @param {*} value The value to check. 38140 * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. 38141 * @example 38142 * 38143 * _.isWeakSet(new WeakSet); 38144 * // => true 38145 * 38146 * _.isWeakSet(new Set); 38147 * // => false 38148 */ 38149 function isWeakSet(value) { 38150 return isObjectLike(value) && baseGetTag(value) == weakSetTag; 38151 } 38152 38153 /** 38154 * Checks if `value` is less than `other`. 38155 * 38156 * @static 38157 * @memberOf _ 38158 * @since 3.9.0 38159 * @category Lang 38160 * @param {*} value The value to compare. 38161 * @param {*} other The other value to compare. 38162 * @returns {boolean} Returns `true` if `value` is less than `other`, 38163 * else `false`. 38164 * @see _.gt 38165 * @example 38166 * 38167 * _.lt(1, 3); 38168 * // => true 38169 * 38170 * _.lt(3, 3); 38171 * // => false 38172 * 38173 * _.lt(3, 1); 38174 * // => false 38175 */ 38176 var lt = createRelationalOperation(baseLt); 38177 38178 /** 38179 * Checks if `value` is less than or equal to `other`. 38180 * 38181 * @static 38182 * @memberOf _ 38183 * @since 3.9.0 38184 * @category Lang 38185 * @param {*} value The value to compare. 38186 * @param {*} other The other value to compare. 38187 * @returns {boolean} Returns `true` if `value` is less than or equal to 38188 * `other`, else `false`. 38189 * @see _.gte 38190 * @example 38191 * 38192 * _.lte(1, 3); 38193 * // => true 38194 * 38195 * _.lte(3, 3); 38196 * // => true 38197 * 38198 * _.lte(3, 1); 38199 * // => false 38200 */ 38201 var lte = createRelationalOperation(function(value, other) { 38202 return value <= other; 38203 }); 38204 38205 /** 38206 * Converts `value` to an array.
vendor: 4,495 bytes, lines 38207-38388
38207 * 38208 * @static 38209 * @since 0.1.0 38210 * @memberOf _ 38211 * @category Lang 38212 * @param {*} value The value to convert. 38213 * @returns {Array} Returns the converted array. 38214 * @example 38215 * 38216 * _.toArray({ 'a': 1, 'b': 2 }); 38217 * // => [1, 2] 38218 * 38219 * _.toArray('abc'); 38220 * // => ['a', 'b', 'c'] 38221 * 38222 * _.toArray(1); 38223 * // => [] 38224 * 38225 * _.toArray(null); 38226 * // => [] 38227 */ 38228 function toArray(value) { 38229 if (!value) { 38230 return []; 38231 } 38232 if (isArrayLike(value)) { 38233 return isString(value) ? stringToArray(value) : copyArray(value); 38234 } 38235 if (symIterator && value[symIterator]) { 38236 return iteratorToArray(value[symIterator]()); 38237 } 38238 var tag = getTag(value), 38239 func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); 38240 38241 return func(value); 38242 } 38243 38244 /** 38245 * Converts `value` to a finite number. 38246 * 38247 * @static 38248 * @memberOf _ 38249 * @since 4.12.0 38250 * @category Lang 38251 * @param {*} value The value to convert. 38252 * @returns {number} Returns the converted number. 38253 * @example 38254 * 38255 * _.toFinite(3.2); 38256 * // => 3.2 38257 * 38258 * _.toFinite(Number.MIN_VALUE); 38259 * // => 5e-324 38260 * 38261 * _.toFinite(Infinity); 38262 * // => 1.7976931348623157e+308 38263 * 38264 * _.toFinite('3.2'); 38265 * // => 3.2 38266 */ 38267 function toFinite(value) { 38268 if (!value) { 38269 return value === 0 ? value : 0; 38270 } 38271 value = toNumber(value); 38272 if (value === INFINITY || value === -INFINITY) { 38273 var sign = (value < 0 ? -1 : 1); 38274 return sign * MAX_INTEGER; 38275 } 38276 return value === value ? value : 0; 38277 } 38278 38279 /** 38280 * Converts `value` to an integer. 38281 * 38282 * **Note:** This method is loosely based on 38283 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). 38284 * 38285 * @static 38286 * @memberOf _ 38287 * @since 4.0.0 38288 * @category Lang 38289 * @param {*} value The value to convert. 38290 * @returns {number} Returns the converted integer. 38291 * @example 38292 * 38293 * _.toInteger(3.2); 38294 * // => 3 38295 * 38296 * _.toInteger(Number.MIN_VALUE); 38297 * // => 0 38298 * 38299 * _.toInteger(Infinity); 38300 * // => 1.7976931348623157e+308 38301 * 38302 * _.toInteger('3.2'); 38303 * // => 3 38304 */ 38305 function toInteger(value) { 38306 var result = toFinite(value), 38307 remainder = result % 1; 38308 38309 return result === result ? (remainder ? result - remainder : result) : 0; 38310 } 38311 38312 /** 38313 * Converts `value` to an integer suitable for use as the length of an 38314 * array-like object. 38315 * 38316 * **Note:** This method is based on 38317 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). 38318 * 38319 * @static 38320 * @memberOf _ 38321 * @since 4.0.0 38322 * @category Lang 38323 * @param {*} value The value to convert. 38324 * @returns {number} Returns the converted integer. 38325 * @example 38326 * 38327 * _.toLength(3.2); 38328 * // => 3 38329 * 38330 * _.toLength(Number.MIN_VALUE); 38331 * // => 0 38332 * 38333 * _.toLength(Infinity); 38334 * // => 4294967295 38335 * 38336 * _.toLength('3.2'); 38337 * // => 3 38338 */ 38339 function toLength(value) { 38340 return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; 38341 } 38342 38343 /** 38344 * Converts `value` to a number. 38345 * 38346 * @static 38347 * @memberOf _ 38348 * @since 4.0.0 38349 * @category Lang 38350 * @param {*} value The value to process. 38351 * @returns {number} Returns the number. 38352 * @example 38353 * 38354 * _.toNumber(3.2); 38355 * // => 3.2 38356 * 38357 * _.toNumber(Number.MIN_VALUE); 38358 * // => 5e-324 38359 * 38360 * _.toNumber(Infinity); 38361 * // => Infinity 38362 * 38363 * _.toNumber('3.2'); 38364 * // => 3.2 38365 */ 38366 function toNumber(value) { 38367 if (typeof value == 'number') { 38368 return value; 38369 } 38370 if (isSymbol(value)) { 38371 return NAN; 38372 } 38373 if (isObject(value)) { 38374 var other = typeof value.valueOf == 'function' ? value.valueOf() : value; 38375 value = isObject(other) ? (other + '') : other; 38376 } 38377 if (typeof value != 'string') { 38378 return value === 0 ? value : +value; 38379 } 38380 value = value.replace(reTrim, ''); 38381 var isBinary = reIsBinary.test(value); 38382 return (isBinary || reIsOctal.test(value)) 38383 ? freeParseInt(value.slice(2), isBinary ? 2 : 8) 38384 : (reIsBadHex.test(value) ? NAN : +value); 38385 } 38386 38387 /** 38388 * Converts `value` to a plain object flattening inherited enumerable str
vendor: 9,060 bytes, lines 38388-38695
38388ing 38389 * keyed properties of `value` to own properties of the plain object. 38390 * 38391 * @static 38392 * @memberOf _ 38393 * @since 3.0.0 38394 * @category Lang 38395 * @param {*} value The value to convert. 38396 * @returns {Object} Returns the converted plain object. 38397 * @example 38398 * 38399 * function Foo() { 38400 * this.b = 2; 38401 * } 38402 * 38403 * Foo.prototype.c = 3; 38404 * 38405 * _.assign({ 'a': 1 }, new Foo); 38406 * // => { 'a': 1, 'b': 2 } 38407 * 38408 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); 38409 * // => { 'a': 1, 'b': 2, 'c': 3 } 38410 */ 38411 function toPlainObject(value) { 38412 return copyObject(value, keysIn(value)); 38413 } 38414 38415 /** 38416 * Converts `value` to a safe integer. A safe integer can be compared and 38417 * represented correctly. 38418 * 38419 * @static 38420 * @memberOf _ 38421 * @since 4.0.0 38422 * @category Lang 38423 * @param {*} value The value to convert. 38424 * @returns {number} Returns the converted integer. 38425 * @example 38426 * 38427 * _.toSafeInteger(3.2); 38428 * // => 3 38429 * 38430 * _.toSafeInteger(Number.MIN_VALUE); 38431 * // => 0 38432 * 38433 * _.toSafeInteger(Infinity); 38434 * // => 9007199254740991 38435 * 38436 * _.toSafeInteger('3.2'); 38437 * // => 3 38438 */ 38439 function toSafeInteger(value) { 38440 return value 38441 ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) 38442 : (value === 0 ? value : 0); 38443 } 38444 38445 /** 38446 * Converts `value` to a string. An empty string is returned for `null` 38447 * and `undefined` values. The sign of `-0` is preserved. 38448 * 38449 * @static 38450 * @memberOf _ 38451 * @since 4.0.0 38452 * @category Lang 38453 * @param {*} value The value to convert. 38454 * @returns {string} Returns the converted string. 38455 * @example 38456 * 38457 * _.toString(null); 38458 * // => '' 38459 * 38460 * _.toString(-0); 38461 * // => '-0' 38462 * 38463 * _.toString([1, 2, 3]); 38464 * // => '1,2,3' 38465 */ 38466 function toString(value) { 38467 return value == null ? '' : baseToString(value); 38468 } 38469 38470 /*------------------------------------------------------------------------*/ 38471 38472 /** 38473 * Assigns own enumerable string keyed properties of source objects to the 38474 * destination object. Source objects are applied from left to right. 38475 * Subsequent sources overwrite property assignments of previous sources. 38476 * 38477 * **Note:** This method mutates `object` and is loosely based on 38478 * [`Object.assign`](https://mdn.io/Object/assign). 38479 * 38480 * @static 38481 * @memberOf _ 38482 * @since 0.10.0 38483 * @category Object 38484 * @param {Object} object The destination object. 38485 * @param {...Object} [sources] The source objects. 38486 * @returns {Object} Returns `object`. 38487 * @see _.assignIn 38488 * @example 38489 * 38490 * function Foo() { 38491 * this.a = 1; 38492 * } 38493 * 38494 * function Bar() { 38495 * this.c = 3; 38496 * } 38497 * 38498 * Foo.prototype.b = 2; 38499 * Bar.prototype.d = 4; 38500 * 38501 * _.assign({ 'a': 0 }, new Foo, new Bar); 38502 * // => { 'a': 1, 'c': 3 } 38503 */ 38504 var assign = createAssigner(function(object, source) { 38505 if (isPrototype(source) || isArrayLike(source)) { 38506 copyObject(source, keys(source), object); 38507 return; 38508 } 38509 for (var key in source) { 38510 if (hasOwnProperty.call(source, key)) { 38511 assignValue(object, key, source[key]); 38512 } 38513 } 38514 }); 38515 38516 /** 38517 * This method is like `_.assign` except that it iterates over own and 38518 * inherited source properties. 38519 * 38520 * **Note:** This method mutates `object`. 38521 * 38522 * @static 38523 * @memberOf _ 38524 * @since 4.0.0 38525 * @alias extend 38526 * @category Object 38527 * @param {Object} object The destination object. 38528 * @param {...Object} [sources] The source objects. 38529 * @returns {Object} Returns `object`. 38530 * @see _.assign 38531 * @example 38532 * 38533 * function Foo() { 38534 * this.a = 1; 38535 * } 38536 * 38537 * function Bar() { 38538 * this.c = 3; 38539 * } 38540 * 38541 * Foo.prototype.b = 2; 38542 * Bar.prototype.d = 4; 38543 * 38544 * _.assignIn({ 'a': 0 }, new Foo, new Bar); 38545 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } 38546 */ 38547 var assignIn = createAssigner(function(object, source) { 38548 copyObject(source, keysIn(source), object); 38549 }); 38550 38551 /** 38552 * This method is like `_.assignIn` except that it accepts `customizer` 38553 * which is invoked to produce the assigned values. If `customizer` returns 38554 * `undefined`, assignment is handled by the method instead. The `customizer` 38555 * is invoked with five arguments: (objValue, srcValue, key, object, source). 38556 * 38557 * **Note:** This method mutates `object`. 38558 * 38559 * @static 38560 * @memberOf _ 38561 * @since 4.0.0 38562 * @alias extendWith 38563 * @category Object 38564 * @param {Object} object The destination object. 38565 * @param {...Object} sources The source objects. 38566 * @param {Function} [customizer] The function to customize assigned values. 38567 * @returns {Object} Returns `object`. 38568 * @see _.assignWith 38569 * @example 38570 * 38571 * function customizer(objValue, srcValue) { 38572 * return _.isUndefined(objValue) ? srcValue : objValue; 38573 * } 38574 * 38575 * var defaults = _.partialRight(_.assignInWith, customizer); 38576 * 38577 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); 38578 * // => { 'a': 1, 'b': 2 } 38579 */ 38580 var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { 38581 copyObject(source, keysIn(source), object, customizer); 38582 }); 38583 38584 /** 38585 * This method is like `_.assign` except that it accepts `customizer` 38586 * which is invoked to produce the assigned values. If `customizer` returns 38587 * `undefined`, assignment is handled by the method instead. The `customizer` 38588 * is invoked with five arguments: (objValue, srcValue, key, object, source). 38589 * 38590 * **Note:** This method mutates `object`. 38591 * 38592 * @static 38593 * @memberOf _ 38594 * @since 4.0.0 38595 * @category Object 38596 * @param {Object} object The destination object. 38597 * @param {...Object} sources The source objects. 38598 * @param {Function} [customizer] The function to customize assigned values. 38599 * @returns {Object} Returns `object`. 38600 * @see _.assignInWith 38601 * @example 38602 * 38603 * function customizer(objValue, srcValue) { 38604 * return _.isUndefined(objValue) ? srcValue : objValue; 38605 * } 38606 * 38607 * var defaults = _.partialRight(_.assignWith, customizer); 38608 * 38609 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); 38610 * // => { 'a': 1, 'b': 2 } 38611 */ 38612 var assignWith = createAssigner(function(object, source, srcIndex, customizer) { 38613 copyObject(source, keys(source), object, customizer); 38614 }); 38615 38616 /** 38617 * Creates an array of values corresponding to `paths` of `object`. 38618 * 38619 * @static 38620 * @memberOf _ 38621 * @since 1.0.0 38622 * @category Object 38623 * @param {Object} object The object to iterate over. 38624 * @param {...(string|string[])} [paths] The property paths to pick. 38625 * @returns {Array} Returns the picked values. 38626 * @example 38627 * 38628 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; 38629 * 38630 * _.at(object, ['a[0].b.c', 'a[1]']); 38631 * // => [3, 4] 38632 */ 38633 var at = flatRest(baseAt); 38634 38635 /** 38636 * Creates an object that inherits from the `prototype` object. If a 38637 * `properties` object is given, its own enumerable string keyed properties 38638 * are assigned to the created object. 38639 * 38640 * @static 38641 * @memberOf _ 38642 * @since 2.3.0 38643 * @category Object 38644 * @param {Object} prototype The object to inherit from. 38645 * @param {Object} [properties] The properties to assign to the object. 38646 * @returns {Object} Returns the new object. 38647 * @example 38648 * 38649 * function Shape() { 38650 * this.x = 0; 38651 * this.y = 0; 38652 * } 38653 * 38654 * function Circle() { 38655 * Shape.call(this); 38656 * } 38657 * 38658 * Circle.prototype = _.create(Shape.prototype, { 38659 * 'constructor': Circle 38660 * }); 38661 * 38662 * var circle = new Circle; 38663 * circle instanceof Circle; 38664 * // => true 38665 * 38666 * circle instanceof Shape; 38667 * // => true 38668 */ 38669 function create(prototype, properties) { 38670 var result = baseCreate(prototype); 38671 return properties == null ? result : baseAssign(result, properties); 38672 } 38673 38674 /** 38675 * Assigns own and inherited enumerable string keyed properties of source 38676 * objects to the destination object for all destination properties that 38677 * resolve to `undefined`. Source objects are applied from left to right. 38678 * Once a property is set, additional values of the same property are ignored. 38679 * 38680 * **Note:** This method mutates `object`. 38681 * 38682 * @static 38683 * @since 0.1.0 38684 * @memberOf _ 38685 * @category Object 38686 * @param {Object} object The destination object. 38687 * @param {...Object} [sources] The source objects. 38688 * @returns {Object} Returns `object`. 38689 * @see _.defaultsDeep 38690 * @example 38691 * 38692 * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); 38693 * // => { 'a': 1, 'b': 2 } 38694 */ 38695 var defaults = baseRest(function(
38695args) { 38696 args.push(undefined, customDefaultsAssignIn); 38697 return apply(assignInWith, undefined, args)
vendor: 11,675 bytes, lines 38697-39094
38697; 38698 }); 38699 38700 /** 38701 * This method is like `_.defaults` except that it recursively assigns 38702 * default properties. 38703 * 38704 * **Note:** This method mutates `object`. 38705 * 38706 * @static 38707 * @memberOf _ 38708 * @since 3.10.0 38709 * @category Object 38710 * @param {Object} object The destination object. 38711 * @param {...Object} [sources] The source objects. 38712 * @returns {Object} Returns `object`. 38713 * @see _.defaults 38714 * @example 38715 * 38716 * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); 38717 * // => { 'a': { 'b': 2, 'c': 3 } } 38718 */ 38719 var defaultsDeep = baseRest(function(args) { 38720 args.push(undefined, customDefaultsMerge); 38721 return apply(mergeWith, undefined, args); 38722 }); 38723 38724 /** 38725 * This method is like `_.find` except that it returns the key of the first 38726 * element `predicate` returns truthy for instead of the element itself. 38727 * 38728 * @static 38729 * @memberOf _ 38730 * @since 1.1.0 38731 * @category Object 38732 * @param {Object} object The object to inspect. 38733 * @param {Function} [predicate=_.identity] The function invoked per iteration. 38734 * @returns {string|undefined} Returns the key of the matched element, 38735 * else `undefined`. 38736 * @example 38737 * 38738 * var users = { 38739 * 'barney': { 'age': 36, 'active': true }, 38740 * 'fred': { 'age': 40, 'active': false }, 38741 * 'pebbles': { 'age': 1, 'active': true } 38742 * }; 38743 * 38744 * _.findKey(users, function(o) { return o.age < 40; }); 38745 * // => 'barney' (iteration order is not guaranteed) 38746 * 38747 * // The `_.matches` iteratee shorthand. 38748 * _.findKey(users, { 'age': 1, 'active': true }); 38749 * // => 'pebbles' 38750 * 38751 * // The `_.matchesProperty` iteratee shorthand. 38752 * _.findKey(users, ['active', false]); 38753 * // => 'fred' 38754 * 38755 * // The `_.property` iteratee shorthand. 38756 * _.findKey(users, 'active'); 38757 * // => 'barney' 38758 */ 38759 function findKey(object, predicate) { 38760 return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); 38761 } 38762 38763 /** 38764 * This method is like `_.findKey` except that it iterates over elements of 38765 * a collection in the opposite order. 38766 * 38767 * @static 38768 * @memberOf _ 38769 * @since 2.0.0 38770 * @category Object 38771 * @param {Object} object The object to inspect. 38772 * @param {Function} [predicate=_.identity] The function invoked per iteration. 38773 * @returns {string|undefined} Returns the key of the matched element, 38774 * else `undefined`. 38775 * @example 38776 * 38777 * var users = { 38778 * 'barney': { 'age': 36, 'active': true }, 38779 * 'fred': { 'age': 40, 'active': false }, 38780 * 'pebbles': { 'age': 1, 'active': true } 38781 * }; 38782 * 38783 * _.findLastKey(users, function(o) { return o.age < 40; }); 38784 * // => returns 'pebbles' assuming `_.findKey` returns 'barney' 38785 * 38786 * // The `_.matches` iteratee shorthand. 38787 * _.findLastKey(users, { 'age': 36, 'active': true }); 38788 * // => 'barney' 38789 * 38790 * // The `_.matchesProperty` iteratee shorthand. 38791 * _.findLastKey(users, ['active', false]); 38792 * // => 'fred' 38793 * 38794 * // The `_.property` iteratee shorthand. 38795 * _.findLastKey(users, 'active'); 38796 * // => 'pebbles' 38797 */ 38798 function findLastKey(object, predicate) { 38799 return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); 38800 } 38801 38802 /** 38803 * Iterates over own and inherited enumerable string keyed properties of an 38804 * object and invokes `iteratee` for each property. The iteratee is invoked 38805 * with three arguments: (value, key, object). Iteratee functions may exit 38806 * iteration early by explicitly returning `false`. 38807 * 38808 * @static 38809 * @memberOf _ 38810 * @since 0.3.0 38811 * @category Object 38812 * @param {Object} object The object to iterate over. 38813 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 38814 * @returns {Object} Returns `object`. 38815 * @see _.forInRight 38816 * @example 38817 * 38818 * function Foo() { 38819 * this.a = 1; 38820 * this.b = 2; 38821 * } 38822 * 38823 * Foo.prototype.c = 3; 38824 * 38825 * _.forIn(new Foo, function(value, key) { 38826 * console.log(key); 38827 * }); 38828 * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). 38829 */ 38830 function forIn(object, iteratee) { 38831 return object == null 38832 ? object 38833 : baseFor(object, getIteratee(iteratee, 3), keysIn); 38834 } 38835 38836 /** 38837 * This method is like `_.forIn` except that it iterates over properties of 38838 * `object` in the opposite order. 38839 * 38840 * @static 38841 * @memberOf _ 38842 * @since 2.0.0 38843 * @category Object 38844 * @param {Object} object The object to iterate over. 38845 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 38846 * @returns {Object} Returns `object`. 38847 * @see _.forIn 38848 * @example 38849 * 38850 * function Foo() { 38851 * this.a = 1; 38852 * this.b = 2; 38853 * } 38854 * 38855 * Foo.prototype.c = 3; 38856 * 38857 * _.forInRight(new Foo, function(value, key) { 38858 * console.log(key); 38859 * }); 38860 * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. 38861 */ 38862 function forInRight(object, iteratee) { 38863 return object == null 38864 ? object 38865 : baseForRight(object, getIteratee(iteratee, 3), keysIn); 38866 } 38867 38868 /** 38869 * Iterates over own enumerable string keyed properties of an object and 38870 * invokes `iteratee` for each property. The iteratee is invoked with three 38871 * arguments: (value, key, object). Iteratee functions may exit iteration 38872 * early by explicitly returning `false`. 38873 * 38874 * @static 38875 * @memberOf _ 38876 * @since 0.3.0 38877 * @category Object 38878 * @param {Object} object The object to iterate over. 38879 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 38880 * @returns {Object} Returns `object`. 38881 * @see _.forOwnRight 38882 * @example 38883 * 38884 * function Foo() { 38885 * this.a = 1; 38886 * this.b = 2; 38887 * } 38888 * 38889 * Foo.prototype.c = 3; 38890 * 38891 * _.forOwn(new Foo, function(value, key) { 38892 * console.log(key); 38893 * }); 38894 * // => Logs 'a' then 'b' (iteration order is not guaranteed). 38895 */ 38896 function forOwn(object, iteratee) { 38897 return object && baseForOwn(object, getIteratee(iteratee, 3)); 38898 } 38899 38900 /** 38901 * This method is like `_.forOwn` except that it iterates over properties of 38902 * `object` in the opposite order. 38903 * 38904 * @static 38905 * @memberOf _ 38906 * @since 2.0.0 38907 * @category Object 38908 * @param {Object} object The object to iterate over. 38909 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 38910 * @returns {Object} Returns `object`. 38911 * @see _.forOwn 38912 * @example 38913 * 38914 * function Foo() { 38915 * this.a = 1; 38916 * this.b = 2; 38917 * } 38918 * 38919 * Foo.prototype.c = 3; 38920 * 38921 * _.forOwnRight(new Foo, function(value, key) { 38922 * console.log(key); 38923 * }); 38924 * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. 38925 */ 38926 function forOwnRight(object, iteratee) { 38927 return object && baseForOwnRight(object, getIteratee(iteratee, 3)); 38928 } 38929 38930 /** 38931 * Creates an array of function property names from own enumerable properties 38932 * of `object`. 38933 * 38934 * @static 38935 * @since 0.1.0 38936 * @memberOf _ 38937 * @category Object 38938 * @param {Object} object The object to inspect. 38939 * @returns {Array} Returns the function names. 38940 * @see _.functionsIn 38941 * @example 38942 * 38943 * function Foo() { 38944 * this.a = _.constant('a'); 38945 * this.b = _.constant('b'); 38946 * } 38947 * 38948 * Foo.prototype.c = _.constant('c'); 38949 * 38950 * _.functions(new Foo); 38951 * // => ['a', 'b'] 38952 */ 38953 function functions(object) { 38954 return object == null ? [] : baseFunctions(object, keys(object)); 38955 } 38956 38957 /** 38958 * Creates an array of function property names from own and inherited 38959 * enumerable properties of `object`. 38960 * 38961 * @static 38962 * @memberOf _ 38963 * @since 4.0.0 38964 * @category Object 38965 * @param {Object} object The object to inspect. 38966 * @returns {Array} Returns the function names. 38967 * @see _.functions 38968 * @example 38969 * 38970 * function Foo() { 38971 * this.a = _.constant('a'); 38972 * this.b = _.constant('b'); 38973 * } 38974 * 38975 * Foo.prototype.c = _.constant('c'); 38976 * 38977 * _.functionsIn(new Foo); 38978 * // => ['a', 'b', 'c'] 38979 */ 38980 function functionsIn(object) { 38981 return object == null ? [] : baseFunctions(object, keysIn(object)); 38982 } 38983 38984 /** 38985 * Gets the value at `path` of `object`. If the resolved value is 38986 * `undefined`, the `defaultValue` is returned in its place. 38987 * 38988 * @static 38989 * @memberOf _ 38990 * @since 3.7.0 38991 * @category Object 38992 * @param {Object} object The object to query. 38993 * @param {Array|string} path The path of the property to get. 38994 * @param {*} [defaultValue] The value returned for `undefined` resolved values. 38995 * @returns {*} Returns the resolved value. 38996 * @example 38997 * 38998 * var object = { 'a': [{ 'b': { 'c': 3 } }] }; 38999 * 39000 * _.get(object, 'a[0].b.c'); 39001 * // => 3 39002 * 39003 * _.get(object, ['a', '0', 'b', 'c']); 39004 * // => 3 39005 * 39006 * _.get(object, 'a.b.c', 'default'); 39007 * // => 'default' 39008 */ 39009 function get(object, path, defaultValue) { 39010 var result = object == null ? undefined : baseGet(object, path); 39011 return result === undefined ? defaultValue : result; 39012 } 39013 39014 /** 39015 * Checks if `path` is a direct property of `object`. 39016 * 39017 * @static 39018 * @since 0.1.0 39019 * @memberOf _ 39020 * @category Object 39021 * @param {Object} object The object to query. 39022 * @param {Array|string} path The path to check. 39023 * @returns {boolean} Returns `true` if `path` exists, else `false`. 39024 * @example 39025 * 39026 * var object = { 'a': { 'b': 2 } }; 39027 * var other = _.create({ 'a': _.create({ 'b': 2 }) }); 39028 * 39029 * _.has(object, 'a'); 39030 * // => true 39031 * 39032 * _.has(object, 'a.b'); 39033 * // => true 39034 * 39035 * _.has(object, ['a', 'b']); 39036 * // => true 39037 * 39038 * _.has(other, 'a'); 39039 * // => false 39040 */ 39041 function has(object, path) { 39042 return object != null && hasPath(object, path, baseHas); 39043 } 39044 39045 /** 39046 * Checks if `path` is a direct or inherited property of `object`. 39047 * 39048 * @static 39049 * @memberOf _ 39050 * @since 4.0.0 39051 * @category Object 39052 * @param {Object} object The object to query. 39053 * @param {Array|string} path The path to check. 39054 * @returns {boolean} Returns `true` if `path` exists, else `false`. 39055 * @example 39056 * 39057 * var object = _.create({ 'a': _.create({ 'b': 2 }) }); 39058 * 39059 * _.hasIn(object, 'a'); 39060 * // => true 39061 * 39062 * _.hasIn(object, 'a.b'); 39063 * // => true 39064 * 39065 * _.hasIn(object, ['a', 'b']); 39066 * // => true 39067 * 39068 * _.hasIn(object, 'b'); 39069 * // => false 39070 */ 39071 function hasIn(object, path) { 39072 return object != null && hasPath(object, path, baseHasIn); 39073 } 39074 39075 /** 39076 * Creates an object composed of the inverted keys and values of `object`. 39077 * If `object` contains duplicate values, subsequent values overwrite 39078 * property assignments of previous values. 39079 * 39080 * @static 39081 * @memberOf _ 39082 * @since 0.7.0 39083 * @category Object 39084 * @param {Object} object The object to invert. 39085 * @returns {Object} Returns the new inverted object. 39086 * @example 39087 * 39088 * var object = { 'a': 1, 'b': 2, 'c': 1 }; 39089 * 39090 * _.invert(object); 39091 * // => { '1': 'c', '2': 'b' } 39092 */ 39093 var invert = createInverter(function(result, value, key) { 39094
39094result[value] = key; 39095 }, constant(identity)); 39096 39097 /** 39098 * This method is like `_.invert` except that the inverted object is generated 39099 * from the results of running each element of `object` thru `iteratee`. The 39100 * corresponding inverted value of each inverted key is an array of keys 39101 * responsible for generating the inverted value. The iteratee is invoked 39102 * with one argument: (value). 39103 * 39104 * @static 39105 * @memberOf _ 39106 * @since 4.1.0 39107 * @category Object 39108 * @param {Object} object The object to invert. 39109 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 39110 * @returns {Object} Returns the new inverted object. 39111 * @example 39112 * 39113 * var object = { 'a': 1, 'b': 2, 'c': 1 }; 39114 * 39115 * _.invertBy(object); 39116 * // => { '1': ['a', 'c'], '2': ['b'] } 39117 * 39118 * _.invertBy(object, function(value) { 39119 * return 'group' + value; 39120 * }); 39121 * // => { 'group1': ['a', 'c'], 'group2': ['b'] } 39122 */ 39123 var invertBy = createInverter(function(result, value, key) {
vendor: 9,906 bytes, lines 39123-39436
39123 39124 if (hasOwnProperty.call(result, value)) { 39125 result[value].push(key); 39126 } else { 39127 result[value] = [key]; 39128 } 39129 }, getIteratee); 39130 39131 /** 39132 * Invokes the method at `path` of `object`. 39133 * 39134 * @static 39135 * @memberOf _ 39136 * @since 4.0.0 39137 * @category Object 39138 * @param {Object} object The object to query. 39139 * @param {Array|string} path The path of the method to invoke. 39140 * @param {...*} [args] The arguments to invoke the method with. 39141 * @returns {*} Returns the result of the invoked method. 39142 * @example 39143 * 39144 * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; 39145 * 39146 * _.invoke(object, 'a[0].b.c.slice', 1, 3); 39147 * // => [2, 3] 39148 */ 39149 var invoke = baseRest(baseInvoke); 39150 39151 /** 39152 * Creates an array of the own enumerable property names of `object`. 39153 * 39154 * **Note:** Non-object values are coerced to objects. See the 39155 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) 39156 * for more details. 39157 * 39158 * @static 39159 * @since 0.1.0 39160 * @memberOf _ 39161 * @category Object 39162 * @param {Object} object The object to query. 39163 * @returns {Array} Returns the array of property names. 39164 * @example 39165 * 39166 * function Foo() { 39167 * this.a = 1; 39168 * this.b = 2; 39169 * } 39170 * 39171 * Foo.prototype.c = 3; 39172 * 39173 * _.keys(new Foo); 39174 * // => ['a', 'b'] (iteration order is not guaranteed) 39175 * 39176 * _.keys('hi'); 39177 * // => ['0', '1'] 39178 */ 39179 function keys(object) { 39180 return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); 39181 } 39182 39183 /** 39184 * Creates an array of the own and inherited enumerable property names of `object`. 39185 * 39186 * **Note:** Non-object values are coerced to objects. 39187 * 39188 * @static 39189 * @memberOf _ 39190 * @since 3.0.0 39191 * @category Object 39192 * @param {Object} object The object to query. 39193 * @returns {Array} Returns the array of property names. 39194 * @example 39195 * 39196 * function Foo() { 39197 * this.a = 1; 39198 * this.b = 2; 39199 * } 39200 * 39201 * Foo.prototype.c = 3; 39202 * 39203 * _.keysIn(new Foo); 39204 * // => ['a', 'b', 'c'] (iteration order is not guaranteed) 39205 */ 39206 function keysIn(object) { 39207 return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); 39208 } 39209 39210 /** 39211 * The opposite of `_.mapValues`; this method creates an object with the 39212 * same values as `object` and keys generated by running each own enumerable 39213 * string keyed property of `object` thru `iteratee`. The iteratee is invoked 39214 * with three arguments: (value, key, object). 39215 * 39216 * @static 39217 * @memberOf _ 39218 * @since 3.8.0 39219 * @category Object 39220 * @param {Object} object The object to iterate over. 39221 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 39222 * @returns {Object} Returns the new mapped object. 39223 * @see _.mapValues 39224 * @example 39225 * 39226 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { 39227 * return key + value; 39228 * }); 39229 * // => { 'a1': 1, 'b2': 2 } 39230 */ 39231 function mapKeys(object, iteratee) { 39232 var result = {}; 39233 iteratee = getIteratee(iteratee, 3); 39234 39235 baseForOwn(object, function(value, key, object) { 39236 baseAssignValue(result, iteratee(value, key, object), value); 39237 }); 39238 return result; 39239 } 39240 39241 /** 39242 * Creates an object with the same keys as `object` and values generated 39243 * by running each own enumerable string keyed property of `object` thru 39244 * `iteratee`. The iteratee is invoked with three arguments: 39245 * (value, key, object). 39246 * 39247 * @static 39248 * @memberOf _ 39249 * @since 2.4.0 39250 * @category Object 39251 * @param {Object} object The object to iterate over. 39252 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 39253 * @returns {Object} Returns the new mapped object. 39254 * @see _.mapKeys 39255 * @example 39256 * 39257 * var users = { 39258 * 'fred': { 'user': 'fred', 'age': 40 }, 39259 * 'pebbles': { 'user': 'pebbles', 'age': 1 } 39260 * }; 39261 * 39262 * _.mapValues(users, function(o) { return o.age; }); 39263 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) 39264 * 39265 * // The `_.property` iteratee shorthand. 39266 * _.mapValues(users, 'age'); 39267 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) 39268 */ 39269 function mapValues(object, iteratee) { 39270 var result = {}; 39271 iteratee = getIteratee(iteratee, 3); 39272 39273 baseForOwn(object, function(value, key, object) { 39274 baseAssignValue(result, key, iteratee(value, key, object)); 39275 }); 39276 return result; 39277 } 39278 39279 /** 39280 * This method is like `_.assign` except that it recursively merges own and 39281 * inherited enumerable string keyed properties of source objects into the 39282 * destination object. Source properties that resolve to `undefined` are 39283 * skipped if a destination value exists. Array and plain object properties 39284 * are merged recursively. Other objects and value types are overridden by 39285 * assignment. Source objects are applied from left to right. Subsequent 39286 * sources overwrite property assignments of previous sources. 39287 * 39288 * **Note:** This method mutates `object`. 39289 * 39290 * @static 39291 * @memberOf _ 39292 * @since 0.5.0 39293 * @category Object 39294 * @param {Object} object The destination object. 39295 * @param {...Object} [sources] The source objects. 39296 * @returns {Object} Returns `object`. 39297 * @example 39298 * 39299 * var object = { 39300 * 'a': [{ 'b': 2 }, { 'd': 4 }] 39301 * }; 39302 * 39303 * var other = { 39304 * 'a': [{ 'c': 3 }, { 'e': 5 }] 39305 * }; 39306 * 39307 * _.merge(object, other); 39308 * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } 39309 */ 39310 var merge = createAssigner(function(object, source, srcIndex) { 39311 baseMerge(object, source, srcIndex); 39312 }); 39313 39314 /** 39315 * This method is like `_.merge` except that it accepts `customizer` which 39316 * is invoked to produce the merged values of the destination and source 39317 * properties. If `customizer` returns `undefined`, merging is handled by the 39318 * method instead. The `customizer` is invoked with six arguments: 39319 * (objValue, srcValue, key, object, source, stack). 39320 * 39321 * **Note:** This method mutates `object`. 39322 * 39323 * @static 39324 * @memberOf _ 39325 * @since 4.0.0 39326 * @category Object 39327 * @param {Object} object The destination object. 39328 * @param {...Object} sources The source objects. 39329 * @param {Function} customizer The function to customize assigned values. 39330 * @returns {Object} Returns `object`. 39331 * @example 39332 * 39333 * function customizer(objValue, srcValue) { 39334 * if (_.isArray(objValue)) { 39335 * return objValue.concat(srcValue); 39336 * } 39337 * } 39338 * 39339 * var object = { 'a': [1], 'b': [2] }; 39340 * var other = { 'a': [3], 'b': [4] }; 39341 * 39342 * _.mergeWith(object, other, customizer); 39343 * // => { 'a': [1, 3], 'b': [2, 4] } 39344 */ 39345 var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { 39346 baseMerge(object, source, srcIndex, customizer); 39347 }); 39348 39349 /** 39350 * The opposite of `_.pick`; this method creates an object composed of the 39351 * own and inherited enumerable property paths of `object` that are not omitted. 39352 * 39353 * **Note:** This method is considerably slower than `_.pick`. 39354 * 39355 * @static 39356 * @since 0.1.0 39357 * @memberOf _ 39358 * @category Object 39359 * @param {Object} object The source object. 39360 * @param {...(string|string[])} [paths] The property paths to omit. 39361 * @returns {Object} Returns the new object. 39362 * @example 39363 * 39364 * var object = { 'a': 1, 'b': '2', 'c': 3 }; 39365 * 39366 * _.omit(object, ['a', 'c']); 39367 * // => { 'b': '2' } 39368 */ 39369 var omit = flatRest(function(object, paths) { 39370 var result = {}; 39371 if (object == null) { 39372 return result; 39373 } 39374 var isDeep = false; 39375 paths = arrayMap(paths, function(path) { 39376 path = castPath(path, object); 39377 isDeep || (isDeep = path.length > 1); 39378 return path; 39379 }); 39380 copyObject(object, getAllKeysIn(object), result); 39381 if (isDeep) { 39382 result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); 39383 } 39384 var length = paths.length; 39385 while (length--) { 39386 baseUnset(result, paths[length]); 39387 } 39388 return result; 39389 }); 39390 39391 /** 39392 * The opposite of `_.pickBy`; this method creates an object composed of 39393 * the own and inherited enumerable string keyed properties of `object` that 39394 * `predicate` doesn't return truthy for. The predicate is invoked with two 39395 * arguments: (value, key). 39396 * 39397 * @static 39398 * @memberOf _ 39399 * @since 4.0.0 39400 * @category Object 39401 * @param {Object} object The source object. 39402 * @param {Function} [predicate=_.identity] The function invoked per property. 39403 * @returns {Object} Returns the new object. 39404 * @example 39405 * 39406 * var object = { 'a': 1, 'b': '2', 'c': 3 }; 39407 * 39408 * _.omitBy(object, _.isNumber); 39409 * // => { 'b': '2' } 39410 */ 39411 function omitBy(object, predicate) { 39412 return pickBy(object, negate(getIteratee(predicate))); 39413 } 39414 39415 /** 39416 * Creates an object composed of the picked `object` properties. 39417 * 39418 * @static 39419 * @since 0.1.0 39420 * @memberOf _ 39421 * @category Object 39422 * @param {Object} object The source object. 39423 * @param {...(string|string[])} [paths] The property paths to pick. 39424 * @returns {Object} Returns the new object. 39425 * @example 39426 * 39427 * var object = { 'a': 1, 'b': '2', 'c': 3 }; 39428 * 39429 * _.pick(object, ['a', 'c']); 39430 * // => { 'a': 1, 'c': 3 } 39431 */ 39432 var pick = flatRest(function(object, paths) { 39433 return object == null ? {} : basePick(object, paths); 39434 }); 39435 39436 /**
vendor: 11,160 bytes, lines 39437-39775
39437 * Creates an object composed of the `object` properties `predicate` returns 39438 * truthy for. The predicate is invoked with two arguments: (value, key). 39439 * 39440 * @static 39441 * @memberOf _ 39442 * @since 4.0.0 39443 * @category Object 39444 * @param {Object} object The source object. 39445 * @param {Function} [predicate=_.identity] The function invoked per property. 39446 * @returns {Object} Returns the new object. 39447 * @example 39448 * 39449 * var object = { 'a': 1, 'b': '2', 'c': 3 }; 39450 * 39451 * _.pickBy(object, _.isNumber); 39452 * // => { 'a': 1, 'c': 3 } 39453 */ 39454 function pickBy(object, predicate) { 39455 if (object == null) { 39456 return {}; 39457 } 39458 var props = arrayMap(getAllKeysIn(object), function(prop) { 39459 return [prop]; 39460 }); 39461 predicate = getIteratee(predicate); 39462 return basePickBy(object, props, function(value, path) { 39463 return predicate(value, path[0]); 39464 }); 39465 } 39466 39467 /** 39468 * This method is like `_.get` except that if the resolved value is a 39469 * function it's invoked with the `this` binding of its parent object and 39470 * its result is returned. 39471 * 39472 * @static 39473 * @since 0.1.0 39474 * @memberOf _ 39475 * @category Object 39476 * @param {Object} object The object to query. 39477 * @param {Array|string} path The path of the property to resolve. 39478 * @param {*} [defaultValue] The value returned for `undefined` resolved values. 39479 * @returns {*} Returns the resolved value. 39480 * @example 39481 * 39482 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; 39483 * 39484 * _.result(object, 'a[0].b.c1'); 39485 * // => 3 39486 * 39487 * _.result(object, 'a[0].b.c2'); 39488 * // => 4 39489 * 39490 * _.result(object, 'a[0].b.c3', 'default'); 39491 * // => 'default' 39492 * 39493 * _.result(object, 'a[0].b.c3', _.constant('default')); 39494 * // => 'default' 39495 */ 39496 function result(object, path, defaultValue) { 39497 path = castPath(path, object); 39498 39499 var index = -1, 39500 length = path.length; 39501 39502 // Ensure the loop is entered when path is empty. 39503 if (!length) { 39504 length = 1; 39505 object = undefined; 39506 } 39507 while (++index < length) { 39508 var value = object == null ? undefined : object[toKey(path[index])]; 39509 if (value === undefined) { 39510 index = length; 39511 value = defaultValue; 39512 } 39513 object = isFunction(value) ? value.call(object) : value; 39514 } 39515 return object; 39516 } 39517 39518 /** 39519 * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, 39520 * it's created. Arrays are created for missing index properties while objects 39521 * are created for all other missing properties. Use `_.setWith` to customize 39522 * `path` creation. 39523 * 39524 * **Note:** This method mutates `object`. 39525 * 39526 * @static 39527 * @memberOf _ 39528 * @since 3.7.0 39529 * @category Object 39530 * @param {Object} object The object to modify. 39531 * @param {Array|string} path The path of the property to set. 39532 * @param {*} value The value to set. 39533 * @returns {Object} Returns `object`. 39534 * @example 39535 * 39536 * var object = { 'a': [{ 'b': { 'c': 3 } }] }; 39537 * 39538 * _.set(object, 'a[0].b.c', 4); 39539 * console.log(object.a[0].b.c); 39540 * // => 4 39541 * 39542 * _.set(object, ['x', '0', 'y', 'z'], 5); 39543 * console.log(object.x[0].y.z); 39544 * // => 5 39545 */ 39546 function set(object, path, value) { 39547 return object == null ? object : baseSet(object, path, value); 39548 } 39549 39550 /** 39551 * This method is like `_.set` except that it accepts `customizer` which is 39552 * invoked to produce the objects of `path`. If `customizer` returns `undefined` 39553 * path creation is handled by the method instead. The `customizer` is invoked 39554 * with three arguments: (nsValue, key, nsObject). 39555 * 39556 * **Note:** This method mutates `object`. 39557 * 39558 * @static 39559 * @memberOf _ 39560 * @since 4.0.0 39561 * @category Object 39562 * @param {Object} object The object to modify. 39563 * @param {Array|string} path The path of the property to set. 39564 * @param {*} value The value to set. 39565 * @param {Function} [customizer] The function to customize assigned values. 39566 * @returns {Object} Returns `object`. 39567 * @example 39568 * 39569 * var object = {}; 39570 * 39571 * _.setWith(object, '[0][1]', 'a', Object); 39572 * // => { '0': { '1': 'a' } } 39573 */ 39574 function setWith(object, path, value, customizer) { 39575 customizer = typeof customizer == 'function' ? customizer : undefined; 39576 return object == null ? object : baseSet(object, path, value, customizer); 39577 } 39578 39579 /** 39580 * Creates an array of own enumerable string keyed-value pairs for `object` 39581 * which can be consumed by `_.fromPairs`. If `object` is a map or set, its 39582 * entries are returned. 39583 * 39584 * @static 39585 * @memberOf _ 39586 * @since 4.0.0 39587 * @alias entries 39588 * @category Object 39589 * @param {Object} object The object to query. 39590 * @returns {Array} Returns the key-value pairs. 39591 * @example 39592 * 39593 * function Foo() { 39594 * this.a = 1; 39595 * this.b = 2; 39596 * } 39597 * 39598 * Foo.prototype.c = 3; 39599 * 39600 * _.toPairs(new Foo); 39601 * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) 39602 */ 39603 var toPairs = createToPairs(keys); 39604 39605 /** 39606 * Creates an array of own and inherited enumerable string keyed-value pairs 39607 * for `object` which can be consumed by `_.fromPairs`. If `object` is a map 39608 * or set, its entries are returned. 39609 * 39610 * @static 39611 * @memberOf _ 39612 * @since 4.0.0 39613 * @alias entriesIn 39614 * @category Object 39615 * @param {Object} object The object to query. 39616 * @returns {Array} Returns the key-value pairs. 39617 * @example 39618 * 39619 * function Foo() { 39620 * this.a = 1; 39621 * this.b = 2; 39622 * } 39623 * 39624 * Foo.prototype.c = 3; 39625 * 39626 * _.toPairsIn(new Foo); 39627 * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) 39628 */ 39629 var toPairsIn = createToPairs(keysIn); 39630 39631 /** 39632 * An alternative to `_.reduce`; this method transforms `object` to a new 39633 * `accumulator` object which is the result of running each of its own 39634 * enumerable string keyed properties thru `iteratee`, with each invocation 39635 * potentially mutating the `accumulator` object. If `accumulator` is not 39636 * provided, a new object with the same `[[Prototype]]` will be used. The 39637 * iteratee is invoked with four arguments: (accumulator, value, key, object). 39638 * Iteratee functions may exit iteration early by explicitly returning `false`. 39639 * 39640 * @static 39641 * @memberOf _ 39642 * @since 1.3.0 39643 * @category Object 39644 * @param {Object} object The object to iterate over. 39645 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 39646 * @param {*} [accumulator] The custom accumulator value. 39647 * @returns {*} Returns the accumulated value. 39648 * @example 39649 * 39650 * _.transform([2, 3, 4], function(result, n) { 39651 * result.push(n *= n); 39652 * return n % 2 == 0; 39653 * }, []); 39654 * // => [4, 9] 39655 * 39656 * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { 39657 * (result[value] || (result[value] = [])).push(key); 39658 * }, {}); 39659 * // => { '1': ['a', 'c'], '2': ['b'] } 39660 */ 39661 function transform(object, iteratee, accumulator) { 39662 var isArr = isArray(object), 39663 isArrLike = isArr || isBuffer(object) || isTypedArray(object); 39664 39665 iteratee = getIteratee(iteratee, 4); 39666 if (accumulator == null) { 39667 var Ctor = object && object.constructor; 39668 if (isArrLike) { 39669 accumulator = isArr ? new Ctor : []; 39670 } 39671 else if (isObject(object)) { 39672 accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; 39673 } 39674 else { 39675 accumulator = {}; 39676 } 39677 } 39678 (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { 39679 return iteratee(accumulator, value, index, object); 39680 }); 39681 return accumulator; 39682 } 39683 39684 /** 39685 * Removes the property at `path` of `object`. 39686 * 39687 * **Note:** This method mutates `object`. 39688 * 39689 * @static 39690 * @memberOf _ 39691 * @since 4.0.0 39692 * @category Object 39693 * @param {Object} object The object to modify. 39694 * @param {Array|string} path The path of the property to unset. 39695 * @returns {boolean} Returns `true` if the property is deleted, else `false`. 39696 * @example 39697 * 39698 * var object = { 'a': [{ 'b': { 'c': 7 } }] }; 39699 * _.unset(object, 'a[0].b.c'); 39700 * // => true 39701 * 39702 * console.log(object); 39703 * // => { 'a': [{ 'b': {} }] }; 39704 * 39705 * _.unset(object, ['a', '0', 'b', 'c']); 39706 * // => true 39707 * 39708 * console.log(object); 39709 * // => { 'a': [{ 'b': {} }] }; 39710 */ 39711 function unset(object, path) { 39712 return object == null ? true : baseUnset(object, path); 39713 } 39714 39715 /** 39716 * This method is like `_.set` except that accepts `updater` to produce the 39717 * value to set. Use `_.updateWith` to customize `path` creation. The `updater` 39718 * is invoked with one argument: (value). 39719 * 39720 * **Note:** This method mutates `object`. 39721 * 39722 * @static 39723 * @memberOf _ 39724 * @since 4.6.0 39725 * @category Object 39726 * @param {Object} object The object to modify. 39727 * @param {Array|string} path The path of the property to set. 39728 * @param {Function} updater The function to produce the updated value. 39729 * @returns {Object} Returns `object`. 39730 * @example 39731 * 39732 * var object = { 'a': [{ 'b': { 'c': 3 } }] }; 39733 * 39734 * _.update(object, 'a[0].b.c', function(n) { return n * n; }); 39735 * console.log(object.a[0].b.c); 39736 * // => 9 39737 * 39738 * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); 39739 * console.log(object.x[0].y.z); 39740 * // => 0 39741 */ 39742 function update(object, path, updater) { 39743 return object == null ? object : baseUpdate(object, path, castFunction(updater)); 39744 } 39745 39746 /** 39747 * This method is like `_.update` except that it accepts `customizer` which is 39748 * invoked to produce the objects of `path`. If `customizer` returns `undefined` 39749 * path creation is handled by the method instead. The `customizer` is invoked 39750 * with three arguments: (nsValue, key, nsObject). 39751 * 39752 * **Note:** This method mutates `object`. 39753 * 39754 * @static 39755 * @memberOf _ 39756 * @since 4.6.0 39757 * @category Object 39758 * @param {Object} object The object to modify. 39759 * @param {Array|string} path The path of the property to set. 39760 * @param {Function} updater The function to produce the updated value. 39761 * @param {Function} [customizer] The function to customize assigned values. 39762 * @returns {Object} Returns `object`. 39763 * @example 39764 * 39765 * var object = {}; 39766 * 39767 * _.updateWith(object, '[0][1]', _.constant('a'), Object); 39768 * // => { '0': { '1': 'a' } } 39769 */ 39770 function updateWith(object, path, updater, customizer) { 39771 customizer = typeof customizer == 'function' ? customizer : undefined; 39772 return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); 39773 } 39774 39775 /**
vendor: 1,263 bytes, lines 39776-39825
39776 * Creates an array of the own enumerable string keyed property values of `object`. 39777 * 39778 * **Note:** Non-object values are coerced to objects. 39779 * 39780 * @static 39781 * @since 0.1.0 39782 * @memberOf _ 39783 * @category Object 39784 * @param {Object} object The object to query. 39785 * @returns {Array} Returns the array of property values. 39786 * @example 39787 * 39788 * function Foo() { 39789 * this.a = 1; 39790 * this.b = 2; 39791 * } 39792 * 39793 * Foo.prototype.c = 3; 39794 * 39795 * _.values(new Foo); 39796 * // => [1, 2] (iteration order is not guaranteed) 39797 * 39798 * _.values('hi'); 39799 * // => ['h', 'i'] 39800 */ 39801 function values(object) { 39802 return object == null ? [] : baseValues(object, keys(object)); 39803 } 39804 39805 /** 39806 * Creates an array of the own and inherited enumerable string keyed property 39807 * values of `object`. 39808 * 39809 * **Note:** Non-object values are coerced to objects. 39810 * 39811 * @static 39812 * @memberOf _ 39813 * @since 3.0.0 39814 * @category Object 39815 * @param {Object} object The object to query. 39816 * @returns {Array} Returns the array of property values. 39817 * @example 39818 * 39819 * function Foo() { 39820 * this.a = 1; 39821 * this.b = 2; 39822 * } 39823 * 39824 * Foo.prototype.c = 3; 39825 *
vendor: 9,679 bytes, lines 39826-40146
39826 * _.valuesIn(new Foo); 39827 * // => [1, 2, 3] (iteration order is not guaranteed) 39828 */ 39829 function valuesIn(object) { 39830 return object == null ? [] : baseValues(object, keysIn(object)); 39831 } 39832 39833 /*------------------------------------------------------------------------*/ 39834 39835 /** 39836 * Clamps `number` within the inclusive `lower` and `upper` bounds. 39837 * 39838 * @static 39839 * @memberOf _ 39840 * @since 4.0.0 39841 * @category Number 39842 * @param {number} number The number to clamp. 39843 * @param {number} [lower] The lower bound. 39844 * @param {number} upper The upper bound. 39845 * @returns {number} Returns the clamped number. 39846 * @example 39847 * 39848 * _.clamp(-10, -5, 5); 39849 * // => -5 39850 * 39851 * _.clamp(10, -5, 5); 39852 * // => 5 39853 */ 39854 function clamp(number, lower, upper) { 39855 if (upper === undefined) { 39856 upper = lower; 39857 lower = undefined; 39858 } 39859 if (upper !== undefined) { 39860 upper = toNumber(upper); 39861 upper = upper === upper ? upper : 0; 39862 } 39863 if (lower !== undefined) { 39864 lower = toNumber(lower); 39865 lower = lower === lower ? lower : 0; 39866 } 39867 return baseClamp(toNumber(number), lower, upper); 39868 } 39869 39870 /** 39871 * Checks if `n` is between `start` and up to, but not including, `end`. If 39872 * `end` is not specified, it's set to `start` with `start` then set to `0`. 39873 * If `start` is greater than `end` the params are swapped to support 39874 * negative ranges. 39875 * 39876 * @static 39877 * @memberOf _ 39878 * @since 3.3.0 39879 * @category Number 39880 * @param {number} number The number to check. 39881 * @param {number} [start=0] The start of the range. 39882 * @param {number} end The end of the range. 39883 * @returns {boolean} Returns `true` if `number` is in the range, else `false`. 39884 * @see _.range, _.rangeRight 39885 * @example 39886 * 39887 * _.inRange(3, 2, 4); 39888 * // => true 39889 * 39890 * _.inRange(4, 8); 39891 * // => true 39892 * 39893 * _.inRange(4, 2); 39894 * // => false 39895 * 39896 * _.inRange(2, 2); 39897 * // => false 39898 * 39899 * _.inRange(1.2, 2); 39900 * // => true 39901 * 39902 * _.inRange(5.2, 4); 39903 * // => false 39904 * 39905 * _.inRange(-3, -2, -6); 39906 * // => true 39907 */ 39908 function inRange(number, start, end) { 39909 start = toFinite(start); 39910 if (end === undefined) { 39911 end = start; 39912 start = 0; 39913 } else { 39914 end = toFinite(end); 39915 } 39916 number = toNumber(number); 39917 return baseInRange(number, start, end); 39918 } 39919 39920 /** 39921 * Produces a random number between the inclusive `lower` and `upper` bounds. 39922 * If only one argument is provided a number between `0` and the given number 39923 * is returned. If `floating` is `true`, or either `lower` or `upper` are 39924 * floats, a floating-point number is returned instead of an integer. 39925 * 39926 * **Note:** JavaScript follows the IEEE-754 standard for resolving 39927 * floating-point values which can produce unexpected results. 39928 * 39929 * @static 39930 * @memberOf _ 39931 * @since 0.7.0 39932 * @category Number 39933 * @param {number} [lower=0] The lower bound. 39934 * @param {number} [upper=1] The upper bound. 39935 * @param {boolean} [floating] Specify returning a floating-point number. 39936 * @returns {number} Returns the random number. 39937 * @example 39938 * 39939 * _.random(0, 5); 39940 * // => an integer between 0 and 5 39941 * 39942 * _.random(5); 39943 * // => also an integer between 0 and 5 39944 * 39945 * _.random(5, true); 39946 * // => a floating-point number between 0 and 5 39947 * 39948 * _.random(1.2, 5.2); 39949 * // => a floating-point number between 1.2 and 5.2 39950 */ 39951 function random(lower, upper, floating) { 39952 if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { 39953 upper = floating = undefined; 39954 } 39955 if (floating === undefined) { 39956 if (typeof upper == 'boolean') { 39957 floating = upper; 39958 upper = undefined; 39959 } 39960 else if (typeof lower == 'boolean') { 39961 floating = lower; 39962 lower = undefined; 39963 } 39964 } 39965 if (lower === undefined && upper === undefined) { 39966 lower = 0; 39967 upper = 1; 39968 } 39969 else { 39970 lower = toFinite(lower); 39971 if (upper === undefined) { 39972 upper = lower; 39973 lower = 0; 39974 } else { 39975 upper = toFinite(upper); 39976 } 39977 } 39978 if (lower > upper) { 39979 var temp = lower; 39980 lower = upper; 39981 upper = temp; 39982 } 39983 if (floating || lower % 1 || upper % 1) { 39984 var rand = nativeRandom(); 39985 return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); 39986 } 39987 return baseRandom(lower, upper); 39988 } 39989 39990 /*------------------------------------------------------------------------*/ 39991 39992 /** 39993 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). 39994 * 39995 * @static 39996 * @memberOf _ 39997 * @since 3.0.0 39998 * @category String 39999 * @param {string} [string=''] The string to convert. 40000 * @returns {string} Returns the camel cased string. 40001 * @example 40002 * 40003 * _.camelCase('Foo Bar'); 40004 * // => 'fooBar' 40005 * 40006 * _.camelCase('--foo-bar--'); 40007 * // => 'fooBar' 40008 * 40009 * _.camelCase('__FOO_BAR__'); 40010 * // => 'fooBar' 40011 */ 40012 var camelCase = createCompounder(function(result, word, index) { 40013 word = word.toLowerCase(); 40014 return result + (index ? capitalize(word) : word); 40015 }); 40016 40017 /** 40018 * Converts the first character of `string` to upper case and the remaining 40019 * to lower case. 40020 * 40021 * @static 40022 * @memberOf _ 40023 * @since 3.0.0 40024 * @category String 40025 * @param {string} [string=''] The string to capitalize. 40026 * @returns {string} Returns the capitalized string. 40027 * @example 40028 * 40029 * _.capitalize('FRED'); 40030 * // => 'Fred' 40031 */ 40032 function capitalize(string) { 40033 return upperFirst(toString(string).toLowerCase()); 40034 } 40035 40036 /** 40037 * Deburrs `string` by converting 40038 * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) 40039 * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) 40040 * letters to basic Latin letters and removing 40041 * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). 40042 * 40043 * @static 40044 * @memberOf _ 40045 * @since 3.0.0 40046 * @category String 40047 * @param {string} [string=''] The string to deburr. 40048 * @returns {string} Returns the deburred string. 40049 * @example 40050 * 40051 * _.deburr('déjà vu'); 40052 * // => 'deja vu' 40053 */ 40054 function deburr(string) { 40055 string = toString(string); 40056 return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); 40057 } 40058 40059 /** 40060 * Checks if `string` ends with the given target string. 40061 * 40062 * @static 40063 * @memberOf _ 40064 * @since 3.0.0 40065 * @category String 40066 * @param {string} [string=''] The string to inspect. 40067 * @param {string} [target] The string to search for. 40068 * @param {number} [position=string.length] The position to search up to. 40069 * @returns {boolean} Returns `true` if `string` ends with `target`, 40070 * else `false`. 40071 * @example 40072 * 40073 * _.endsWith('abc', 'c'); 40074 * // => true 40075 * 40076 * _.endsWith('abc', 'b'); 40077 * // => false 40078 * 40079 * _.endsWith('abc', 'b', 2); 40080 * // => true 40081 */ 40082 function endsWith(string, target, position) { 40083 string = toString(string); 40084 target = baseToString(target); 40085 40086 var length = string.length; 40087 position = position === undefined 40088 ? length 40089 : baseClamp(toInteger(position), 0, length); 40090 40091 var end = position; 40092 position -= target.length; 40093 return position >= 0 && string.slice(position, end) == target; 40094 } 40095 40096 /** 40097 * Converts the characters "&", "<", ">", '"', and "'" in `string` to their 40098 * corresponding HTML entities. 40099 * 40100 * **Note:** No other characters are escaped. To escape additional 40101 * characters use a third-party library like [_he_](https://mths.be/he). 40102 * 40103 * Though the ">" character is escaped for symmetry, characters like 40104 * ">" and "/" don't need escaping in HTML and have no special meaning 40105 * unless they're part of a tag or unquoted attribute value. See 40106 * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) 40107 * (under "semi-related fun fact") for more details. 40108 * 40109 * When working with HTML you should always 40110 * [quote attribute values](http://wonko.com/post/html-escaping) to reduce 40111 * XSS vectors. 40112 * 40113 * @static 40114 * @since 0.1.0 40115 * @memberOf _ 40116 * @category String 40117 * @param {string} [string=''] The string to escape. 40118 * @returns {string} Returns the escaped string. 40119 * @example 40120 * 40121 * _.escape('fred, barney, & pebbles'); 40122 * // => 'fred, barney, & pebbles' 40123 */ 40124 function escape(string) { 40125 string = toString(string); 40126 return (string && reHasUnescapedHtml.test(string)) 40127 ? string.replace(reUnescapedHtml, escapeHtmlChar) 40128 : string; 40129 } 40130 40131 /** 40132 * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", 40133 * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. 40134 * 40135 * @static 40136 * @memberOf _ 40137 * @since 3.0.0 40138 * @category String 40139 * @param {string} [string=''] The string to escape. 40140 * @returns {string} Returns the escaped string. 40141 * @example 40142 * 40143 * _.escapeRegExp('[lodash](https://lodash.com/)'); 40144 * // => '\[lodash\]\(https://lodash\.com/\)' 40145 */ 40146 function escapeRegExp(string) {
vendor: 4,658 bytes, lines 40147-40316
40147 string = toString(string); 40148 return (string && reHasRegExpChar.test(string)) 40149 ? string.replace(reRegExpChar, '\\$&') 40150 : string; 40151 } 40152 40153 /** 40154 * Converts `string` to 40155 * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). 40156 * 40157 * @static 40158 * @memberOf _ 40159 * @since 3.0.0 40160 * @category String 40161 * @param {string} [string=''] The string to convert. 40162 * @returns {string} Returns the kebab cased string. 40163 * @example 40164 * 40165 * _.kebabCase('Foo Bar'); 40166 * // => 'foo-bar' 40167 * 40168 * _.kebabCase('fooBar'); 40169 * // => 'foo-bar' 40170 * 40171 * _.kebabCase('__FOO_BAR__'); 40172 * // => 'foo-bar' 40173 */ 40174 var kebabCase = createCompounder(function(result, word, index) { 40175 return result + (index ? '-' : '') + word.toLowerCase(); 40176 }); 40177 40178 /** 40179 * Converts `string`, as space separated words, to lower case. 40180 * 40181 * @static 40182 * @memberOf _ 40183 * @since 4.0.0 40184 * @category String 40185 * @param {string} [string=''] The string to convert. 40186 * @returns {string} Returns the lower cased string. 40187 * @example 40188 * 40189 * _.lowerCase('--Foo-Bar--'); 40190 * // => 'foo bar' 40191 * 40192 * _.lowerCase('fooBar'); 40193 * // => 'foo bar' 40194 * 40195 * _.lowerCase('__FOO_BAR__'); 40196 * // => 'foo bar' 40197 */ 40198 var lowerCase = createCompounder(function(result, word, index) { 40199 return result + (index ? ' ' : '') + word.toLowerCase(); 40200 }); 40201 40202 /** 40203 * Converts the first character of `string` to lower case. 40204 * 40205 * @static 40206 * @memberOf _ 40207 * @since 4.0.0 40208 * @category String 40209 * @param {string} [string=''] The string to convert. 40210 * @returns {string} Returns the converted string. 40211 * @example 40212 * 40213 * _.lowerFirst('Fred'); 40214 * // => 'fred' 40215 * 40216 * _.lowerFirst('FRED'); 40217 * // => 'fRED' 40218 */ 40219 var lowerFirst = createCaseFirst('toLowerCase'); 40220 40221 /** 40222 * Pads `string` on the left and right sides if it's shorter than `length`. 40223 * Padding characters are truncated if they can't be evenly divided by `length`. 40224 * 40225 * @static 40226 * @memberOf _ 40227 * @since 3.0.0 40228 * @category String 40229 * @param {string} [string=''] The string to pad. 40230 * @param {number} [length=0] The padding length. 40231 * @param {string} [chars=' '] The string used as padding. 40232 * @returns {string} Returns the padded string. 40233 * @example 40234 * 40235 * _.pad('abc', 8); 40236 * // => ' abc ' 40237 * 40238 * _.pad('abc', 8, '_-'); 40239 * // => '_-abc_-_' 40240 * 40241 * _.pad('abc', 3); 40242 * // => 'abc' 40243 */ 40244 function pad(string, length, chars) { 40245 string = toString(string); 40246 length = toInteger(length); 40247 40248 var strLength = length ? stringSize(string) : 0; 40249 if (!length || strLength >= length) { 40250 return string; 40251 } 40252 var mid = (length - strLength) / 2; 40253 return ( 40254 createPadding(nativeFloor(mid), chars) + 40255 string + 40256 createPadding(nativeCeil(mid), chars) 40257 ); 40258 } 40259 40260 /** 40261 * Pads `string` on the right side if it's shorter than `length`. Padding 40262 * characters are truncated if they exceed `length`. 40263 * 40264 * @static 40265 * @memberOf _ 40266 * @since 4.0.0 40267 * @category String 40268 * @param {string} [string=''] The string to pad. 40269 * @param {number} [length=0] The padding length. 40270 * @param {string} [chars=' '] The string used as padding. 40271 * @returns {string} Returns the padded string. 40272 * @example 40273 * 40274 * _.padEnd('abc', 6); 40275 * // => 'abc ' 40276 * 40277 * _.padEnd('abc', 6, '_-'); 40278 * // => 'abc_-_' 40279 * 40280 * _.padEnd('abc', 3); 40281 * // => 'abc' 40282 */ 40283 function padEnd(string, length, chars) { 40284 string = toString(string); 40285 length = toInteger(length); 40286 40287 var strLength = length ? stringSize(string) : 0; 40288 return (length && strLength < length) 40289 ? (string + createPadding(length - strLength, chars)) 40290 : string; 40291 } 40292 40293 /** 40294 * Pads `string` on the left side if it's shorter than `length`. Padding 40295 * characters are truncated if they exceed `length`. 40296 * 40297 * @static 40298 * @memberOf _ 40299 * @since 4.0.0 40300 * @category String 40301 * @param {string} [string=''] The string to pad. 40302 * @param {number} [length=0] The padding length. 40303 * @param {string} [chars=' '] The string used as padding. 40304 * @returns {string} Returns the padded string. 40305 * @example 40306 * 40307 * _.padStart('abc', 6); 40308 * // => ' abc' 40309 * 40310 * _.padStart('abc', 6, '_-'); 40311 * // => '_-_abc' 40312 * 40313 * _.padStart('abc', 3); 40314 * // => 'abc' 40315 */ 40316 function padStart(string, length, chars) {
vendor: 12,646 bytes, lines 40317-40674
40317 string = toString(string); 40318 length = toInteger(length); 40319 40320 var strLength = length ? stringSize(string) : 0; 40321 return (length && strLength < length) 40322 ? (createPadding(length - strLength, chars) + string) 40323 : string; 40324 } 40325 40326 /** 40327 * Converts `string` to an integer of the specified radix. If `radix` is 40328 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a 40329 * hexadecimal, in which case a `radix` of `16` is used. 40330 * 40331 * **Note:** This method aligns with the 40332 * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. 40333 * 40334 * @static 40335 * @memberOf _ 40336 * @since 1.1.0 40337 * @category String 40338 * @param {string} string The string to convert. 40339 * @param {number} [radix=10] The radix to interpret `value` by. 40340 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 40341 * @returns {number} Returns the converted integer. 40342 * @example 40343 * 40344 * _.parseInt('08'); 40345 * // => 8 40346 * 40347 * _.map(['6', '08', '10'], _.parseInt); 40348 * // => [6, 8, 10] 40349 */ 40350 function parseInt(string, radix, guard) { 40351 if (guard || radix == null) { 40352 radix = 0; 40353 } else if (radix) { 40354 radix = +radix; 40355 } 40356 return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); 40357 } 40358 40359 /** 40360 * Repeats the given string `n` times. 40361 * 40362 * @static 40363 * @memberOf _ 40364 * @since 3.0.0 40365 * @category String 40366 * @param {string} [string=''] The string to repeat. 40367 * @param {number} [n=1] The number of times to repeat the string. 40368 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 40369 * @returns {string} Returns the repeated string. 40370 * @example 40371 * 40372 * _.repeat('*', 3); 40373 * // => '***' 40374 * 40375 * _.repeat('abc', 2); 40376 * // => 'abcabc' 40377 * 40378 * _.repeat('abc', 0); 40379 * // => '' 40380 */ 40381 function repeat(string, n, guard) { 40382 if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { 40383 n = 1; 40384 } else { 40385 n = toInteger(n); 40386 } 40387 return baseRepeat(toString(string), n); 40388 } 40389 40390 /** 40391 * Replaces matches for `pattern` in `string` with `replacement`. 40392 * 40393 * **Note:** This method is based on 40394 * [`String#replace`](https://mdn.io/String/replace). 40395 * 40396 * @static 40397 * @memberOf _ 40398 * @since 4.0.0 40399 * @category String 40400 * @param {string} [string=''] The string to modify. 40401 * @param {RegExp|string} pattern The pattern to replace. 40402 * @param {Function|string} replacement The match replacement. 40403 * @returns {string} Returns the modified string. 40404 * @example 40405 * 40406 * _.replace('Hi Fred', 'Fred', 'Barney'); 40407 * // => 'Hi Barney' 40408 */ 40409 function replace() { 40410 var args = arguments, 40411 string = toString(args[0]); 40412 40413 return args.length < 3 ? string : string.replace(args[1], args[2]); 40414 } 40415 40416 /** 40417 * Converts `string` to 40418 * [snake case](https://en.wikipedia.org/wiki/Snake_case). 40419 * 40420 * @static 40421 * @memberOf _ 40422 * @since 3.0.0 40423 * @category String 40424 * @param {string} [string=''] The string to convert. 40425 * @returns {string} Returns the snake cased string. 40426 * @example 40427 * 40428 * _.snakeCase('Foo Bar'); 40429 * // => 'foo_bar' 40430 * 40431 * _.snakeCase('fooBar'); 40432 * // => 'foo_bar' 40433 * 40434 * _.snakeCase('--FOO-BAR--'); 40435 * // => 'foo_bar' 40436 */ 40437 var snakeCase = createCompounder(function(result, word, index) { 40438 return result + (index ? '_' : '') + word.toLowerCase(); 40439 }); 40440 40441 /** 40442 * Splits `string` by `separator`. 40443 * 40444 * **Note:** This method is based on 40445 * [`String#split`](https://mdn.io/String/split). 40446 * 40447 * @static 40448 * @memberOf _ 40449 * @since 4.0.0 40450 * @category String 40451 * @param {string} [string=''] The string to split. 40452 * @param {RegExp|string} separator The separator pattern to split by. 40453 * @param {number} [limit] The length to truncate results to. 40454 * @returns {Array} Returns the string segments. 40455 * @example 40456 * 40457 * _.split('a-b-c', '-', 2); 40458 * // => ['a', 'b'] 40459 */ 40460 function split(string, separator, limit) { 40461 if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { 40462 separator = limit = undefined; 40463 } 40464 limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; 40465 if (!limit) { 40466 return []; 40467 } 40468 string = toString(string); 40469 if (string && ( 40470 typeof separator == 'string' || 40471 (separator != null && !isRegExp(separator)) 40472 )) { 40473 separator = baseToString(separator); 40474 if (!separator && hasUnicode(string)) { 40475 return castSlice(stringToArray(string), 0, limit); 40476 } 40477 } 40478 return string.split(separator, limit); 40479 } 40480 40481 /** 40482 * Converts `string` to 40483 * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). 40484 * 40485 * @static 40486 * @memberOf _ 40487 * @since 3.1.0 40488 * @category String 40489 * @param {string} [string=''] The string to convert. 40490 * @returns {string} Returns the start cased string. 40491 * @example 40492 * 40493 * _.startCase('--foo-bar--'); 40494 * // => 'Foo Bar' 40495 * 40496 * _.startCase('fooBar'); 40497 * // => 'Foo Bar' 40498 * 40499 * _.startCase('__FOO_BAR__'); 40500 * // => 'FOO BAR' 40501 */ 40502 var startCase = createCompounder(function(result, word, index) { 40503 return result + (index ? ' ' : '') + upperFirst(word); 40504 }); 40505 40506 /** 40507 * Checks if `string` starts with the given target string. 40508 * 40509 * @static 40510 * @memberOf _ 40511 * @since 3.0.0 40512 * @category String 40513 * @param {string} [string=''] The string to inspect. 40514 * @param {string} [target] The string to search for. 40515 * @param {number} [position=0] The position to search from. 40516 * @returns {boolean} Returns `true` if `string` starts with `target`, 40517 * else `false`. 40518 * @example 40519 * 40520 * _.startsWith('abc', 'a'); 40521 * // => true 40522 * 40523 * _.startsWith('abc', 'b'); 40524 * // => false 40525 * 40526 * _.startsWith('abc', 'b', 1); 40527 * // => true 40528 */ 40529 function startsWith(string, target, position) { 40530 string = toString(string); 40531 position = position == null 40532 ? 0 40533 : baseClamp(toInteger(position), 0, string.length); 40534 40535 target = baseToString(target); 40536 return string.slice(position, position + target.length) == target; 40537 } 40538 40539 /** 40540 * Creates a compiled template function that can interpolate data properties 40541 * in "interpolate" delimiters, HTML-escape interpolated data properties in 40542 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data 40543 * properties may be accessed as free variables in the template. If a setting 40544 * object is given, it takes precedence over `_.templateSettings` values. 40545 * 40546 * **Note:** In the development build `_.template` utilizes 40547 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) 40548 * for easier debugging. 40549 * 40550 * For more information on precompiling templates see 40551 * [lodash's custom builds documentation](https://lodash.com/custom-builds). 40552 * 40553 * For more information on Chrome extension sandboxes see 40554 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). 40555 * 40556 * @static 40557 * @since 0.1.0 40558 * @memberOf _ 40559 * @category String 40560 * @param {string} [string=''] The template string. 40561 * @param {Object} [options={}] The options object. 40562 * @param {RegExp} [options.escape=_.templateSettings.escape] 40563 * The HTML "escape" delimiter. 40564 * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] 40565 * The "evaluate" delimiter. 40566 * @param {Object} [options.imports=_.templateSettings.imports] 40567 * An object to import into the template as free variables. 40568 * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] 40569 * The "interpolate" delimiter. 40570 * @param {string} [options.sourceURL='lodash.templateSources[n]'] 40571 * The sourceURL of the compiled template. 40572 * @param {string} [options.variable='obj'] 40573 * The data object variable name. 40574 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 40575 * @returns {Function} Returns the compiled template function. 40576 * @example 40577 * 40578 * // Use the "interpolate" delimiter to create a compiled template. 40579 * var compiled = _.template('hello <%= user %>!'); 40580 * compiled({ 'user': 'fred' }); 40581 * // => 'hello fred!' 40582 * 40583 * // Use the HTML "escape" delimiter to escape data property values. 40584 * var compiled = _.template('<b><%- value %></b>'); 40585 * compiled({ 'value': '<script>' }); 40586 * // => '<b><script></b>' 40587 * 40588 * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. 40589 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); 40590 * compiled({ 'users': ['fred', 'barney'] }); 40591 * // => '<li>fred</li><li>barney</li>' 40592 * 40593 * // Use the internal `print` function in "evaluate" delimiters. 40594 * var compiled = _.template('<% print("hello " + user); %>!'); 40595 * compiled({ 'user': 'barney' }); 40596 * // => 'hello barney!' 40597 * 40598 * // Use the ES template literal delimiter as an "interpolate" delimiter. 40599 * // Disable support by replacing the "interpolate" delimiter. 40600 * var compiled = _.template('hello ${ user }!'); 40601 * compiled({ 'user': 'pebbles' }); 40602 * // => 'hello pebbles!' 40603 * 40604 * // Use backslashes to treat delimiters as plain text. 40605 * var compiled = _.template('<%= "\\<%- value %\\>" %>'); 40606 * compiled({ 'value': 'ignored' }); 40607 * // => '<%- value %>' 40608 * 40609 * // Use the `imports` option to import `jQuery` as `jq`. 40610 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; 40611 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); 40612 * compiled({ 'users': ['fred', 'barney'] }); 40613 * // => '<li>fred</li><li>barney</li>' 40614 * 40615 * // Use the `sourceURL` option to specify a custom sourceURL for the template. 40616 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); 40617 * compiled(data); 40618 * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. 40619 * 40620 * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. 40621 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); 40622 * compiled.source; 40623 * // => function(data) { 40624 * // var __t, __p = ''; 40625 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; 40626 * // return __p; 40627 * // } 40628 * 40629 * // Use custom template delimiters. 40630 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; 40631 * var compiled = _.template('hello {{ user }}!'); 40632 * compiled({ 'user': 'mustache' }); 40633 * // => 'hello mustache!' 40634 * 40635 * // Use the `source` property to inline compiled templates for meaningful 40636 * // line numbers in error messages and stack traces. 40637 * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ 40638 * var JST = {\ 40639 * "main": ' + _.template(mainText).source + '\ 40640 * };\ 40641 * '); 40642 */ 40643 function template(string, options, guard) { 40644 // Based on John Resig's `tmpl` implementation 40645 // (http://ejohn.org/blog/javascript-micro-templating/) 40646 // and Laura Doktorova's doT.js (https://github.com/olado/doT). 40647 var settings = lodash.templateSettings; 40648 40649 if (guard && isIterateeCall(string, options, guard)) { 40650 options = undefined; 40651 } 40652 string = toString(string); 40653 options = assignInWith({}, options, settings, customDefaultsAssignIn); 40654 40655 var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), 40656 importsKeys = keys(imports), 40657 importsValues = baseValues(imports, importsKeys); 40658 40659 var isEscaping, 40660 isEvaluating, 40661 index = 0, 40662 interpolate = options.interpolate || reNoMatch, 40663 source = "__p += '"; 40664 40665 // Compile the regexp to match each delimiter. 40666 var reDelimiters = RegExp( 40667 (options.escape || reNoMatch).source + '|' + 40668 interpolate.source + '|' + 40669 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + 40670 (options.evaluate || reNoMatch).source + '|$' 40671 , 'g'); 40672 40673 // Use a sourceURL for easier debugging. 40674
vendor: 1,744 bytes, lines 40674-40718
40674var sourceURL = '//# sourceURL=' + 40675 ('sourceURL' in options 40676 ? options.sourceURL 40677 : ('lodash.templateSources[' + (++templateCounter) + ']') 40678 ) + '\n'; 40679 40680 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { 40681 interpolateValue || (interpolateValue = esTemplateValue); 40682 40683 // Escape characters that can't be included in string literals. 40684 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); 40685 40686 // Replace delimiters with snippets. 40687 if (escapeValue) { 40688 isEscaping = true; 40689 source += "' +\n__e(" + escapeValue + ") +\n'"; 40690 } 40691 if (evaluateValue) { 40692 isEvaluating = true; 40693 source += "';\n" + evaluateValue + ";\n__p += '"; 40694 } 40695 if (interpolateValue) { 40696 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; 40697 } 40698 index = offset + match.length; 40699 40700 // The JS engine embedded in Adobe products needs `match` returned in 40701 // order to produce the correct `offset` value. 40702 return match; 40703 }); 40704 40705 source += "';\n"; 40706 40707 // If `variable` is not specified wrap a with-statement around the generated 40708 // code to add the data object to the top of the scope chain. 40709 var variable = options.variable; 40710 if (!variable) { 40711 source = 'with (obj) {\n' + source + '\n}\n'; 40712 } 40713 // Cleanup code by stripping empty strings. 40714 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) 40715 .replace(reEmptyStringMiddle, '$1') 40716 .replace(reEmptyStringTrailing, '$1;'); 40717 40718 // Frame code as the function body.
vendor: 4,089 bytes, lines 40719-40861
40719 source = 'function(' + (variable || 'obj') + ') {\n' + 40720 (variable 40721 ? '' 40722 : 'obj || (obj = {});\n' 40723 ) + 40724 "var __t, __p = ''" + 40725 (isEscaping 40726 ? ', __e = _.escape' 40727 : '' 40728 ) + 40729 (isEvaluating 40730 ? ', __j = Array.prototype.join;\n' + 40731 "function print() { __p += __j.call(arguments, '') }\n" 40732 : ';\n' 40733 ) + 40734 source + 40735 'return __p\n}'; 40736 40737 var result = attempt(function() { 40738 return Function(importsKeys, sourceURL + 'return ' + source) 40739 .apply(undefined, importsValues); 40740 }); 40741 40742 // Provide the compiled function's source by its `toString` method or 40743 // the `source` property as a convenience for inlining compiled templates. 40744 result.source = source; 40745 if (isError(result)) { 40746 throw result; 40747 } 40748 return result; 40749 } 40750 40751 /** 40752 * Converts `string`, as a whole, to lower case just like 40753 * [String#toLowerCase](https://mdn.io/toLowerCase). 40754 * 40755 * @static 40756 * @memberOf _ 40757 * @since 4.0.0 40758 * @category String 40759 * @param {string} [string=''] The string to convert. 40760 * @returns {string} Returns the lower cased string. 40761 * @example 40762 * 40763 * _.toLower('--Foo-Bar--'); 40764 * // => '--foo-bar--' 40765 * 40766 * _.toLower('fooBar'); 40767 * // => 'foobar' 40768 * 40769 * _.toLower('__FOO_BAR__'); 40770 * // => '__foo_bar__' 40771 */ 40772 function toLower(value) { 40773 return toString(value).toLowerCase(); 40774 } 40775 40776 /** 40777 * Converts `string`, as a whole, to upper case just like 40778 * [String#toUpperCase](https://mdn.io/toUpperCase). 40779 * 40780 * @static 40781 * @memberOf _ 40782 * @since 4.0.0 40783 * @category String 40784 * @param {string} [string=''] The string to convert. 40785 * @returns {string} Returns the upper cased string. 40786 * @example 40787 * 40788 * _.toUpper('--foo-bar--'); 40789 * // => '--FOO-BAR--' 40790 * 40791 * _.toUpper('fooBar'); 40792 * // => 'FOOBAR' 40793 * 40794 * _.toUpper('__foo_bar__'); 40795 * // => '__FOO_BAR__' 40796 */ 40797 function toUpper(value) { 40798 return toString(value).toUpperCase(); 40799 } 40800 40801 /** 40802 * Removes leading and trailing whitespace or specified characters from `string`. 40803 * 40804 * @static 40805 * @memberOf _ 40806 * @since 3.0.0 40807 * @category String 40808 * @param {string} [string=''] The string to trim. 40809 * @param {string} [chars=whitespace] The characters to trim. 40810 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 40811 * @returns {string} Returns the trimmed string. 40812 * @example 40813 * 40814 * _.trim(' abc '); 40815 * // => 'abc' 40816 * 40817 * _.trim('-_-abc-_-', '_-'); 40818 * // => 'abc' 40819 * 40820 * _.map([' foo ', ' bar '], _.trim); 40821 * // => ['foo', 'bar'] 40822 */ 40823 function trim(string, chars, guard) { 40824 string = toString(string); 40825 if (string && (guard || chars === undefined)) { 40826 return string.replace(reTrim, ''); 40827 } 40828 if (!string || !(chars = baseToString(chars))) { 40829 return string; 40830 } 40831 var strSymbols = stringToArray(string), 40832 chrSymbols = stringToArray(chars), 40833 start = charsStartIndex(strSymbols, chrSymbols), 40834 end = charsEndIndex(strSymbols, chrSymbols) + 1; 40835 40836 return castSlice(strSymbols, start, end).join(''); 40837 } 40838 40839 /** 40840 * Removes trailing whitespace or specified characters from `string`. 40841 * 40842 * @static 40843 * @memberOf _ 40844 * @since 4.0.0 40845 * @category String 40846 * @param {string} [string=''] The string to trim. 40847 * @param {string} [chars=whitespace] The characters to trim. 40848 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 40849 * @returns {string} Returns the trimmed string. 40850 * @example 40851 * 40852 * _.trimEnd(' abc '); 40853 * // => ' abc' 40854 * 40855 * _.trimEnd('-_-abc-_-', '_-'); 40856 * // => '-_-abc' 40857 */ 40858 function trimEnd(string, chars, guard) { 40859 string = toString(string); 40860 if (string && (guard || chars === undefined)) { 40861 return string.replace(reTrimEnd, ''
vendor: 10,736 bytes, lines 40861-41205
40861); 40862 } 40863 if (!string || !(chars = baseToString(chars))) { 40864 return string; 40865 } 40866 var strSymbols = stringToArray(string), 40867 end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; 40868 40869 return castSlice(strSymbols, 0, end).join(''); 40870 } 40871 40872 /** 40873 * Removes leading whitespace or specified characters from `string`. 40874 * 40875 * @static 40876 * @memberOf _ 40877 * @since 4.0.0 40878 * @category String 40879 * @param {string} [string=''] The string to trim. 40880 * @param {string} [chars=whitespace] The characters to trim. 40881 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 40882 * @returns {string} Returns the trimmed string. 40883 * @example 40884 * 40885 * _.trimStart(' abc '); 40886 * // => 'abc ' 40887 * 40888 * _.trimStart('-_-abc-_-', '_-'); 40889 * // => 'abc-_-' 40890 */ 40891 function trimStart(string, chars, guard) { 40892 string = toString(string); 40893 if (string && (guard || chars === undefined)) { 40894 return string.replace(reTrimStart, ''); 40895 } 40896 if (!string || !(chars = baseToString(chars))) { 40897 return string; 40898 } 40899 var strSymbols = stringToArray(string), 40900 start = charsStartIndex(strSymbols, stringToArray(chars)); 40901 40902 return castSlice(strSymbols, start).join(''); 40903 } 40904 40905 /** 40906 * Truncates `string` if it's longer than the given maximum string length. 40907 * The last characters of the truncated string are replaced with the omission 40908 * string which defaults to "...". 40909 * 40910 * @static 40911 * @memberOf _ 40912 * @since 4.0.0 40913 * @category String 40914 * @param {string} [string=''] The string to truncate. 40915 * @param {Object} [options={}] The options object. 40916 * @param {number} [options.length=30] The maximum string length. 40917 * @param {string} [options.omission='...'] The string to indicate text is omitted. 40918 * @param {RegExp|string} [options.separator] The separator pattern to truncate to. 40919 * @returns {string} Returns the truncated string. 40920 * @example 40921 * 40922 * _.truncate('hi-diddly-ho there, neighborino'); 40923 * // => 'hi-diddly-ho there, neighbo...' 40924 * 40925 * _.truncate('hi-diddly-ho there, neighborino', { 40926 * 'length': 24, 40927 * 'separator': ' ' 40928 * }); 40929 * // => 'hi-diddly-ho there,...' 40930 * 40931 * _.truncate('hi-diddly-ho there, neighborino', { 40932 * 'length': 24, 40933 * 'separator': /,? +/ 40934 * }); 40935 * // => 'hi-diddly-ho there...' 40936 * 40937 * _.truncate('hi-diddly-ho there, neighborino', { 40938 * 'omission': ' [...]' 40939 * }); 40940 * // => 'hi-diddly-ho there, neig [...]' 40941 */ 40942 function truncate(string, options) { 40943 var length = DEFAULT_TRUNC_LENGTH, 40944 omission = DEFAULT_TRUNC_OMISSION; 40945 40946 if (isObject(options)) { 40947 var separator = 'separator' in options ? options.separator : separator; 40948 length = 'length' in options ? toInteger(options.length) : length; 40949 omission = 'omission' in options ? baseToString(options.omission) : omission; 40950 } 40951 string = toString(string); 40952 40953 var strLength = string.length; 40954 if (hasUnicode(string)) { 40955 var strSymbols = stringToArray(string); 40956 strLength = strSymbols.length; 40957 } 40958 if (length >= strLength) { 40959 return string; 40960 } 40961 var end = length - stringSize(omission); 40962 if (end < 1) { 40963 return omission; 40964 } 40965 var result = strSymbols 40966 ? castSlice(strSymbols, 0, end).join('') 40967 : string.slice(0, end); 40968 40969 if (separator === undefined) { 40970 return result + omission; 40971 } 40972 if (strSymbols) { 40973 end += (result.length - end); 40974 } 40975 if (isRegExp(separator)) { 40976 if (string.slice(end).search(separator)) { 40977 var match, 40978 substring = result; 40979 40980 if (!separator.global) { 40981 separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); 40982 } 40983 separator.lastIndex = 0; 40984 while ((match = separator.exec(substring))) { 40985 var newEnd = match.index; 40986 } 40987 result = result.slice(0, newEnd === undefined ? end : newEnd); 40988 } 40989 } else if (string.indexOf(baseToString(separator), end) != end) { 40990 var index = result.lastIndexOf(separator); 40991 if (index > -1) { 40992 result = result.slice(0, index); 40993 } 40994 } 40995 return result + omission; 40996 } 40997 40998 /** 40999 * The inverse of `_.escape`; this method converts the HTML entities 41000 * `&`, `<`, `>`, `"`, and `'` in `string` to 41001 * their corresponding characters. 41002 * 41003 * **Note:** No other HTML entities are unescaped. To unescape additional 41004 * HTML entities use a third-party library like [_he_](https://mths.be/he). 41005 * 41006 * @static 41007 * @memberOf _ 41008 * @since 0.6.0 41009 * @category String 41010 * @param {string} [string=''] The string to unescape. 41011 * @returns {string} Returns the unescaped string. 41012 * @example 41013 * 41014 * _.unescape('fred, barney, & pebbles'); 41015 * // => 'fred, barney, & pebbles' 41016 */ 41017 function unescape(string) { 41018 string = toString(string); 41019 return (string && reHasEscapedHtml.test(string)) 41020 ? string.replace(reEscapedHtml, unescapeHtmlChar) 41021 : string; 41022 } 41023 41024 /** 41025 * Converts `string`, as space separated words, to upper case. 41026 * 41027 * @static 41028 * @memberOf _ 41029 * @since 4.0.0 41030 * @category String 41031 * @param {string} [string=''] The string to convert. 41032 * @returns {string} Returns the upper cased string. 41033 * @example 41034 * 41035 * _.upperCase('--foo-bar'); 41036 * // => 'FOO BAR' 41037 * 41038 * _.upperCase('fooBar'); 41039 * // => 'FOO BAR' 41040 * 41041 * _.upperCase('__foo_bar__'); 41042 * // => 'FOO BAR' 41043 */ 41044 var upperCase = createCompounder(function(result, word, index) { 41045 return result + (index ? ' ' : '') + word.toUpperCase(); 41046 }); 41047 41048 /** 41049 * Converts the first character of `string` to upper case. 41050 * 41051 * @static 41052 * @memberOf _ 41053 * @since 4.0.0 41054 * @category String 41055 * @param {string} [string=''] The string to convert. 41056 * @returns {string} Returns the converted string. 41057 * @example 41058 * 41059 * _.upperFirst('fred'); 41060 * // => 'Fred' 41061 * 41062 * _.upperFirst('FRED'); 41063 * // => 'FRED' 41064 */ 41065 var upperFirst = createCaseFirst('toUpperCase'); 41066 41067 /** 41068 * Splits `string` into an array of its words. 41069 * 41070 * @static 41071 * @memberOf _ 41072 * @since 3.0.0 41073 * @category String 41074 * @param {string} [string=''] The string to inspect. 41075 * @param {RegExp|string} [pattern] The pattern to match words. 41076 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. 41077 * @returns {Array} Returns the words of `string`. 41078 * @example 41079 * 41080 * _.words('fred, barney, & pebbles'); 41081 * // => ['fred', 'barney', 'pebbles'] 41082 * 41083 * _.words('fred, barney, & pebbles', /[^, ]+/g); 41084 * // => ['fred', 'barney', '&', 'pebbles'] 41085 */ 41086 function words(string, pattern, guard) { 41087 string = toString(string); 41088 pattern = guard ? undefined : pattern; 41089 41090 if (pattern === undefined) { 41091 return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); 41092 } 41093 return string.match(pattern) || []; 41094 } 41095 41096 /*------------------------------------------------------------------------*/ 41097 41098 /** 41099 * Attempts to invoke `func`, returning either the result or the caught error 41100 * object. Any additional arguments are provided to `func` when it's invoked. 41101 * 41102 * @static 41103 * @memberOf _ 41104 * @since 3.0.0 41105 * @category Util 41106 * @param {Function} func The function to attempt. 41107 * @param {...*} [args] The arguments to invoke `func` with. 41108 * @returns {*} Returns the `func` result or error object. 41109 * @example 41110 * 41111 * // Avoid throwing errors for invalid selectors. 41112 * var elements = _.attempt(function(selector) { 41113 * return document.querySelectorAll(selector); 41114 * }, '>_>'); 41115 * 41116 * if (_.isError(elements)) { 41117 * elements = []; 41118 * } 41119 */ 41120 var attempt = baseRest(function(func, args) { 41121 try { 41122 return apply(func, undefined, args); 41123 } catch (e) { 41124 return isError(e) ? e : new Error(e); 41125 } 41126 }); 41127 41128 /** 41129 * Binds methods of an object to the object itself, overwriting the existing 41130 * method. 41131 * 41132 * **Note:** This method doesn't set the "length" property of bound functions. 41133 * 41134 * @static 41135 * @since 0.1.0 41136 * @memberOf _ 41137 * @category Util 41138 * @param {Object} object The object to bind and assign the bound methods to. 41139 * @param {...(string|string[])} methodNames The object method names to bind. 41140 * @returns {Object} Returns `object`. 41141 * @example 41142 * 41143 * var view = { 41144 * 'label': 'docs', 41145 * 'click': function() { 41146 * console.log('clicked ' + this.label); 41147 * } 41148 * }; 41149 * 41150 * _.bindAll(view, ['click']); 41151 * jQuery(element).on('click', view.click); 41152 * // => Logs 'clicked docs' when clicked. 41153 */ 41154 var bindAll = flatRest(function(object, methodNames) { 41155 arrayEach(methodNames, function(key) { 41156 key = toKey(key); 41157 baseAssignValue(object, key, bind(object[key], object)); 41158 }); 41159 return object; 41160 }); 41161 41162 /** 41163 * Creates a function that iterates over `pairs` and invokes the corresponding 41164 * function of the first predicate to return truthy. The predicate-function 41165 * pairs are invoked with the `this` binding and arguments of the created 41166 * function. 41167 * 41168 * @static 41169 * @memberOf _ 41170 * @since 4.0.0 41171 * @category Util 41172 * @param {Array} pairs The predicate-function pairs. 41173 * @returns {Function} Returns the new composite function. 41174 * @example 41175 * 41176 * var func = _.cond([ 41177 * [_.matches({ 'a': 1 }), _.constant('matches A')], 41178 * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], 41179 * [_.stubTrue, _.constant('no match')] 41180 * ]); 41181 * 41182 * func({ 'a': 1, 'b': 2 }); 41183 * // => 'matches A' 41184 * 41185 * func({ 'a': 0, 'b': 1 }); 41186 * // => 'matches B' 41187 * 41188 * func({ 'a': '1', 'b': '2' }); 41189 * // => 'no match' 41190 */ 41191 function cond(pairs) { 41192 var length = pairs == null ? 0 : pairs.length, 41193 toIteratee = getIteratee(); 41194 41195 pairs = !length ? [] : arrayMap(pairs, function(pair) { 41196 if (typeof pair[1] != 'function') { 41197 throw new TypeError(FUNC_ERROR_TEXT); 41198 } 41199 return [toIteratee(pair[0]), pair[1]]; 41200 }); 41201 41202 return baseRest(function(args) { 41203 var index = -1; 41204 while (++index < length) { 41205 var pair = pairs[index];
vendor: 19,681 bytes, lines 41206-41901
41206 if (apply(pair[0], this, args)) { 41207 return apply(pair[1], this, args); 41208 } 41209 } 41210 }); 41211 } 41212 41213 /** 41214 * Creates a function that invokes the predicate properties of `source` with 41215 * the corresponding property values of a given object, returning `true` if 41216 * all predicates return truthy, else `false`. 41217 * 41218 * **Note:** The created function is equivalent to `_.conformsTo` with 41219 * `source` partially applied. 41220 * 41221 * @static 41222 * @memberOf _ 41223 * @since 4.0.0 41224 * @category Util 41225 * @param {Object} source The object of property predicates to conform to. 41226 * @returns {Function} Returns the new spec function. 41227 * @example 41228 * 41229 * var objects = [ 41230 * { 'a': 2, 'b': 1 }, 41231 * { 'a': 1, 'b': 2 } 41232 * ]; 41233 * 41234 * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); 41235 * // => [{ 'a': 1, 'b': 2 }] 41236 */ 41237 function conforms(source) { 41238 return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); 41239 } 41240 41241 /** 41242 * Creates a function that returns `value`. 41243 * 41244 * @static 41245 * @memberOf _ 41246 * @since 2.4.0 41247 * @category Util 41248 * @param {*} value The value to return from the new function. 41249 * @returns {Function} Returns the new constant function. 41250 * @example 41251 * 41252 * var objects = _.times(2, _.constant({ 'a': 1 })); 41253 * 41254 * console.log(objects); 41255 * // => [{ 'a': 1 }, { 'a': 1 }] 41256 * 41257 * console.log(objects[0] === objects[1]); 41258 * // => true 41259 */ 41260 function constant(value) { 41261 return function() { 41262 return value; 41263 }; 41264 } 41265 41266 /** 41267 * Checks `value` to determine whether a default value should be returned in 41268 * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, 41269 * or `undefined`. 41270 * 41271 * @static 41272 * @memberOf _ 41273 * @since 4.14.0 41274 * @category Util 41275 * @param {*} value The value to check. 41276 * @param {*} defaultValue The default value. 41277 * @returns {*} Returns the resolved value. 41278 * @example 41279 * 41280 * _.defaultTo(1, 10); 41281 * // => 1 41282 * 41283 * _.defaultTo(undefined, 10); 41284 * // => 10 41285 */ 41286 function defaultTo(value, defaultValue) { 41287 return (value == null || value !== value) ? defaultValue : value; 41288 } 41289 41290 /** 41291 * Creates a function that returns the result of invoking the given functions 41292 * with the `this` binding of the created function, where each successive 41293 * invocation is supplied the return value of the previous. 41294 * 41295 * @static 41296 * @memberOf _ 41297 * @since 3.0.0 41298 * @category Util 41299 * @param {...(Function|Function[])} [funcs] The functions to invoke. 41300 * @returns {Function} Returns the new composite function. 41301 * @see _.flowRight 41302 * @example 41303 * 41304 * function square(n) { 41305 * return n * n; 41306 * } 41307 * 41308 * var addSquare = _.flow([_.add, square]); 41309 * addSquare(1, 2); 41310 * // => 9 41311 */ 41312 var flow = createFlow(); 41313 41314 /** 41315 * This method is like `_.flow` except that it creates a function that 41316 * invokes the given functions from right to left. 41317 * 41318 * @static 41319 * @since 3.0.0 41320 * @memberOf _ 41321 * @category Util 41322 * @param {...(Function|Function[])} [funcs] The functions to invoke. 41323 * @returns {Function} Returns the new composite function. 41324 * @see _.flow 41325 * @example 41326 * 41327 * function square(n) { 41328 * return n * n; 41329 * } 41330 * 41331 * var addSquare = _.flowRight([square, _.add]); 41332 * addSquare(1, 2); 41333 * // => 9 41334 */ 41335 var flowRight = createFlow(true); 41336 41337 /** 41338 * This method returns the first argument it receives. 41339 * 41340 * @static 41341 * @since 0.1.0 41342 * @memberOf _ 41343 * @category Util 41344 * @param {*} value Any value. 41345 * @returns {*} Returns `value`. 41346 * @example 41347 * 41348 * var object = { 'a': 1 }; 41349 * 41350 * console.log(_.identity(object) === object); 41351 * // => true 41352 */ 41353 function identity(value) { 41354 return value; 41355 } 41356 41357 /** 41358 * Creates a function that invokes `func` with the arguments of the created 41359 * function. If `func` is a property name, the created function returns the 41360 * property value for a given element. If `func` is an array or object, the 41361 * created function returns `true` for elements that contain the equivalent 41362 * source properties, otherwise it returns `false`. 41363 * 41364 * @static 41365 * @since 4.0.0 41366 * @memberOf _ 41367 * @category Util 41368 * @param {*} [func=_.identity] The value to convert to a callback. 41369 * @returns {Function} Returns the callback. 41370 * @example 41371 * 41372 * var users = [ 41373 * { 'user': 'barney', 'age': 36, 'active': true }, 41374 * { 'user': 'fred', 'age': 40, 'active': false } 41375 * ]; 41376 * 41377 * // The `_.matches` iteratee shorthand. 41378 * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); 41379 * // => [{ 'user': 'barney', 'age': 36, 'active': true }] 41380 * 41381 * // The `_.matchesProperty` iteratee shorthand. 41382 * _.filter(users, _.iteratee(['user', 'fred'])); 41383 * // => [{ 'user': 'fred', 'age': 40 }] 41384 * 41385 * // The `_.property` iteratee shorthand. 41386 * _.map(users, _.iteratee('user')); 41387 * // => ['barney', 'fred'] 41388 * 41389 * // Create custom iteratee shorthands. 41390 * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { 41391 * return !_.isRegExp(func) ? iteratee(func) : function(string) { 41392 * return func.test(string); 41393 * }; 41394 * }); 41395 * 41396 * _.filter(['abc', 'def'], /ef/); 41397 * // => ['def'] 41398 */ 41399 function iteratee(func) { 41400 return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); 41401 } 41402 41403 /** 41404 * Creates a function that performs a partial deep comparison between a given 41405 * object and `source`, returning `true` if the given object has equivalent 41406 * property values, else `false`. 41407 * 41408 * **Note:** The created function is equivalent to `_.isMatch` with `source` 41409 * partially applied. 41410 * 41411 * Partial comparisons will match empty array and empty object `source` 41412 * values against any array or object value, respectively. See `_.isEqual` 41413 * for a list of supported value comparisons. 41414 * 41415 * @static 41416 * @memberOf _ 41417 * @since 3.0.0 41418 * @category Util 41419 * @param {Object} source The object of property values to match. 41420 * @returns {Function} Returns the new spec function. 41421 * @example 41422 * 41423 * var objects = [ 41424 * { 'a': 1, 'b': 2, 'c': 3 }, 41425 * { 'a': 4, 'b': 5, 'c': 6 } 41426 * ]; 41427 * 41428 * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); 41429 * // => [{ 'a': 4, 'b': 5, 'c': 6 }] 41430 */ 41431 function matches(source) { 41432 return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); 41433 } 41434 41435 /** 41436 * Creates a function that performs a partial deep comparison between the 41437 * value at `path` of a given object to `srcValue`, returning `true` if the 41438 * object value is equivalent, else `false`. 41439 * 41440 * **Note:** Partial comparisons will match empty array and empty object 41441 * `srcValue` values against any array or object value, respectively. See 41442 * `_.isEqual` for a list of supported value comparisons. 41443 * 41444 * @static 41445 * @memberOf _ 41446 * @since 3.2.0 41447 * @category Util 41448 * @param {Array|string} path The path of the property to get. 41449 * @param {*} srcValue The value to match. 41450 * @returns {Function} Returns the new spec function. 41451 * @example 41452 * 41453 * var objects = [ 41454 * { 'a': 1, 'b': 2, 'c': 3 }, 41455 * { 'a': 4, 'b': 5, 'c': 6 } 41456 * ]; 41457 * 41458 * _.find(objects, _.matchesProperty('a', 4)); 41459 * // => { 'a': 4, 'b': 5, 'c': 6 } 41460 */ 41461 function matchesProperty(path, srcValue) { 41462 return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); 41463 } 41464 41465 /** 41466 * Creates a function that invokes the method at `path` of a given object. 41467 * Any additional arguments are provided to the invoked method. 41468 * 41469 * @static 41470 * @memberOf _ 41471 * @since 3.7.0 41472 * @category Util 41473 * @param {Array|string} path The path of the method to invoke. 41474 * @param {...*} [args] The arguments to invoke the method with. 41475 * @returns {Function} Returns the new invoker function. 41476 * @example 41477 * 41478 * var objects = [ 41479 * { 'a': { 'b': _.constant(2) } }, 41480 * { 'a': { 'b': _.constant(1) } } 41481 * ]; 41482 * 41483 * _.map(objects, _.method('a.b')); 41484 * // => [2, 1] 41485 * 41486 * _.map(objects, _.method(['a', 'b'])); 41487 * // => [2, 1] 41488 */ 41489 var method = baseRest(function(path, args) { 41490 return function(object) { 41491 return baseInvoke(object, path, args); 41492 }; 41493 }); 41494 41495 /** 41496 * The opposite of `_.method`; this method creates a function that invokes 41497 * the method at a given path of `object`. Any additional arguments are 41498 * provided to the invoked method. 41499 * 41500 * @static 41501 * @memberOf _ 41502 * @since 3.7.0 41503 * @category Util 41504 * @param {Object} object The object to query. 41505 * @param {...*} [args] The arguments to invoke the method with. 41506 * @returns {Function} Returns the new invoker function. 41507 * @example 41508 * 41509 * var array = _.times(3, _.constant), 41510 * object = { 'a': array, 'b': array, 'c': array }; 41511 * 41512 * _.map(['a[2]', 'c[0]'], _.methodOf(object)); 41513 * // => [2, 0] 41514 * 41515 * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); 41516 * // => [2, 0] 41517 */ 41518 var methodOf = baseRest(function(object, args) { 41519 return function(path) { 41520 return baseInvoke(object, path, args); 41521 }; 41522 }); 41523 41524 /** 41525 * Adds all own enumerable string keyed function properties of a source 41526 * object to the destination object. If `object` is a function, then methods 41527 * are added to its prototype as well. 41528 * 41529 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to 41530 * avoid conflicts caused by modifying the original. 41531 * 41532 * @static 41533 * @since 0.1.0 41534 * @memberOf _ 41535 * @category Util 41536 * @param {Function|Object} [object=lodash] The destination object. 41537 * @param {Object} source The object of functions to add. 41538 * @param {Object} [options={}] The options object. 41539 * @param {boolean} [options.chain=true] Specify whether mixins are chainable. 41540 * @returns {Function|Object} Returns `object`. 41541 * @example 41542 * 41543 * function vowels(string) { 41544 * return _.filter(string, function(v) { 41545 * return /[aeiou]/i.test(v); 41546 * }); 41547 * } 41548 * 41549 * _.mixin({ 'vowels': vowels }); 41550 * _.vowels('fred'); 41551 * // => ['e'] 41552 * 41553 * _('fred').vowels().value(); 41554 * // => ['e'] 41555 * 41556 * _.mixin({ 'vowels': vowels }, { 'chain': false }); 41557 * _('fred').vowels(); 41558 * // => ['e'] 41559 */ 41560 function mixin(object, source, options) { 41561 var props = keys(source), 41562 methodNames = baseFunctions(source, props); 41563 41564 if (options == null && 41565 !(isObject(source) && (methodNames.length || !props.length))) { 41566 options = source; 41567 source = object; 41568 object = this; 41569 methodNames = baseFunctions(source, keys(source)); 41570 } 41571 var chain = !(isObject(options) && 'chain' in options) || !!options.chain, 41572 isFunc = isFunction(object); 41573 41574 arrayEach(methodNames, function(methodName) { 41575 var func = source[methodName]; 41576 object[methodName] = func; 41577 if (isFunc) { 41578 object.prototype[methodName] = function() { 41579 var chainAll = this.__chain__; 41580 if (chain || chainAll) { 41581 var result = object(this.__wrapped__), 41582 actions = result.__actions__ = copyArray(this.__actions__); 41583 41584 actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); 41585 result.__chain__ = chainAll; 41586 return result; 41587 } 41588 return func.apply(object, arrayPush([this.value()], arguments)); 41589 }; 41590 } 41591 }); 41592 41593 return object; 41594 } 41595 41596 /** 41597 * Reverts the `_` variable to its previous value and returns a reference to 41598 * the `lodash` function. 41599 * 41600 * @static 41601 * @since 0.1.0 41602 * @memberOf _ 41603 * @category Util 41604 * @returns {Function} Returns the `lodash` function. 41605 * @example 41606 * 41607 * var lodash = _.noConflict(); 41608 */ 41609 function noConflict() { 41610 if (root._ === this) { 41611 root._ = oldDash; 41612 } 41613 return this; 41614 } 41615 41616 /** 41617 * This method returns `undefined`. 41618 * 41619 * @static 41620 * @memberOf _ 41621 * @since 2.3.0 41622 * @category Util 41623 * @example 41624 * 41625 * _.times(2, _.noop); 41626 * // => [undefined, undefined] 41627 */ 41628 function noop() { 41629 // No operation performed. 41630 } 41631 41632 /** 41633 * Creates a function that gets the argument at index `n`. If `n` is negative, 41634 * the nth argument from the end is returned. 41635 * 41636 * @static 41637 * @memberOf _ 41638 * @since 4.0.0 41639 * @category Util 41640 * @param {number} [n=0] The index of the argument to return. 41641 * @returns {Function} Returns the new pass-thru function. 41642 * @example 41643 * 41644 * var func = _.nthArg(1); 41645 * func('a', 'b', 'c', 'd'); 41646 * // => 'b' 41647 * 41648 * var func = _.nthArg(-2); 41649 * func('a', 'b', 'c', 'd'); 41650 * // => 'c' 41651 */ 41652 function nthArg(n) { 41653 n = toInteger(n); 41654 return baseRest(function(args) { 41655 return baseNth(args, n); 41656 }); 41657 } 41658 41659 /** 41660 * Creates a function that invokes `iteratees` with the arguments it receives 41661 * and returns their results. 41662 * 41663 * @static 41664 * @memberOf _ 41665 * @since 4.0.0 41666 * @category Util 41667 * @param {...(Function|Function[])} [iteratees=[_.identity]] 41668 * The iteratees to invoke. 41669 * @returns {Function} Returns the new function. 41670 * @example 41671 * 41672 * var func = _.over([Math.max, Math.min]); 41673 * 41674 * func(1, 2, 3, 4); 41675 * // => [4, 1] 41676 */ 41677 var over = createOver(arrayMap); 41678 41679 /** 41680 * Creates a function that checks if **all** of the `predicates` return 41681 * truthy when invoked with the arguments it receives. 41682 * 41683 * @static 41684 * @memberOf _ 41685 * @since 4.0.0 41686 * @category Util 41687 * @param {...(Function|Function[])} [predicates=[_.identity]] 41688 * The predicates to check. 41689 * @returns {Function} Returns the new function. 41690 * @example 41691 * 41692 * var func = _.overEvery([Boolean, isFinite]); 41693 * 41694 * func('1'); 41695 * // => true 41696 * 41697 * func(null); 41698 * // => false 41699 * 41700 * func(NaN); 41701 * // => false 41702 */ 41703 var overEvery = createOver(arrayEvery); 41704 41705 /** 41706 * Creates a function that checks if **any** of the `predicates` return 41707 * truthy when invoked with the arguments it receives. 41708 * 41709 * @static 41710 * @memberOf _ 41711 * @since 4.0.0 41712 * @category Util 41713 * @param {...(Function|Function[])} [predicates=[_.identity]] 41714 * The predicates to check. 41715 * @returns {Function} Returns the new function. 41716 * @example 41717 * 41718 * var func = _.overSome([Boolean, isFinite]); 41719 * 41720 * func('1'); 41721 * // => true 41722 * 41723 * func(null); 41724 * // => true 41725 * 41726 * func(NaN); 41727 * // => false 41728 */ 41729 var overSome = createOver(arraySome); 41730 41731 /** 41732 * Creates a function that returns the value at `path` of a given object. 41733 * 41734 * @static 41735 * @memberOf _ 41736 * @since 2.4.0 41737 * @category Util 41738 * @param {Array|string} path The path of the property to get. 41739 * @returns {Function} Returns the new accessor function. 41740 * @example 41741 * 41742 * var objects = [ 41743 * { 'a': { 'b': 2 } }, 41744 * { 'a': { 'b': 1 } } 41745 * ]; 41746 * 41747 * _.map(objects, _.property('a.b')); 41748 * // => [2, 1] 41749 * 41750 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); 41751 * // => [1, 2] 41752 */ 41753 function property(path) { 41754 return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); 41755 } 41756 41757 /** 41758 * The opposite of `_.property`; this method creates a function that returns 41759 * the value at a given path of `object`. 41760 * 41761 * @static 41762 * @memberOf _ 41763 * @since 3.0.0 41764 * @category Util 41765 * @param {Object} object The object to query. 41766 * @returns {Function} Returns the new accessor function. 41767 * @example 41768 * 41769 * var array = [0, 1, 2], 41770 * object = { 'a': array, 'b': array, 'c': array }; 41771 * 41772 * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); 41773 * // => [2, 0] 41774 * 41775 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); 41776 * // => [2, 0] 41777 */ 41778 function propertyOf(object) { 41779 return function(path) { 41780 return object == null ? undefined : baseGet(object, path); 41781 }; 41782 } 41783 41784 /** 41785 * Creates an array of numbers (positive and/or negative) progressing from 41786 * `start` up to, but not including, `end`. A step of `-1` is used if a negative 41787 * `start` is specified without an `end` or `step`. If `end` is not specified, 41788 * it's set to `start` with `start` then set to `0`. 41789 * 41790 * **Note:** JavaScript follows the IEEE-754 standard for resolving 41791 * floating-point values which can produce unexpected results. 41792 * 41793 * @static 41794 * @since 0.1.0 41795 * @memberOf _ 41796 * @category Util 41797 * @param {number} [start=0] The start of the range. 41798 * @param {number} end The end of the range. 41799 * @param {number} [step=1] The value to increment or decrement by. 41800 * @returns {Array} Returns the range of numbers. 41801 * @see _.inRange, _.rangeRight 41802 * @example 41803 * 41804 * _.range(4); 41805 * // => [0, 1, 2, 3] 41806 * 41807 * _.range(-4); 41808 * // => [0, -1, -2, -3] 41809 * 41810 * _.range(1, 5); 41811 * // => [1, 2, 3, 4] 41812 * 41813 * _.range(0, 20, 5); 41814 * // => [0, 5, 10, 15] 41815 * 41816 * _.range(0, -4, -1); 41817 * // => [0, -1, -2, -3] 41818 * 41819 * _.range(1, 4, 0); 41820 * // => [1, 1, 1] 41821 * 41822 * _.range(0); 41823 * // => [] 41824 */ 41825 var range = createRange(); 41826 41827 /** 41828 * This method is like `_.range` except that it populates values in 41829 * descending order. 41830 * 41831 * @static 41832 * @memberOf _ 41833 * @since 4.0.0 41834 * @category Util 41835 * @param {number} [start=0] The start of the range. 41836 * @param {number} end The end of the range. 41837 * @param {number} [step=1] The value to increment or decrement by. 41838 * @returns {Array} Returns the range of numbers. 41839 * @see _.inRange, _.range 41840 * @example 41841 * 41842 * _.rangeRight(4); 41843 * // => [3, 2, 1, 0] 41844 * 41845 * _.rangeRight(-4); 41846 * // => [-3, -2, -1, 0] 41847 * 41848 * _.rangeRight(1, 5); 41849 * // => [4, 3, 2, 1] 41850 * 41851 * _.rangeRight(0, 20, 5); 41852 * // => [15, 10, 5, 0] 41853 * 41854 * _.rangeRight(0, -4, -1); 41855 * // => [-3, -2, -1, 0] 41856 * 41857 * _.rangeRight(1, 4, 0); 41858 * // => [1, 1, 1] 41859 * 41860 * _.rangeRight(0); 41861 * // => [] 41862 */ 41863 var rangeRight = createRange(true); 41864 41865 /** 41866 * This method returns a new empty array. 41867 * 41868 * @static 41869 * @memberOf _ 41870 * @since 4.13.0 41871 * @category Util 41872 * @returns {Array} Returns the new empty array. 41873 * @example 41874 * 41875 * var arrays = _.times(2, _.stubArray); 41876 * 41877 * console.log(arrays); 41878 * // => [[], []] 41879 * 41880 * console.log(arrays[0] === arrays[1]); 41881 * // => false 41882 */ 41883 function stubArray() { 41884 return []; 41885 } 41886 41887 /** 41888 * This method returns `false`. 41889 * 41890 * @static 41891 * @memberOf _ 41892 * @since 4.13.0 41893 * @category Util 41894 * @returns {boolean} Returns `false`. 41895 * @example 41896 * 41897 * _.times(2, _.stubFalse); 41898 * // => [false, false] 41899 */ 41900 function stubFalse() { 41901 return false;
vendor: 1,044 bytes, lines 41902-41955
41902 } 41903 41904 /** 41905 * This method returns a new empty object. 41906 * 41907 * @static 41908 * @memberOf _ 41909 * @since 4.13.0 41910 * @category Util 41911 * @returns {Object} Returns the new empty object. 41912 * @example 41913 * 41914 * var objects = _.times(2, _.stubObject); 41915 * 41916 * console.log(objects); 41917 * // => [{}, {}] 41918 * 41919 * console.log(objects[0] === objects[1]); 41920 * // => false 41921 */ 41922 function stubObject() { 41923 return {}; 41924 } 41925 41926 /** 41927 * This method returns an empty string. 41928 * 41929 * @static 41930 * @memberOf _ 41931 * @since 4.13.0 41932 * @category Util 41933 * @returns {string} Returns the empty string. 41934 * @example 41935 * 41936 * _.times(2, _.stubString); 41937 * // => ['', ''] 41938 */ 41939 function stubString() { 41940 return ''; 41941 } 41942 41943 /** 41944 * This method returns `true`. 41945 * 41946 * @static 41947 * @memberOf _ 41948 * @since 4.13.0 41949 * @category Util 41950 * @returns {boolean} Returns `true`. 41951 * @example 41952 * 41953 * _.times(2, _.stubTrue); 41954 * // => [true, true] 41955 */
vendor: 9,081 bytes, lines 41956-42299
41956 function stubTrue() { 41957 return true; 41958 } 41959 41960 /** 41961 * Invokes the iteratee `n` times, returning an array of the results of 41962 * each invocation. The iteratee is invoked with one argument; (index). 41963 * 41964 * @static 41965 * @since 0.1.0 41966 * @memberOf _ 41967 * @category Util 41968 * @param {number} n The number of times to invoke `iteratee`. 41969 * @param {Function} [iteratee=_.identity] The function invoked per iteration. 41970 * @returns {Array} Returns the array of results. 41971 * @example 41972 * 41973 * _.times(3, String); 41974 * // => ['0', '1', '2'] 41975 * 41976 * _.times(4, _.constant(0)); 41977 * // => [0, 0, 0, 0] 41978 */ 41979 function times(n, iteratee) { 41980 n = toInteger(n); 41981 if (n < 1 || n > MAX_SAFE_INTEGER) { 41982 return []; 41983 } 41984 var index = MAX_ARRAY_LENGTH, 41985 length = nativeMin(n, MAX_ARRAY_LENGTH); 41986 41987 iteratee = getIteratee(iteratee); 41988 n -= MAX_ARRAY_LENGTH; 41989 41990 var result = baseTimes(length, iteratee); 41991 while (++index < n) { 41992 iteratee(index); 41993 } 41994 return result; 41995 } 41996 41997 /** 41998 * Converts `value` to a property path array. 41999 * 42000 * @static 42001 * @memberOf _ 42002 * @since 4.0.0 42003 * @category Util 42004 * @param {*} value The value to convert. 42005 * @returns {Array} Returns the new property path array. 42006 * @example 42007 * 42008 * _.toPath('a.b.c'); 42009 * // => ['a', 'b', 'c'] 42010 * 42011 * _.toPath('a[0].b.c'); 42012 * // => ['a', '0', 'b', 'c'] 42013 */ 42014 function toPath(value) { 42015 if (isArray(value)) { 42016 return arrayMap(value, toKey); 42017 } 42018 return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); 42019 } 42020 42021 /** 42022 * Generates a unique ID. If `prefix` is given, the ID is appended to it. 42023 * 42024 * @static 42025 * @since 0.1.0 42026 * @memberOf _ 42027 * @category Util 42028 * @param {string} [prefix=''] The value to prefix the ID with. 42029 * @returns {string} Returns the unique ID. 42030 * @example 42031 * 42032 * _.uniqueId('contact_'); 42033 * // => 'contact_104' 42034 * 42035 * _.uniqueId(); 42036 * // => '105' 42037 */ 42038 function uniqueId(prefix) { 42039 var id = ++idCounter; 42040 return toString(prefix) + id; 42041 } 42042 42043 /*------------------------------------------------------------------------*/ 42044 42045 /** 42046 * Adds two numbers. 42047 * 42048 * @static 42049 * @memberOf _ 42050 * @since 3.4.0 42051 * @category Math 42052 * @param {number} augend The first number in an addition. 42053 * @param {number} addend The second number in an addition. 42054 * @returns {number} Returns the total. 42055 * @example 42056 * 42057 * _.add(6, 4); 42058 * // => 10 42059 */ 42060 var add = createMathOperation(function(augend, addend) { 42061 return augend + addend; 42062 }, 0); 42063 42064 /** 42065 * Computes `number` rounded up to `precision`. 42066 * 42067 * @static 42068 * @memberOf _ 42069 * @since 3.10.0 42070 * @category Math 42071 * @param {number} number The number to round up. 42072 * @param {number} [precision=0] The precision to round up to. 42073 * @returns {number} Returns the rounded up number. 42074 * @example 42075 * 42076 * _.ceil(4.006); 42077 * // => 5 42078 * 42079 * _.ceil(6.004, 2); 42080 * // => 6.01 42081 * 42082 * _.ceil(6040, -2); 42083 * // => 6100 42084 */ 42085 var ceil = createRound('ceil'); 42086 42087 /** 42088 * Divide two numbers. 42089 * 42090 * @static 42091 * @memberOf _ 42092 * @since 4.7.0 42093 * @category Math 42094 * @param {number} dividend The first number in a division. 42095 * @param {number} divisor The second number in a division. 42096 * @returns {number} Returns the quotient. 42097 * @example 42098 * 42099 * _.divide(6, 4); 42100 * // => 1.5 42101 */ 42102 var divide = createMathOperation(function(dividend, divisor) { 42103 return dividend / divisor; 42104 }, 1); 42105 42106 /** 42107 * Computes `number` rounded down to `precision`. 42108 * 42109 * @static 42110 * @memberOf _ 42111 * @since 3.10.0 42112 * @category Math 42113 * @param {number} number The number to round down. 42114 * @param {number} [precision=0] The precision to round down to. 42115 * @returns {number} Returns the rounded down number. 42116 * @example 42117 * 42118 * _.floor(4.006); 42119 * // => 4 42120 * 42121 * _.floor(0.046, 2); 42122 * // => 0.04 42123 * 42124 * _.floor(4060, -2); 42125 * // => 4000 42126 */ 42127 var floor = createRound('floor'); 42128 42129 /** 42130 * Computes the maximum value of `array`. If `array` is empty or falsey, 42131 * `undefined` is returned. 42132 * 42133 * @static 42134 * @since 0.1.0 42135 * @memberOf _ 42136 * @category Math 42137 * @param {Array} array The array to iterate over. 42138 * @returns {*} Returns the maximum value. 42139 * @example 42140 * 42141 * _.max([4, 2, 8, 6]); 42142 * // => 8 42143 * 42144 * _.max([]); 42145 * // => undefined 42146 */ 42147 function max(array) { 42148 return (array && array.length) 42149 ? baseExtremum(array, identity, baseGt) 42150 : undefined; 42151 } 42152 42153 /** 42154 * This method is like `_.max` except that it accepts `iteratee` which is 42155 * invoked for each element in `array` to generate the criterion by which 42156 * the value is ranked. The iteratee is invoked with one argument: (value). 42157 * 42158 * @static 42159 * @memberOf _ 42160 * @since 4.0.0 42161 * @category Math 42162 * @param {Array} array The array to iterate over. 42163 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 42164 * @returns {*} Returns the maximum value. 42165 * @example 42166 * 42167 * var objects = [{ 'n': 1 }, { 'n': 2 }]; 42168 * 42169 * _.maxBy(objects, function(o) { return o.n; }); 42170 * // => { 'n': 2 } 42171 * 42172 * // The `_.property` iteratee shorthand. 42173 * _.maxBy(objects, 'n'); 42174 * // => { 'n': 2 } 42175 */ 42176 function maxBy(array, iteratee) { 42177 return (array && array.length) 42178 ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) 42179 : undefined; 42180 } 42181 42182 /** 42183 * Computes the mean of the values in `array`. 42184 * 42185 * @static 42186 * @memberOf _ 42187 * @since 4.0.0 42188 * @category Math 42189 * @param {Array} array The array to iterate over. 42190 * @returns {number} Returns the mean. 42191 * @example 42192 * 42193 * _.mean([4, 2, 8, 6]); 42194 * // => 5 42195 */ 42196 function mean(array) { 42197 return baseMean(array, identity); 42198 } 42199 42200 /** 42201 * This method is like `_.mean` except that it accepts `iteratee` which is 42202 * invoked for each element in `array` to generate the value to be averaged. 42203 * The iteratee is invoked with one argument: (value). 42204 * 42205 * @static 42206 * @memberOf _ 42207 * @since 4.7.0 42208 * @category Math 42209 * @param {Array} array The array to iterate over. 42210 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 42211 * @returns {number} Returns the mean. 42212 * @example 42213 * 42214 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; 42215 * 42216 * _.meanBy(objects, function(o) { return o.n; }); 42217 * // => 5 42218 * 42219 * // The `_.property` iteratee shorthand. 42220 * _.meanBy(objects, 'n'); 42221 * // => 5 42222 */ 42223 function meanBy(array, iteratee) { 42224 return baseMean(array, getIteratee(iteratee, 2)); 42225 } 42226 42227 /** 42228 * Computes the minimum value of `array`. If `array` is empty or falsey, 42229 * `undefined` is returned. 42230 * 42231 * @static 42232 * @since 0.1.0 42233 * @memberOf _ 42234 * @category Math 42235 * @param {Array} array The array to iterate over. 42236 * @returns {*} Returns the minimum value. 42237 * @example 42238 * 42239 * _.min([4, 2, 8, 6]); 42240 * // => 2 42241 * 42242 * _.min([]); 42243 * // => undefined 42244 */ 42245 function min(array) { 42246 return (array && array.length) 42247 ? baseExtremum(array, identity, baseLt) 42248 : undefined; 42249 } 42250 42251 /** 42252 * This method is like `_.min` except that it accepts `iteratee` which is 42253 * invoked for each element in `array` to generate the criterion by which 42254 * the value is ranked. The iteratee is invoked with one argument: (value). 42255 * 42256 * @static 42257 * @memberOf _ 42258 * @since 4.0.0 42259 * @category Math 42260 * @param {Array} array The array to iterate over. 42261 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 42262 * @returns {*} Returns the minimum value. 42263 * @example 42264 * 42265 * var objects = [{ 'n': 1 }, { 'n': 2 }]; 42266 * 42267 * _.minBy(objects, function(o) { return o.n; }); 42268 * // => { 'n': 1 } 42269 * 42270 * // The `_.property` iteratee shorthand. 42271 * _.minBy(objects, 'n'); 42272 * // => { 'n': 1 } 42273 */ 42274 function minBy(array, iteratee) { 42275 return (array && array.length) 42276 ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) 42277 : undefined; 42278 } 42279 42280 /** 42281 * Multiply two numbers. 42282 * 42283 * @static 42284 * @memberOf _ 42285 * @since 4.7.0 42286 * @category Math 42287 * @param {number} multiplier The first number in a multiplication. 42288 * @param {number} multiplicand The second number in a multiplication. 42289 * @returns {number} Returns the product. 42290 * @example 42291 * 42292 * _.multiply(6, 4); 42293 * // => 24 42294 */ 42295 var multiply = createMathOperation(function(multiplier, multiplicand) { 42296 return multiplier * multiplicand; 42297 }, 1); 42298 42299 /**
vendor: 13,137 bytes, lines 42300-42738
42300 * Computes `number` rounded to `precision`. 42301 * 42302 * @static 42303 * @memberOf _ 42304 * @since 3.10.0 42305 * @category Math 42306 * @param {number} number The number to round. 42307 * @param {number} [precision=0] The precision to round to. 42308 * @returns {number} Returns the rounded number. 42309 * @example 42310 * 42311 * _.round(4.006); 42312 * // => 4 42313 * 42314 * _.round(4.006, 2); 42315 * // => 4.01 42316 * 42317 * _.round(4060, -2); 42318 * // => 4100 42319 */ 42320 var round = createRound('round'); 42321 42322 /** 42323 * Subtract two numbers. 42324 * 42325 * @static 42326 * @memberOf _ 42327 * @since 4.0.0 42328 * @category Math 42329 * @param {number} minuend The first number in a subtraction. 42330 * @param {number} subtrahend The second number in a subtraction. 42331 * @returns {number} Returns the difference. 42332 * @example 42333 * 42334 * _.subtract(6, 4); 42335 * // => 2 42336 */ 42337 var subtract = createMathOperation(function(minuend, subtrahend) { 42338 return minuend - subtrahend; 42339 }, 0); 42340 42341 /** 42342 * Computes the sum of the values in `array`. 42343 * 42344 * @static 42345 * @memberOf _ 42346 * @since 3.4.0 42347 * @category Math 42348 * @param {Array} array The array to iterate over. 42349 * @returns {number} Returns the sum. 42350 * @example 42351 * 42352 * _.sum([4, 2, 8, 6]); 42353 * // => 20 42354 */ 42355 function sum(array) { 42356 return (array && array.length) 42357 ? baseSum(array, identity) 42358 : 0; 42359 } 42360 42361 /** 42362 * This method is like `_.sum` except that it accepts `iteratee` which is 42363 * invoked for each element in `array` to generate the value to be summed. 42364 * The iteratee is invoked with one argument: (value). 42365 * 42366 * @static 42367 * @memberOf _ 42368 * @since 4.0.0 42369 * @category Math 42370 * @param {Array} array The array to iterate over. 42371 * @param {Function} [iteratee=_.identity] The iteratee invoked per element. 42372 * @returns {number} Returns the sum. 42373 * @example 42374 * 42375 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; 42376 * 42377 * _.sumBy(objects, function(o) { return o.n; }); 42378 * // => 20 42379 * 42380 * // The `_.property` iteratee shorthand. 42381 * _.sumBy(objects, 'n'); 42382 * // => 20 42383 */ 42384 function sumBy(array, iteratee) { 42385 return (array && array.length) 42386 ? baseSum(array, getIteratee(iteratee, 2)) 42387 : 0; 42388 } 42389 42390 /*------------------------------------------------------------------------*/ 42391 42392 // Add methods that return wrapped values in chain sequences. 42393 lodash.after = after; 42394 lodash.ary = ary; 42395 lodash.assign = assign; 42396 lodash.assignIn = assignIn; 42397 lodash.assignInWith = assignInWith; 42398 lodash.assignWith = assignWith; 42399 lodash.at = at; 42400 lodash.before = before; 42401 lodash.bind = bind; 42402 lodash.bindAll = bindAll; 42403 lodash.bindKey = bindKey; 42404 lodash.castArray = castArray; 42405 lodash.chain = chain; 42406 lodash.chunk = chunk; 42407 lodash.compact = compact; 42408 lodash.concat = concat; 42409 lodash.cond = cond; 42410 lodash.conforms = conforms; 42411 lodash.constant = constant; 42412 lodash.countBy = countBy; 42413 lodash.create = create; 42414 lodash.curry = curry; 42415 lodash.curryRight = curryRight; 42416 lodash.debounce = debounce; 42417 lodash.defaults = defaults; 42418 lodash.defaultsDeep = defaultsDeep; 42419 lodash.defer = defer; 42420 lodash.delay = delay; 42421 lodash.difference = difference; 42422 lodash.differenceBy = differenceBy; 42423 lodash.differenceWith = differenceWith; 42424 lodash.drop = drop; 42425 lodash.dropRight = dropRight; 42426 lodash.dropRightWhile = dropRightWhile; 42427 lodash.dropWhile = dropWhile; 42428 lodash.fill = fill; 42429 lodash.filter = filter; 42430 lodash.flatMap = flatMap; 42431 lodash.flatMapDeep = flatMapDeep; 42432 lodash.flatMapDepth = flatMapDepth; 42433 lodash.flatten = flatten; 42434 lodash.flattenDeep = flattenDeep; 42435 lodash.flattenDepth = flattenDepth; 42436 lodash.flip = flip; 42437 lodash.flow = flow; 42438 lodash.flowRight = flowRight; 42439 lodash.fromPairs = fromPairs; 42440 lodash.functions = functions; 42441 lodash.functionsIn = functionsIn; 42442 lodash.groupBy = groupBy; 42443 lodash.initial = initial; 42444 lodash.intersection = intersection; 42445 lodash.intersectionBy = intersectionBy; 42446 lodash.intersectionWith = intersectionWith; 42447 lodash.invert = invert; 42448 lodash.invertBy = invertBy; 42449 lodash.invokeMap = invokeMap; 42450 lodash.iteratee = iteratee; 42451 lodash.keyBy = keyBy; 42452 lodash.keys = keys; 42453 lodash.keysIn = keysIn; 42454 lodash.map = map; 42455 lodash.mapKeys = mapKeys; 42456 lodash.mapValues = mapValues; 42457 lodash.matches = matches; 42458 lodash.matchesProperty = matchesProperty; 42459 lodash.memoize = memoize; 42460 lodash.merge = merge; 42461 lodash.mergeWith = mergeWith; 42462 lodash.method = method; 42463 lodash.methodOf = methodOf; 42464 lodash.mixin = mixin; 42465 lodash.negate = negate; 42466 lodash.nthArg = nthArg; 42467 lodash.omit = omit; 42468 lodash.omitBy = omitBy; 42469 lodash.once = once; 42470 lodash.orderBy = orderBy; 42471 lodash.over = over; 42472 lodash.overArgs = overArgs; 42473 lodash.overEvery = overEvery; 42474 lodash.overSome = overSome; 42475 lodash.partial = partial; 42476 lodash.partialRight = partialRight; 42477 lodash.partition = partition; 42478 lodash.pick = pick; 42479 lodash.pickBy = pickBy; 42480 lodash.property = property; 42481 lodash.propertyOf = propertyOf; 42482 lodash.pull = pull; 42483 lodash.pullAll = pullAll; 42484 lodash.pullAllBy = pullAllBy; 42485 lodash.pullAllWith = pullAllWith; 42486 lodash.pullAt = pullAt; 42487 lodash.range = range; 42488 lodash.rangeRight = rangeRight; 42489 lodash.rearg = rearg; 42490 lodash.reject = reject; 42491 lodash.remove = remove; 42492 lodash.rest = rest; 42493 lodash.reverse = reverse; 42494 lodash.sampleSize = sampleSize; 42495 lodash.set = set; 42496 lodash.setWith = setWith; 42497 lodash.shuffle = shuffle; 42498 lodash.slice = slice; 42499 lodash.sortBy = sortBy; 42500 lodash.sortedUniq = sortedUniq; 42501 lodash.sortedUniqBy = sortedUniqBy; 42502 lodash.split = split; 42503 lodash.spread = spread; 42504 lodash.tail = tail; 42505 lodash.take = take; 42506 lodash.takeRight = takeRight; 42507 lodash.takeRightWhile = takeRightWhile; 42508 lodash.takeWhile = takeWhile; 42509 lodash.tap = tap; 42510 lodash.throttle = throttle; 42511 lodash.thru = thru; 42512 lodash.toArray = toArray; 42513 lodash.toPairs = toPairs; 42514 lodash.toPairsIn = toPairsIn; 42515 lodash.toPath = toPath; 42516 lodash.toPlainObject = toPlainObject; 42517 lodash.transform = transform; 42518 lodash.unary = unary; 42519 lodash.union = union; 42520 lodash.unionBy = unionBy; 42521 lodash.unionWith = unionWith; 42522 lodash.uniq = uniq; 42523 lodash.uniqBy = uniqBy; 42524 lodash.uniqWith = uniqWith; 42525 lodash.unset = unset; 42526 lodash.unzip = unzip; 42527 lodash.unzipWith = unzipWith; 42528 lodash.update = update; 42529 lodash.updateWith = updateWith; 42530 lodash.values = values; 42531 lodash.valuesIn = valuesIn; 42532 lodash.without = without; 42533 lodash.words = words; 42534 lodash.wrap = wrap; 42535 lodash.xor = xor; 42536 lodash.xorBy = xorBy; 42537 lodash.xorWith = xorWith; 42538 lodash.zip = zip; 42539 lodash.zipObject = zipObject; 42540 lodash.zipObjectDeep = zipObjectDeep; 42541 lodash.zipWith = zipWith; 42542 42543 // Add aliases. 42544 lodash.entries = toPairs; 42545 lodash.entriesIn = toPairsIn; 42546 lodash.extend = assignIn; 42547 lodash.extendWith = assignInWith; 42548 42549 // Add methods to `lodash.prototype`. 42550 mixin(lodash, lodash); 42551 42552 /*------------------------------------------------------------------------*/ 42553 42554 // Add methods that return unwrapped values in chain sequences. 42555 lodash.add = add; 42556 lodash.attempt = attempt; 42557 lodash.camelCase = camelCase; 42558 lodash.capitalize = capitalize; 42559 lodash.ceil = ceil; 42560 lodash.clamp = clamp; 42561 lodash.clone = clone; 42562 lodash.cloneDeep = cloneDeep; 42563 lodash.cloneDeepWith = cloneDeepWith; 42564 lodash.cloneWith = cloneWith; 42565 lodash.conformsTo = conformsTo; 42566 lodash.deburr = deburr; 42567 lodash.defaultTo = defaultTo; 42568 lodash.divide = divide; 42569 lodash.endsWith = endsWith; 42570 lodash.eq = eq; 42571 lodash.escape = escape; 42572 lodash.escapeRegExp = escapeRegExp; 42573 lodash.every = every; 42574 lodash.find = find; 42575 lodash.findIndex = findIndex; 42576 lodash.findKey = findKey; 42577 lodash.findLast = findLast; 42578 lodash.findLastIndex = findLastIndex; 42579 lodash.findLastKey = findLastKey; 42580 lodash.floor = floor; 42581 lodash.forEach = forEach; 42582 lodash.forEachRight = forEachRight; 42583 lodash.forIn = forIn; 42584 lodash.forInRight = forInRight; 42585 lodash.forOwn = forOwn; 42586 lodash.forOwnRight = forOwnRight; 42587 lodash.get = get; 42588 lodash.gt = gt; 42589 lodash.gte = gte; 42590 lodash.has = has; 42591 lodash.hasIn = hasIn; 42592 lodash.head = head; 42593 lodash.identity = identity; 42594 lodash.includes = includes; 42595 lodash.indexOf = indexOf; 42596 lodash.inRange = inRange; 42597 lodash.invoke = invoke; 42598 lodash.isArguments = isArguments; 42599 lodash.isArray = isArray; 42600 lodash.isArrayBuffer = isArrayBuffer; 42601 lodash.isArrayLike = isArrayLike; 42602 lodash.isArrayLikeObject = isArrayLikeObject; 42603 lodash.isBoolean = isBoolean; 42604 lodash.isBuffer = isBuffer; 42605 lodash.isDate = isDate; 42606 lodash.isElement = isElement; 42607 lodash.isEmpty = isEmpty; 42608 lodash.isEqual = isEqual; 42609 lodash.isEqualWith = isEqualWith; 42610 lodash.isError = isError; 42611 lodash.isFinite = isFinite; 42612 lodash.isFunction = isFunction; 42613 lodash.isInteger = isInteger; 42614 lodash.isLength = isLength; 42615 lodash.isMap = isMap; 42616 lodash.isMatch = isMatch; 42617 lodash.isMatchWith = isMatchWith; 42618 lodash.isNaN = isNaN; 42619 lodash.isNative = isNative; 42620 lodash.isNil = isNil; 42621 lodash.isNull = isNull; 42622 lodash.isNumber = isNumber; 42623 lodash.isObject = isObject; 42624 lodash.isObjectLike = isObjectLike; 42625 lodash.isPlainObject = isPlainObject; 42626 lodash.isRegExp = isRegExp; 42627 lodash.isSafeInteger = isSafeInteger; 42628 lodash.isSet = isSet; 42629 lodash.isString = isString; 42630 lodash.isSymbol = isSymbol; 42631 lodash.isTypedArray = isTypedArray; 42632 lodash.isUndefined = isUndefined; 42633 lodash.isWeakMap = isWeakMap; 42634 lodash.isWeakSet = isWeakSet; 42635 lodash.join = join; 42636 lodash.kebabCase = kebabCase; 42637 lodash.last = last; 42638 lodash.lastIndexOf = lastIndexOf; 42639 lodash.lowerCase = lowerCase; 42640 lodash.lowerFirst = lowerFirst; 42641 lodash.lt = lt; 42642 lodash.lte = lte; 42643 lodash.max = max; 42644 lodash.maxBy = maxBy; 42645 lodash.mean = mean; 42646 lodash.meanBy = meanBy; 42647 lodash.min = min; 42648 lodash.minBy = minBy; 42649 lodash.stubArray = stubArray; 42650 lodash.stubFalse = stubFalse; 42651 lodash.stubObject = stubObject; 42652 lodash.stubString = stubString; 42653 lodash.stubTrue = stubTrue; 42654 lodash.multiply = multiply; 42655 lodash.nth = nth; 42656 lodash.noConflict = noConflict; 42657 lodash.noop = noop; 42658 lodash.now = now; 42659 lodash.pad = pad; 42660 lodash.padEnd = padEnd; 42661 lodash.padStart = padStart; 42662 lodash.parseInt = parseInt; 42663 lodash.random = random; 42664 lodash.reduce = reduce; 42665 lodash.reduceRight = reduceRight; 42666 lodash.repeat = repeat; 42667 lodash.replace = replace; 42668 lodash.result = result; 42669 lodash.round = round; 42670 lodash.runInContext = runInContext; 42671 lodash.sample = sample; 42672 lodash.size = size; 42673 lodash.snakeCase = snakeCase; 42674 lodash.some = some; 42675 lodash.sortedIndex = sortedIndex; 42676 lodash.sortedIndexBy = sortedIndexBy; 42677 lodash.sortedIndexOf = sortedIndexOf; 42678 lodash.sortedLastIndex = sortedLastIndex; 42679 lodash.sortedLastIndexBy = sortedLastIndexBy; 42680 lodash.sortedLastIndexOf = sortedLastIndexOf; 42681 lodash.startCase = startCase; 42682 lodash.startsWith = startsWith; 42683 lodash.subtract = subtract; 42684 lodash.sum = sum; 42685 lodash.sumBy = sumBy; 42686 lodash.template = template; 42687 lodash.times = times; 42688 lodash.toFinite = toFinite; 42689 lodash.toInteger = toInteger; 42690 lodash.toLength = toLength; 42691 lodash.toLower = toLower; 42692 lodash.toNumber = toNumber; 42693 lodash.toSafeInteger = toSafeInteger; 42694 lodash.toString = toString; 42695 lodash.toUpper = toUpper; 42696 lodash.trim = trim; 42697 lodash.trimEnd = trimEnd; 42698 lodash.trimStart = trimStart; 42699 lodash.truncate = truncate; 42700 lodash.unescape = unescape; 42701 lodash.uniqueId = uniqueId; 42702 lodash.upperCase = upperCase; 42703 lodash.upperFirst = upperFirst; 42704 42705 // Add aliases. 42706 lodash.each = forEach; 42707 lodash.eachRight = forEachRight; 42708 lodash.first = head; 42709 42710 mixin(lodash, (function() { 42711 var source = {}; 42712 baseForOwn(lodash, function(func, methodName) { 42713 if (!hasOwnProperty.call(lodash.prototype, methodName)) { 42714 source[methodName] = func; 42715 } 42716 }); 42717 return source; 42718 }()), { 'chain': false }); 42719 42720 /*------------------------------------------------------------------------*/ 42721 42722 /** 42723 * The semantic version number. 42724 * 42725 * @static 42726 * @memberOf _ 42727 * @type {string} 42728 */ 42729 lodash.VERSION = VERSION; 42730 42731 // Assign default placeholders. 42732 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { 42733 lodash[methodName].placeholder = lodash; 42734 }); 42735 42736 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. 42737 arrayEach(['drop', 'take'], function(methodName, index) { 42738 LazyWrapper.prototype[methodName] = function(n) {
vendor: 6,109 bytes, lines 42739-42914
42739 n = n === undefined ? 1 : nativeMax(toInteger(n), 0); 42740 42741 var result = (this.__filtered__ && !index) 42742 ? new LazyWrapper(this) 42743 : this.clone(); 42744 42745 if (result.__filtered__) { 42746 result.__takeCount__ = nativeMin(n, result.__takeCount__); 42747 } else { 42748 result.__views__.push({ 42749 'size': nativeMin(n, MAX_ARRAY_LENGTH), 42750 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') 42751 }); 42752 } 42753 return result; 42754 }; 42755 42756 LazyWrapper.prototype[methodName + 'Right'] = function(n) { 42757 return this.reverse()[methodName](n).reverse(); 42758 }; 42759 }); 42760 42761 // Add `LazyWrapper` methods that accept an `iteratee` value. 42762 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { 42763 var type = index + 1, 42764 isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; 42765 42766 LazyWrapper.prototype[methodName] = function(iteratee) { 42767 var result = this.clone(); 42768 result.__iteratees__.push({ 42769 'iteratee': getIteratee(iteratee, 3), 42770 'type': type 42771 }); 42772 result.__filtered__ = result.__filtered__ || isFilter; 42773 return result; 42774 }; 42775 }); 42776 42777 // Add `LazyWrapper` methods for `_.head` and `_.last`. 42778 arrayEach(['head', 'last'], function(methodName, index) { 42779 var takeName = 'take' + (index ? 'Right' : ''); 42780 42781 LazyWrapper.prototype[methodName] = function() { 42782 return this[takeName](1).value()[0]; 42783 }; 42784 }); 42785 42786 // Add `LazyWrapper` methods for `_.initial` and `_.tail`. 42787 arrayEach(['initial', 'tail'], function(methodName, index) { 42788 var dropName = 'drop' + (index ? '' : 'Right'); 42789 42790 LazyWrapper.prototype[methodName] = function() { 42791 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); 42792 }; 42793 }); 42794 42795 LazyWrapper.prototype.compact = function() { 42796 return this.filter(identity); 42797 }; 42798 42799 LazyWrapper.prototype.find = function(predicate) { 42800 return this.filter(predicate).head(); 42801 }; 42802 42803 LazyWrapper.prototype.findLast = function(predicate) { 42804 return this.reverse().find(predicate); 42805 }; 42806 42807 LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { 42808 if (typeof path == 'function') { 42809 return new LazyWrapper(this); 42810 } 42811 return this.map(function(value) { 42812 return baseInvoke(value, path, args); 42813 }); 42814 }); 42815 42816 LazyWrapper.prototype.reject = function(predicate) { 42817 return this.filter(negate(getIteratee(predicate))); 42818 }; 42819 42820 LazyWrapper.prototype.slice = function(start, end) { 42821 start = toInteger(start); 42822 42823 var result = this; 42824 if (result.__filtered__ && (start > 0 || end < 0)) { 42825 return new LazyWrapper(result); 42826 } 42827 if (start < 0) { 42828 result = result.takeRight(-start); 42829 } else if (start) { 42830 result = result.drop(start); 42831 } 42832 if (end !== undefined) { 42833 end = toInteger(end); 42834 result = end < 0 ? result.dropRight(-end) : result.take(end - start); 42835 } 42836 return result; 42837 }; 42838 42839 LazyWrapper.prototype.takeRightWhile = function(predicate) { 42840 return this.reverse().takeWhile(predicate).reverse(); 42841 }; 42842 42843 LazyWrapper.prototype.toArray = function() { 42844 return this.take(MAX_ARRAY_LENGTH); 42845 }; 42846 42847 // Add `LazyWrapper` methods to `lodash.prototype`. 42848 baseForOwn(LazyWrapper.prototype, function(func, methodName) { 42849 var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), 42850 isTaker = /^(?:head|last)$/.test(methodName), 42851 lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], 42852 retUnwrapped = isTaker || /^find/.test(methodName); 42853 42854 if (!lodashFunc) { 42855 return; 42856 } 42857 lodash.prototype[methodName] = function() { 42858 var value = this.__wrapped__, 42859 args = isTaker ? [1] : arguments, 42860 isLazy = value instanceof LazyWrapper, 42861 iteratee = args[0], 42862 useLazy = isLazy || isArray(value); 42863 42864 var interceptor = function(value) { 42865 var result = lodashFunc.apply(lodash, arrayPush([value], args)); 42866 return (isTaker && chainAll) ? result[0] : result; 42867 }; 42868 42869 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { 42870 // Avoid lazy use if the iteratee has a "length" value other than `1`. 42871 isLazy = useLazy = false; 42872 } 42873 var chainAll = this.__chain__, 42874 isHybrid = !!this.__actions__.length, 42875 isUnwrapped = retUnwrapped && !chainAll, 42876 onlyLazy = isLazy && !isHybrid; 42877 42878 if (!retUnwrapped && useLazy) { 42879 value = onlyLazy ? value : new LazyWrapper(this); 42880 var result = func.apply(value, args); 42881 result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); 42882 return new LodashWrapper(result, chainAll); 42883 } 42884 if (isUnwrapped && onlyLazy) { 42885 return func.apply(this, args); 42886 } 42887 result = this.thru(interceptor); 42888 return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; 42889 }; 42890 }); 42891 42892 // Add `Array` methods to `lodash.prototype`. 42893 arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { 42894 var func = arrayProto[methodName], 42895 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', 42896 retUnwrapped = /^(?:pop|shift)$/.test(methodName); 42897 42898 lodash.prototype[methodName] = function() { 42899 var args = arguments; 42900 if (retUnwrapped && !this.__chain__) { 42901 var value = this.value(); 42902 return func.apply(isArray(value) ? value : [], args); 42903 } 42904 return this[chainName](function(value) { 42905 return func.apply(isArray(value) ? value : [], args); 42906 }); 42907 }; 42908 }); 42909 42910 // Map minified method names to their real names. 42911 baseForOwn(LazyWrapper.prototype, function(func, methodName) { 42912 var lodashFunc = lodash[methodName]; 42913 if (lodashFunc) { 42914 var key =
42914(lodashFunc.name + ''), 42915 names = realNames[key] || (realNames[key] = []); 42916 42917 names.push({ 'name': methodName, 'func': lodashFunc }); 42918 } 42919 }); 42920 42921 realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ 42922 'name': 'wrapper', 42923 'func': undefined 42924 }]; 42925 42926 // Add methods to `LazyWrapper`. 42927 LazyWrapper.prototype.clone = lazyClone; 42928 LazyWrapper.prototype.reverse = lazyReverse; 42929 LazyWrapper.prototype.value = lazyValue; 42930 42931 // Add chain sequence methods to the `lodash` wrapper. 42932 lodash.prototype.at = wrapperAt; 42933 lodash.prototype.chain = wrapperChain; 42934 lodash.prototype.commit = wrapperCommit; 42935 lodash.prototype.next = wrapperNext; 42936 lodash.prototype.plant = wrapperPlant; 42937 lodash.prototype.reverse = wrapperReverse; 42938 lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; 42939 42940 // Add lazy aliases. 42941 lodash.prototype.first = lodash.prototype.head; 42942 42943 if (symIterator) { 42944 lodash.prototype[symIterator] = wrapperToIterator; 42945 } 42946 return lodash; 42947 }); 42948 42949 /*--------------------------------------------------------------------------*/ 42950 42951 // Export lodash. 42952 var _ = runInContext(); 42953 42954 // Some AMD build optimizers, like r.js, check for condition patterns like: 42955 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { 42956 // Expose Lodash on the global object to prevent errors when Lodash is 42957 // loaded by a script tag in the presence of an AMD loader. 42958 // See http://requirejs.org/docs/errors.html#mismatch for more details. 42959 // Use `_.noConflict` to remove Lodash from the global object. 42960 root._ = _; 42961 42962 // Define as an anonymous module so, through path mapping, it can be 42963 // referenced as the "underscore" module. 42964 define(function() { 42965 return _; 42966 }); 42967 } 42968 // Check for `exports` after `define` in case a build optimizer adds it. 42969 else if (freeModule) { 42970 // Export for Node.js. 42971 (freeModule.exports = _)._ = _; 42972 // Export for CommonJS support. 42973 freeExports._ = _; 42974 } 42975 else { 42976 // Export to the global object. 42977 root._ = _; 42978 } 42979}.call(this)); 42980 42981}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 42982},{}],172:[function(require,module,exports){ 42983'use strict'; 42984 42985var range; // Create a range object for efficently rendering strings to elements. 42986var NS_XHTML = 'http://www.w3.org/1999/xhtml'; 42987 42988var doc = typeof document === 'undefined' ? undefined : document; 42989 42990var testEl = doc ? 42991 doc.body || doc.createElement('div') : 42992 {}; 42993 42994// Fixes <https://github.com/patrick-steele-idem/morphdom/issues/32>
42995// (IE7+ support) <=IE7 does not support el.hasAttribute(name) 42996var actualHasAttributeNS; 42997 42998if (testEl.hasAttributeNS) { 42999 actualHasAttributeNS = function(el, namespaceURI, name) { 43000 return el.hasAttributeNS(namespaceURI, name); 43001 }; 43002} else if (testEl.hasAttribute) { 43003 actualHasAttributeNS = function(el, namespaceURI, name) { 43004 return el.hasAttribute(name); 43005 }; 43006} else { 43007 actualHasAttributeNS = function(el, namespaceURI, name) { 43008 return el.getAttributeNode(namespaceURI, name) != null; 43009 }; 43010} 43011 43012var hasAttributeNS = actualHasAttributeNS; 43013 43014 43015function toElement(str) { 43016 if (!range && doc.createRange) { 43017 range = doc.createRange(); 43018 range.selectNode(doc.body); 43019 } 43020 43021 var fragment; 43022 if (range && range.createContextualFragment) { 43023 fragment = range.createContextualFragment(str); 43024 } else { 43025 fragment = doc.createElement('body'); 43026 fragment.innerHTML = str; 43027 } 43028 return fragment.childNodes[0]; 43029} 43030 43031/** 43032 * Returns true if two node's names are the same. 43033 * 43034 * NOTE: We don't bother checking `namespaceURI` because you will never find two HTML elements with the same 43035 * nodeName and different namespace URIs. 43036 * 43037 * @param {Element} a 43038 * @param {Element} b The target element 43039 * @return {boolean} 43040 */ 43041function compareNodeNames(fromEl, toEl) { 43042 var fromNodeName = fromEl.nodeName; 43043 var toNodeName = toEl.nodeName; 43044 43045 if (fromNodeName === toNodeName) { 43046 return true; 43047 } 43048 43049 if (toEl.actualize && 43050 fromNodeName.charCodeAt(0) < 91 && /* from tag name is upper case */ 43051 toNodeName.charCodeAt(0) > 90 /* target tag name is lower case */) { 43052 // If the target element is a virtual DOM node then we may need to normalize the tag name 43053 // before comparing. Normal HTML elements that are in the "http://www.w3.org/1999/xhtml" 43054 // are converted to upper case 43055 return fromNodeName === toNodeName.toUpperCase(); 43056 } else { 43057 return false; 43058 } 43059} 43060 43061/** 43062 * Create an element, optionally with a known namespace URI. 43063 * 43064 * @param {string} name the element name, e.g. 'div' or 'svg' 43065 * @param {string} [namespaceURI] the element's namespace URI, i.e. the value of 43066 * its `xmlns` attribute or its inferred namespace. 43067 * 43068 * @return {Element} 43069 */ 43070function createElementNS(name, namespaceURI) { 43071 return !namespaceURI || namespaceURI === NS_XHTML ? 43072 doc.createElement(name) : 43073 doc.createElementNS(namespaceURI, name); 43074} 43075 43076/** 43077 * Copies the children of one DOM element to another DOM element 43078 */ 43079function moveChildren(fromEl, toEl) { 43080 var curChild = fromEl.firstChild; 43081 while (curChild) { 43082 var nextChild = curChild.nextSibling; 43083 toEl.appendChild(curChild); 43084 curChild = nextChild; 43085 } 43086 return toEl; 43087} 43088 43089function morphAttrs(fromNode, toNode) { 43090 var attrs = toNode.attributes; 43091 var i; 43092 var attr; 43093 var attrName; 43094 var attrNamespaceURI; 43095 var attrValue; 43096 var fromValue; 43097 43098 for (i = attrs.length - 1; i >= 0; --i) { 43099 attr = attrs[i]; 43100 attrName = attr.name; 43101 attrNamespaceURI = attr.namespaceURI; 43102 attrValue = attr.value; 43103 43104 if (attrNamespaceURI) { 43105 attrName = attr.localName || attrName; 43106 fromValue = fromNode.getAttributeNS(attrNamespaceURI, attrName); 43107 43108 if (fromValue !== attrValue) { 43109 fromNode.setAttributeNS(attrNamespaceURI, attrName, attrValue); 43110 } 43111 } else { 43112 fromValue = fromNode.getAttribute(attrName); 43113 43114 if (fromValue !== attrValue) { 43115 fromNode.setAttribute(attrName, attrValue); 43116 } 43117 } 43118 } 43119 43120 // Remove any extra attributes found on the original DOM element that 43121 // weren't found on the target element. 43122 attrs = fromNode.attributes; 43123 43124 for (i = attrs.length - 1; i >= 0; --i) { 43125 attr = attrs[i]; 43126 if (attr.specified !== false) { 43127 attrName = attr.name; 43128 attrNamespaceURI = attr.namespaceURI; 43129 43130 if (attrNamespaceURI) { 43131 attrName = attr.localName || attrName; 43132 43133 if (!hasAttributeNS(toNode, attrNamespaceURI, attrName)) { 43134 fromNode.removeAttributeNS(attrNamespaceURI, attrName); 43135 } 43136 } else { 43137 if (!hasAttributeNS(toNode, null, attrName)) { 43138 fromNode.removeAttribute(attrName); 43139 } 43140 } 43141 } 43142 } 43143} 43144 43145function syncBooleanAttrProp(fromEl, toEl, name) { 43146 if (fromEl[name] !== toEl[name]) { 43147 fromEl[name] = toEl[name]; 43148 if (fromEl[name]) { 43149 fromEl.setAttribute(name, ''); 43150 } else { 43151 fromEl.removeAttribute(name, ''); 43152 } 43153 } 43154} 43155 43156var specialElHandlers = { 43157 /** 43158 * Needed for IE. Apparently IE doesn't think that "selected" is an 43159 * attribute when reading over the attributes using selectEl.attributes 43160 */ 43161 OPTION: function(fromEl, toEl) { 43162 syncBooleanAttrProp(fromEl, toEl, 'selected'); 43163 }, 43164 /** 43165 * The "value" attribute is special for the <input> element since it sets 43166 * the initial value. Changing the "value" attribute without changing the 43167 * "value" property will have no effect since it is only used to the set the 43168 * initial value. Similar for the "checked" attribute, and "disabled". 43169 */ 43170 INPUT: function(fromEl, toEl) { 43171 syncBooleanAttrProp(fromEl, toEl, 'checked'); 43172 syncBooleanAttrProp(fromEl, toEl, 'disabled'); 43173 43174 if (fromEl.value !== toEl.value) { 43175 fromEl.value = toEl.value; 43176 } 43177 43178 if (!hasAttributeNS(toEl, null, 'value')) { 43179 fromEl.removeAttribute('value'); 43180 } 43181 }, 43182 43183 TEXTAREA: function(fromEl, toEl) { 43184 var newValue = toEl.value; 43185 if (fromEl.value !== newValue) { 43186 fromEl.value = newValue; 43187 } 43188 43189 if (fromEl.firstChild) { 43190 // Needed for IE. Apparently IE sets the placeholder as the 43191 // node value and vise versa. This ignores an empty update. 43192 if (newValue === '' && fromEl.firstChild.nodeValue === fromEl.placeholder) { 43193 return; 43194 } 43195 43196 fromEl.firstChild.nodeValue = newValue; 43197 } 43198 }, 43199 SELECT: function(fromEl, toEl) { 43200 if (!hasAttributeNS(toEl, null, 'multiple')) { 43201 var selectedIndex = -1; 43202 var i = 0; 43203 var curChild = toEl.firstChild; 43204 while(curChild) { 43205 var nodeName = curChild.nodeName; 43206 if (nodeName && nodeName.toUpperCase() === 'OPTION') { 43207 if (hasAttributeNS(curChild, null, 'selected')) { 43208 selectedIndex = i; 43209 break; 43210 } 43211 i++; 43212 } 43213 curChild = curChild.nextSibling; 43214 } 43215 43216 fromEl.selectedIndex = i; 43217 } 43218 } 43219}; 43220 43221var ELEMENT_NODE = 1; 43222var TEXT_NODE = 3; 43223var COMMENT_NODE = 8; 43224 43225function noop() {} 43226 43227function defaultGetNodeKey(node) { 43228 return node.id; 43229} 43230 43231function morphdomFactory(morphAttrs) { 43232 43233 return function morphdom(fromNode, toNode, options) { 43234 if (!options) { 43235 options = {}; 43236 } 43237 43238 if (typeof toNode === 'string') { 43239 if (fromNode.nodeName === '#document' || fromNode.nodeName === 'HTML') { 43240 var toNodeHtml = toNode; 43241 toNode = doc.createElement('html'); 43242 toNode.innerHTML = toNodeHtml; 43243 } else { 43244 toNode = toElement(toNode); 43245 } 43246 } 43247 43248 var getNodeKey = options.getNodeKey || defaultGetNodeKey; 43249 var onBeforeNodeAdded = options.onBeforeNodeAdded || noop; 43250 var onNodeAdded = options.onNodeAdded || noop; 43251 var onBeforeElUpdated = options.onBeforeElUpdated || noop; 43252 var onElUpdated = options.onElUpdated || noop; 43253 var onBeforeNodeDiscarded = options.onBeforeNodeDiscarded || noop; 43254 var onNodeDiscarded = options.onNodeDiscarded || noop; 43255 var onBeforeElChildrenUpdated = options.onBeforeElChildrenUpdated || noop; 43256 var childrenOnly = options.childrenOnly === true; 43257 43258 // This object is used as a lookup to quickly find all keyed elements in the original DOM tree. 43259 var fromNodesLookup = {}; 43260 var keyedRemovalList; 43261 43262 function addKeyedRemoval(key) { 43263 if (keyedRemovalList) { 43264 keyedRemovalList.push(key); 43265 } else { 43266 keyedRemovalList = [key]; 43267 } 43268 } 43269 43270 function walkDiscardedChildNodes(node, skipKeyedNodes) { 43271 if (node.nodeType === ELEMENT_NODE) { 43272 var curChild = node.firstChild; 43273 while (curChild) { 43274 43275 var key = undefined; 43276 43277 if (skipKeyedNodes && (key = getNodeKey(curChild))) { 43278 // If we are skipping keyed nodes then we add the key 43279 // to a list so that it can be handled at the very end. 43280 addKeyedRemoval(key); 43281 } else { 43282 // Only report the node as discarded if it is not keyed. We do this because 43283 // at the end we loop through all keyed elements that were unmatched 43284 // and then discard them in one final pass. 43285 onNodeDiscarded(curChild); 43286 if (curChild.firstChild) { 43287 walkDiscardedChildNodes(curChild, skipKeyedNodes); 43288 } 43289 } 43290 43291 curChild = curChild.nextSibling; 43292 } 43293 } 43294 } 43295 43296 /** 43297 * Removes a DOM node out of the original DOM 43298 * 43299 * @param {Node} node The node to remove 43300 * @param {Node} parentNode The nodes parent 43301 * @param {Boolean} skipKeyedNodes If true then elements with keys will be skipped and not discarded. 43302 * @return {undefined} 43303 */ 43304 function removeNode(node, parentNode, skipKeyedNodes) { 43305 if (onBeforeNodeDiscarded(node) === false) { 43306 return; 43307 } 43308 43309 if (parentNode) { 43310 parentNode.removeChild(node); 43311 } 43312 43313 onNodeDiscarded(node); 43314 walkDiscardedChildNodes(node, skipKeyedNodes); 43315 } 43316 43317 // // TreeWalker implementation is no faster, but keeping this around in case this changes in the future 43318 // function indexTree(root) { 43319 // var treeWalker = document.createTreeWalker( 43320 // root, 43321 // NodeFilter.SHOW_ELEMENT); 43322 // 43323 // var el; 43324 // while((el = treeWalker.nextNode())) { 43325 // var key = getNodeKey(el); 43326 // if (key) { 43327 // fromNodesLookup[key] = el; 43328 // } 43329 // } 43330 // } 43331 43332 // // NodeIterator implementation is no faster, but keeping this around in case this changes in the future 43333 // 43334 // function indexTree(node) { 43335 // var nodeIterator = document.createNodeIterator(node, NodeFilter.SHOW_ELEMENT); 43336 // var el; 43337 // while((el = nodeIterator.nextNode())) { 43338 // var key = getNodeKey(el); 43339 // if (key) { 43340 // fromNodesLookup[key] = el; 43341 // } 43342 // } 43343 // } 43344 43345 function indexTree(node) { 43346 if (node.nodeType === ELEMENT_NODE) { 43347 var curChild = node.firstChild; 43348 while (curChild) { 43349 var key = getNodeKey(curChild); 43350 if (key) { 43351 fromNodesLookup[key] = curChild; 43352 } 43353 43354 // Walk recursively 43355 indexTree(curChild); 43356 43357 curChild = curChild.nextSibling; 43358 } 43359 } 43360 } 43361 43362 indexTree(fromNode); 43363 43364 function handleNodeAdded(el) { 43365 onNodeAdded(el); 43366 43367 var curChild = el.firstChild; 43368 while (curChild) { 43369 var nextSibling = curChild.nextSibling; 43370 43371 var key = getNodeKey(curChild); 43372 if (key) { 43373 var unmatchedFromEl = fromNodesLookup[key]; 43374 if (unmatchedFromEl && compareNodeNames(curChild, unmatchedFromEl)) { 43375 curChild.parentNode.replaceChild(unmatchedFromEl, curChild); 43376 morphEl(unmatchedFromEl, curChild); 43377 } 43378 } 43379 43380 handleNodeAdded(curChild); 43381 curChild = nextSibling; 43382 } 43383 } 43384 43385 function morphEl(fromEl, toEl, childrenOnly) { 43386 var toElKey = getNodeKey(toEl); 43387 var curFromNodeKey; 43388 43389 if (toElKey) { 43390 // If an element with an ID is being morphed then it is will be in the final 43391 // DOM so clear it out of the saved elements collection 43392 delete fromNodesLookup[toElKey]; 43393 } 43394 43395 if (toNode.isSameNode && toNode.isSameNode(fromNode)) { 43396 return; 43397 } 43398 43399 if (!childrenOnly) { 43400 if (onBeforeElUpdated(fromEl, toEl) === false) { 43401 return; 43402 } 43403 43404 morphAttrs(fromEl, toEl); 43405 onElUpdated(fromEl); 43406 43407 if (onBeforeElChildrenUpdated(fromEl, toEl) === false) { 43408 return; 43409 } 43410 } 43411 43412 if (fromEl.nodeName !== 'TEXTAREA') { 43413 var curToNodeChild = toEl.firstChild; 43414 var curFromNodeChild = fromEl.firstChild; 43415 var curToNodeKey; 43416 43417 var fromNextSibling; 43418 var toNextSibling; 43419 var matchingFromEl; 43420 43421 outer: while (curToNodeChild) { 43422 toNextSibling = curToNodeChild.nextSibling; 43423 curToNodeKey = getNodeKey(curToNodeChild); 43424 43425 while (curFromNodeChild) { 43426 fromNextSibling = curFromNodeChild.nextSibling; 43427 43428 if (curToNodeChild.isSameNode && curToNodeChild.isSameNode(curFromNodeChild)) { 43429 curToNodeChild = toNextSibling; 43430 curFromNodeChild = fromNextSibling; 43431 continue outer; 43432 } 43433 43434 curFromNodeKey = getNodeKey(curFromNodeChild); 43435 43436 var curFromNodeType = curFromNodeChild.nodeType; 43437 43438 var isCompatible = undefined; 43439 43440 if (curFromNodeType === curToNodeChild.nodeType) { 43441 if (curFromNodeType === ELEMENT_NODE) {
43442 // Both nodes being compared are Element nodes 43443 43444 if (curToNodeKey) { 43445 // The target node has a key so we want to match it up with the correct element 43446 // in the original DOM tree 43447 if (curToNodeKey !== curFromNodeKey) { 43448 // The current element in the original DOM tree does not have a matching key so 43449 // let's check our lookup to see if there is a matching element in the original 43450 // DOM tree 43451 if ((matchingFromEl = fromNodesLookup[curToNodeKey])) { 43452 if (curFromNodeChild.nextSibling === matchingFromEl) { 43453 // Special case for single element removals. To avoid removing the original 43454 // DOM node out of the tree (since that can break CSS transitions, etc.), 43455 // we will instead discard the current node and wait until the next 43456 // iteration to properly match up the keyed target element with its matching 43457 // element in the original tree 43458 isCompatible = false; 43459 } else { 43460 // We found a matching keyed element somewhere in the original DOM tree. 43461 // Let's moving the original DOM node into the current position and morph 43462 // it. 43463 43464 // NOTE: We use insertBefore instead of replaceChild because we want to go through 43465 // the `removeNode()` function for the node that is being discarded so that 43466 // all lifecycle hooks are correctly invoked 43467 fromEl.insertBefore(matchingFromEl, curFromNodeChild); 43468 43469 fromNextSibling = curFromNodeChild.nextSibling; 43470 43471 if (curFromNodeKey) { 43472 // Since the node is keyed it might be matched up later so we defer 43473 // the actual removal to later 43474 addKeyedRemoval(curFromNodeKey); 43475 } else { 43476 // NOTE: we skip nested keyed nodes from being removed since there is 43477 // still a chance they will be matched up later 43478 removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */); 43479 } 43480 43481 curFromNodeChild = matchingFromEl; 43482 } 43483 } else { 43484 // The nodes are not compatible since the "to" node has a key and there 43485 // is no matching keyed node in the source tree 43486 isCompatible = false; 43487 } 43488 } 43489 } else if (curFromNodeKey) { 43490 // The original has a key 43491 isCompatible = false; 43492 } 43493 43494 isCompatible = isCompatible !== false && compareNodeNames(curFromNodeChild, curToNodeChild); 43495 if (isCompatible) { 43496 // We found compatible DOM elements so transform 43497 // the current "from" node to match the current 43498 // target DOM node. 43499 morphEl(curFromNodeChild, curToNodeChild); 43500 } 43501 43502 } else if (curFromNodeType === TEXT_NODE || curFromNodeType == COMMENT_NODE) {
43503 // Both nodes being compared are Text or Comment nodes 43504 isCompatible = true; 43505 // Simply update nodeValue on the original node to 43506 // change the text value 43507 curFromNodeChild.nodeValue = curToNodeChild.nodeValue; 43508 } 43509 } 43510 43511 if (isCompatible) { 43512 // Advance both the "to" child and the "from" child since we found a match 43513 curToNodeChild = toNextSibling; 43514 curFromNodeChild = fromNextSibling; 43515 continue outer; 43516 } 43517 43518 // No compatible match so remove the old node from the DOM and continue trying to find a 43519 // match in the original DOM. However, we only do this if the from node is not keyed 43520 // since it is possible that a keyed node might match up with a node somewhere else in the 43521 // target tree and we don't want to discard it just yet since it still might find a 43522 // home in the final DOM tree. After everything is done we will remove any keyed nodes 43523 // that didn't find a home 43524 if (curFromNodeKey) { 43525 // Since the node is keyed it might be matched up later so we defer 43526 // the actual removal to later 43527 addKeyedRemoval(curFromNodeKey); 43528 } else { 43529 // NOTE: we skip nested keyed nodes from being removed since there is 43530 // still a chance they will be matched up later 43531 removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */); 43532 } 43533 43534 curFromNodeChild = fromNextSibling; 43535 } 43536 43537 // If we got this far then we did not find a candidate match for 43538 // our "to node" and we exhausted all of the children "from" 43539 // nodes. Therefore, we will just append the current "to" node 43540 // to the end 43541 if (curToNodeKey && (matchingFromEl = fromNodesLookup[curToNodeKey]) && compareNodeNames(matchingFromEl, curToNodeChild)) { 43542 fromEl.appendChild(matchingFromEl); 43543 morphEl(matchingFromEl, curToNodeChild); 43544 } else { 43545 var onBeforeNodeAddedResult = onBeforeNodeAdded(curToNodeChild); 43546 if (onBeforeNodeAddedResult !== false) { 43547 if (onBeforeNodeAddedResult) { 43548 curToNodeChild = onBeforeNodeAddedResult; 43549 } 43550 43551 if (curToNodeChild.actualize) { 43552 curToNodeChild = curToNodeChild.actualize(fromEl.ownerDocument || doc); 43553 } 43554 fromEl.appendChild(curToNodeChild); 43555 handleNodeAdded(curToNodeChild); 43556 } 43557 } 43558 43559 curToNodeChild = toNextSibling; 43560 curFromNodeChild = fromNextSibling; 43561 } 43562 43563 // We have processed all of the "to nodes". If curFromNodeChild is 43564 // non-null then we still have some from nodes left over that need 43565 // to be removed 43566 while (curFromNodeChild) { 43567 fromNextSibling = curFromNodeChild.nextSibling; 43568 if ((curFromNodeKey = getNodeKey(curFromNodeChild))) { 43569 // Since the node is keyed it might be matched up later so we defer 43570 // the actual removal to later 43571 addKeyedRemoval(curFromNodeKey); 43572 } else { 43573 // NOTE: we skip nested keyed nodes from being removed since there is 43574 // still a chance they will be matched up later 43575 removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */); 43576 } 43577 curFromNodeChild = fromNextSibling; 43578 } 43579 } 43580 43581 var specialElHandler = specialElHandlers[fromEl.nodeName]; 43582 if (specialElHandler) { 43583 specialElHandler(fromEl, toEl); 43584 } 43585 } // END: morphEl(...) 43586 43587 var morphedNode = fromNode; 43588 var morphedNodeType = morphedNode.nodeType; 43589 var toNodeType = toNode.nodeType; 43590 43591 if (!childrenOnly) { 43592 // Handle the case where we are given two DOM nodes that are not 43593 // compatible (e.g. <div> --> <span> or <div> --> TEXT) 43594 if (morphedNodeType === ELEMENT_NODE) { 43595 if (toNodeType === ELEMENT_NODE) { 43596 if (!compareNodeNames(fromNode, toNode)) { 43597 onNodeDiscarded(fromNode); 43598 morphedNode = moveChildren(fromNode, createElementNS(toNode.nodeName, toNode.namespaceURI)); 43599 } 43600 } else { 43601 // Going from an element node to a text node 43602 morphedNode = toNode; 43603 } 43604 } else if (morphedNodeType === TEXT_NODE || morphedNodeType === COMMENT_NODE) { // Text or comment node 43605 if (toNodeType === morphedNodeType) { 43606 morphedNode.nodeValue = toNode.nodeValue; 43607 return morphedNode; 43608 } else { 43609 // Text node to something else 43610 morphedNode = toNode; 43611 } 43612 } 43613 } 43614 43615 if (morphedNode === toNode) { 43616 // The "to node" was not compatible with the "from node" so we had to 43617 // toss out the "from node" and use the "to node" 43618 onNodeDiscarded(fromNode); 43619 } else { 43620 morphEl(morphedNode, toNode, childrenOnly); 43621 43622 // We now need to loop over any keyed nodes that might need to be 43623 // removed. We only do the removal if we know that the keyed node 43624 // never found a match. When a keyed node is matched up we remove 43625 // it out of fromNodesLookup and we use fromNodesLookup to determine 43626 // if a keyed node has been matched up or not 43627 if (keyedRemovalList) { 43628 for (var i=0, len=keyedRemovalList.length; i<len; i++) { 43629 var elToRemove = fromNodesLookup[keyedRemovalList[i]]; 43630 if (elToRemove) { 43631 removeNode(elToRemove, elToRemove.parentNode, false); 43632 } 43633 } 43634 } 43635 } 43636 43637 if (!childrenOnly && morphedNode !== fromNode && fromNode.parentNode) { 43638 if (morphedNode.actualize) { 43639 morphedNode = morphedNode.actualize(fromNode.ownerDocument || doc); 43640 } 43641 // If we had to swap out the from node with a new node because the old 43642 // node was not compatible with the target node then we need to 43643 // replace the old DOM node in the original DOM tree. This is only 43644 // possible if the original DOM node was part of a DOM tree which 43645 // we know is the case if it has a parent node. 43646 fromNode.parentNode.replaceChild(morphedNode, fromNode); 43647 } 43648 43649 return morphedNode; 43650 }; 43651} 43652 43653var morphdom = morphdomFactory(morphAttrs); 43654 43655module.exports = morphdom; 43656 43657},{}],173:[function(require,module,exports){ 43658var window = require('global/window') 43659var assert = require('assert') 43660 43661module.exports = nanoraf 43662 43663// Only call RAF when needed 43664// (fn, fn?) -> fn 43665function nanoraf (render, raf) { 43666 assert.equal(typeof render, 'function', 'nanoraf: render should be a function') 43667 assert.ok(typeof raf === 'function' || typeof raf === 'undefined', 'nanoraf: raf should be a function or undefined') 43668 43669 raf = raf || window.requestAnimationFrame 43670 43671 var inRenderingTransaction = false 43672 var redrawScheduled = false 43673 var currentState = null 43674 43675 // pass new state to be rendered 43676 // (obj, obj?) -> null 43677 return function frame (state, prev) { 43678 assert.equal(typeof state, 'object', 'nanoraf: state should be an object') 43679 assert.equal(typeof prev, 'object', 'nanoraf: prev should be an object') 43680 assert.equal(inRenderingTransaction, false, 'nanoraf: new frame was created before previous frame finished') 43681 43682 // request a redraw for next frame 43683 if (currentState === null && !redrawScheduled) { 43684 redrawScheduled = true 43685 43686 raf(function redraw () { 43687 redrawScheduled = false 43688 if (!currentState) return 43689 43690 inRenderingTransaction = true 43691 render(currentState, prev) 43692 inRenderingTransaction = false 43693 43694 currentState = null 43695 }) 43696 } 43697 43698 // update data for redraw 43699 currentState = state 43700 } 43701} 43702 43703},{"assert":78,"global/window":158}],174:[function(require,module,exports){ 43704/* eslint-disable no-eval */ 43705var assert = require('assert') 43706 43707module.exports = nanotick
43708var delay = (typeof window !== 'undefined' && window.document) 43709 ? (typeof setImmediate !== 'undefined') 43710 ? setImmediate 43711 : setTimeout 43712 : eval('process.nextTick') 43713 43714// Process.nextTick() batching ulity 43715// null -> fn(any) -> fn(any) 43716function nanotick () { 43717 var callbacks = [] 43718 var interval = false 43719 43720 return function tick (cb) { 43721 assert.equal(typeof cb, 'function', 'nanotick.tick: cb should be a function') 43722 43723 var isAsync = false 43724 43725 executeAsync(function () { 43726 isAsync = true 43727 }) 43728 43729 return function wrappedTick () { 43730 var length = arguments.length 43731 var args = new Array(length) 43732 for (var i = 0; i < length; i++) args[i] = arguments[i] 43733 43734 if (isAsync) { 43735 cb.apply(cb, args) 43736 } else { 43737 executeAsync(function () { 43738 cb.apply(cb, args) 43739 }) 43740 } 43741 } 43742 } 43743 43744 function executeAsync (cb) { 43745 callbacks.push(cb) 43746 43747 if (!interval) { 43748 interval = true 43749 delay(function () { 43750 while (callbacks.length > 0) { 43751 callbacks.shift()() 43752 } 43753 interval = false 43754 }) 43755 } 43756 } 43757} 43758 43759},{"assert":78}],175:[function(require,module,exports){ 43760(function (process,Buffer){ 43761var req = require('request') 43762 43763module.exports = Nets 43764 43765function Nets (opts, cb) { 43766 if (typeof opts === 'string') opts = { uri: opts } 43767 43768 // in node, if encoding === null then response will be a Buffer. we want this to be the default 43769 if (!opts.hasOwnProperty('encoding')) opts.encoding = null 43770 43771 // in browser, we should by default convert the arraybuffer into a Buffer 43772 if (process.browser && !opts.hasOwnProperty('json') && opts.encoding === null) { 43773 opts.responseType = 'arraybuffer' 43774 var originalCb = cb 43775 cb = bufferify 43776 } 43777 43778 function bufferify (err, resp, body) { 43779 if (body) body = new Buffer(new Uint8Array(body)) 43780 originalCb(err, resp, body) 43781 } 43782 43783 return req(opts, cb) 43784} 43785 43786}).call(this,require('_process'),require("buffer").Buffer) 43787},{"_process":84,"buffer":86,"request":250}],176:[function(require,module,exports){ 43788/* global MutationObserver */ 43789var document = require('global/document') 43790var window = require('global/window') 43791var watch = Object.create(null) 43792var KEY_ID = 'onloadid' + (new Date() % 9e6).toString(36) 43793var KEY_ATTR = 'data-' + KEY_ID 43794var INDEX = 0 43795 43796if (window && window.MutationObserver) { 43797 var observer = new MutationObserver(function (mutations) { 43798 if (Object.keys(watch).length < 1) return 43799 for (var i = 0; i < mutations.length; i++) { 43800 if (mutations[i].attributeName === KEY_ATTR) { 43801 eachAttr(mutations[i], turnon, turnoff) 43802 continue 43803 } 43804 eachMutation(mutations[i].removedNodes, turnoff) 43805 eachMutation(mutations[i].addedNodes, turnon) 43806 } 43807 }) 43808 observer.observe(document.body, { 43809 childList: true, 43810 subtree: true, 43811 attributes: true, 43812 attributeOldValue: true, 43813 attributeFilter: [KEY_ATTR] 43814 }) 43815} 43816 43817module.exports = function onload (el, on, off, caller) { 43818 on = on || function () {} 43819 off = off || function () {} 43820 el.setAttribute(KEY_ATTR, 'o' + INDEX) 43821 watch['o' + INDEX] = [on, off, 0, caller || onload.caller] 43822 INDEX += 1 43823 return el 43824} 43825 43826function turnon (index, el) { 43827 if (watch[index][0] && watch[index][2] === 0) { 43828 watch[index][0](el) 43829 watch[index][2] = 1 43830 } 43831} 43832 43833function turnoff (index, el) { 43834 if (watch[index][1] && watch[index][2] === 1) { 43835 watch[index][1](el) 43836 watch[index][2] = 0 43837 } 43838} 43839 43840function eachAttr (mutation, on, off) { 43841 var newValue = mutation.target.getAttribute(KEY_ATTR) 43842 if (sameOrigin(mutation.oldValue, newValue)) { 43843 watch[newValue] = watch[mutation.oldValue] 43844 return 43845 } 43846 if (watch[mutation.oldValue]) { 43847 off(mutation.oldValue, mutation.target) 43848 } 43849 if (watch[newValue]) { 43850 on(newValue, mutation.target) 43851 } 43852} 43853 43854function sameOrigin (oldValue, newValue) { 43855 if (!oldValue || !newValue) return false 43856 return watch[oldValue][3] === watch[newValue][3] 43857} 43858 43859function eachMutation (nodes, fn) { 43860 var keys = Object.keys(watch) 43861 for (var i = 0; i < nodes.length; i++) { 43862 if (nodes[i] && nodes[i].getAttribute && nodes[i].getAttribute(KEY_ATTR)) { 43863 var onloadid = nodes[i].getAttribute(KEY_ATTR) 43864 keys.forEach(function (k) { 43865 if (onloadid === k) { 43866 fn(k, nodes[i]) 43867 } 43868 }) 43869 } 43870 if (nodes[i].childNodes.length > 0) { 43871 eachMutation(nodes[i].childNodes, fn) 43872 } 43873 } 43874} 43875 43876},{"global/document":157,"global/window":158}],177:[function(require,module,exports){ 43877var wrappy = require('wrappy') 43878module.exports = wrappy(once) 43879 43880once.proto = once(function () { 43881 Object.defineProperty(Function.prototype, 'once', { 43882 value: function () { 43883 return once(this) 43884 }, 43885 configurable: true 43886 }) 43887}) 43888 43889function once (fn) { 43890 var f = function () { 43891 if (f.called) return f.value 43892 f.called = true 43893 return f.value = fn.apply(this, arguments) 43894 } 43895 f.called = false 43896 return f 43897} 43898 43899},{"wrappy":249}],178:[function(require,module,exports){ 43900var trim = require('trim') 43901 , forEach = require('for-each') 43902 , isArray = function(arg) { 43903 return Object.prototype.toString.call(arg) === '[object Array]'; 43904 } 43905 43906module.exports = function (headers) { 43907 if (!headers) 43908 return {} 43909 43910 var result = {} 43911 43912 forEach( 43913 trim(headers).split('\n') 43914 , function (row) { 43915 var index = row.indexOf(':') 43916 , key = trim(row.slice(0, index)).toLowerCase() 43917 , value = trim(row.slice(index + 1)) 43918 43919 if (typeof(result[key]) === 'undefined') { 43920 result[key] = value 43921 } else if (isArray(result[key])) { 43922 result[key].push(value) 43923 } else { 43924 result[key] = [ result[key], value ] 43925 } 43926 } 43927 ) 43928 43929 return result 43930} 43931},{"for-each":155,"trim":240}],179:[function(require,module,exports){ 43932module.exports = require('./src/PathFinding'); 43933 43934},{"./src/PathFinding":180}],180:[function(require,module,exports){ 43935module.exports = { 43936 'Heap' : require('heap'), 43937 'Node' : require('./core/Node'), 43938 'Grid' : require('./core/Grid'), 43939 'Util' : require('./core/Util'), 43940 'DiagonalMovement' : require('./core/DiagonalMovement'), 43941 'Heuristic' : require('./core/Heuristic'), 43942 'AStarFinder' : require('./finders/AStarFinder'), 43943 'BestFirstFinder' : require('./finders/BestFirstFinder'), 43944 'BreadthFirstFinder' : require('./finders/BreadthFirstFinder'), 43945 'DijkstraFinder' : require('./finders/DijkstraFinder'), 43946 'BiAStarFinder' : require('./finders/BiAStarFinder'), 43947 'BiBestFirstFinder' : require('./finders/BiBestFirstFinder'), 43948 'BiBreadthFirstFinder' : require('./finders/BiBreadthFirstFinder'), 43949 'BiDijkstraFinder' : require('./finders/BiDijkstraFinder'), 43950 'IDAStarFinder' : require('./finders/IDAStarFinder'), 43951 'JumpPointFinder' : require('./finders/JumpPointFinder'), 43952}; 43953 43954},{"./core/DiagonalMovement":181,"./core/Grid":182,"./core/Heuristic":183,"./core/Node":184,"./core/Util":185,"./finders/AStarFinder":186,"./finders/BestFirstFinder":187,"./finders/BiAStarFinder":188,"./finders/BiBestFirstFinder":189,"./finders/BiBreadthFirstFinder":190,"./finders/BiDijkstraFinder":191,"./finders/BreadthFirstFinder":192,"./finders/DijkstraFinder":193,"./finders/IDAStarFinder":194,"./finders/JumpPointFinder":199,"heap":159}],181:[function(require,module,exports){ 43955var DiagonalMovement = { 43956 Always: 1, 43957 Never: 2, 43958 IfAtMostOneObstacle: 3,
43959 OnlyWhenNoObstacles: 4 43960}; 43961 43962module.exports = DiagonalMovement; 43963},{}],182:[function(require,module,exports){ 43964var Node = require('./Node'); 43965var DiagonalMovement = require('./DiagonalMovement'); 43966 43967/** 43968 * The Grid class, which serves as the encapsulation of the layout of the nodes. 43969 * @constructor 43970 * @param {number|Array<Array<(number|boolean)>>} width_or_matrix Number of columns of the grid, or matrix 43971 * @param {number} height Number of rows of the grid. 43972 * @param {Array<Array<(number|boolean)>>} [matrix] - A 0-1 matrix 43973 * representing the walkable status of the nodes(0 or false for walkable). 43974 * If the matrix is not supplied, all the nodes will be walkable. */ 43975function Grid(width_or_matrix, height, matrix) { 43976 var width; 43977 43978 if (typeof width_or_matrix !== 'object') { 43979 width = width_or_matrix; 43980 } else { 43981 height = width_or_matrix.length; 43982 width = width_or_matrix[0].length; 43983 matrix = width_or_matrix; 43984 } 43985 43986 /** 43987 * The number of columns of the grid. 43988 * @type number 43989 */ 43990 this.width = width; 43991 /** 43992 * The number of rows of the grid. 43993 * @type number 43994 */ 43995 this.height = height; 43996 43997 /** 43998 * A 2D array of nodes. 43999 */ 44000 this.nodes = this._buildNodes(width, height, matrix); 44001} 44002 44003/** 44004 * Build and return the nodes. 44005 * @private 44006 * @param {number} width 44007 * @param {number} height 44008 * @param {Array<Array<number|boolean>>} [matrix] - A 0-1 matrix representing 44009 * the walkable status of the nodes.
44010 * @see Grid 44011 */ 44012Grid.prototype._buildNodes = function(width, height, matrix) { 44013 var i, j, 44014 nodes = new Array(height); 44015 44016 for (i = 0; i < height; ++i) { 44017 nodes[i] = new Array(width); 44018 for (j = 0; j < width; ++j) { 44019 nodes[i][j] = new Node(j, i); 44020 } 44021 } 44022 44023 44024 if (matrix === undefined) { 44025 return nodes; 44026 } 44027 44028 if (matrix.length !== height || matrix[0].length !== width) { 44029 throw new Error('Matrix size does not fit'); 44030 } 44031 44032 for (i = 0; i < height; ++i) { 44033 for (j = 0; j < width; ++j) { 44034 if (matrix[i][j]) { 44035 // 0, false, null will be walkable 44036 // while others will be un-walkable 44037 nodes[i][j].walkable = false; 44038 } 44039 } 44040 } 44041 44042 return nodes; 44043}; 44044 44045 44046Grid.prototype.getNodeAt = function(x, y) { 44047 return this.nodes[y][x]; 44048}; 44049 44050 44051/** 44052 * Determine whether the node at the given position is walkable. 44053 * (Also returns false if the position is outside the grid.) 44054 * @param {number} x - The x coordinate of the node. 44055 * @param {number} y - The y coordinate of the node. 44056 * @return {boolean} - The walkability of the node. 44057 */ 44058Grid.prototype.isWalkableAt = function(x, y) { 44059 return this.isInside(x, y) && this.nodes[y][x].walkable; 44060}; 44061 44062 44063/** 44064 * Determine whether the position is inside the grid. 44065 * XXX: `grid.isInside(x, y)` is wierd to read. 44066 * It should be `(x, y) is inside grid`, but I failed to find a better 44067 * name for this method. 44068 * @param {number} x 44069 * @param {number} y 44070 * @return {boolean} 44071 */ 44072Grid.prototype.isInside = function(x, y) { 44073 return (x >= 0 && x < this.width) && (y >= 0 && y < this.height); 44074}; 44075 44076 44077/** 44078 * Set whether the node on the given position is walkable. 44079 * NOTE: throws exception if the coordinate is not inside the grid. 44080 * @param {number} x - The x coordinate of the node. 44081 * @param {number} y - The y coordinate of the node. 44082 * @param {boolean} walkable - Whether the position is walkable. 44083 */ 44084Grid.prototype.setWalkableAt = function(x, y, walkable) { 44085 this.nodes[y][x].walkable = walkable; 44086}; 44087 44088 44089/** 44090 * Get the neighbors of the given node. 44091 * 44092 * offsets diagonalOffsets: 44093 * +---+---+---+ +---+---+---+ 44094 * | | 0 | | | 0 | | 1 | 44095 * +---+---+---+ +---+---+---+ 44096 * | 3 | | 1 | | | | | 44097 * +---+---+---+ +---+---+---+ 44098 * | | 2 | | | 3 | | 2 | 44099 * +---+---+---+ +---+---+---+ 44100 * 44101 * When allowDiagonal is true, if offsets[i] is valid, then 44102 * diagonalOffsets[i] and 44103 * diagonalOffsets[(i + 1) % 4] is valid. 44104 * @param {Node} node 44105 * @param {DiagonalMovement} diagonalMovement 44106 */ 44107Grid.prototype.getNeighbors = function(node, diagonalMovement) { 44108 var x = node.x, 44109 y = node.y, 44110 neighbors = [], 44111 s0 = false, d0 = false, 44112 s1 = false, d1 = false, 44113 s2 = false, d2 = false, 44114 s3 = false, d3 = false, 44115 nodes = this.nodes; 44116 44117 // â 44118 if (this.isWalkableAt(x, y - 1)) { 44119 neighbors.push(nodes[y - 1][x]); 44120 s0 = true; 44121 } 44122 // â 44123 if (this.isWalkableAt(x + 1, y)) { 44124 neighbors.push(nodes[y][x + 1]); 44125 s1 = true; 44126 } 44127 // â 44128 if (this.isWalkableAt(x, y + 1)) { 44129 neighbors.push(nodes[y + 1][x]); 44130 s2 = true; 44131 } 44132 // â 44133 if (this.isWalkableAt(x - 1, y)) { 44134 neighbors.push(nodes[y][x - 1]); 44135 s3 = true; 44136 } 44137 44138 if (diagonalMovement === DiagonalMovement.Never) { 44139 return neighbors; 44140 } 44141 44142 if (diagonalMovement === DiagonalMovement.OnlyWhenNoObstacles) { 44143 d0 = s3 && s0; 44144 d1 = s0 && s1; 44145 d2 = s1 && s2; 44146 d3 = s2 && s3; 44147 } else if (diagonalMovement === DiagonalMovement.IfAtMostOneObstacle) { 44148 d0 = s3 || s0; 44149 d1 = s0 || s1; 44150 d2 = s1 || s2; 44151 d3 = s2 || s3; 44152 } else if (diagonalMovement === DiagonalMovement.Always) { 44153 d0 = true; 44154 d1 = true; 44155 d2 = true; 44156 d3 = true; 44157 } else { 44158 throw new Error('Incorrect value of diagonalMovement'); 44159 } 44160 44161 // â 44162 if (d0 && this.isWalkableAt(x - 1, y - 1)) { 44163 neighbors.push(nodes[y - 1][x - 1]); 44164 } 44165 // â 44166 if (d1 && this.isWalkableAt(x + 1, y - 1)) { 44167 neighbors.push(nodes[y - 1][x + 1]); 44168 } 44169 // â 44170 if (d2 && this.isWalkableAt(x + 1, y + 1)) { 44171 neighbors.push(nodes[y + 1][x + 1]); 44172 } 44173 // â 44174 if (d3 && this.isWalkableAt(x - 1, y + 1)) { 44175 neighbors.push(nodes[y + 1][x - 1]); 44176 } 44177 44178 return neighbors; 44179}; 44180 44181 44182/** 44183 * Get a clone of this grid. 44184 * @return {Grid} Cloned grid. 44185 */ 44186Grid.prototype.clone = function() { 44187 var i, j, 44188 44189 width = this.width, 44190 height = this.height, 44191 thisNodes = this.nodes, 44192 44193 newGrid = new Grid(width, height), 44194 newNodes = new Array(height); 44195 44196 for (i = 0; i < height; ++i) { 44197 newNodes[i] = new Array(width); 44198 for (j = 0; j < width; ++j) { 44199 newNodes[i][j] = new Node(j, i, thisNodes[i][j].walkable); 44200 } 44201 } 44202 44203 newGrid.nodes = newNodes; 44204 44205 return newGrid; 44206}; 44207 44208module.exports = Grid; 44209 44210},{"./DiagonalMovement":181,"./Node":184}],183:[function(require,module,exports){ 44211/** 44212 * @namespace PF.Heuristic 44213 * @description A collection of heuristic functions. 44214 */ 44215module.exports = { 44216 44217 /** 44218 * Manhattan distance. 44219 * @param {number} dx - Difference in x. 44220 * @param {number} dy - Difference in y. 44221 * @return {number} dx + dy 44222 */ 44223 manhattan: function(dx, dy) { 44224 return dx + dy; 44225 }, 44226 44227 /** 44228 * Euclidean distance. 44229 * @param {number} dx - Difference in x. 44230 * @param {number} dy - Difference in y. 44231 * @return {number} sqrt(dx * dx + dy * dy) 44232 */ 44233 euclidean: function(dx, dy) { 44234 return Math.sqrt(dx * dx + dy * dy); 44235 }, 44236 44237 /** 44238 * Octile distance. 44239 * @param {number} dx - Difference in x. 44240 * @param {number} dy - Difference in y. 44241 * @return {number} sqrt(dx * dx + dy * dy) for grids 44242 */ 44243 octile: function(dx, dy) { 44244 var F = Math.SQRT2 - 1; 44245 return (dx < dy) ? F * dx + dy : F * dy + dx; 44246 }, 44247 44248 /** 44249 * Chebyshev distance. 44250 * @param {number} dx - Difference in x. 44251 * @param {number} dy - Difference in y. 44252 * @return {number} max(dx, dy) 44253 */ 44254 chebyshev: function(dx, dy) { 44255 return Math.max(dx, dy); 44256 } 44257 44258}; 44259 44260},{}],184:[function(require,module,exports){ 44261/** 44262 * A node in grid. 44263 * This class holds some basic information about a node and custom 44264 * attributes may be added, depending on the algorithms' needs. 44265 * @constructor 44266 * @param {number} x - The x coordinate of the node on the grid. 44267 * @param {number} y - The y coordinate of the node on the grid. 44268 * @param {boolean} [walkable] - Whether this node is walkable. 44269 */ 44270function Node(x, y, walkable) { 44271 /** 44272 * The x coordinate of the node on the grid. 44273 * @type number 44274 */ 44275 this.x = x; 44276 /** 44277 * The y coordinate of the node on the grid. 44278 * @type number 44279 */ 44280 this.y = y; 44281 /**
44282 * Whether this node can be walked through. 44283 * @type boolean 44284 */ 44285 this.walkable = (walkable === undefined ? true : walkable); 44286} 44287 44288module.exports = Node; 44289 44290},{}],185:[function(require,module,exports){ 44291/** 44292 * Backtrace according to the parent records and return the path. 44293 * (including both start and end nodes) 44294 * @param {Node} node End node 44295 * @return {Array<Array<number>>} the path 44296 */ 44297function backtrace(node) { 44298 var path = [[node.x, node.y]]; 44299 while (node.parent) { 44300 node = node.parent; 44301 path.push([node.x, node.y]); 44302 } 44303 return path.reverse(); 44304} 44305exports.backtrace = backtrace; 44306 44307/** 44308 * Backtrace from start and end node, and return the path. 44309 * (including both start and end nodes) 44310 * @param {Node} 44311 * @param {Node} 44312 */ 44313function biBacktrace(nodeA, nodeB) { 44314 var pathA = backtrace(nodeA), 44315 pathB = backtrace(nodeB); 44316 return pathA.concat(pathB.reverse()); 44317} 44318exports.biBacktrace = biBacktrace; 44319 44320/** 44321 * Compute the length of the path. 44322 * @param {Array<Array<number>>} path The path 44323 * @return {number} The length of the path 44324 */ 44325function pathLength(path) { 44326 var i, sum = 0, a, b, dx, dy; 44327 for (i = 1; i < path.length; ++i) { 44328 a = path[i - 1]; 44329 b = path[i]; 44330 dx = a[0] - b[0]; 44331 dy = a[1] - b[1]; 44332 sum += Math.sqrt(dx * dx + dy * dy); 44333 } 44334 return sum; 44335} 44336exports.pathLength = pathLength; 44337 44338 44339/** 44340 * Given the start and end coordinates, return all the coordinates lying 44341 * on the line formed by these coordinates, based on Bresenham's algorithm. 44342 * http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification 44343 * @param {number} x0 Start x coordinate 44344 * @param {number} y0 Start y coordinate 44345 * @param {number} x1 End x coordinate 44346 * @param {number} y1 End y coordinate 44347 * @return {Array<Array<number>>} The coordinates on the line 44348 */ 44349function interpolate(x0, y0, x1, y1) { 44350 var abs = Math.abs, 44351 line = [], 44352 sx, sy, dx, dy, err, e2; 44353 44354 dx = abs(x1 - x0); 44355 dy = abs(y1 - y0); 44356 44357 sx = (x0 < x1) ? 1 : -1; 44358 sy = (y0 < y1) ? 1 : -1; 44359 44360 err = dx - dy; 44361 44362 while (true) { 44363 line.push([x0, y0]); 44364 44365 if (x0 === x1 && y0 === y1) { 44366 break; 44367 } 44368 44369 e2 = 2 * err; 44370 if (e2 > -dy) { 44371 err = err - dy; 44372 x0 = x0 + sx; 44373 } 44374 if (e2 < dx) { 44375 err = err + dx; 44376 y0 = y0 + sy; 44377 } 44378 } 44379 44380 return line; 44381} 44382exports.interpolate = interpolate; 44383 44384 44385/** 44386 * Given a compressed path, return a new path that has all the segments 44387 * in it interpolated. 44388 * @param {Array<Array<number>>} path The path 44389 * @return {Array<Array<number>>} expanded path 44390 */ 44391function expandPath(path) { 44392 var expanded = [], 44393 len = path.length, 44394 coord0, coord1, 44395 interpolated, 44396 interpolatedLen, 44397 i, j; 44398 44399 if (len < 2) { 44400 return expanded; 44401 } 44402 44403 for (i = 0; i < len - 1; ++i) { 44404 coord0 = path[i]; 44405 coord1 = path[i + 1]; 44406 44407 interpolated = interpolate(coord0[0], coord0[1], coord1[0], coord1[1]); 44408 interpolatedLen = interpolated.length; 44409 for (j = 0; j < interpolatedLen - 1; ++j) { 44410 expanded.push(interpolated[j]); 44411 } 44412 } 44413 expanded.push(path[len - 1]); 44414 44415 return expanded; 44416} 44417exports.expandPath = expandPath; 44418 44419 44420/** 44421 * Smoothen the give path. 44422 * The original path will not be modified; a new path will be returned. 44423 * @param {PF.Grid} grid 44424 * @param {Array<Array<number>>} path The path 44425 */ 44426function smoothenPath(grid, path) { 44427 var len = path.length, 44428 x0 = path[0][0], // path start x 44429 y0 = path[0][1], // path start y 44430 x1 = path[len - 1][0], // path end x 44431 y1 = path[len - 1][1], // path end y 44432 sx, sy, // current start coordinate 44433 ex, ey, // current end coordinate 44434 newPath, 44435 i, j, coord, line, testCoord, blocked; 44436 44437 sx = x0; 44438 sy = y0; 44439 newPath = [[sx, sy]]; 44440 44441 for (i = 2; i < len; ++i) { 44442 coord = path[i]; 44443 ex = coord[0]; 44444 ey = coord[1]; 44445 line = interpolate(sx, sy, ex, ey); 44446 44447 blocked = false; 44448 for (j = 1; j < line.length; ++j) {
44449 testCoord = line[j]; 44450 44451 if (!grid.isWalkableAt(testCoord[0], testCoord[1])) { 44452 blocked = true; 44453 break; 44454 } 44455 } 44456 if (blocked) { 44457 lastValidCoord = path[i - 1]; 44458 newPath.push(lastValidCoord); 44459 sx = lastValidCoord[0]; 44460 sy = lastValidCoord[1]; 44461 } 44462 } 44463 newPath.push([x1, y1]); 44464 44465 return newPath; 44466} 44467exports.smoothenPath = smoothenPath; 44468 44469 44470/** 44471 * Compress a path, remove redundant nodes without altering the shape 44472 * The original path is not modified 44473 * @param {Array<Array<number>>} path The path 44474 * @return {Array<Array<number>>} The compressed path 44475 */ 44476function compressPath(path) { 44477 44478 // nothing to compress 44479 if(path.length < 3) { 44480 return path; 44481 } 44482 44483 var compressed = [], 44484 sx = path[0][0], // start x 44485 sy = path[0][1], // start y 44486 px = path[1][0], // second point x 44487 py = path[1][1], // second point y 44488 dx = px - sx, // direction between the two points 44489 dy = py - sy, // direction between the two points 44490 lx, ly, 44491 ldx, ldy, 44492 sq, i; 44493 44494 // normalize the direction 44495 sq = Math.sqrt(dx*dx + dy*dy); 44496 dx /= sq; 44497 dy /= sq; 44498 44499 // start the new path 44500 compressed.push([sx,sy]); 44501 44502 for(i = 2; i < path.length; i++) { 44503 44504 // store the last point 44505 lx = px; 44506 ly = py; 44507 44508 // store the last direction 44509 ldx = dx; 44510 ldy = dy; 44511 44512 // next point 44513 px = path[i][0]; 44514 py = path[i][1]; 44515 44516 // next direction 44517 dx = px - lx; 44518 dy = py - ly; 44519 44520 // normalize 44521 sq = Math.sqrt(dx*dx + dy*dy); 44522 dx /= sq; 44523 dy /= sq; 44524 44525 // if the direction has changed, store the point 44526 if ( dx !== ldx || dy !== ldy ) { 44527 compressed.push([lx,ly]); 44528 } 44529 } 44530 44531 // store the last point 44532 compressed.push([px,py]); 44533 44534 return compressed; 44535} 44536exports.compressPath = compressPath; 44537 44538},{}],186:[function(require,module,exports){ 44539var Heap = require('heap'); 44540var Util = require('../core/Util'); 44541var Heuristic = require('../core/Heuristic'); 44542var DiagonalMovement = require('../core/DiagonalMovement'); 44543 44544/** 44545 * A* path-finder. Based upon https://github.com/bgrins/javascript-astar 44546 * @constructor 44547 * @param {Object} opt 44548 * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. 44549 * Deprecated, use diagonalMovement instead. 44550 * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching 44551 * block corners. Deprecated, use diagonalMovement instead. 44552 * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. 44553 * @param {function} opt.heuristic Heuristic function to estimate the distance 44554 * (defaults to manhattan). 44555 * @param {number} opt.weight Weight to apply to the heuristic to allow for 44556 * suboptimal paths, in order to speed up the search. 44557 */ 44558function AStarFinder(opt) { 44559 opt = opt || {}; 44560 this.allowDiagonal = opt.allowDiagonal; 44561 this.dontCrossCorners = opt.dontCrossCorners; 44562 this.heuristic = opt.heuristic || Heuristic.manhattan; 44563 this.weight = opt.weight || 1; 44564 this.diagonalMovement = opt.diagonalMovement; 44565 44566 if (!this.diagonalMovement) { 44567 if (!this.allowDiagonal) { 44568 this.diagonalMovement = DiagonalMovement.Never; 44569 } else { 44570 if (this.dontCrossCorners) { 44571 this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles; 44572 } else { 44573 this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle; 44574 } 44575 } 44576 } 44577 44578 // When diagonal movement is allowed the manhattan heuristic is not 44579 //admissible. It should be octile instead 44580 if (this.diagonalMovement === DiagonalMovement.Never) { 44581 this.heuristic = opt.heuristic || Heuristic.manhattan; 44582 } else { 44583 this.heuristic = opt.heuristic || Heuristic.octile; 44584 } 44585} 44586 44587/** 44588 * Find and return the the path. 44589 * @return {Array<Array<number>>} The path, including both start and 44590 * end positions. 44591 */ 44592AStarFinder.prototype.findPath = function(startX, startY, endX, endY, grid) { 44593 var openList = new Heap(function(nodeA, nodeB) { 44594 return nodeA.f - nodeB.f; 44595 }), 44596 startNode = grid.getNodeAt(startX, startY), 44597 endNode = grid.getNodeAt(endX, endY), 44598 heuristic = this.heuristic, 44599 diagonalMovement = this.diagonalMovement, 44600 weight = this.weight, 44601 abs = Math.abs, SQRT2 = Math.SQRT2, 44602 node, neighbors, neighbor, i, l, x, y, ng; 44603 44604 // set the `g` and `f` value of the start node to be 0 44605 startNode.g = 0; 44606 startNode.f = 0; 44607 44608 // push the start node into the open list 44609 openList.push(startNode); 44610 startNode.opened = true; 44611 44612 // while the open list is not empty 44613 while (!openList.empty()) { 44614 // pop the position of node which has the minimum `f` value. 44615 node = openList.pop();
44616 node.closed = true; 44617 44618 // if reached the end position, construct the path and return it 44619 if (node === endNode) { 44620 return Util.backtrace(endNode); 44621 } 44622 44623 // get neigbours of the current node 44624 neighbors = grid.getNeighbors(node, diagonalMovement); 44625 for (i = 0, l = neighbors.length; i < l; ++i) { 44626 neighbor = neighbors[i]; 44627 44628 if (neighbor.closed) { 44629 continue; 44630 } 44631 44632 x = neighbor.x; 44633 y = neighbor.y; 44634 44635 // get the distance between current node and the neighbor 44636 // and calculate the next g score 44637 ng = node.g + ((x - node.x === 0 || y - node.y === 0) ? 1 : SQRT2); 44638 44639 // check if the neighbor has not been inspected yet, or 44640 // can be reached with smaller cost from the current node 44641 if (!neighbor.opened || ng < neighbor.g) { 44642 neighbor.g = ng; 44643 neighbor.h = neighbor.h || weight * heuristic(abs(x - endX), abs(y - endY)); 44644 neighbor.f = neighbor.g + neighbor.h; 44645 neighbor.parent = node; 44646 44647 if (!neighbor.opened) { 44648 openList.push(neighbor); 44649 neighbor.opened = true; 44650 } else { 44651 // the neighbor can be reached with smaller cost. 44652 // Since its f value has been updated, we have to 44653 // update its position in the open list 44654 openList.updateItem(neighbor); 44655 } 44656 } 44657 } // end for each neighbor 44658 } // end while not open list empty 44659 44660 // fail to find the path 44661 return []; 44662}; 44663 44664module.exports = AStarFinder; 44665 44666},{"../core/DiagonalMovement":181,"../core/Heuristic":183,"../core/Util":185,"heap":159}],187:[function(require,module,exports){ 44667var AStarFinder = require('./AStarFinder'); 44668 44669/** 44670 * Best-First-Search path-finder. 44671 * @constructor 44672 * @extends AStarFinder 44673 * @param {Object} opt 44674 * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. 44675 * Deprecated, use diagonalMovement instead. 44676 * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching 44677 * block corners. Deprecated, use diagonalMovement instead. 44678 * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. 44679 * @param {function} opt.heuristic Heuristic function to estimate the distance 44680 * (defaults to manhattan). 44681 */ 44682function BestFirstFinder(opt) { 44683 AStarFinder.call(this, opt); 44684 44685 var orig = this.heuristic; 44686 this.heuristic = function(dx, dy) { 44687 return orig(dx, dy) * 1000000; 44688 }; 44689} 44690 44691BestFirstFinder.prototype = new AStarFinder(); 44692BestFirstFinder.prototype.constructor = BestFirstFinder; 44693 44694module.exports = BestFirstFinder; 44695 44696},{"./AStarFinder":186}],188:[function(require,module,exports){ 44697var Heap = require('heap'); 44698var Util = require('../core/Util'); 44699var Heuristic = require('../core/Heuristic'); 44700var DiagonalMovement = require('../core/DiagonalMovement'); 44701 44702/** 44703 * A* path-finder. 44704 * based upon https://github.com/bgrins/javascript-astar 44705 * @constructor 44706 * @param {Object} opt 44707 * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. 44708 * Deprecated, use diagonalMovement instead. 44709 * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching 44710 * block corners. Deprecated, use diagonalMovement instead. 44711 * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. 44712 * @param {function} opt.heuristic Heuristic function to estimate the distance 44713 * (defaults to manhattan). 44714 * @param {number} opt.weight Weight to apply to the heuristic to allow for 44715 * suboptimal paths, in order to speed up the search. 44716 */ 44717function BiAStarFinder(opt) { 44718 opt = opt || {}; 44719 this.allowDiagonal = opt.allowDiagonal; 44720 this.dontCrossCorners = opt.dontCrossCorners; 44721 this.diagonalMovement = opt.diagonalMovement; 44722 this.heuristic = opt.heuristic || Heuristic.manhattan; 44723 this.weight = opt.weight || 1; 44724 44725 if (!this.diagonalMovement) { 44726 if (!this.allowDiagonal) { 44727 this.diagonalMovement = DiagonalMovement.Never; 44728 } else { 44729 if (this.dontCrossCorners) { 44730 this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles; 44731 } else { 44732 this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle; 44733 } 44734 } 44735 } 44736 44737 //When diagonal movement is allowed the manhattan heuristic is not admissible 44738 //It should be octile instead 44739 if (this.diagonalMovement === DiagonalMovement.Never) { 44740 this.heuristic = opt.heuristic || Heuristic.manhattan; 44741 } else { 44742 this.heuristic = opt.heuristic || Heuristic.octile; 44743 } 44744} 44745 44746/** 44747 * Find and return the the path. 44748 * @return {Array<Array<number>>} The path, including both start and 44749 * end positions. 44750 */ 44751BiAStarFinder.prototype.findPath = function(startX, startY, endX, endY, grid) { 44752 var cmp = function(nodeA, nodeB) { 44753 return nodeA.f - nodeB.f; 44754 }, 44755 startOpenList = new Heap(cmp),
44756 endOpenList = new Heap(cmp), 44757 startNode = grid.getNodeAt(startX, startY), 44758 endNode = grid.getNodeAt(endX, endY), 44759 heuristic = this.heuristic, 44760 diagonalMovement = this.diagonalMovement, 44761 weight = this.weight, 44762 abs = Math.abs, SQRT2 = Math.SQRT2, 44763 node, neighbors, neighbor, i, l, x, y, ng, 44764 BY_START = 1, BY_END = 2; 44765 44766 // set the `g` and `f` value of the start node to be 0 44767 // and push it into the start open list 44768 startNode.g = 0; 44769 startNode.f = 0; 44770 startOpenList.push(startNode); 44771 startNode.opened = BY_START; 44772 44773 // set the `g` and `f` value of the end node to be 0 44774 // and push it into the open open list 44775 endNode.g = 0; 44776 endNode.f = 0; 44777 endOpenList.push(endNode); 44778 endNode.opened = BY_END; 44779 44780 // while both the open lists are not empty 44781 while (!startOpenList.empty() && !endOpenList.empty()) { 44782 44783 // pop the position of start node which has the minimum `f` value. 44784 node = startOpenList.pop(); 44785 node.closed = true; 44786 44787 // get neigbours of the current node 44788 neighbors = grid.getNeighbors(node, diagonalMovement); 44789 for (i = 0, l = neighbors.length; i < l; ++i) { 44790 neighbor = neighbors[i]; 44791 44792 if (neighbor.closed) { 44793 continue; 44794 } 44795 if (neighbor.opened === BY_END) { 44796 return Util.biBacktrace(node, neighbor); 44797 } 44798 44799 x = neighbor.x; 44800 y = neighbor.y; 44801 44802 // get the distance between current node and the neighbor 44803 // and calculate the next g score 44804 ng = node.g + ((x - node.x === 0 || y - node.y === 0) ? 1 : SQRT2); 44805 44806 // check if the neighbor has not been inspected yet, or 44807 // can be reached with smaller cost from the current node 44808 if (!neighbor.opened || ng < neighbor.g) { 44809 neighbor.g = ng; 44810 neighbor.h = neighbor.h || 44811 weight * heuristic(abs(x - endX), abs(y - endY)); 44812 neighbor.f = neighbor.g + neighbor.h; 44813 neighbor.parent = node; 44814 44815 if (!neighbor.opened) { 44816 startOpenList.push(neighbor); 44817 neighbor.opened = BY_START; 44818 } else { 44819 // the neighbor can be reached with smaller cost. 44820 // Since its f value has been updated, we have to 44821 // update its position in the open list 44822 startOpenList.updateItem(neighbor); 44823 } 44824 } 44825 } // end for each neighbor 44826 44827 44828 // pop the position of end node which has the minimum `f` value. 44829 node = endOpenList.pop(); 44830 node.closed = true; 44831 44832 // get neigbours of the current node 44833 neighbors = grid.getNeighbors(node, diagonalMovement); 44834 for (i = 0, l = neighbors.length; i < l; ++i) { 44835 neighbor = neighbors[i]; 44836 44837 if (neighbor.closed) { 44838 continue; 44839 } 44840 if (neighbor.opened === BY_START) { 44841 return Util.biBacktrace(neighbor, node); 44842 } 44843 44844 x = neighbor.x; 44845 y = neighbor.y; 44846 44847 // get the distance between current node and the neighbor 44848 // and calculate the next g score 44849 ng = node.g + ((x - node.x === 0 || y - node.y === 0) ? 1 : SQRT2); 44850 44851 // check if the neighbor has not been inspected yet, or 44852 // can be reached with smaller cost from the current node 44853 if (!neighbor.opened || ng < neighbor.g) { 44854 neighbor.g = ng; 44855 neighbor.h = neighbor.h || 44856 weight * heuristic(abs(x - startX), abs(y - startY)); 44857 neighbor.f = neighbor.g + neighbor.h; 44858 neighbor.parent = node; 44859 44860 if (!neighbor.opened) { 44861 endOpenList.push(neighbor); 44862 neighbor.opened = BY_END; 44863 } else { 44864 // the neighbor can be reached with smaller cost. 44865 // Since its f value has been updated, we have to 44866 // update its position in the open list
44867 endOpenList.updateItem(neighbor); 44868 } 44869 } 44870 } // end for each neighbor 44871 } // end while not open list empty 44872 44873 // fail to find the path 44874 return []; 44875}; 44876 44877module.exports = BiAStarFinder; 44878 44879},{"../core/DiagonalMovement":181,"../core/Heuristic":183,"../core/Util":185,"heap":159}],189:[function(require,module,exports){ 44880var BiAStarFinder = require('./BiAStarFinder'); 44881 44882/** 44883 * Bi-direcitional Best-First-Search path-finder. 44884 * @constructor 44885 * @extends BiAStarFinder 44886 * @param {Object} opt 44887 * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. 44888 * Deprecated, use diagonalMovement instead. 44889 * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching 44890 * block corners. Deprecated, use diagonalMovement instead. 44891 * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. 44892 * @param {function} opt.heuristic Heuristic function to estimate the distance 44893 * (defaults to manhattan). 44894 */ 44895function BiBestFirstFinder(opt) { 44896 BiAStarFinder.call(this, opt); 44897 44898 var orig = this.heuristic; 44899 this.heuristic = function(dx, dy) { 44900 return orig(dx, dy) * 1000000; 44901 }; 44902} 44903 44904BiBestFirstFinder.prototype = new BiAStarFinder(); 44905BiBestFirstFinder.prototype.constructor = BiBestFirstFinder; 44906 44907module.exports = BiBestFirstFinder; 44908 44909},{"./BiAStarFinder":188}],190:[function(require,module,exports){ 44910var Util = require('../core/Util'); 44911var DiagonalMovement = require('../core/DiagonalMovement'); 44912 44913/** 44914 * Bi-directional Breadth-First-Search path finder. 44915 * @constructor 44916 * @param {object} opt 44917 * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. 44918 * Deprecated, use diagonalMovement instead. 44919 * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching 44920 * block corners. Deprecated, use diagonalMovement instead. 44921 * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. 44922 */ 44923function BiBreadthFirstFinder(opt) { 44924 opt = opt || {}; 44925 this.allowDiagonal = opt.allowDiagonal; 44926 this.dontCrossCorners = opt.dontCrossCorners; 44927 this.diagonalMovement = opt.diagonalMovement; 44928 44929 if (!this.diagonalMovement) { 44930 if (!this.allowDiagonal) { 44931 this.diagonalMovement = DiagonalMovement.Never; 44932 } else { 44933 if (this.dontCrossCorners) { 44934 this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles; 44935 } else { 44936 this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle; 44937 } 44938 } 44939 } 44940} 44941 44942 44943/** 44944 * Find and return the the path. 44945 * @return {Array<Array<number>>} The path, including both start and 44946 * end positions. 44947 */ 44948BiBreadthFirstFinder.prototype.findPath = function(startX, startY, endX, endY, grid) { 44949 var startNode = grid.getNodeAt(startX, startY), 44950 endNode = grid.getNodeAt(endX, endY),
44951 startOpenList = [], endOpenList = [], 44952 neighbors, neighbor, node, 44953 diagonalMovement = this.diagonalMovement, 44954 BY_START = 0, BY_END = 1, 44955 i, l; 44956 44957 // push the start and end nodes into the queues 44958 startOpenList.push(startNode); 44959 startNode.opened = true; 44960 startNode.by = BY_START; 44961 44962 endOpenList.push(endNode); 44963 endNode.opened = true; 44964 endNode.by = BY_END; 44965 44966 // while both the queues are not empty 44967 while (startOpenList.length && endOpenList.length) { 44968 44969 // expand start open list 44970 44971 node = startOpenList.shift(); 44972 node.closed = true; 44973 44974 neighbors = grid.getNeighbors(node, diagonalMovement); 44975 for (i = 0, l = neighbors.length; i < l; ++i) { 44976 neighbor = neighbors[i]; 44977 44978 if (neighbor.closed) { 44979 continue; 44980 } 44981 if (neighbor.opened) { 44982 // if this node has been inspected by the reversed search, 44983 // then a path is found. 44984 if (neighbor.by === BY_END) { 44985 return Util.biBacktrace(node, neighbor); 44986 } 44987 continue; 44988 } 44989 startOpenList.push(neighbor); 44990 neighbor.parent = node; 44991 neighbor.opened = true; 44992 neighbor.by = BY_START; 44993 } 44994 44995 // expand end open list 44996 44997 node = endOpenList.shift(); 44998 node.closed = true; 44999 45000 neighbors = grid.getNeighbors(node, diagonalMovement); 45001 for (i = 0, l = neighbors.length; i < l; ++i) { 45002 neighbor = neighbors[i]; 45003 45004 if (neighbor.closed) { 45005 continue; 45006 } 45007 if (neighbor.opened) { 45008 if (neighbor.by === BY_START) { 45009 return Util.biBacktrace(neighbor, node); 45010 } 45011 continue; 45012 } 45013 endOpenList.push(neighbor); 45014 neighbor.parent = node; 45015 neighbor.opened = true; 45016 neighbor.by = BY_END; 45017 } 45018 } 45019 45020 // fail to find the path 45021 return []; 45022}; 45023 45024module.exports = BiBreadthFirstFinder; 45025 45026},{"../core/DiagonalMovement":181,"../core/Util":185}],191:[function(require,module,exports){ 45027var BiAStarFinder = require('./BiAStarFinder'); 45028 45029/** 45030 * Bi-directional Dijkstra path-finder. 45031 * @constructor 45032 * @extends BiAStarFinder 45033 * @param {Object} opt 45034 * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. 45035 * Deprecated, use diagonalMovement instead. 45036 * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching 45037 * block corners. Deprecated, use diagonalMovement instead. 45038 * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. 45039 */ 45040function BiDijkstraFinder(opt) { 45041 BiAStarFinder.call(this, opt); 45042 this.heuristic = function(dx, dy) { 45043 return 0; 45044 }; 45045} 45046 45047BiDijkstraFinder.prototype = new BiAStarFinder(); 45048BiDijkstraFinder.prototype.constructor = BiDijkstraFinder; 45049 45050module.exports = BiDijkstraFinder; 45051 45052},{"./BiAStarFinder":188}],192:[function(require,module,exports){ 45053var Util = require('../core/Util'); 45054var DiagonalMovement = require('../core/DiagonalMovement'); 45055 45056/** 45057 * Breadth-First-Search path finder. 45058 * @constructor 45059 * @param {Object} opt 45060 * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. 45061 * Deprecated, use diagonalMovement instead. 45062 * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching 45063 * block corners. Deprecated, use diagonalMovement instead. 45064 * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. 45065 */ 45066function BreadthFirstFinder(opt) { 45067 opt = opt || {}; 45068 this.allowDiagonal = opt.allowDiagonal; 45069 this.dontCrossCorners = opt.dontCrossCorners; 45070 this.diagonalMovement = opt.diagonalMovement; 45071 45072 if (!this.diagonalMovement) { 45073 if (!this.allowDiagonal) { 45074 this.diagonalMovement = DiagonalMovement.Never; 45075 } else { 45076 if (this.dontCrossCorners) { 45077 this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles; 45078 } else { 45079 this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle; 45080 } 45081 } 45082 } 45083} 45084 45085/** 45086 * Find and return the the path. 45087 * @return {Array<Array<number>>} The path, including both start and 45088 * end positions. 45089 */ 45090BreadthFirstFinder.prototype.findPath = function(startX, startY, endX, endY, grid) { 45091 var openList = [], 45092 diagonalMovement = this.diagonalMovement, 45093 startNode = grid.getNodeAt(startX, startY), 45094 endNode = grid.getNodeAt(endX, endY), 45095 neighbors, neighbor, node, i, l; 45096 45097 // push the start pos into the queue 45098 openList.push(startNode); 45099 startNode.opened = true; 45100 45101 // while the queue is not empty 45102 while (openList.length) { 45103 // take the front node from the queue 45104 node = openList.shift(); 45105 node.closed = true; 45106 45107 // reached the end position 45108 if (node === endNode) { 45109 return Util.backtrace(endNode); 45110 } 45111 45112 neighbors = grid.getNeighbors(node, diagonalMovement); 45113 for (i = 0, l = neighbors.length; i < l; ++i) { 45114 neighbor = neighbors[i]; 45115 45116 // skip this neighbor if it has been inspected before 45117 if (neighbor.closed || neighbor.opened) { 45118 continue; 45119 } 45120 45121 openList.push(neighbor); 45122 neighbor.opened = true; 45123 neighbor.parent = node; 45124 } 45125 } 45126 45127 // fail to find the path 45128 return []; 45129}; 45130 45131module.exports = BreadthFirstFinder; 45132 45133},{"../core/DiagonalMovement":181,"../core/Util":185}],193:[function(require,module,exports){ 45134var AStarFinder = require('./AStarFinder'); 45135 45136/** 45137 * Dijkstra path-finder. 45138 * @constructor 45139 * @extends AStarFinder 45140 * @param {Object} opt 45141 * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. 45142 * Deprecated, use diagonalMovement instead. 45143 * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching 45144 * block corners. Deprecated, use diagonalMovement instead. 45145 * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. 45146 */ 45147function DijkstraFinder(opt) { 45148 AStarFinder.call(this, opt); 45149 this.heuristic = function(dx, dy) { 45150 return 0; 45151 }; 45152} 45153 45154DijkstraFinder.prototype = new AStarFinder(); 45155DijkstraFinder.prototype.constructor = DijkstraFinder; 45156 45157module.exports = DijkstraFinder; 45158 45159},{"./AStarFinder":186}],194:[function(require,module,exports){ 45160var Util = require('../core/Util'); 45161var Heuristic = require('../core/Heuristic'); 45162var Node = require('../core/Node'); 45163var DiagonalMovement = require('../core/DiagonalMovement'); 45164 45165/** 45166 * Iterative Deeping A Star (IDA*) path-finder. 45167 * 45168 * Recursion based on: 45169 * http://www.apl.jhu.edu/~hall/AI-Programming/IDA-Star.html 45170 * 45171 * Path retracing based on: 45172 * V. Nageshwara Rao, Vipin Kumar and K. Ramesh 45173 * "A Parallel Implementation of Iterative-Deeping-A*", January 1987. 45174 * ftp://ftp.cs.utexas.edu/.snapshot/hourly.1/pub/AI-Lab/tech-reports/UT-AI-TR-87-46.pdf 45175 * 45176 * @author Gerard Meier (www.gerardmeier.com) 45177 * 45178 * @constructor 45179 * @param {Object} opt 45180 * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. 45181 * Deprecated, use diagonalMovement instead. 45182 * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching 45183 * block corners. Deprecated, use diagonalMovement instead. 45184 * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. 45185 * @param {function} opt.heuristic Heuristic function to estimate the distance 45186 * (defaults to manhattan). 45187 * @param {number} opt.weight Weight to apply to the heuristic to allow for 45188 * suboptimal paths, in order to speed up the search. 45189 * @param {boolean} opt.trackRecursion Whether to track recursion for 45190 * statistical purposes. 45191 * @param {number} opt.timeLimit Maximum execution time. Use <= 0 for infinite. 45192 */ 45193function IDAStarFinder(opt) { 45194 opt = opt || {}; 45195 this.allowDiagonal = opt.allowDiagonal; 45196 this.dontCrossCorners = opt.dontCrossCorners; 45197 this.diagonalMovement = opt.diagonalMovement; 45198 this.heuristic = opt.heuristic || Heuristic.manhattan; 45199 this.weight = opt.weight || 1; 45200 this.trackRecursion = opt.trackRecursion || false; 45201 this.timeLimit = opt.timeLimit || Infinity; // Default: no time limit. 45202 45203 if (!this.diagonalMovement) { 45204 if (!this.allowDiagonal) { 45205 this.diagonalMovement = DiagonalMovement.Never; 45206 } else { 45207 if (this.dontCrossCorners) { 45208 this.diagonalMovement = DiagonalMovement.OnlyWhenNoObstacles; 45209 } else { 45210 this.diagonalMovement = DiagonalMovement.IfAtMostOneObstacle; 45211 } 45212 } 45213 } 45214 45215 // When diagonal movement is allowed the manhattan heuristic is not 45216 // admissible, it should be octile instead 45217 if (this.diagonalMovement === DiagonalMovement.Never) { 45218 this.heuristic = opt.heuristic || Heuristic.manhattan; 45219 } else { 45220 this.heuristic = opt.heuristic || Heuristic.octile; 45221 } 45222} 45223 45224/** 45225 * Find and return the the path. When an empty array is returned, either 45226 * no path is possible, or the maximum execution time is reached. 45227 * 45228 * @return {Array<Array<number>>} The path, including both start and 45229 * end positions. 45230 */ 45231IDAStarFinder.prototype.findPath = function(startX, startY, endX, endY, grid) { 45232 // Used for statistics: 45233 var nodesVisited = 0; 45234 45235 // Execution time limitation: 45236 var startTime = new Date().getTime(); 45237 45238 // Heuristic helper: 45239 var h = function(a, b) { 45240 return this.heuristic(Math.abs(b.x - a.x), Math.abs(b.y - a.y)); 45241 }.bind(this); 45242 45243 // Step cost from a to b: 45244 var cost = function(a, b) { 45245 return (a.x === b.x || a.y === b.y) ? 1 : Math.SQRT2; 45246 }; 45247 45248 /** 45249 * IDA* search implementation. 45250 * 45251 * @param {Node} The node currently expanding from. 45252 * @param {number} Cost to reach the given node. 45253 * @param {number} Maximum search depth (cut-off value). 45254 * @param {Array<Array<number>>} The found route. 45255 * @param {number} Recursion depth. 45256 * 45257 * @return {Object} either a number with the new optimal cut-off depth, 45258 * or a valid node instance, in which case a path was found. 45259 */ 45260 var search = function(node, g, cutoff, route, depth) { 45261 nodesVisited++; 45262 45263 // Enforce timelimit: 45264 if (this.timeLimit > 0 && 45265 new Date().getTime() - startTime > this.timeLimit * 1000) { 45266 // Enforced as "path-not-found". 45267 return Infinity; 45268 } 45269 45270 var f = g + h(node, end) * this.weight; 45271 45272 // We've searched too deep for this iteration. 45273 if (f > cutoff) { 45274 return f; 45275 } 45276 45277 if (node == end) { 45278 route[depth] = [node.x, node.y]; 45279 return node; 45280 } 45281 45282 var min, t, k, neighbour; 45283 45284 var neighbours = grid.getNeighbors(node, this.diagonalMovement); 45285 45286 // Sort the neighbours, gives nicer paths. But, this deviates 45287 // from the original algorithm - so I left it out. 45288 //neighbours.sort(function(a, b){ 45289 // return h(a, end) - h(b, end); 45290 //}); 45291 45292 45293 /*jshint -W084 *///Disable warning: Expected a conditional expression and instead saw an assignment 45294 for (k = 0, min = Infinity; neighbour = neighbours[k]; ++k) { 45295 /*jshint +W084 *///Enable warning: Expected a conditional expression and instead saw an assignment 45296 if (this.trackRecursion) { 45297 // Retain a copy for visualisation. Due to recursion, this 45298 // node may be part of other paths too. 45299 neighbour.retainCount = neighbour.retainCount + 1 || 1; 45300 45301 if(neighbour.tested !== true) { 45302 neighbour.tested = true; 45303 } 45304 } 45305 45306 t = search(neighbour, g + cost(node, neighbour), cutoff, route, depth + 1); 45307 45308 if (t instanceof Node) { 45309 route[depth] = [node.x, node.y]; 45310 45311 // For a typical A* linked list, this would work: 45312 // neighbour.parent = node; 45313 return t; 45314 } 45315 45316 // Decrement count, then determine whether it's actually closed. 45317 if (this.trackRecursion && (--neighbour.retainCount) === 0) { 45318 neighbour.tested = false; 45319 } 45320 45321 if (t < min) { 45322 min = t; 45323 } 45324 } 45325 45326 return min; 45327 45328 }.bind(this); 45329 45330 // Node instance lookups: 45331 var start = grid.getNodeAt(startX, startY); 45332 var end = grid.getNodeAt(endX, endY); 45333 45334 // Initial search depth, given the typical heuristic contraints, 45335 // there should be no cheaper route possible. 45336 var cutOff = h(start, end); 45337 45338 var j, route, t; 45339 45340 // With an overflow protection. 45341 for (j = 0; true; ++j) { 45342 45343 route = []; 45344 45345 // Search till cut-off depth: 45346 t = search(start, 0, cutOff, route, 0); 45347 45348 // Route not possible, or not found in time limit. 45349 if (t === Infinity) { 45350 return []; 45351 } 45352
45353 // If t is a node, it's also the end node. Route is now 45354 // populated with a valid path to the end node. 45355 if (t instanceof Node) { 45356 return route; 45357 } 45358 45359 // Try again, this time with a deeper cut-off. The t score 45360 // is the closest we got to the end node. 45361 cutOff = t; 45362 } 45363 45364 // This _should_ never to be reached. 45365 return []; 45366}; 45367 45368module.exports = IDAStarFinder; 45369 45370},{"../core/DiagonalMovement":181,"../core/Heuristic":183,"../core/Node":184,"../core/Util":185}],195:[function(require,module,exports){ 45371/** 45372 * @author imor / https://github.com/imor 45373 */ 45374var JumpPointFinderBase = require('./JumpPointFinderBase'); 45375var DiagonalMovement = require('../core/DiagonalMovement'); 45376 45377/** 45378 * Path finder using the Jump Point Search algorithm which always moves 45379 * diagonally irrespective of the number of obstacles. 45380 */ 45381function JPFAlwaysMoveDiagonally(opt) { 45382 JumpPointFinderBase.call(this, opt); 45383} 45384 45385JPFAlwaysMoveDiagonally.prototype = new JumpPointFinderBase(); 45386JPFAlwaysMoveDiagonally.prototype.constructor = JPFAlwaysMoveDiagonally; 45387 45388/** 45389 * Search recursively in the direction (parent -> child), stopping only when a 45390 * jump point is found. 45391 * @protected 45392 * @return {Array<Array<number>>} The x, y coordinate of the jump point 45393 * found, or null if not found 45394 */ 45395JPFAlwaysMoveDiagonally.prototype._jump = function(x, y, px, py) { 45396 var grid = this.grid, 45397 dx = x - px, dy = y - py; 45398 45399 if (!grid.isWalkableAt(x, y)) { 45400 return null; 45401 } 45402 45403 if(this.trackJumpRecursion === true) { 45404 grid.getNodeAt(x, y).tested = true; 45405 } 45406 45407 if (grid.getNodeAt(x, y) === this.endNode) { 45408 return [x, y]; 45409 } 45410 45411 // check for forced neighbors 45412 // along the diagonal 45413 if (dx !== 0 && dy !== 0) { 45414 if ((grid.isWalkableAt(x - dx, y + dy) && !grid.isWalkableAt(x - dx, y)) || 45415 (grid.isWalkableAt(x + dx, y - dy) && !grid.isWalkableAt(x, y - dy))) { 45416 return [x, y]; 45417 } 45418 // when moving diagonally, must check for vertical/horizontal jump points 45419 if (this._jump(x + dx, y, x, y) || this._jump(x, y + dy, x, y)) { 45420 return [x, y]; 45421 } 45422 } 45423 // horizontally/vertically 45424 else { 45425 if( dx !== 0 ) { // moving along x 45426 if((grid.isWalkableAt(x + dx, y + 1) && !grid.isWalkableAt(x, y + 1)) || 45427 (grid.isWalkableAt(x + dx, y - 1) && !grid.isWalkableAt(x, y - 1))) { 45428 return [x, y]; 45429 } 45430 } 45431 else { 45432 if((grid.isWalkableAt(x + 1, y + dy) && !grid.isWalkableAt(x + 1, y)) || 45433 (grid.isWalkableAt(x - 1, y + dy) && !grid.isWalkableAt(x - 1, y))) { 45434 return [x, y]; 45435 } 45436 } 45437 } 45438 45439 return this._jump(x + dx, y + dy, x, y); 45440}; 45441 45442/** 45443 * Find the neighbors for the given node. If the node has a parent, 45444 * prune the neighbors based on the jump point search algorithm, otherwise 45445 * return all available neighbors. 45446 * @return {Array<Array<number>>} The neighbors found. 45447 */ 45448JPFAlwaysMoveDiagonally.prototype._findNeighbors = function(node) { 45449 var parent = node.parent, 45450 x = node.x, y = node.y, 45451 grid = this.grid, 45452 px, py, nx, ny, dx, dy, 45453 neighbors = [], neighborNodes, neighborNode, i, l; 45454 45455 // directed pruning: can ignore most neighbors, unless forced. 45456 if (parent) { 45457 px = parent.x; 45458 py = parent.y; 45459 // get the normalized direction of travel 45460 dx = (x - px) / Math.max(Math.abs(x - px), 1); 45461 dy = (y - py) / Math.max(Math.abs(y - py), 1); 45462 45463 // search diagonally 45464 if (dx !== 0 && dy !== 0) { 45465 if (grid.isWalkableAt(x, y + dy)) { 45466 neighbors.push([x, y + dy]); 45467 } 45468 if (grid.isWalkableAt(x + dx, y)) { 45469 neighbors.push([x + dx, y]); 45470 } 45471 if (grid.isWalkableAt(x + dx, y + dy)) { 45472 neighbors.push([x + dx, y + dy]); 45473 } 45474 if (!grid.isWalkableAt(x - dx, y)) {
45475 neighbors.push([x - dx, y + dy]); 45476 } 45477 if (!grid.isWalkableAt(x, y - dy)) { 45478 neighbors.push([x + dx, y - dy]); 45479 } 45480 } 45481 // search horizontally/vertically 45482 else { 45483 if(dx === 0) { 45484 if (grid.isWalkableAt(x, y + dy)) { 45485 neighbors.push([x, y + dy]); 45486 } 45487 if (!grid.isWalkableAt(x + 1, y)) { 45488 neighbors.push([x + 1, y + dy]); 45489 } 45490 if (!grid.isWalkableAt(x - 1, y)) { 45491 neighbors.push([x - 1, y + dy]); 45492 } 45493 } 45494 else { 45495 if (grid.isWalkableAt(x + dx, y)) { 45496 neighbors.push([x + dx, y]); 45497 } 45498 if (!grid.isWalkableAt(x, y + 1)) { 45499 neighbors.push([x + dx, y + 1]); 45500 } 45501 if (!grid.isWalkableAt(x, y - 1)) { 45502 neighbors.push([x + dx, y - 1]); 45503 } 45504 } 45505 } 45506 } 45507 // return all neighbors 45508 else { 45509 neighborNodes = grid.getNeighbors(node, DiagonalMovement.Always); 45510 for (i = 0, l = neighborNodes.length; i < l; ++i) { 45511 neighborNode = neighborNodes[i]; 45512 neighbors.push([neighborNode.x, neighborNode.y]); 45513 } 45514 } 45515 45516 return neighbors; 45517}; 45518 45519module.exports = JPFAlwaysMoveDiagonally; 45520 45521},{"../core/DiagonalMovement":181,"./JumpPointFinderBase":200}],196:[function(require,module,exports){ 45522/** 45523 * @author imor / https://github.com/imor 45524 */ 45525var JumpPointFinderBase = require('./JumpPointFinderBase'); 45526var DiagonalMovement = require('../core/DiagonalMovement'); 45527 45528/** 45529 * Path finder using the Jump Point Search algorithm which moves 45530 * diagonally only when there is at most one obstacle. 45531 */ 45532function JPFMoveDiagonallyIfAtMostOneObstacle(opt) { 45533 JumpPointFinderBase.call(this, opt); 45534} 45535 45536JPFMoveDiagonallyIfAtMostOneObstacle.prototype = new JumpPointFinderBase(); 45537JPFMoveDiagonallyIfAtMostOneObstacle.prototype.constructor = JPFMoveDiagonallyIfAtMostOneObstacle; 45538 45539/** 45540 * Search recursively in the direction (parent -> child), stopping only when a 45541 * jump point is found. 45542 * @protected 45543 * @return {Array<Array<number>>} The x, y coordinate of the jump point 45544 * found, or null if not found 45545 */ 45546JPFMoveDiagonallyIfAtMostOneObstacle.prototype._jump = function(x, y, px, py) { 45547 var grid = this.grid, 45548 dx = x - px, dy = y - py; 45549 45550 if (!grid.isWalkableAt(x, y)) { 45551 return null; 45552 } 45553 45554 if(this.trackJumpRecursion === true) { 45555 grid.getNodeAt(x, y).tested = true; 45556 } 45557 45558 if (grid.getNodeAt(x, y) === this.endNode) { 45559 return [x, y]; 45560 } 45561 45562 // check for forced neighbors 45563 // along the diagonal 45564 if (dx !== 0 && dy !== 0) { 45565 if ((grid.isWalkableAt(x - dx, y + dy) && !grid.isWalkableAt(x - dx, y)) || 45566 (grid.isWalkableAt(x + dx, y - dy) && !grid.isWalkableAt(x, y - dy))) { 45567 return [x, y]; 45568 } 45569 // when moving diagonally, must check for vertical/horizontal jump points 45570 if (this._jump(x + dx, y, x, y) || this._jump(x, y + dy, x, y)) { 45571 return [x, y]; 45572 } 45573 } 45574 // horizontally/vertically 45575 else { 45576 if( dx !== 0 ) { // moving along x 45577 if((grid.isWalkableAt(x + dx, y + 1) && !grid.isWalkableAt(x, y + 1)) || 45578 (grid.isWalkableAt(x + dx, y - 1) && !grid.isWalkableAt(x, y - 1))) { 45579 return [x, y]; 45580 } 45581 } 45582 else { 45583 if((grid.isWalkableAt(x + 1, y + dy) && !grid.isWalkableAt(x + 1, y)) || 45584 (grid.isWalkableAt(x - 1, y + dy) && !grid.isWalkableAt(x - 1, y))) { 45585 return [x, y]; 45586 } 45587 } 45588 } 45589 45590 // moving diagonally, must make sure one of the vertical/horizontal 45591 // neighbors is open to allow the path 45592 if (grid.isWalkableAt(x + dx, y) || grid.isWalkableAt(x, y + dy)) { 45593 return this._jump(x + dx, y + dy, x, y); 45594 } else { 45595 return null; 45596 } 45597}; 45598 45599/** 45600 * Find the neighbors for the given node. If the node has a parent, 45601 * prune the neighbors based on the jump point search algorithm, otherwise 45602 * return all available neighbors. 45603 * @return {Array<Array<number>>} The neighbors found. 45604 */ 45605JPFMoveDiagonallyIfAtMostOneObstacle.prototype._findNeighbors = function(node) { 45606 var parent = node.parent, 45607 x = node.x, y = node.y, 45608 grid = this.grid, 45609 px, py, nx, ny, dx, dy, 45610 neighbors = [], neighborNodes, neighborNode, i, l; 45611 45612 // directed pruning: can ignore most neighbors, unless forced. 45613 if (parent) { 45614 px = parent.x; 45615 py = parent.y; 45616 // get the normalized direction of travel 45617 dx = (x - px) / Math.max(Math.abs(x - px), 1); 45618 dy = (y - py) / Math.max(Math.abs(y - py), 1); 45619 45620 // search diagonally 45621 if (dx !== 0 && dy !== 0) { 45622 if (grid.isWalkableAt(x, y + dy)) {
45623 neighbors.push([x, y + dy]); 45624 } 45625 if (grid.isWalkableAt(x + dx, y)) { 45626 neighbors.push([x + dx, y]); 45627 } 45628 if (grid.isWalkableAt(x, y + dy) || grid.isWalkableAt(x + dx, y)) { 45629 neighbors.push([x + dx, y + dy]); 45630 } 45631 if (!grid.isWalkableAt(x - dx, y) && grid.isWalkableAt(x, y + dy)) { 45632 neighbors.push([x - dx, y + dy]); 45633 } 45634 if (!grid.isWalkableAt(x, y - dy) && grid.isWalkableAt(x + dx, y)) { 45635 neighbors.push([x + dx, y - dy]); 45636 } 45637 } 45638 // search horizontally/vertically 45639 else { 45640 if(dx === 0) { 45641 if (grid.isWalkableAt(x, y + dy)) { 45642 neighbors.push([x, y + dy]); 45643 if (!grid.isWalkableAt(x + 1, y)) { 45644 neighbors.push([x + 1, y + dy]); 45645 } 45646 if (!grid.isWalkableAt(x - 1, y)) { 45647 neighbors.push([x - 1, y + dy]); 45648 } 45649 } 45650 } 45651 else { 45652 if (grid.isWalkableAt(x + dx, y)) { 45653 neighbors.push([x + dx, y]); 45654 if (!grid.isWalkableAt(x, y + 1)) { 45655 neighbors.push([x + dx, y + 1]); 45656 } 45657 if (!grid.isWalkableAt(x, y - 1)) { 45658 neighbors.push([x + dx, y - 1]); 45659 } 45660 } 45661 } 45662 } 45663 } 45664 // return all neighbors 45665 else { 45666 neighborNodes = grid.getNeighbors(node, DiagonalMovement.IfAtMostOneObstacle); 45667 for (i = 0, l = neighborNodes.length; i < l; ++i) { 45668 neighborNode = neighborNodes[i]; 45669 neighbors.push([neighborNode.x, neighborNode.y]); 45670 } 45671 } 45672 45673 return neighbors; 45674}; 45675 45676module.exports = JPFMoveDiagonallyIfAtMostOneObstacle; 45677 45678},{"../core/DiagonalMovement":181,"./JumpPointFinderBase":200}],197:[function(require,module,exports){ 45679/** 45680 * @author imor / https://github.com/imor 45681 */ 45682var JumpPointFinderBase = require('./JumpPointFinderBase'); 45683var DiagonalMovement = require('../core/DiagonalMovement'); 45684 45685/** 45686 * Path finder using the Jump Point Search algorithm which moves 45687 * diagonally only when there are no obstacles. 45688 */ 45689function JPFMoveDiagonallyIfNoObstacles(opt) { 45690 JumpPointFinderBase.call(this, opt); 45691} 45692 45693JPFMoveDiagonallyIfNoObstacles.prototype = new JumpPointFinderBase(); 45694JPFMoveDiagonallyIfNoObstacles.prototype.constructor = JPFMoveDiagonallyIfNoObstacles; 45695 45696/** 45697 * Search recursively in the direction (parent -> child), stopping only when a 45698 * jump point is found. 45699 * @protected 45700 * @return {Array<Array<number>>} The x, y coordinate of the jump point 45701 * found, or null if not found 45702 */ 45703JPFMoveDiagonallyIfNoObstacles.prototype._jump = function(x, y, px, py) { 45704 var grid = this.grid, 45705 dx = x - px, dy = y - py; 45706 45707 if (!grid.isWalkableAt(x, y)) { 45708 return null; 45709 } 45710 45711 if(this.trackJumpRecursion === true) { 45712 grid.getNodeAt(x, y).tested = true; 45713 } 45714 45715 if (grid.getNodeAt(x, y) === this.endNode) { 45716 return [x, y]; 45717 } 45718 45719 // check for forced neighbors 45720 // along the diagonal 45721 if (dx !== 0 && dy !== 0) { 45722 // if ((grid.isWalkableAt(x - dx, y + dy) && !grid.isWalkableAt(x - dx, y)) || 45723 // (grid.isWalkableAt(x + dx, y - dy) && !grid.isWalkableAt(x, y - dy))) { 45724 // return [x, y]; 45725 // } 45726 // when moving diagonally, must check for vertical/horizontal jump points 45727 if (this._jump(x + dx, y, x, y) || this._jump(x, y + dy, x, y)) { 45728 return [x, y]; 45729 } 45730 } 45731 // horizontally/vertically 45732 else { 45733 if (dx !== 0) { 45734 if ((grid.isWalkableAt(x, y - 1) && !grid.isWalkableAt(x - dx, y - 1)) || 45735 (grid.isWalkableAt(x, y + 1) && !grid.isWalkableAt(x - dx, y + 1))) { 45736 return [x, y]; 45737 } 45738 } 45739 else if (dy !== 0) { 45740 if ((grid.isWalkableAt(x - 1, y) && !grid.isWalkableAt(x - 1, y - dy)) || 45741 (grid.isWalkableAt(x + 1, y) && !grid.isWalkableAt(x + 1, y - dy))
45741) { 45742 return [x, y]; 45743 } 45744 // When moving vertically, must check for horizontal jump points 45745 // if (this._jump(x + 1, y, x, y) || this._jump(x - 1, y, x, y)) { 45746 // return [x, y]; 45747 // } 45748 } 45749 } 45750 45751 // moving diagonally, must make sure one of the vertical/horizontal 45752 // neighbors is open to allow the path 45753 if (grid.isWalkableAt(x + dx, y) && grid.isWalkableAt(x, y + dy)) { 45754 return this._jump(x + dx, y + dy, x, y); 45755 } else { 45756 return null; 45757 } 45758}; 45759 45760/** 45761 * Find the neighbors for the given node. If the node has a parent, 45762 * prune the neighbors based on the jump point search algorithm, otherwise 45763 * return all available neighbors. 45764 * @return {Array<Array<number>>} The neighbors found. 45765 */ 45766JPFMoveDiagonallyIfNoObstacles.prototype._findNeighbors = function(node) { 45767 var parent = node.parent, 45768 x = node.x, y = node.y, 45769 grid = this.grid, 45770 px, py, nx, ny, dx, dy, 45771 neighbors = [], neighborNodes, neighborNode, i, l; 45772 45773 // directed pruning: can ignore most neighbors, unless forced. 45774 if (parent) { 45775 px = parent.x; 45776 py = parent.y; 45777 // get the normalized direction of travel 45778 dx = (x - px) / Math.max(Math.abs(x - px), 1); 45779 dy = (y - py) / Math.max(Math.abs(y - py), 1); 45780 45781 // search diagonally 45782 if (dx !== 0 && dy !== 0) { 45783 if (grid.isWalkableAt(x, y + dy)) { 45784 neighbors.push([x, y + dy]); 45785 } 45786 if (grid.isWalkableAt(x + dx, y)) { 45787 neighbors.push([x + dx, y]); 45788 } 45789 if (grid.isWalkableAt(x, y + dy) && grid.isWalkableAt(x + dx, y)) { 45790 neighbors.push([x + dx, y + dy]); 45791 } 45792 } 45793 // search horizontally/vertically 45794 else { 45795 var isNextWalkable; 45796 if (dx !== 0) { 45797 isNextWalkable = grid.isWalkableAt(x + dx, y); 45798 var isTopWalkable = grid.isWalkableAt(x, y + 1); 45799 var isBottomWalkable = grid.isWalkableAt(x, y - 1); 45800 45801 if (isNextWalkable) { 45802 neighbors.push([x + dx, y]); 45803 if (isTopWalkable) { 45804 neighbors.push([x + dx, y + 1]); 45805 } 45806 if (isBottomWalkable) { 45807 neighbors.push([x + dx, y - 1]); 45808 } 45809 } 45810 if (isTopWalkable) { 45811 neighbors.push([x, y + 1]); 45812 } 45813 if (isBottomWalkable) { 45814 neighbors.push([x, y - 1]); 45815 } 45816 } 45817 else if (dy !== 0) { 45818 isNextWalkable = grid.isWalkableAt(x, y + dy); 45819 var isRightWalkable = grid.isWalkableAt(x + 1, y); 45820 var isLeftWalkable = grid.isWalkableAt(x - 1, y); 45821 45822 if (isNextWalkable) { 45823 neighbors.push([x, y + dy]); 45824 if (isRightWalkable) {
45825 neighbors.push([x + 1, y + dy]); 45826 } 45827 if (isLeftWalkable) { 45828 neighbors.push([x - 1, y + dy]); 45829 } 45830 } 45831 if (isRightWalkable) { 45832 neighbors.push([x + 1, y]); 45833 } 45834 if (isLeftWalkable) { 45835 neighbors.push([x - 1, y]); 45836 } 45837 } 45838 } 45839 } 45840 // return all neighbors 45841 else { 45842 neighborNodes = grid.getNeighbors(node, DiagonalMovement.OnlyWhenNoObstacles); 45843 for (i = 0, l = neighborNodes.length; i < l; ++i) { 45844 neighborNode = neighborNodes[i]; 45845 neighbors.push([neighborNode.x, neighborNode.y]); 45846 } 45847 } 45848 45849 return neighbors; 45850}; 45851 45852module.exports = JPFMoveDiagonallyIfNoObstacles; 45853 45854},{"../core/DiagonalMovement":181,"./JumpPointFinderBase":200}],198:[function(require,module,exports){ 45855/** 45856 * @author imor / https://github.com/imor 45857 */ 45858var JumpPointFinderBase = require('./JumpPointFinderBase'); 45859var DiagonalMovement = require('../core/DiagonalMovement'); 45860 45861/** 45862 * Path finder using the Jump Point Search algorithm allowing only horizontal 45863 * or vertical movements. 45864 */ 45865function JPFNeverMoveDiagonally(opt) { 45866 JumpPointFinderBase.call(this, opt); 45867} 45868 45869JPFNeverMoveDiagonally.prototype = new JumpPointFinderBase(); 45870JPFNeverMoveDiagonally.prototype.constructor = JPFNeverMoveDiagonally; 45871 45872/** 45873 * Search recursively in the direction (parent -> child), stopping only when a 45874 * jump point is found. 45875 * @protected 45876 * @return {Array<Array<number>>} The x, y coordinate of the jump point 45877 * found, or null if not found 45878 */ 45879JPFNeverMoveDiagonally.prototype._jump = function(x, y, px, py) { 45880 var grid = this.grid, 45881 dx = x - px, dy = y - py; 45882 45883 if (!grid.isWalkableAt(x, y)) { 45884 return null; 45885 } 45886 45887 if(this.trackJumpRecursion === true) { 45888 grid.getNodeAt(x, y).tested = true; 45889 } 45890 45891 if (grid.getNodeAt(x, y) === this.endNode) { 45892 return [x, y]; 45893 } 45894 45895 if (dx !== 0) { 45896 if ((grid.isWalkableAt(x, y - 1) && !grid.isWalkableAt(x - dx, y - 1)) || 45897 (grid.isWalkableAt(x, y + 1) && !grid.isWalkableAt(x - dx, y + 1))) { 45898 return [x, y]; 45899 } 45900 } 45901 else if (dy !== 0) { 45902 if ((grid.isWalkableAt(x - 1, y) && !grid.isWalkableAt(x - 1, y - dy)) || 45903 (grid.isWalkableAt(x + 1, y) && !grid.isWalkableAt(x + 1, y - dy))) { 45904 return [x, y]; 45905 } 45906 //When moving vertically, must check for horizontal jump points 45907 if (this._jump(x + 1, y, x, y) || this._jump(x - 1, y, x, y)) { 45908 return [x, y]; 45909 } 45910 } 45911 else { 45912 throw new Error("Only horizontal and vertical movements are allowed"); 45913 } 45914 45915 return this._jump(x + dx, y + dy, x, y); 45916}; 45917 45918/** 45919 * Find the neighbors for the given node. If the node has a parent, 45920 * prune the neighbors based on the jump point search algorithm, otherwise 45921 * return all available neighbors. 45922 * @return {Array<Array<number>>} The neighbors found. 45923 */ 45924JPFNeverMoveDiagonally.prototype._findNeighbors = function(node) { 45925 var parent = node.parent, 45926 x = node.x, y = node.y, 45927 grid = this.grid, 45928 px, py, nx, ny, dx, dy, 45929 neighbors = [], neighborNodes, neighborNode, i, l; 45930 45931 // directed pruning: can ignore most neighbors, unless forced. 45932 if (parent) { 45933 px = parent.x; 45934 py = parent.y; 45935 // get the normalized direction of travel 45936 dx = (x - px) / Math.max(Math.abs(x - px), 1); 45937 dy = (y - py) / Math.max(Math.abs(y - py), 1); 45938 45939 if (dx !== 0) { 45940 if (grid.isWalkableAt(x, y - 1)) { 45941 neighbors.push([x, y - 1]); 45942 } 45943 if (grid.isWalkableAt(x, y + 1)) { 45944 neighbors.push([x, y + 1]); 45945 } 45946 if (grid.isWalkableAt(x + dx, y)) { 45947 neighbors.push([x + dx, y]); 45948 } 45949 } 45950 else if (dy !== 0) { 45951 if (grid.isWalkableAt(x - 1, y)) { 45952 neighbors.push([x - 1, y]); 45953 } 45954 if (grid.isWalkableAt(x + 1, y)) { 45955 neighbors.push([x + 1, y]); 45956 } 45957 if (grid.isWalkableAt(x, y + dy)) {
45958 neighbors.push([x, y + dy]); 45959 } 45960 } 45961 } 45962 // return all neighbors 45963 else { 45964 neighborNodes = grid.getNeighbors(node, DiagonalMovement.Never); 45965 for (i = 0, l = neighborNodes.length; i < l; ++i) { 45966 neighborNode = neighborNodes[i]; 45967 neighbors.push([neighborNode.x, neighborNode.y]); 45968 } 45969 } 45970 45971 return neighbors; 45972}; 45973 45974module.exports = JPFNeverMoveDiagonally; 45975 45976},{"../core/DiagonalMovement":181,"./JumpPointFinderBase":200}],199:[function(require,module,exports){ 45977/** 45978 * @author aniero / https://github.com/aniero 45979 */ 45980var DiagonalMovement = require('../core/DiagonalMovement'); 45981var JPFNeverMoveDiagonally = require('./JPFNeverMoveDiagonally'); 45982var JPFAlwaysMoveDiagonally = require('./JPFAlwaysMoveDiagonally'); 45983var JPFMoveDiagonallyIfNoObstacles = require('./JPFMoveDiagonallyIfNoObstacles'); 45984var JPFMoveDiagonallyIfAtMostOneObstacle = require('./JPFMoveDiagonallyIfAtMostOneObstacle'); 45985 45986/** 45987 * Path finder using the Jump Point Search algorithm 45988 * @param {Object} opt 45989 * @param {function} opt.heuristic Heuristic function to estimate the distance 45990 * (defaults to manhattan). 45991 * @param {DiagonalMovement} opt.diagonalMovement Condition under which diagonal 45992 * movement will be allowed. 45993 */ 45994function JumpPointFinder(opt) { 45995 opt = opt || {}; 45996 if (opt.diagonalMovement === DiagonalMovement.Never) { 45997 return new JPFNeverMoveDiagonally(opt); 45998 } else if (opt.diagonalMovement === DiagonalMovement.Always) { 45999 return new JPFAlwaysMoveDiagonally(opt); 46000 } else if (opt.diagonalMovement === DiagonalMovement.OnlyWhenNoObstacles) { 46001 return new JPFMoveDiagonallyIfNoObstacles(opt); 46002 } else { 46003 return new JPFMoveDiagonallyIfAtMostOneObstacle(opt); 46004 } 46005} 46006 46007module.exports = JumpPointFinder; 46008 46009},{"../core/DiagonalMovement":181,"./JPFAlwaysMoveDiagonally":195,"./JPFMoveDiagonallyIfAtMostOneObstacle":196,"./JPFMoveDiagonallyIfNoObstacles":197,"./JPFNeverMoveDiagonally":198}],200:[function(require,module,exports){ 46010/** 46011 * @author imor / https://github.com/imor 46012 */ 46013var Heap = require('heap'); 46014var Util = require('../core/Util'); 46015var Heuristic = require('../core/Heuristic'); 46016var DiagonalMovement = require('../core/DiagonalMovement'); 46017 46018/** 46019 * Base class for the Jump Point Search algorithm 46020 * @param {object} opt 46021 * @param {function} opt.heuristic Heuristic function to estimate the distance 46022 * (defaults to manhattan). 46023 */ 46024function JumpPointFinderBase(opt) { 46025 opt = opt || {}; 46026 this.heuristic = opt.heuristic || Heuristic.manhattan; 46027 this.trackJumpRecursion = opt.trackJumpRecursion || false; 46028} 46029 46030/** 46031 * Find and return the path. 46032 * @return {Array<Array<number>>} The path, including both start and 46033 * end positions. 46034 */ 46035JumpPointFinderBase.prototype.findPath = function(startX, startY, endX, endY, grid) { 46036 var openList = this.openList = new Heap(function(nodeA, nodeB) { 46037 return nodeA.f - nodeB.f; 46038 }), 46039 startNode = this.startNode = grid.getNodeAt(startX, startY), 46040 endNode = this.endNode = grid.getNodeAt(endX, endY), node; 46041 46042 this.grid = grid; 46043 46044 46045 // set the `g` and `f` value of the start node to be 0 46046 startNode.g = 0; 46047 startNode.f = 0; 46048 46049 // push the start node into the open list 46050 openList.push(startNode); 46051 startNode.opened = true; 46052 46053 // while the open list is not empty 46054 while (!openList.empty()) { 46055 // pop the position of node which has the minimum `f` value. 46056 node = openList.pop(); 46057 node.closed = true; 46058 46059 if (node === endNode) { 46060 return Util.expandPath(Util.backtrace(endNode)); 46061 } 46062 46063 this._identifySuccessors(node); 46064 } 46065 46066 // fail to find the path 46067 return []; 46068}; 46069 46070/** 46071 * Identify successors for the given node. Runs a jump point search in the 46072 * direction of each available neighbor, adding any points found to the open 46073 * list. 46074 * @protected 46075 */ 46076JumpPointFinderBase.prototype._identifySuccessors = function(node) { 46077 var grid = this.grid, 46078 heuristic = this.heuristic, 46079 openList = this.openList, 46080 endX = this.endNode.x, 46081 endY = this.endNode.y, 46082 neighbors, neighbor, 46083 jumpPoint, i, l, 46084 x = node.x, y = node.y, 46085 jx, jy, dx, dy, d, ng, jumpNode,
46086 abs = Math.abs, max = Math.max; 46087 46088 neighbors = this._findNeighbors(node); 46089 for(i = 0, l = neighbors.length; i < l; ++i) { 46090 neighbor = neighbors[i]; 46091 jumpPoint = this._jump(neighbor[0], neighbor[1], x, y); 46092 if (jumpPoint) { 46093 46094 jx = jumpPoint[0]; 46095 jy = jumpPoint[1]; 46096 jumpNode = grid.getNodeAt(jx, jy); 46097 46098 if (jumpNode.closed) { 46099 continue; 46100 } 46101 46102 // include distance, as parent may not be immediately adjacent: 46103 d = Heuristic.octile(abs(jx - x), abs(jy - y)); 46104 ng = node.g + d; // next `g` value 46105 46106 if (!jumpNode.opened || ng < jumpNode.g) { 46107 jumpNode.g = ng; 46108 jumpNode.h = jumpNode.h || heuristic(abs(jx - endX), abs(jy - endY)); 46109 jumpNode.f = jumpNode.g + jumpNode.h; 46110 jumpNode.parent = node; 46111 46112 if (!jumpNode.opened) { 46113 openList.push(jumpNode); 46114 jumpNode.opened = true; 46115 } else { 46116 openList.updateItem(jumpNode); 46117 } 46118 } 46119 } 46120 } 46121}; 46122 46123module.exports = JumpPointFinderBase; 46124 46125},{"../core/DiagonalMovement":181,"../core/Heuristic":183,"../core/Util":185,"heap":159}],201:[function(require,module,exports){ 46126(function (process){ 46127module.exports = PeerStar 46128 46129const SimplePeer = require('simple-peer') 46130const signalhub = require('signalhub') 46131const inherits = require('inherits') 46132const events = require('events') 46133const through = require('through2') 46134const once = require('once') 46135const cuid = require('cuid') 46136const debug = require('debug')('peer-star') 46137const MAIN = 'MAIN' 46138const ALL = 'ALL' 46139 46140function PeerStar (opts) { 46141 if (!(this instanceof PeerStar)) return new PeerStar(opts) 46142 if (!opts) { 46143 throw new Error('Please pass an opts object with GID and hubURL!') 46144 } 46145 if (!opts.GID) { 46146 throw new Error('group ID required!') 46147 } 46148 if (!opts.hubURL) { 46149 throw new Error('hubURL required!') 46150 } 46151 46152 var hubURL 46153 46154 var self = this 46155 self.wrap = opts.wrap || function (data) { return data } 46156 self.unwrap = opts.unwrap || function (data) { return data } 46157 self.hub = null 46158 self.wrtc = opts.wrtc 46159 self.channelConfig = opts.channelConfig 46160 self.config = opts.config 46161 self.stream = opts.stream 46162 self.offerConstraints = opts.offerConstraints || {} 46163 self.maxPeers = opts.maxPeers || Infinity 46164 self.closed = false 46165 self.contacts = {} 46166 self.peers = [] 46167 self.CID = opts.CID 46168 self.GID = opts.GID 46169 46170 hubURL = opts.hubURL 46171 if (opts.isMain) { 46172 self.CID = MAIN 46173 } 46174 if (!self.CID || (self.CID === MAIN && !opts.isMain)) { 46175 self.CID = cuid() 46176 } 46177 46178 function startUp () { 46179 self.hub = signalhub(self.GID, hubURL) 46180 self.hub.subscribe(ALL).pipe(through.obj(function (data, enc, cb) { 46181 data = self.unwrap(data, ALL) 46182 if (self.closed || !data) return cb() 46183 46184 if (data.from === self.CID) { 46185 debug('skipping self', data.from) 46186 return cb() 46187 } 46188 46189 if (!self.contacts[data.from] && data.type === 'connect' && data.from === MAIN) { 46190 debug('connecting to MAIN (as initiator)', data.from) 46191 var peer = new SimplePeer({ 46192 wrtc: self.wrtc, 46193 initiator: true, 46194 channelConfig: self.channelConfig, 46195 config: self.config, 46196 stream: self.stream, 46197 offerConstraints: self.offerConstraints 46198 }) 46199 46200 setup(self, peer, MAIN) 46201 self.contacts[data.from] = peer 46202 } 46203 46204 cb() 46205 })) 46206 self.hub.subscribe(self.CID).once('open', connect.bind(null, self)).pipe(through.obj(function (data, enc, cb) { 46207 data = self.unwrap(data, self.CID) 46208 if (self.closed || !data) return cb() 46209 46210 var peer = self.contacts[data.from] 46211 if (!peer) { 46212 if (!data.signal || data.signal.type !== 'offer') { 46213 debug('skipping non-offer', self.CID) 46214 return cb() 46215 } 46216 46217 debug('connecting to new peer: ' + data.from, self.CID) 46218 peer = self.contacts[data.from] = new SimplePeer({ 46219 wrtc: self.wrtc, 46220 channelConfig: self.channelConfig, 46221 config: self.config, 46222 stream: self.stream, 46223 offerConstraints: self.offerConstraints 46224 }) 46225 46226 setup(self, peer, data.from) 46227 } 46228 46229 debug('signalling to ' + data.from + ': ', data.signal, self.CID)
46230 peer.signal(data.signal) 46231 cb() 46232 })) 46233 } 46234 46235 function setup (star, peer, id) { 46236 peer.on('connect', function () { 46237 debug('connected to peer ' + id) 46238 star.peers.push(peer) 46239 star.emit('peer', peer, id) 46240 star.emit('connect', peer, id) 46241 }) 46242 46243 var onclose = once(function (err) { 46244 debug('disconnected from peer: ' + id + (err ? ', ' + err : '')) 46245 if (star.contacts[id] === peer) delete star.contacts[id] 46246 var i = star.peers.indexOf(peer) 46247 if (i > -1) star.peers.splice(i, 1) 46248 star.emit('disconnect', peer, id) 46249 }) 46250 46251 var signals = [] 46252 var sending = false 46253 46254 function kick () { 46255 if (star.closed || sending || !signals.length) return 46256 sending = true 46257 var data = {from: star.CID, signal: signals.shift()} 46258 data = star.wrap(data, id) 46259 debug('returndata: ', data, id) 46260 star.hub.broadcast(id, data, function () { 46261 sending = false 46262 kick() 46263 }) 46264 } 46265 46266 peer.on('signal', function (sig) { 46267 debug('signal incoming: ', id, sig) 46268 signals.push(sig) 46269 kick() 46270 }) 46271 46272 peer.on('error', onclose) 46273 peer.once('close', onclose) 46274 } 46275 46276 function connect (star) { 46277 if (star.closed || !opts.isMain) return 46278 var data = {type: 'connect', from: self.CID} 46279 data = star.wrap(data, ALL) 46280 star.hub.broadcast(ALL, data, function () { 46281 setTimeout(connect.bind(null, star), Math.floor(Math.random() * 2000) + 6000) 46282 }) 46283 } 46284 46285 startUp() 46286 46287 return self 46288} 46289 46290inherits(PeerStar, events.EventEmitter) 46291 46292PeerStar.WEBRTC_SUPPORT = SimplePeer.WEBRTC_SUPPORT 46293 46294PeerStar.prototype.close = function (cb) { 46295 if (this.closed) return 46296 this.closed = true 46297 46298 if (cb) this.once('close', cb) 46299 46300 var self = this 46301 this.hub.close(function () { 46302 var len = self.peers.length 46303 if (len > 0) { 46304 var closed = 0 46305 self.peers.forEach(function (peer) { 46306 peer.once('close', function () { 46307 if (++closed === len) { 46308 self.emit('close') 46309 } 46310 }) 46311 process.nextTick(function () { 46312 peer.destroy() 46313 }) 46314 }) 46315 } else { 46316 self.emit('close') 46317 } 46318 }) 46319} 46320 46321}).call(this,require('_process')) 46322},{"_process":84,"cuid":95,"debug":97,"events":154,"inherits":165,"once":177,"signalhub":229,"simple-peer":236,"through2":239}],202:[function(require,module,exports){ 46323(function (process){ 46324// Generated by CoffeeScript 1.7.1 46325(function() { 46326 var getNanoSeconds, hrtime, loadTime; 46327 46328 if ((typeof performance !== "undefined" && performance !== null) && performance.now) { 46329 module.exports = function() { 46330 return performance.now(); 46331 }; 46332 } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { 46333 module.exports = function() { 46334 return (getNanoSeconds() - loadTime) / 1e6; 46335 }; 46336 hrtime = process.hrtime; 46337 getNanoSeconds = function() { 46338 var hr; 46339 hr = hrtime(); 46340 return hr[0] * 1e9 + hr[1]; 46341 }; 46342 loadTime = getNanoSeconds(); 46343 } else if (Date.now) { 46344 module.exports = function() { 46345 return Date.now() - loadTime; 46346 }; 46347 loadTime = Date.now(); 46348 } else { 46349 module.exports = function() { 46350 return new Date().getTime() - loadTime; 46351 }; 46352 loadTime = new Date().getTime(); 46353 } 46354 46355}).call(this); 46356 46357}).call(this,require('_process')) 46358},{"_process":84}],203:[function(require,module,exports){ 46359(function (process){ 46360'use strict'; 46361 46362if (!process.version || 46363 process.version.indexOf('v0.') === 0 || 46364 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { 46365 module.exports = nextTick; 46366} else { 46367 module.exports = process.nextTick; 46368} 46369 46370function nextTick(fn, arg1, arg2, arg3) { 46371 if (typeof fn !== 'function') { 46372 throw new TypeError('"callback" argument must be a function'); 46373 } 46374 var len = arguments.length; 46375 var args, i; 46376 switch (len) { 46377 case 0: 46378 case 1: 46379 return process.nextTick(fn); 46380 case 2: 46381 return process.nextTick(function afterTickOne() { 46382 fn.call(null, arg1); 46383 }); 46384 case 3: 46385 return process.nextTick(function afterTickTwo() { 46386 fn.call(null, arg1, arg2); 46387 }); 46388 case 4: 46389 return process.nextTick(function afterTickThree() { 46390 fn.call(null, arg1, arg2, arg3); 46391 }); 46392 default: 46393 args = new Array(len - 1); 46394 i = 0; 46395 while (i < args.length) { 46396 args[i++] = arguments[i]; 46397 } 46398 return process.nextTick(function afterTick() {
46399 fn.apply(null, args); 46400 }); 46401 } 46402} 46403 46404}).call(this,require('_process')) 46405},{"_process":84}],204:[function(require,module,exports){ 46406var once = require('once') 46407var eos = require('end-of-stream') 46408var fs = require('fs') // we only need fs to get the ReadStream and WriteStream prototypes 46409 46410var noop = function () {} 46411 46412var isFn = function (fn) { 46413 return typeof fn === 'function' 46414} 46415 46416var isFS = function (stream) { 46417 if (!fs) return false // browser 46418 return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) 46419} 46420 46421var isRequest = function (stream) { 46422 return stream.setHeader && isFn(stream.abort) 46423} 46424 46425var destroyer = function (stream, reading, writing, callback) { 46426 callback = once(callback) 46427 46428 var closed = false 46429 stream.on('close', function () { 46430 closed = true 46431 }) 46432 46433 eos(stream, {readable: reading, writable: writing}, function (err) { 46434 if (err) return callback(err) 46435 closed = true 46436 callback() 46437 }) 46438 46439 var destroyed = false 46440 return function (err) { 46441 if (closed) return 46442 if (destroyed) return 46443 destroyed = true 46444 46445 if (isFS(stream)) return stream.close(noop) // use close for fs streams to avoid fd leaks 46446 if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want 46447 46448 if (isFn(stream.destroy)) return stream.destroy() 46449 46450 callback(err || new Error('stream was destroyed')) 46451 } 46452} 46453 46454var call = function (fn) { 46455 fn() 46456} 46457 46458var pipe = function (from, to) { 46459 return from.pipe(to) 46460} 46461 46462var pump = function () { 46463 var streams = Array.prototype.slice.call(arguments) 46464 var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop 46465 46466 if (Array.isArray(streams[0])) streams = streams[0] 46467 if (streams.length < 2) throw new Error('pump requires two streams per minimum') 46468 46469 var error 46470 var destroys = streams.map(function (stream, i) { 46471 var reading = i < streams.length - 1 46472 var writing = i > 0 46473 return destroyer(stream, reading, writing, function (err) { 46474 if (!error) error = err 46475 if (err) destroys.forEach(call) 46476 if (reading) return 46477 destroys.forEach(call) 46478 callback(error) 46479 }) 46480 }) 46481 46482 return streams.reduce(pipe) 46483} 46484 46485module.exports = pump 46486 46487},{"end-of-stream":99,"fs":83,"once":177}],205:[function(require,module,exports){ 46488(function (global){ 46489var now = require('performance-now') 46490 , root = typeof window === 'undefined' ? global : window 46491 , vendors = ['moz', 'webkit'] 46492 , suffix = 'AnimationFrame' 46493 , raf = root['request' + suffix] 46494 , caf = root['cancel' + suffix] || root['cancelRequest' + suffix] 46495 46496for(var i = 0; !raf && i < vendors.length; i++) { 46497 raf = root[vendors[i] + 'Request' + suffix] 46498 caf = root[vendors[i] + 'Cancel' + suffix] 46499 || root[vendors[i] + 'CancelRequest' + suffix] 46500} 46501 46502// Some versions of FF have rAF but not cAF 46503if(!raf || !caf) { 46504 var last = 0 46505 , id = 0 46506 , queue = [] 46507 , frameDuration = 1000 / 60 46508 46509 raf = function(callback) { 46510 if(queue.length === 0) { 46511 var _now = now() 46512 , next = Math.max(0, frameDuration - (_now - last)) 46513 last = next + _now 46514 setTimeout(function() { 46515 var cp = queue.slice(0) 46516 // Clear queue here to prevent 46517 // callbacks from appending listeners 46518 // to the current frame's queue 46519 queue.length = 0 46520 for(var i = 0; i < cp.length; i++) { 46521 if(!cp[i].cancelled) { 46522 try{ 46523 cp[i].callback(last) 46524 } catch(e) { 46525 setTimeout(function() { throw e }, 0) 46526 } 46527 } 46528 } 46529 }, Math.round(next)) 46530 } 46531 queue.push({ 46532 handle: ++id, 46533 callback: callback, 46534 cancelled: false 46535 }) 46536 return id 46537 } 46538 46539 caf = function(handle) { 46540 for(var i = 0; i < queue.length; i++) { 46541 if(queue[i].handle === handle) { 46542 queue[i].cancelled = true 46543 } 46544 } 46545 } 46546} 46547 46548module.exports = function(fn) { 46549 // Wrap in a new function to prevent 46550 // `cancel` potentially being assigned 46551 // to the native rAF function 46552 return raf.call(root, fn) 46553} 46554module.exports.cancel = function() { 46555 caf.apply(root, arguments) 46556} 46557module.exports.polyfill = function() { 46558 root.requestAnimationFrame = raf 46559 root.cancelAnimationFrame = caf 46560} 46561 46562}
46562).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 46563},{"performance-now":202}],206:[function(require,module,exports){ 46564(function (process,global){ 46565'use strict' 46566 46567function oldBrowser () { 46568 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') 46569} 46570 46571var Buffer = require('safe-buffer').Buffer 46572var crypto = global.crypto || global.msCrypto 46573 46574if (crypto && crypto.getRandomValues) { 46575 module.exports = randomBytes 46576} else { 46577 module.exports = oldBrowser 46578} 46579 46580function randomBytes (size, cb) { 46581 // phantomjs needs to throw 46582 if (size > 65536) throw new Error('requested too many random bytes') 46583 // in case browserify isn't using the Uint8Array version 46584 var rawBytes = new global.Uint8Array(size) 46585 46586 // This will not work in older browsers. 46587 // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues 46588 if (size > 0) { // getRandomValues fails on IE if size == 0 46589 crypto.getRandomValues(rawBytes) 46590 } 46591 46592 // XXX: phantomjs doesn't like a buffer being passed here 46593 var bytes = Buffer.from(rawBytes.buffer) 46594 46595 if (typeof cb === 'function') { 46596 return process.nextTick(function () { 46597 cb(null, bytes) 46598 }) 46599 } 46600 46601 return bytes 46602} 46603 46604}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 46605},{"_process":84,"safe-buffer":219}],207:[function(require,module,exports){ 46606module.exports = require("./lib/_stream_duplex.js") 46607 46608},{"./lib/_stream_duplex.js":208}],208:[function(require,module,exports){ 46609// a duplex stream is just a stream that is both readable and writable. 46610// Since JS doesn't have multiple prototypal inheritance, this class 46611// prototypally inherits from Readable, and then parasitically from 46612// Writable. 46613 46614'use strict'; 46615 46616/*<replacement>*/ 46617 46618var objectKeys = Object.keys || function (obj) { 46619 var keys = []; 46620 for (var key in obj) { 46621 keys.push(key); 46622 }return keys; 46623}; 46624/*</replacement>*/ 46625 46626module.exports = Duplex; 46627 46628/*<replacement>*/ 46629var processNextTick = require('process-nextick-args'); 46630/*</replacement>*/ 46631 46632/*<replacement>*/ 46633var util = require('core-util-is'); 46634util.inherits = require('inherits'); 46635/*</replacement>*/ 46636 46637var Readable = require('./_stream_readable'); 46638var Writable = require('./_stream_writable'); 46639 46640util.inherits(Duplex, Readable); 46641 46642var keys = objectKeys(Writable.prototype); 46643for (var v = 0; v < keys.length; v++) { 46644 var method = keys[v]; 46645 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; 46646} 46647 46648function Duplex(options) { 46649 if (!(this instanceof Duplex)) return new Duplex(options); 46650 46651 Readable.call(this, options); 46652 Writable.call(this, options); 46653 46654 if (options && options.readable === false) this.readable = false; 46655 46656 if (options && options.writable === false) this.writable = false; 46657 46658 this.allowHalfOpen = true; 46659 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; 46660 46661 this.once('end', onend); 46662} 46663 46664// the no-half-open enforcer 46665function onend() { 46666 // if we allow half-open state, or if the writable side ended, 46667 // then we're ok. 46668 if (this.allowHalfOpen || this._writableState.ended) return; 46669 46670 // no more data can be written. 46671 // But allow more writes to happen in this tick. 46672 processNextTick(onEndNT, this); 46673} 46674 46675function onEndNT(self) { 46676 self.end(); 46677} 46678 46679function forEach(xs, f) { 46680 for (var i = 0, l = xs.length; i < l; i++) { 46681 f(xs[i], i); 46682 } 46683} 46684},{"./_stream_readable":210,"./_stream_writable":212,"core-util-is":94,"inherits":165,"process-nextick-args":203}],209:[function(require,module,exports){ 46685// a passthrough stream. 46686// basically just the most minimal sort of Transform stream. 46687// Every written chunk gets output as-is. 46688 46689'use strict'; 46690 46691module.exports = PassThrough; 46692 46693var Transform = require('./_stream_transform'); 46694 46695/*<replacement>*/ 46696var util = require('core-util-is'); 46697util.inherits = require('inherits'); 46698/*</replacement>*/ 46699 46700util.inherits(PassThrough, Transform); 46701 46702function PassThrough(options) { 46703 if (!(this instanceof PassThrough)) return new PassThrough(options); 46704 46705 Transform.call(this, options); 46706} 46707 46708PassThrough.prototype._transform = function (chunk, encoding, cb) { 46709 cb(null, chunk); 46710}; 46711},{"./_stream_transform":211,"core-util-is":94,"inherits":165}],210
vendor: 28,373 bytes, lines 46711-47655
46711:[function(require,module,exports){ 46712(function (process){ 46713'use strict'; 46714 46715module.exports = Readable; 46716 46717/*<replacement>*/ 46718var processNextTick = require('process-nextick-args'); 46719/*</replacement>*/ 46720 46721/*<replacement>*/ 46722var isArray = require('isarray'); 46723/*</replacement>*/ 46724 46725/*<replacement>*/ 46726var Duplex; 46727/*</replacement>*/ 46728 46729Readable.ReadableState = ReadableState; 46730 46731/*<replacement>*/ 46732var EE = require('events').EventEmitter; 46733 46734var EElistenerCount = function (emitter, type) { 46735 return emitter.listeners(type).length; 46736}; 46737/*</replacement>*/ 46738 46739/*<replacement>*/ 46740var Stream; 46741(function () { 46742 try { 46743 Stream = require('st' + 'ream'); 46744 } catch (_) {} finally { 46745 if (!Stream) Stream = require('events').EventEmitter; 46746 } 46747})(); 46748/*</replacement>*/ 46749 46750var Buffer = require('buffer').Buffer; 46751/*<replacement>*/ 46752var bufferShim = require('buffer-shims'); 46753/*</replacement>*/ 46754 46755/*<replacement>*/ 46756var util = require('core-util-is'); 46757util.inherits = require('inherits'); 46758/*</replacement>*/ 46759 46760/*<replacement>*/ 46761var debugUtil = require('util'); 46762var debug = void 0; 46763if (debugUtil && debugUtil.debuglog) { 46764 debug = debugUtil.debuglog('stream'); 46765} else { 46766 debug = function () {}; 46767} 46768/*</replacement>*/ 46769 46770var BufferList = require('./internal/streams/BufferList'); 46771var StringDecoder; 46772 46773util.inherits(Readable, Stream); 46774 46775function prependListener(emitter, event, fn) { 46776 // Sadly this is not cacheable as some libraries bundle their own 46777 // event emitter implementation with them. 46778 if (typeof emitter.prependListener === 'function') { 46779 return emitter.prependListener(event, fn); 46780 } else { 46781 // This is a hack to make sure that our error handler is attached before any 46782 // userland ones. NEVER DO THIS. This is here only because this code needs 46783 // to continue to work with older versions of Node.js that do not include 46784 // the prependListener() method. The goal is to eventually remove this hack. 46785 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; 46786 } 46787} 46788 46789function ReadableState(options, stream) { 46790 Duplex = Duplex || require('./_stream_duplex'); 46791 46792 options = options || {}; 46793 46794 // object stream flag. Used to make read(n) ignore n and to 46795 // make all the buffer merging and length checks go away 46796 this.objectMode = !!options.objectMode; 46797 46798 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; 46799 46800 // the point at which it stops calling _read() to fill the buffer 46801 // Note: 0 is a valid value, means "don't call _read preemptively ever" 46802 var hwm = options.highWaterMark; 46803 var defaultHwm = this.objectMode ? 16 : 16 * 1024; 46804 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; 46805 46806 // cast to ints. 46807 this.highWaterMark = ~~this.highWaterMark; 46808 46809 // A linked list is used to store data chunks instead of an array because the 46810 // linked list can remove elements from the beginning faster than 46811 // array.shift() 46812 this.buffer = new BufferList(); 46813 this.length = 0; 46814 this.pipes = null; 46815 this.pipesCount = 0; 46816 this.flowing = null; 46817 this.ended = false; 46818 this.endEmitted = false; 46819 this.reading = false; 46820 46821 // a flag to be able to tell if the onwrite cb is called immediately, 46822 // or on a later tick. We set this to true at first, because any 46823 // actions that shouldn't happen until "later" should generally also 46824 // not happen before the first write call. 46825 this.sync = true; 46826 46827 // whenever we return null, then we set a flag to say 46828 // that we're awaiting a 'readable' event emission. 46829 this.needReadable = false; 46830 this.emittedReadable = false; 46831 this.readableListening = false; 46832 this.resumeScheduled = false; 46833 46834 // Crypto is kind of old and crusty. Historically, its default string 46835 // encoding is 'binary' so we have to make this configurable. 46836 // Everything else in the universe uses 'utf8', though. 46837 this.defaultEncoding = options.defaultEncoding || 'utf8'; 46838 46839 // when piping, we only care about 'readable' events that happen 46840 // after read()ing all the bytes and not getting any pushback. 46841 this.ranOut = false; 46842 46843 // the number of writers that are awaiting a drain event in .pipe()s 46844 this.awaitDrain = 0; 46845 46846 // if true, a maybeReadMore has been scheduled 46847 this.readingMore = false; 46848 46849 this.decoder = null; 46850 this.encoding = null; 46851 if (options.encoding) { 46852 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; 46853 this.decoder = new StringDecoder(options.encoding); 46854 this.encoding = options.encoding; 46855 } 46856} 46857 46858function Readable(options) { 46859 Duplex = Duplex || require('./_stream_duplex'); 46860 46861 if (!(this instanceof Readable)) return new Readable(options); 46862 46863 this._readableState = new ReadableState(options, this); 46864 46865 // legacy 46866 this.readable = true; 46867 46868 if (options && typeof options.read === 'function') this._read = options.read; 46869 46870 Stream.call(this); 46871} 46872 46873// Manually shove something into the read() buffer. 46874// This returns true if the highWaterMark has not been hit yet, 46875// similar to how Writable.write() returns true if you should 46876// write() some more. 46877Readable.prototype.push = function (chunk, encoding) { 46878 var state = this._readableState; 46879 46880 if (!state.objectMode && typeof chunk === 'string') { 46881 encoding = encoding || state.defaultEncoding; 46882 if (encoding !== state.encoding) { 46883 chunk = bufferShim.from(chunk, encoding); 46884 encoding = ''; 46885 } 46886 } 46887 46888 return readableAddChunk(this, state, chunk, encoding, false); 46889}; 46890 46891// Unshift should *always* be something directly out of read() 46892Readable.prototype.unshift = function (chunk) { 46893 var state = this._readableState; 46894 return readableAddChunk(this, state, chunk, '', true); 46895}; 46896 46897Readable.prototype.isPaused = function () { 46898 return this._readableState.flowing === false; 46899}; 46900 46901function readableAddChunk(stream, state, chunk, encoding, addToFront) { 46902 var er = chunkInvalid(state, chunk); 46903 if (er) { 46904 stream.emit('error', er); 46905 } else if (chunk === null) { 46906 state.reading = false; 46907 onEofChunk(stream, state); 46908 } else if (state.objectMode || chunk && chunk.length > 0) { 46909 if (state.ended && !addToFront) { 46910 var e = new Error('stream.push() after EOF'); 46911 stream.emit('error', e); 46912 } else if (state.endEmitted && addToFront) { 46913 var _e = new Error('stream.unshift() after end event'); 46914 stream.emit('error', _e); 46915 } else { 46916 var skipAdd; 46917 if (state.decoder && !addToFront && !encoding) { 46918 chunk = state.decoder.write(chunk); 46919 skipAdd = !state.objectMode && chunk.length === 0; 46920 } 46921 46922 if (!addToFront) state.reading = false; 46923 46924 // Don't add to the buffer if we've decoded to an empty string chunk and 46925 // we're not in object mode 46926 if (!skipAdd) { 46927 // if we want the data now, just emit it. 46928 if (state.flowing && state.length === 0 && !state.sync) { 46929 stream.emit('data', chunk); 46930 stream.read(0); 46931 } else { 46932 // update the buffer info. 46933 state.length += state.objectMode ? 1 : chunk.length; 46934 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); 46935 46936 if (state.needReadable) emitReadable(stream); 46937 } 46938 } 46939 46940 maybeReadMore(stream, state); 46941 } 46942 } else if (!addToFront) { 46943 state.reading = false; 46944 } 46945 46946 return needMoreData(state); 46947} 46948 46949// if it's past the high water mark, we can push in some more. 46950// Also, if we have no data yet, we can stand some 46951// more bytes. This is to work around cases where hwm=0, 46952// such as the repl. Also, if the push() triggered a 46953// readable event, and the user called read(largeNumber) such that 46954// needReadable was set, then we ought to push more, so that another 46955// 'readable' event will be triggered. 46956function needMoreData(state) { 46957 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); 46958} 46959 46960// backwards compatibility. 46961Readable.prototype.setEncoding = function (enc) { 46962 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; 46963 this._readableState.decoder = new StringDecoder(enc); 46964 this._readableState.encoding = enc; 46965 return this; 46966}; 46967 46968// Don't raise the hwm > 8MB 46969var MAX_HWM = 0x800000; 46970function computeNewHighWaterMark(n) { 46971 if (n >= MAX_HWM) { 46972 n = MAX_HWM; 46973 } else { 46974 // Get the next highest power of 2 to prevent increasing hwm excessively in 46975 // tiny amounts 46976 n--; 46977 n |= n >>> 1; 46978 n |= n >>> 2; 46979 n |= n >>> 4; 46980 n |= n >>> 8; 46981 n |= n >>> 16; 46982 n++; 46983 } 46984 return n; 46985} 46986 46987// This function is designed to be inlinable, so please take care when making 46988// changes to the function body. 46989function howMuchToRead(n, state) { 46990 if (n <= 0 || state.length === 0 && state.ended) return 0; 46991 if (state.objectMode) return 1; 46992 if (n !== n) { 46993 // Only flow one buffer at a time 46994 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; 46995 } 46996 // If we're asking for more than the current hwm, then raise the hwm. 46997 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); 46998 if (n <= state.length) return n; 46999 // Don't have enough 47000 if (!state.ended) { 47001 state.needReadable = true; 47002 return 0; 47003 } 47004 return state.length; 47005} 47006 47007// you can override either this method, or the async _read(n) below. 47008Readable.prototype.read = function (n) { 47009 debug('read', n); 47010 n = parseInt(n, 10); 47011 var state = this._readableState; 47012 var nOrig = n; 47013 47014 if (n !== 0) state.emittedReadable = false; 47015 47016 // if we're doing read(0) to trigger a readable event, but we 47017 // already have a bunch of data in the buffer, then just trigger 47018 // the 'readable' event and move on. 47019 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { 47020 debug('read: emitReadable', state.length, state.ended); 47021 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); 47022 return null; 47023 } 47024 47025 n = howMuchToRead(n, state); 47026 47027 // if we've ended, and we're now clear, then finish it up. 47028 if (n === 0 && state.ended) { 47029 if (state.length === 0) endReadable(this); 47030 return null; 47031 } 47032 47033 // All the actual chunk generation logic needs to be 47034 // *below* the call to _read. The reason is that in certain 47035 // synthetic stream cases, such as passthrough streams, _read 47036 // may be a completely synchronous operation which may change 47037 // the state of the read buffer, providing enough data when 47038 // before there was *not* enough. 47039 // 47040 // So, the steps are: 47041 // 1. Figure out what the state of things will be after we do 47042 // a read from the buffer. 47043 // 47044 // 2. If that resulting state will trigger a _read, then call _read. 47045 // Note that this may be asynchronous, or synchronous. Yes, it is 47046 // deeply ugly to write APIs this way, but that still doesn't mean 47047 // that the Readable class should behave improperly, as streams are 47048 // designed to be sync/async agnostic. 47049 // Take note if the _read call is sync or async (ie, if the read call 47050 // has returned yet), so that we know whether or not it's safe to emit 47051 // 'readable' etc. 47052 // 47053 // 3. Actually pull the requested chunks out of the buffer and return. 47054 47055 // if we need a readable event, then we need to do some reading. 47056 var doRead = state.needReadable; 47057 debug('need readable', doRead); 47058 47059 // if we currently have less than the highWaterMark, then also read some 47060 if (state.length === 0 || state.length - n < state.highWaterMark) { 47061 doRead = true; 47062 debug('length less than watermark', doRead); 47063 } 47064 47065 // however, if we've ended, then there's no point, and if we're already 47066 // reading, then it's unnecessary. 47067 if (state.ended || state.reading) { 47068 doRead = false; 47069 debug('reading or ended', doRead); 47070 } else if (doRead) { 47071 debug('do read'); 47072 state.reading = true; 47073 state.sync = true; 47074 // if the length is currently zero, then we *need* a readable event. 47075 if (state.length === 0) state.needReadable = true; 47076 // call internal read method 47077 this._read(state.highWaterMark); 47078 state.sync = false; 47079 // If _read pushed data synchronously, then `reading` will be false, 47080 // and we need to re-evaluate how much data we can return to the user. 47081 if (!state.reading) n = howMuchToRead(nOrig, state); 47082 } 47083 47084 var ret; 47085 if (n > 0) ret = fromList(n, state);else ret = null; 47086 47087 if (ret === null) { 47088 state.needReadable = true; 47089 n = 0; 47090 } else { 47091 state.length -= n; 47092 } 47093 47094 if (state.length === 0) { 47095 // If we have nothing in the buffer, then we want to know 47096 // as soon as we *do* get something into the buffer. 47097 if (!state.ended) state.needReadable = true; 47098 47099 // If we tried to read() past the EOF, then emit end on the next tick. 47100 if (nOrig !== n && state.ended) endReadable(this); 47101 } 47102 47103 if (ret !== null) this.emit('data', ret); 47104 47105 return ret; 47106}; 47107 47108function chunkInvalid(state, chunk) { 47109 var er = null; 47110 if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { 47111 er = new TypeError('Invalid non-string/buffer chunk'); 47112 } 47113 return er; 47114} 47115 47116function onEofChunk(stream, state) { 47117 if (state.ended) return; 47118 if (state.decoder) { 47119 var chunk = state.decoder.end(); 47120 if (chunk && chunk.length) { 47121 state.buffer.push(chunk); 47122 state.length += state.objectMode ? 1 : chunk.length; 47123 } 47124 } 47125 state.ended = true; 47126 47127 // emit 'readable' now to make sure it gets picked up. 47128 emitReadable(stream); 47129} 47130 47131// Don't emit readable right away in sync mode, because this can trigger 47132// another read() call => stack overflow. This way, it might trigger 47133// a nextTick recursion warning, but that's not so bad. 47134function emitReadable(stream) { 47135 var state = stream._readableState; 47136 state.needReadable = false; 47137 if (!state.emittedReadable) { 47138 debug('emitReadable', state.flowing); 47139 state.emittedReadable = true; 47140 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); 47141 } 47142} 47143 47144function emitReadable_(stream) { 47145 debug('emit readable'); 47146 stream.emit('readable'); 47147 flow(stream); 47148} 47149 47150// at this point, the user has presumably seen the 'readable' event, 47151// and called read() to consume some data. that may have triggered 47152// in turn another _read(n) call, in which case reading = true if 47153// it's in progress. 47154// However, if we're not ended, or reading, and the length < hwm, 47155// then go ahead and try to read some more preemptively. 47156function maybeReadMore(stream, state) { 47157 if (!state.readingMore) { 47158 state.readingMore = true; 47159 processNextTick(maybeReadMore_, stream, state); 47160 } 47161} 47162 47163function maybeReadMore_(stream, state) { 47164 var len = state.length; 47165 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { 47166 debug('maybeReadMore read 0'); 47167 stream.read(0); 47168 if (len === state.length) 47169 // didn't get any data, stop spinning. 47170 break;else len = state.length; 47171 } 47172 state.readingMore = false; 47173} 47174 47175// abstract method. to be overridden in specific implementation classes. 47176// call cb(er, data) where data is <= n in length. 47177// for virtual (non-string, non-buffer) streams, "length" is somewhat 47178// arbitrary, and perhaps not very meaningful. 47179Readable.prototype._read = function (n) { 47180 this.emit('error', new Error('_read() is not implemented')); 47181}; 47182 47183Readable.prototype.pipe = function (dest, pipeOpts) { 47184 var src = this; 47185 var state = this._readableState; 47186 47187 switch (state.pipesCount) { 47188 case 0: 47189 state.pipes = dest; 47190 break; 47191 case 1: 47192 state.pipes = [state.pipes, dest]; 47193 break; 47194 default: 47195 state.pipes.push(dest); 47196 break; 47197 } 47198 state.pipesCount += 1; 47199 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); 47200 47201 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; 47202 47203 var endFn = doEnd ? onend : cleanup; 47204 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); 47205 47206 dest.on('unpipe', onunpipe); 47207 function onunpipe(readable) { 47208 debug('onunpipe'); 47209 if (readable === src) { 47210 cleanup(); 47211 } 47212 } 47213 47214 function onend() { 47215 debug('onend'); 47216 dest.end(); 47217 } 47218 47219 // when the dest drains, it reduces the awaitDrain counter 47220 // on the source. This would be more elegant with a .once() 47221 // handler in flow(), but adding and removing repeatedly is 47222 // too slow. 47223 var ondrain = pipeOnDrain(src); 47224 dest.on('drain', ondrain); 47225 47226 var cleanedUp = false; 47227 function cleanup() { 47228 debug('cleanup'); 47229 // cleanup event handlers once the pipe is broken 47230 dest.removeListener('close', onclose); 47231 dest.removeListener('finish', onfinish); 47232 dest.removeListener('drain', ondrain); 47233 dest.removeListener('error', onerror); 47234 dest.removeListener('unpipe', onunpipe); 47235 src.removeListener('end', onend); 47236 src.removeListener('end', cleanup); 47237 src.removeListener('data', ondata); 47238 47239 cleanedUp = true; 47240 47241 // if the reader is waiting for a drain event from this 47242 // specific writer, then it would cause it to never start 47243 // flowing again. 47244 // So, if this is awaiting a drain, then we just call it now. 47245 // If we don't know, then assume that we are waiting for one. 47246 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); 47247 } 47248 47249 // If the user pushes more data while we're writing to dest then we'll end up 47250 // in ondata again. However, we only want to increase awaitDrain once because 47251 // dest will only emit one 'drain' event for the multiple writes. 47252 // => Introduce a guard on increasing awaitDrain. 47253 var increasedAwaitDrain = false; 47254 src.on('data', ondata); 47255 function ondata(chunk) { 47256 debug('ondata'); 47257 increasedAwaitDrain = false; 47258 var ret = dest.write(chunk); 47259 if (false === ret && !increasedAwaitDrain) { 47260 // If the user unpiped during `dest.write()`, it is possible 47261 // to get stuck in a permanently paused state if that write 47262 // also returned false. 47263 // => Check whether `dest` is still a piping destination. 47264 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { 47265 debug('false write response, pause', src._readableState.awaitDrain); 47266 src._readableState.awaitDrain++; 47267 increasedAwaitDrain = true; 47268 } 47269 src.pause(); 47270 } 47271 } 47272 47273 // if the dest has an error, then stop piping into it. 47274 // however, don't suppress the throwing behavior for this. 47275 function onerror(er) { 47276 debug('onerror', er); 47277 unpipe(); 47278 dest.removeListener('error', onerror); 47279 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); 47280 } 47281 47282 // Make sure our error handler is attached before userland ones. 47283 prependListener(dest, 'error', onerror); 47284 47285 // Both close and finish should trigger unpipe, but only once. 47286 function onclose() { 47287 dest.removeListener('finish', onfinish); 47288 unpipe(); 47289 } 47290 dest.once('close', onclose); 47291 function onfinish() { 47292 debug('onfinish'); 47293 dest.removeListener('close', onclose); 47294 unpipe(); 47295 } 47296 dest.once('finish', onfinish); 47297 47298 function unpipe() { 47299 debug('unpipe'); 47300 src.unpipe(dest); 47301 } 47302 47303 // tell the dest that it's being piped to 47304 dest.emit('pipe', src); 47305 47306 // start the flow if it hasn't been started already. 47307 if (!state.flowing) { 47308 debug('pipe resume'); 47309 src.resume(); 47310 } 47311 47312 return dest; 47313}; 47314 47315function pipeOnDrain(src) { 47316 return function () { 47317 var state = src._readableState; 47318 debug('pipeOnDrain', state.awaitDrain); 47319 if (state.awaitDrain) state.awaitDrain--; 47320 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { 47321 state.flowing = true; 47322 flow(src); 47323 } 47324 }; 47325} 47326 47327Readable.prototype.unpipe = function (dest) { 47328 var state = this._readableState; 47329 47330 // if we're not piping anywhere, then do nothing. 47331 if (state.pipesCount === 0) return this; 47332 47333 // just one destination. most common case. 47334 if (state.pipesCount === 1) { 47335 // passed in one, but it's not the right one. 47336 if (dest && dest !== state.pipes) return this; 47337 47338 if (!dest) dest = state.pipes; 47339 47340 // got a match. 47341 state.pipes = null; 47342 state.pipesCount = 0; 47343 state.flowing = false; 47344 if (dest) dest.emit('unpipe', this); 47345 return this; 47346 } 47347 47348 // slow case. multiple pipe destinations. 47349 47350 if (!dest) { 47351 // remove all. 47352 var dests = state.pipes; 47353 var len = state.pipesCount; 47354 state.pipes = null; 47355 state.pipesCount = 0; 47356 state.flowing = false; 47357 47358 for (var i = 0; i < len; i++) { 47359 dests[i].emit('unpipe', this); 47360 }return this; 47361 } 47362 47363 // try to find the right one. 47364 var index = indexOf(state.pipes, dest); 47365 if (index === -1) return this; 47366 47367 state.pipes.splice(index, 1); 47368 state.pipesCount -= 1; 47369 if (state.pipesCount === 1) state.pipes = state.pipes[0]; 47370 47371 dest.emit('unpipe', this); 47372 47373 return this; 47374}; 47375 47376// set up data events if they are asked for 47377// Ensure readable listeners eventually get something 47378Readable.prototype.on = function (ev, fn) { 47379 var res = Stream.prototype.on.call(this, ev, fn); 47380 47381 if (ev === 'data') { 47382 // Start flowing on next tick if stream isn't explicitly paused 47383 if (this._readableState.flowing !== false) this.resume(); 47384 } else if (ev === 'readable') { 47385 var state = this._readableState; 47386 if (!state.endEmitted && !state.readableListening) { 47387 state.readableListening = state.needReadable = true; 47388 state.emittedReadable = false; 47389 if (!state.reading) { 47390 processNextTick(nReadingNextTick, this); 47391 } else if (state.length) { 47392 emitReadable(this, state); 47393 } 47394 } 47395 } 47396 47397 return res; 47398}; 47399Readable.prototype.addListener = Readable.prototype.on; 47400 47401function nReadingNextTick(self) { 47402 debug('readable nexttick read 0'); 47403 self.read(0); 47404} 47405 47406// pause() and resume() are remnants of the legacy readable stream API 47407// If the user uses them, then switch into old mode. 47408Readable.prototype.resume = function () { 47409 var state = this._readableState; 47410 if (!state.flowing) { 47411 debug('resume'); 47412 state.flowing = true; 47413 resume(this, state); 47414 } 47415 return this; 47416}; 47417 47418function resume(stream, state) { 47419 if (!state.resumeScheduled) { 47420 state.resumeScheduled = true; 47421 processNextTick(resume_, stream, state); 47422 } 47423} 47424 47425function resume_(stream, state) { 47426 if (!state.reading) { 47427 debug('resume read 0'); 47428 stream.read(0); 47429 } 47430 47431 state.resumeScheduled = false; 47432 state.awaitDrain = 0; 47433 stream.emit('resume'); 47434 flow(stream); 47435 if (state.flowing && !state.reading) stream.read(0); 47436} 47437 47438Readable.prototype.pause = function () { 47439 debug('call pause flowing=%j', this._readableState.flowing); 47440 if (false !== this._readableState.flowing) { 47441 debug('pause'); 47442 this._readableState.flowing = false; 47443 this.emit('pause'); 47444 } 47445 return this; 47446}; 47447 47448function flow(stream) { 47449 var state = stream._readableState; 47450 debug('flow', state.flowing); 47451 while (state.flowing && stream.read() !== null) {} 47452} 47453 47454// wrap an old-style stream as the async data source. 47455// This is *not* part of the readable stream interface. 47456// It is an ugly unfortunate mess of history. 47457Readable.prototype.wrap = function (stream) { 47458 var state = this._readableState; 47459 var paused = false; 47460 47461 var self = this; 47462 stream.on('end', function () { 47463 debug('wrapped end'); 47464 if (state.decoder && !state.ended) { 47465 var chunk = state.decoder.end(); 47466 if (chunk && chunk.length) self.push(chunk); 47467 } 47468 47469 self.push(null); 47470 }); 47471 47472 stream.on('data', function (chunk) { 47473 debug('wrapped data'); 47474 if (state.decoder) chunk = state.decoder.write(chunk); 47475 47476 // don't skip over falsy values in objectMode 47477 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; 47478 47479 var ret = self.push(chunk); 47480 if (!ret) { 47481 paused = true; 47482 stream.pause(); 47483 } 47484 }); 47485 47486 // proxy all the other methods. 47487 // important when wrapping filters and duplexes. 47488 for (var i in stream) { 47489 if (this[i] === undefined && typeof stream[i] === 'function') { 47490 this[i] = function (method) { 47491 return function () { 47492 return stream[method].apply(stream, arguments); 47493 }; 47494 }(i); 47495 } 47496 } 47497 47498 // proxy certain important events. 47499 var events = ['error', 'close', 'destroy', 'pause', 'resume']; 47500 forEach(events, function (ev) { 47501 stream.on(ev, self.emit.bind(self, ev)); 47502 }); 47503 47504 // when we try to consume some more bytes, simply unpause the 47505 // underlying stream. 47506 self._read = function (n) { 47507 debug('wrapped _read', n); 47508 if (paused) { 47509 paused = false; 47510 stream.resume(); 47511 } 47512 }; 47513 47514 return self; 47515}; 47516 47517// exposed for testing purposes only. 47518Readable._fromList = fromList; 47519 47520// Pluck off n bytes from an array of buffers. 47521// Length is the combined lengths of all the buffers in the list. 47522// This function is designed to be inlinable, so please take care when making 47523// changes to the function body. 47524function fromList(n, state) { 47525 // nothing buffered 47526 if (state.length === 0) return null; 47527 47528 var ret; 47529 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { 47530 // read it all, truncate the list 47531 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); 47532 state.buffer.clear(); 47533 } else { 47534 // read part of list 47535 ret = fromListPartial(n, state.buffer, state.decoder); 47536 } 47537 47538 return ret; 47539} 47540 47541// Extracts only enough buffered data to satisfy the amount requested. 47542// This function is designed to be inlinable, so please take care when making 47543// changes to the function body. 47544function fromListPartial(n, list, hasStrings) { 47545 var ret; 47546 if (n < list.head.data.length) { 47547 // slice is the same for buffers and strings 47548 ret = list.head.data.slice(0, n); 47549 list.head.data = list.head.data.slice(n); 47550 } else if (n === list.head.data.length) { 47551 // first chunk is a perfect match 47552 ret = list.shift(); 47553 } else { 47554 // result spans more than one buffer 47555 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); 47556 } 47557 return ret; 47558} 47559 47560// Copies a specified amount of characters from the list of buffered data 47561// chunks. 47562// This function is designed to be inlinable, so please take care when making 47563// changes to the function body. 47564function copyFromBufferString(n, list) { 47565 var p = list.head; 47566 var c = 1; 47567 var ret = p.data; 47568 n -= ret.length; 47569 while (p = p.next) { 47570 var str = p.data; 47571 var nb = n > str.length ? str.length : n; 47572 if (nb === str.length) ret += str;else ret += str.slice(0, n); 47573 n -= nb; 47574 if (n === 0) { 47575 if (nb === str.length) { 47576 ++c; 47577 if (p.next) list.head = p.next;else list.head = list.tail = null; 47578 } else { 47579 list.head = p; 47580 p.data = str.slice(nb); 47581 } 47582 break; 47583 } 47584 ++c; 47585 } 47586 list.length -= c; 47587 return ret; 47588} 47589 47590// Copies a specified amount of bytes from the list of buffered data chunks. 47591// This function is designed to be inlinable, so please take care when making 47592// changes to the function body. 47593function copyFromBuffer(n, list) { 47594 var ret = bufferShim.allocUnsafe(n); 47595 var p = list.head; 47596 var c = 1; 47597 p.data.copy(ret); 47598 n -= p.data.length; 47599 while (p = p.next) { 47600 var buf = p.data; 47601 var nb = n > buf.length ? buf.length : n; 47602 buf.copy(ret, ret.length - n, 0, nb); 47603 n -= nb; 47604 if (n === 0) { 47605 if (nb === buf.length) { 47606 ++c; 47607 if (p.next) list.head = p.next;else list.head = list.tail = null; 47608 } else { 47609 list.head = p; 47610 p.data = buf.slice(nb); 47611 } 47612 break; 47613 } 47614 ++c; 47615 } 47616 list.length -= c; 47617 return ret; 47618} 47619 47620function endReadable(stream) { 47621 var state = stream._readableState; 47622 47623 // If we get here before consuming all the bytes, then that is a 47624 // bug in node. Should never happen. 47625 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); 47626 47627 if (!state.endEmitted) { 47628 state.ended = true; 47629 processNextTick(endReadableNT, state, stream); 47630 } 47631} 47632 47633function endReadableNT(state, stream) { 47634 // Check that we didn't get one last unshift. 47635 if (!state.endEmitted && state.length === 0) { 47636 state.endEmitted = true; 47637 stream.readable = false; 47638 stream.emit('end'); 47639 } 47640} 47641 47642function forEach(xs, f) { 47643 for (var i = 0, l = xs.length; i < l; i++) { 47644 f(xs[i], i); 47645 } 47646} 47647 47648function indexOf(xs, x) { 47649 for (var i = 0, l = xs.length; i < l; i++) { 47650 if (xs[i] === x) return i; 47651 } 47652 return -1; 47653} 47654}).call(this,require('_process')) 47655},{"./_stream_duplex":
47655208,"./internal/streams/BufferList":213,"_process":84,"buffer":86,"buffer-shims":85,"core-util-is":94,"events":154,"inherits":165,"isarray":214,"process-nextick-args":203,"string_decoder/":238,"util":83}],211:[function(require,module,exports){ 47656// a transform stream is a readable/writable stream where you do 47657// something with the data. Sometimes it's called a "filter", 47658// but that's not a great name for it, since that implies a thing where 47659// some bits pass through, and others are simply ignored. (That would 47660// be a valid example of a transform, of course.) 47661// 47662// While the output is causally related to the input, it's not a 47663// necessarily symmetric or synchronous transformation. For example, 47664// a zlib stream might take multiple plain-text writes(), and then 47665// emit a single compressed chunk some time in the future. 47666// 47667// Here's how this works: 47668// 47669// The Transform stream has all the aspects of the readable and writable 47670// stream classes. When you write(chunk), that calls _write(chunk,cb) 47671// internally, and returns false if there's a lot of pending writes 47672// buffered up. When you call read(), that calls _read(n) until 47673// there's enough pending readable data buffered up.
vendor: 5,569 bytes, lines 47674-47838
47674// 47675// In a transform stream, the written data is placed in a buffer. When 47676// _read(n) is called, it transforms the queued up data, calling the 47677// buffered _write cb's as it consumes chunks. If consuming a single 47678// written chunk would result in multiple output chunks, then the first 47679// outputted bit calls the readcb, and subsequent chunks just go into 47680// the read buffer, and will cause it to emit 'readable' if necessary. 47681// 47682// This way, back-pressure is actually determined by the reading side, 47683// since _read has to be called to start processing a new chunk. However, 47684// a pathological inflate type of transform can cause excessive buffering 47685// here. For example, imagine a stream where every byte of input is 47686// interpreted as an integer from 0-255, and then results in that many 47687// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in 47688// 1kb of data being output. In this case, you could write a very small 47689// amount of input, and end up with a very large amount of output. In 47690// such a pathological inflating mechanism, there'd be no way to tell 47691// the system to stop doing the transform. A single 4MB write could 47692// cause the system to run out of memory. 47693// 47694// However, even in such a pathological case, only a single written chunk 47695// would be consumed, and then the rest would wait (un-transformed) until 47696// the results of the previous transformed chunk were consumed. 47697 47698'use strict'; 47699 47700module.exports = Transform; 47701 47702var Duplex = require('./_stream_duplex'); 47703 47704/*<replacement>*/ 47705var util = require('core-util-is'); 47706util.inherits = require('inherits'); 47707/*</replacement>*/ 47708 47709util.inherits(Transform, Duplex); 47710 47711function TransformState(stream) { 47712 this.afterTransform = function (er, data) { 47713 return afterTransform(stream, er, data); 47714 }; 47715 47716 this.needTransform = false; 47717 this.transforming = false; 47718 this.writecb = null; 47719 this.writechunk = null; 47720 this.writeencoding = null; 47721} 47722 47723function afterTransform(stream, er, data) { 47724 var ts = stream._transformState; 47725 ts.transforming = false; 47726 47727 var cb = ts.writecb; 47728 47729 if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); 47730 47731 ts.writechunk = null; 47732 ts.writecb = null; 47733 47734 if (data !== null && data !== undefined) stream.push(data); 47735 47736 cb(er); 47737 47738 var rs = stream._readableState; 47739 rs.reading = false; 47740 if (rs.needReadable || rs.length < rs.highWaterMark) { 47741 stream._read(rs.highWaterMark); 47742 } 47743} 47744 47745function Transform(options) { 47746 if (!(this instanceof Transform)) return new Transform(options); 47747 47748 Duplex.call(this, options); 47749 47750 this._transformState = new TransformState(this); 47751 47752 var stream = this; 47753 47754 // start out asking for a readable event once data is transformed. 47755 this._readableState.needReadable = true; 47756 47757 // we have implemented the _read method, and done the other things 47758 // that Readable wants before the first _read call, so unset the 47759 // sync guard flag. 47760 this._readableState.sync = false; 47761 47762 if (options) { 47763 if (typeof options.transform === 'function') this._transform = options.transform; 47764 47765 if (typeof options.flush === 'function') this._flush = options.flush; 47766 } 47767 47768 // When the writable side finishes, then flush out anything remaining. 47769 this.once('prefinish', function () { 47770 if (typeof this._flush === 'function') this._flush(function (er, data) { 47771 done(stream, er, data); 47772 });else done(stream); 47773 }); 47774} 47775 47776Transform.prototype.push = function (chunk, encoding) { 47777 this._transformState.needTransform = false; 47778 return Duplex.prototype.push.call(this, chunk, encoding); 47779}; 47780 47781// This is the part where you do stuff! 47782// override this function in implementation classes. 47783// 'chunk' is an input chunk. 47784// 47785// Call `push(newChunk)` to pass along transformed output 47786// to the readable side. You may call 'push' zero or more times. 47787// 47788// Call `cb(err)` when you are done with this chunk. If you pass 47789// an error, then that'll put the hurt on the whole operation. If you 47790// never call cb(), then you'll never get another chunk. 47791Transform.prototype._transform = function (chunk, encoding, cb) { 47792 throw new Error('_transform() is not implemented'); 47793}; 47794 47795Transform.prototype._write = function (chunk, encoding, cb) { 47796 var ts = this._transformState; 47797 ts.writecb = cb; 47798 ts.writechunk = chunk; 47799 ts.writeencoding = encoding; 47800 if (!ts.transforming) { 47801 var rs = this._readableState; 47802 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); 47803 } 47804}; 47805 47806// Doesn't matter what the args are here. 47807// _transform does all the work. 47808// That we got here means that the readable side wants more data. 47809Transform.prototype._read = function (n) { 47810 var ts = this._transformState; 47811 47812 if (ts.writechunk !== null && ts.writecb && !ts.transforming) { 47813 ts.transforming = true; 47814 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); 47815 } else { 47816 // mark that we need a transform, so that any data that comes in 47817 // will get processed, now that we've asked for it. 47818 ts.needTransform = true; 47819 } 47820}; 47821 47822function done(stream, er, data) { 47823 if (er) return stream.emit('error', er); 47824 47825 if (data !== null && data !== undefined) stream.push(data); 47826 47827 // if there's nothing in the write buffer, then that means 47828 // that nothing more will ever be provided 47829 var ws = stream._writableState; 47830 var ts = stream._transformState; 47831 47832 if (ws.length) throw new Error('Calling transform done when ws.length != 0'); 47833 47834 if (ts.transforming) throw new Error('Calling transform done when still transforming'); 47835 47836 return stream.push(null); 47837} 47838},{"./_stream_duplex":208,"core-util-is":94,"inherits":165}],212
vendor: 15,988 bytes, lines 47838-48392
47838:[function(require,module,exports){ 47839(function (process){ 47840// A bit simpler than readable streams. 47841// Implement an async ._write(chunk, encoding, cb), and it'll handle all 47842// the drain event emission and buffering. 47843 47844'use strict'; 47845 47846module.exports = Writable; 47847 47848/*<replacement>*/ 47849var processNextTick = require('process-nextick-args'); 47850/*</replacement>*/ 47851 47852/*<replacement>*/ 47853var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; 47854/*</replacement>*/ 47855 47856/*<replacement>*/ 47857var Duplex; 47858/*</replacement>*/ 47859 47860Writable.WritableState = WritableState; 47861 47862/*<replacement>*/ 47863var util = require('core-util-is'); 47864util.inherits = require('inherits'); 47865/*</replacement>*/ 47866 47867/*<replacement>*/ 47868var internalUtil = { 47869 deprecate: require('util-deprecate') 47870}; 47871/*</replacement>*/ 47872 47873/*<replacement>*/ 47874var Stream; 47875(function () { 47876 try { 47877 Stream = require('st' + 'ream'); 47878 } catch (_) {} finally { 47879 if (!Stream) Stream = require('events').EventEmitter; 47880 } 47881})(); 47882/*</replacement>*/ 47883 47884var Buffer = require('buffer').Buffer; 47885/*<replacement>*/ 47886var bufferShim = require('buffer-shims'); 47887/*</replacement>*/ 47888 47889util.inherits(Writable, Stream); 47890 47891function nop() {} 47892 47893function WriteReq(chunk, encoding, cb) { 47894 this.chunk = chunk; 47895 this.encoding = encoding; 47896 this.callback = cb; 47897 this.next = null; 47898} 47899 47900function WritableState(options, stream) { 47901 Duplex = Duplex || require('./_stream_duplex'); 47902 47903 options = options || {}; 47904 47905 // object stream flag to indicate whether or not this stream 47906 // contains buffers or objects. 47907 this.objectMode = !!options.objectMode; 47908 47909 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; 47910 47911 // the point at which write() starts returning false 47912 // Note: 0 is a valid value, means that we always return false if 47913 // the entire buffer is not flushed immediately on write() 47914 var hwm = options.highWaterMark; 47915 var defaultHwm = this.objectMode ? 16 : 16 * 1024; 47916 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; 47917 47918 // cast to ints. 47919 this.highWaterMark = ~~this.highWaterMark; 47920 47921 // drain event flag. 47922 this.needDrain = false; 47923 // at the start of calling end() 47924 this.ending = false; 47925 // when end() has been called, and returned 47926 this.ended = false; 47927 // when 'finish' is emitted 47928 this.finished = false; 47929 47930 // should we decode strings into buffers before passing to _write? 47931 // this is here so that some node-core streams can optimize string 47932 // handling at a lower level. 47933 var noDecode = options.decodeStrings === false; 47934 this.decodeStrings = !noDecode; 47935 47936 // Crypto is kind of old and crusty. Historically, its default string 47937 // encoding is 'binary' so we have to make this configurable. 47938 // Everything else in the universe uses 'utf8', though. 47939 this.defaultEncoding = options.defaultEncoding || 'utf8'; 47940 47941 // not an actual buffer we keep track of, but a measurement 47942 // of how much we're waiting to get pushed to some underlying 47943 // socket or file. 47944 this.length = 0; 47945 47946 // a flag to see when we're in the middle of a write. 47947 this.writing = false; 47948 47949 // when true all writes will be buffered until .uncork() call 47950 this.corked = 0; 47951 47952 // a flag to be able to tell if the onwrite cb is called immediately, 47953 // or on a later tick. We set this to true at first, because any 47954 // actions that shouldn't happen until "later" should generally also 47955 // not happen before the first write call. 47956 this.sync = true; 47957 47958 // a flag to know if we're processing previously buffered items, which 47959 // may call the _write() callback in the same tick, so that we don't 47960 // end up in an overlapped onwrite situation. 47961 this.bufferProcessing = false; 47962 47963 // the callback that's passed to _write(chunk,cb) 47964 this.onwrite = function (er) { 47965 onwrite(stream, er); 47966 }; 47967 47968 // the callback that the user supplies to write(chunk,encoding,cb) 47969 this.writecb = null; 47970 47971 // the amount that is being written when _write is called. 47972 this.writelen = 0; 47973 47974 this.bufferedRequest = null; 47975 this.lastBufferedRequest = null; 47976 47977 // number of pending user-supplied write callbacks 47978 // this must be 0 before 'finish' can be emitted 47979 this.pendingcb = 0; 47980 47981 // emit prefinish if the only thing we're waiting for is _write cbs 47982 // This is relevant for synchronous Transform streams 47983 this.prefinished = false; 47984 47985 // True if the error was already emitted and should not be thrown again 47986 this.errorEmitted = false; 47987 47988 // count buffered requests 47989 this.bufferedRequestCount = 0; 47990 47991 // allocate the first CorkedRequest, there is always 47992 // one allocated and free to use, and we maintain at most two 47993 this.corkedRequestsFree = new CorkedRequest(this); 47994} 47995 47996WritableState.prototype.getBuffer = function getBuffer() { 47997 var current = this.bufferedRequest; 47998 var out = []; 47999 while (current) { 48000 out.push(current); 48001 current = current.next; 48002 } 48003 return out; 48004}; 48005 48006(function () { 48007 try { 48008 Object.defineProperty(WritableState.prototype, 'buffer', { 48009 get: internalUtil.deprecate(function () { 48010 return this.getBuffer(); 48011 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') 48012 }); 48013 } catch (_) {} 48014})(); 48015 48016// Test _writableState for inheritance to account for Duplex streams, 48017// whose prototype chain only points to Readable. 48018var realHasInstance; 48019if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { 48020 realHasInstance = Function.prototype[Symbol.hasInstance]; 48021 Object.defineProperty(Writable, Symbol.hasInstance, { 48022 value: function (object) { 48023 if (realHasInstance.call(this, object)) return true; 48024 48025 return object && object._writableState instanceof WritableState; 48026 } 48027 }); 48028} else { 48029 realHasInstance = function (object) { 48030 return object instanceof this; 48031 }; 48032} 48033 48034function Writable(options) { 48035 Duplex = Duplex || require('./_stream_duplex'); 48036 48037 // Writable ctor is applied to Duplexes, too. 48038 // `realHasInstance` is necessary because using plain `instanceof` 48039 // would return false, as no `_writableState` property is attached. 48040 48041 // Trying to use the custom `instanceof` for Writable here will also break the 48042 // Node.js LazyTransform implementation, which has a non-trivial getter for 48043 // `_writableState` that would lead to infinite recursion. 48044 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { 48045 return new Writable(options); 48046 } 48047 48048 this._writableState = new WritableState(options, this); 48049 48050 // legacy. 48051 this.writable = true; 48052 48053 if (options) { 48054 if (typeof options.write === 'function') this._write = options.write; 48055 48056 if (typeof options.writev === 'function') this._writev = options.writev; 48057 } 48058 48059 Stream.call(this); 48060} 48061 48062// Otherwise people can pipe Writable streams, which is just wrong. 48063Writable.prototype.pipe = function () { 48064 this.emit('error', new Error('Cannot pipe, not readable')); 48065}; 48066 48067function writeAfterEnd(stream, cb) { 48068 var er = new Error('write after end'); 48069 // TODO: defer error events consistently everywhere, not just the cb 48070 stream.emit('error', er); 48071 processNextTick(cb, er); 48072} 48073 48074// Checks that a user-supplied chunk is valid, especially for the particular 48075// mode the stream is in. Currently this means that `null` is never accepted 48076// and undefined/non-string values are only allowed in object mode. 48077function validChunk(stream, state, chunk, cb) { 48078 var valid = true; 48079 var er = false; 48080 48081 if (chunk === null) { 48082 er = new TypeError('May not write null values to stream'); 48083 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { 48084 er = new TypeError('Invalid non-string/buffer chunk'); 48085 } 48086 if (er) { 48087 stream.emit('error', er); 48088 processNextTick(cb, er); 48089 valid = false; 48090 } 48091 return valid; 48092} 48093 48094Writable.prototype.write = function (chunk, encoding, cb) { 48095 var state = this._writableState; 48096 var ret = false; 48097 var isBuf = Buffer.isBuffer(chunk); 48098 48099 if (typeof encoding === 'function') { 48100 cb = encoding; 48101 encoding = null; 48102 } 48103 48104 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; 48105 48106 if (typeof cb !== 'function') cb = nop; 48107 48108 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { 48109 state.pendingcb++; 48110 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); 48111 } 48112 48113 return ret; 48114}; 48115 48116Writable.prototype.cork = function () { 48117 var state = this._writableState; 48118 48119 state.corked++; 48120}; 48121 48122Writable.prototype.uncork = function () { 48123 var state = this._writableState; 48124 48125 if (state.corked) { 48126 state.corked--; 48127 48128 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); 48129 } 48130}; 48131 48132Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { 48133 // node::ParseEncoding() requires lower case. 48134 if (typeof encoding === 'string') encoding = encoding.toLowerCase(); 48135 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); 48136 this._writableState.defaultEncoding = encoding; 48137 return this; 48138}; 48139 48140function decodeChunk(state, chunk, encoding) { 48141 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { 48142 chunk = bufferShim.from(chunk, encoding); 48143 } 48144 return chunk; 48145} 48146 48147// if we're already writing something, then just put this 48148// in the queue, and wait our turn. Otherwise, call _write 48149// If we return false, then we need a drain event, so set that flag. 48150function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { 48151 if (!isBuf) { 48152 chunk = decodeChunk(state, chunk, encoding); 48153 if (Buffer.isBuffer(chunk)) encoding = 'buffer'; 48154 } 48155 var len = state.objectMode ? 1 : chunk.length; 48156 48157 state.length += len; 48158 48159 var ret = state.length < state.highWaterMark; 48160 // we must ensure that previous needDrain will not be reset to false. 48161 if (!ret) state.needDrain = true; 48162 48163 if (state.writing || state.corked) { 48164 var last = state.lastBufferedRequest; 48165 state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); 48166 if (last) { 48167 last.next = state.lastBufferedRequest; 48168 } else { 48169 state.bufferedRequest = state.lastBufferedRequest; 48170 } 48171 state.bufferedRequestCount += 1; 48172 } else { 48173 doWrite(stream, state, false, len, chunk, encoding, cb); 48174 } 48175 48176 return ret; 48177} 48178 48179function doWrite(stream, state, writev, len, chunk, encoding, cb) { 48180 state.writelen = len; 48181 state.writecb = cb; 48182 state.writing = true; 48183 state.sync = true; 48184 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); 48185 state.sync = false; 48186} 48187 48188function onwriteError(stream, state, sync, er, cb) { 48189 --state.pendingcb; 48190 if (sync) processNextTick(cb, er);else cb(er); 48191 48192 stream._writableState.errorEmitted = true; 48193 stream.emit('error', er); 48194} 48195 48196function onwriteStateUpdate(state) { 48197 state.writing = false; 48198 state.writecb = null; 48199 state.length -= state.writelen; 48200 state.writelen = 0; 48201} 48202 48203function onwrite(stream, er) { 48204 var state = stream._writableState; 48205 var sync = state.sync; 48206 var cb = state.writecb; 48207 48208 onwriteStateUpdate(state); 48209 48210 if (er) onwriteError(stream, state, sync, er, cb);else { 48211 // Check if we're actually ready to finish, but don't emit yet 48212 var finished = needFinish(state); 48213 48214 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { 48215 clearBuffer(stream, state); 48216 } 48217 48218 if (sync) { 48219 /*<replacement>*/ 48220 asyncWrite(afterWrite, stream, state, finished, cb); 48221 /*</replacement>*/ 48222 } else { 48223 afterWrite(stream, state, finished, cb); 48224 } 48225 } 48226} 48227 48228function afterWrite(stream, state, finished, cb) { 48229 if (!finished) onwriteDrain(stream, state); 48230 state.pendingcb--; 48231 cb(); 48232 finishMaybe(stream, state); 48233} 48234 48235// Must force callback to be called on nextTick, so that we don't 48236// emit 'drain' before the write() consumer gets the 'false' return 48237// value, and has a chance to attach a 'drain' listener. 48238function onwriteDrain(stream, state) { 48239 if (state.length === 0 && state.needDrain) { 48240 state.needDrain = false; 48241 stream.emit('drain'); 48242 } 48243} 48244 48245// if there's something in the buffer waiting, then process it 48246function clearBuffer(stream, state) { 48247 state.bufferProcessing = true; 48248 var entry = state.bufferedRequest; 48249 48250 if (stream._writev && entry && entry.next) { 48251 // Fast case, write everything using _writev() 48252 var l = state.bufferedRequestCount; 48253 var buffer = new Array(l); 48254 var holder = state.corkedRequestsFree; 48255 holder.entry = entry; 48256 48257 var count = 0; 48258 while (entry) { 48259 buffer[count] = entry; 48260 entry = entry.next; 48261 count += 1; 48262 } 48263 48264 doWrite(stream, state, true, state.length, buffer, '', holder.finish); 48265 48266 // doWrite is almost always async, defer these to save a bit of time 48267 // as the hot path ends with doWrite 48268 state.pendingcb++; 48269 state.lastBufferedRequest = null; 48270 if (holder.next) { 48271 state.corkedRequestsFree = holder.next; 48272 holder.next = null; 48273 } else { 48274 state.corkedRequestsFree = new CorkedRequest(state); 48275 } 48276 } else { 48277 // Slow case, write chunks one-by-one 48278 while (entry) { 48279 var chunk = entry.chunk; 48280 var encoding = entry.encoding; 48281 var cb = entry.callback; 48282 var len = state.objectMode ? 1 : chunk.length; 48283 48284 doWrite(stream, state, false, len, chunk, encoding, cb); 48285 entry = entry.next; 48286 // if we didn't call the onwrite immediately, then 48287 // it means that we need to wait until it does. 48288 // also, that means that the chunk and cb are currently 48289 // being processed, so move the buffer counter past them. 48290 if (state.writing) { 48291 break; 48292 } 48293 } 48294 48295 if (entry === null) state.lastBufferedRequest = null; 48296 } 48297 48298 state.bufferedRequestCount = 0; 48299 state.bufferedRequest = entry; 48300 state.bufferProcessing = false; 48301} 48302 48303Writable.prototype._write = function (chunk, encoding, cb) { 48304 cb(new Error('_write() is not implemented')); 48305}; 48306 48307Writable.prototype._writev = null; 48308 48309Writable.prototype.end = function (chunk, encoding, cb) { 48310 var state = this._writableState; 48311 48312 if (typeof chunk === 'function') { 48313 cb = chunk; 48314 chunk = null; 48315 encoding = null; 48316 } else if (typeof encoding === 'function') { 48317 cb = encoding; 48318 encoding = null; 48319 } 48320 48321 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); 48322 48323 // .end() fully uncorks 48324 if (state.corked) { 48325 state.corked = 1; 48326 this.uncork(); 48327 } 48328 48329 // ignore unnecessary end() calls. 48330 if (!state.ending && !state.finished) endWritable(this, state, cb); 48331}; 48332 48333function needFinish(state) { 48334 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; 48335} 48336 48337function prefinish(stream, state) { 48338 if (!state.prefinished) { 48339 state.prefinished = true; 48340 stream.emit('prefinish'); 48341 } 48342} 48343 48344function finishMaybe(stream, state) { 48345 var need = needFinish(state); 48346 if (need) { 48347 if (state.pendingcb === 0) { 48348 prefinish(stream, state); 48349 state.finished = true; 48350 stream.emit('finish'); 48351 } else { 48352 prefinish(stream, state); 48353 } 48354 } 48355 return need; 48356} 48357 48358function endWritable(stream, state, cb) { 48359 state.ending = true; 48360 finishMaybe(stream, state); 48361 if (cb) { 48362 if (state.finished) processNextTick(cb);else stream.once('finish', cb); 48363 } 48364 state.ended = true; 48365 stream.writable = false; 48366} 48367 48368// It seems a linked list but it is not 48369// there will be only 2 of these for each stream 48370function CorkedRequest(state) { 48371 var _this = this; 48372 48373 this.next = null; 48374 this.entry = null; 48375 this.finish = function (err) { 48376 var entry = _this.entry; 48377 _this.entry = null; 48378 while (entry) { 48379 var cb = entry.callback; 48380 state.pendingcb--; 48381 cb(err); 48382 entry = entry.next; 48383 } 48384 if (state.corkedRequestsFree) { 48385 state.corkedRequestsFree.next = _this; 48386 } else { 48387 state.corkedRequestsFree = _this; 48388 } 48389 }; 48390} 48391}).call(this,require('_process')) 48392},{"./_stream_duplex":
vendor: 2,684 bytes, lines 48392-48486
48392208,"_process":84,"buffer":86,"buffer-shims":85,"core-util-is":94,"events":154,"inherits":165,"process-nextick-args":203,"util-deprecate":242}],213:[function(require,module,exports){ 48393'use strict'; 48394 48395var Buffer = require('buffer').Buffer; 48396/*<replacement>*/ 48397var bufferShim = require('buffer-shims'); 48398/*</replacement>*/ 48399 48400module.exports = BufferList; 48401 48402function BufferList() { 48403 this.head = null; 48404 this.tail = null; 48405 this.length = 0; 48406} 48407 48408BufferList.prototype.push = function (v) { 48409 var entry = { data: v, next: null }; 48410 if (this.length > 0) this.tail.next = entry;else this.head = entry; 48411 this.tail = entry; 48412 ++this.length; 48413}; 48414 48415BufferList.prototype.unshift = function (v) { 48416 var entry = { data: v, next: this.head }; 48417 if (this.length === 0) this.tail = entry; 48418 this.head = entry; 48419 ++this.length; 48420}; 48421 48422BufferList.prototype.shift = function () { 48423 if (this.length === 0) return; 48424 var ret = this.head.data; 48425 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; 48426 --this.length; 48427 return ret; 48428}; 48429 48430BufferList.prototype.clear = function () { 48431 this.head = this.tail = null; 48432 this.length = 0; 48433}; 48434 48435BufferList.prototype.join = function (s) { 48436 if (this.length === 0) return ''; 48437 var p = this.head; 48438 var ret = '' + p.data; 48439 while (p = p.next) { 48440 ret += s + p.data; 48441 }return ret; 48442}; 48443 48444BufferList.prototype.concat = function (n) { 48445 if (this.length === 0) return bufferShim.alloc(0); 48446 if (this.length === 1) return this.head.data; 48447 var ret = bufferShim.allocUnsafe(n >>> 0); 48448 var p = this.head; 48449 var i = 0; 48450 while (p) { 48451 p.data.copy(ret, i); 48452 i += p.data.length; 48453 p = p.next; 48454 } 48455 return ret; 48456}; 48457},{"buffer":86,"buffer-shims":85}],214:[function(require,module,exports){ 48458var toString = {}.toString; 48459 48460module.exports = Array.isArray || function (arr) { 48461 return toString.call(arr) == '[object Array]'; 48462}; 48463 48464},{}],215:[function(require,module,exports){ 48465module.exports = require("./lib/_stream_passthrough.js") 48466 48467},{"./lib/_stream_passthrough.js":209}],216:[function(require,module,exports){ 48468(function (process){ 48469var Stream = (function (){ 48470 try { 48471 return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify 48472 } catch(_){} 48473}()); 48474exports = module.exports = require('./lib/_stream_readable.js'); 48475exports.Stream = Stream || exports; 48476exports.Readable = exports; 48477exports.Writable = require('./lib/_stream_writable.js'); 48478exports.Duplex = require('./lib/_stream_duplex.js'); 48479exports.Transform = require('./lib/_stream_transform.js'); 48480exports.PassThrough = require('./lib/_stream_passthrough.js'); 48481 48482if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { 48483 module.exports = Stream; 48484} 48485 48486}
48486).call(this,require('_process')) 48487},{"./lib/_stream_duplex.js":208,"./lib/_stream_passthrough.js":209,"./lib/_stream_readable.js":210,"./lib/_stream_transform.js":211,"./lib/_stream_writable.js":212,"_process":84}],217:[function(require,module,exports){ 48488module.exports = require("./lib/_stream_transform.js") 48489 48490},{"./lib/_stream_transform.js":211}],218:[function(require,module,exports){ 48491module.exports = require("./lib/_stream_writable.js") 48492 48493},{"./lib/_stream_writable.js":212}],219:[function(require,module,exports){ 48494/* eslint-disable node/no-deprecated-api */ 48495var buffer = require('buffer') 48496var Buffer = buffer.Buffer 48497 48498// alternative to using Object.keys for old browsers 48499function copyProps (src, dst) { 48500 for (var key in src) { 48501 dst[key] = src[key] 48502 } 48503} 48504if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { 48505 module.exports = buffer 48506} else { 48507 // Copy properties from require('buffer') 48508 copyProps(buffer, exports) 48509 exports.Buffer = SafeBuffer 48510} 48511 48512function SafeBuffer (arg, encodingOrOffset, length) { 48513 return Buffer(arg, encodingOrOffset, length) 48514} 48515 48516// Copy static methods from Buffer 48517copyProps(Buffer, SafeBuffer) 48518 48519SafeBuffer.from = function (arg, encodingOrOffset, length) { 48520 if (typeof arg === 'number') { 48521 throw new TypeError('Argument must not be a number') 48522 } 48523 return Buffer(arg, encodingOrOffset, length) 48524} 48525 48526SafeBuffer.alloc = function (size, fill, encoding) { 48527 if (typeof size !== 'number') { 48528 throw new TypeError('Argument must be a number') 48529 } 48530 var buf = Buffer(size) 48531 if (fill !== undefined) { 48532 if (typeof encoding === 'string') { 48533 buf.fill(fill, encoding) 48534 } else { 48535 buf.fill(fill) 48536 } 48537 } else { 48538 buf.fill(0) 48539 } 48540 return buf 48541} 48542 48543SafeBuffer.allocUnsafe = function (size) { 48544 if (typeof size !== 'number') { 48545 throw new TypeError('Argument must be a number') 48546 } 48547 return Buffer(size) 48548} 48549 48550SafeBuffer.allocUnsafeSlow = function (size) { 48551 if (typeof size !== 'number') { 48552 throw new TypeError('Argument must be a number') 48553 } 48554 return buffer.SlowBuffer(size) 48555} 48556 48557},{"buffer":86}],220:[function(require,module,exports){ 48558/* eslint-disable no-useless-escape */ 48559var electron = '^(file:\/\/|\/)(.*\.html?\/?)?' 48560var protocol = '^(http(s)?(:\/\/))?(www\.)?' 48561var domain = '[a-zA-Z0-9-_\.]+(:[0-9]{1,5})?(\/{1})?' 48562var qs = '[\?].*$' 48563/* eslint-enable no-useless-escape */ 48564 48565var stripElectron = new RegExp(electron) 48566var prefix = new RegExp(protocol + domain) 48567var normalize = new RegExp('#') 48568var suffix = new RegExp(qs) 48569 48570module.exports = pathname 48571 48572// replace everything in a route but the pathname and hash 48573// TODO(yw): ditch 'suffix' and allow qs routing 48574// (str, bool) -> str 48575function pathname (route, isElectron) { 48576 if (isElectron) route = route.replace(stripElectron, '') 48577 else route = route.replace(prefix, '') 48578 return route.replace(suffix, '').replace(normalize, '/') 48579} 48580 48581},{}],221:[function(require,module,exports){ 48582var document = require('global/document') 48583var assert = require('assert') 48584var xtend = require('xtend') 48585 48586var qs = require('./qs') 48587 48588module.exports = createLocation 48589 48590// takes an initial representation of the location state 48591// and then synchronize a mutation across all fields 48592// 48593// scenarios: 48594// - create a state object from document.location; we got no state yet 48595// - create a new state object from a string we pass in; full override mode 48596// - patch a state object with some value we pass in - lil patchy stuff 48597// 48598// (obj?, str?) -> obj 48599function createLocation (state, patch) { 48600 if (!state) { 48601 return { 48602 pathname: document.location.pathname, 48603 search: (document.location.search) ? qs(document.location.search) : {}, 48604 hash: document.location.hash, 48605 href: document.location.href 48606 } 48607 } else { 48608 assert.equal(typeof state, 'object', 'sheet-router/create-location: state should be an object') 48609 if (typeof patch === 'string') { 48610 return parseUrl(patch) 48611 } else { 48612 assert.equal(typeof patch, 'object', 'sheet-router/create-location: patch should be an object') 48613 return xtend(state, patch) 48614 } 48615 } 48616 48617 // parse a URL into a kv object inside the browser 48618 // str -> obj 48619 function parseUrl (url) { 48620 var a = document.createElement('a') 48621 a.href = url 48622 48623 return { 48624 href: a.href, 48625 pathname: a.pathname, 48626 search: (a.search) ? qs(a.search) : {}, 48627 hash: a.hash 48628 } 48629 } 48630} 48631 48632},{"./qs":225,"assert":78,"global/document":157,"xtend":251}],222:[function(require,module,exports){ 48633var document = require('global/document') 48634var window = require('global/window') 48635var assert = require('assert') 48636 48637module.exports = history 48638 48639// listen to html5 pushstate events 48640// and update router accordingly 48641// fn(str) -> null 48642function history (cb) { 48643 assert.equal(typeof cb, 'function', 'sheet-router/history: cb must be a function') 48644 window.onpopstate = function () { 48645 cb({ 48646 pathname: document.location.pathname, 48647 search: document.location.search, 48648 href: document.location.href, 48649 hash: document.location.hash 48650 }) 48651 } 48652} 48653 48654},{"assert":78,"global/document":157,"global/window":158}],223:[function(require,module,exports){ 48655var window = require('global/window') 48656var assert = require('assert') 48657 48658var qs = require('./qs') 48659 48660module.exports = href 48661 48662var noRoutingAttrName = 'data-no-routing' 48663 48664// handle a click if is anchor tag with an href 48665// and url lives on the same domain. Replaces 48666// trailing '#' so empty links work as expected. 48667// (fn(str), obj?) -> undefined 48668function href (cb, root) { 48669 assert.equal(typeof cb, 'function', 'sheet-router/href: cb must be a function') 48670 48671 window.onclick = function (e) { 48672 if ((e.button && e.button !== 0) || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return 48673 48674 var node = (function traverse (node) { 48675 if (!node || node === root) return 48676 if (node.localName !== 'a') return traverse(node.parentNode) 48677 if (node.href === undefined) return traverse(node.parentNode) 48678 if (window.location.host !== node.host) return traverse(node.parentNode) 48679 return node 48680 })(e.target) 48681 48682 if (!node) return 48683 48684 var isRoutingDisabled = node.hasAttribute(noRoutingAttrName) 48685 if (isRoutingDisabled) return 48686 48687 e.preventDefault() 48688 cb({ 48689 pathname: node.pathname, 48690 search: (node.search) ? qs(node.search) : {}, 48691 href: node.href, 48692 hash: node.hash 48693 }) 48694 } 48695} 48696 48697},{"./qs":225,"assert":78,"global/window":158}],224:[function(require,module,exports){ 48698var pathname = require('./_pathname') 48699var wayfarer = require('wayfarer') 48700var assert = require('assert') 48701 48702var isLocalFile = (/file:\/\//.test(typeof window === 'object' && 48703 window.location && window.location.origin)) // electron support 48704 48705module.exports = sheetRouter 48706 48707// Fast, modular client router 48708// fn(str, any[..]) -> fn(str, any[..]) 48709function sheetRouter (opts, tree) { 48710 if (!tree) { 48711 tree = opts 48712 opts = {} 48713 } 48714 48715 assert.equal(typeof opts, 'object', 'sheet-router: opts must be a object') 48716 assert.ok(Array.isArray(tree), 'sheet-router: tree must be an array') 48717 48718 var dft = opts.default || '/404' 48719 assert.equal(typeof dft, 'string', 'sheet-router: dft must be a string') 48720 48721 var router = wayfarer(dft) 48722 var prevCallback = null 48723 var prevRoute = null 48724 48725 match._router = router 48726 48727 // register tree in router 48728 // tree[0] is a string, thus a route
48729 // tree[0] is an array, thus not a route 48730 // tree[1] is a function 48731 // tree[2] is an array 48732 // tree[2] is not an array 48733 // tree[1] is an array 48734 ;(function walk (tree, fullRoute) { 48735 if (typeof tree[0] === 'string') { 48736 var route = tree[0].replace(/^[#/]/, '') 48737 } else { 48738 var rootArr = tree[0] 48739 } 48740 48741 var cb = (typeof tree[1] === 'function') ? tree[1] : null 48742 var children = (Array.isArray(tree[1])) 48743 ? tree[1] 48744 : Array.isArray(tree[2]) ? tree[2] : null 48745 48746 if (rootArr) { 48747 tree.forEach(function (node) { 48748 walk(node, fullRoute) 48749 }) 48750 } 48751 48752 if (cb) { 48753 var innerRoute = route 48754 ? fullRoute.concat(route).join('/') 48755 : fullRoute.length ? fullRoute.join('/') : route 48756 48757 // if opts.thunk is false or only enabled for match, don't thunk 48758 var handler = (opts.thunk === false || opts.thunk === 'match') 48759 ? cb 48760 : thunkify(cb) 48761 router.on(innerRoute, handler) 48762 } 48763 48764 if (Array.isArray(children)) { 48765 walk(children, fullRoute.concat(route)) 48766 } 48767 })(tree, []) 48768 48769 return match 48770 48771 // match a route on the router 48772 // 48773 // no thunking -> call route with all arguments 48774 // thunking only for match -> call route with all arguments 48775 // thunking and route is same -> call prev cb with new args 48776 // thunking and route is diff -> create cb and call with new args 48777 // 48778 // (str, [any..]) -> any 48779 function match (route, arg1, arg2, arg3, arg4, arg5) { 48780 assert.equal(typeof route, 'string', 'sheet-router: route must be a string') 48781 48782 if (opts.thunk === false) { 48783 return router(pathname(route, isLocalFile), arg1, arg2, arg3, arg4, arg5) 48784 } else if (route === prevRoute) { 48785 return prevCallback(arg1, arg2, arg3, arg4, arg5) 48786 } else { 48787 prevRoute = pathname(route, isLocalFile) 48788 prevCallback = router(prevRoute) 48789 return prevCallback(arg1, arg2, arg3, arg4, arg5) 48790 } 48791 } 48792} 48793 48794// wrap a function in a function so it can be called at a later time 48795// fn -> obj -> (any, any, any, any, any) 48796function thunkify (cb) { 48797 return function (params) { 48798 return function (arg1, arg2, arg3, arg4, arg5) { 48799 return cb(params, arg1, arg2, arg3, arg4, arg5) 48800 } 48801 } 48802} 48803 48804},{"./_pathname":220,"assert":78,"wayfarer":246}],225:[function(require,module,exports){ 48805var window = require('global/window') 48806 48807var decodeURIComponent = window.decodeURIComponent 48808var reg = new RegExp('([^?=&]+)(=([^&]*))?', 'g') 48809 48810module.exports = qs 48811 48812// decode a uri into a kv representation :: str -> obj 48813function qs (uri) { 48814 var obj = {} 48815 uri.replace(/^.*\?/, '').replace(reg, map) 48816 return obj 48817 48818 function map (a0, a1, a2, a3) { 48819 obj[decodeURIComponent(a1)] = decodeURIComponent(a3) 48820 } 48821} 48822 48823},{"global/window":158}],226:[function(require,module,exports){ 48824const walk = require('wayfarer/walk') 48825const assert = require('assert') 48826 48827module.exports = walkSheetRouter 48828 48829function walkSheetRouter (router, cb) { 48830 assert.equal(typeof router, 'function', 'sheet-router/walk: router should be a function') 48831 assert.equal(typeof cb, 'function', 'sheet-router/walk: cb should be a function') 48832 48833 router = router._router 48834 return walk(router, cb) 48835} 48836 48837},{"assert":78,"wayfarer/walk":248}],227:[function(require,module,exports){ 48838module.exports = require('insert-css') 48839 48840},{"insert-css":228}],228:[function(require,module,exports){ 48841var containers = []; // will store container HTMLElement references 48842var styleElements = []; // will store {prepend: HTMLElement, append: HTMLElement} 48843 48844var usage = 'insert-css: You need to provide a CSS string. Usage: insertCss(cssString[, options]).'; 48845 48846function insertCss(css, options) { 48847 options = options || {}; 48848 48849 if (css === undefined) { 48850 throw new Error(usage); 48851 } 48852 48853 var position = options.prepend === true ? 'prepend' : 'append'; 48854 var container = options.container !== undefined ? options.container : document.querySelector('head'); 48855 var containerId = containers.indexOf(container); 48856 48857 // first time we see this container, create the necessary entries 48858 if (containerId === -1) { 48859 containerId = containers.push(container) - 1; 48860 styleElements[containerId] = {}; 48861 } 48862 48863 // try to get the correponding container + position styleElement, create it otherwise 48864 var styleElement; 48865 48866 if (styleElements[containerId] !== undefined && styleElements[containerId][position] !== undefined) { 48867 styleElement = styleElements[containerId][position]; 48868 } else { 48869 styleElement = styleElements[containerId][position] = createStyleElement(); 48870 48871 if (position === 'prepend') { 48872 container.insertBefore(styleElement, container.childNodes[0]); 48873 } else { 48874 container.appendChild(styleElement); 48875 } 48876 } 48877 48878 // strip potential UTF-8 BOM if css was read from a file 48879 if (css.charCodeAt(0) === 0xFEFF) { css = css.substr(1, css.length); } 48880 48881 // actually add the stylesheet 48882 if (styleElement.styleSheet) { 48883 styleElement.styleSheet.cssText += css 48884 } else { 48885 styleElement.textContent += css; 48886 } 48887 48888 return styleElement; 48889}; 48890 48891function createStyleElement() { 48892 var styleElement = document.createElement('style'); 48893 styleElement.setAttribute('type', 'text/css'); 48894 return styleElement; 48895} 48896 48897module.exports = insertCss; 48898module.exports.insertCss = insertCss; 48899 48900},{}],229:[function(require,module,exports){ 48901(function (process){ 48902var events = require('events') 48903var ess = require('event-source-stream') 48904var nets = require('nets') 48905var pump = require('pump') 48906var through = require('through2') 48907var inherits = require('inherits') 48908 48909module.exports = SignalHub 48910 48911function SignalHub (app, urls) { 48912 if (!(this instanceof SignalHub)) return new SignalHub(app, urls) 48913 if (!app) throw new Error('app name required')
48914 if (!urls || !urls.length) throw new Error('signalhub url(s) required') 48915 48916 events.EventEmitter.call(this) 48917 this.setMaxListeners(0) 48918 48919 this.app = app 48920 if (!Array.isArray(urls)) urls = [urls] 48921 this.urls = urls.map(function (url) { 48922 url = url.replace(/\/$/, '') 48923 return url.indexOf('://') === -1 ? 'http://' + url : url 48924 }) 48925 this.subscribers = [] 48926 this.closed = false 48927} 48928 48929inherits(SignalHub, events.EventEmitter) 48930 48931SignalHub.prototype.subscribe = function (channel) { 48932 if (this.closed) throw new Error('Cannot subscribe after close') 48933 48934 var self = this 48935 var endpoint = Array.isArray(channel) ? channel.join(',') : channel 48936 var streams = this.urls.map(function (url) { 48937 return ess(url + '/v1/' + self.app + '/' + endpoint, {json: true}) 48938 }) 48939 48940 var subscriber 48941 if (streams.length === 1) { 48942 subscriber = streams[0] 48943 } else { 48944 subscriber = through.obj() 48945 subscriber.setMaxListeners(0) 48946 streams.forEach(function (stream) { 48947 stream.on('open', function () { 48948 subscriber.emit('open') 48949 }) 48950 pump(stream, subscriber) 48951 }) 48952 } 48953 48954 this.subscribers.push(subscriber) 48955 48956 subscriber.once('close', function () { 48957 var i = self.subscribers.indexOf(subscriber) 48958 if (i > -1) self.subscribers.splice(i, 1) 48959 }) 48960 48961 return subscriber 48962} 48963 48964SignalHub.prototype.broadcast = function (channel, message, cb) { 48965 if (this.closed) throw new Error('Cannot broadcast after close') 48966 if (!message) message = {} 48967 if (!cb) cb = noop 48968
48969 var pending = this.urls.length 48970 var errors = 0 48971 48972 var self = this 48973 this.urls.forEach(function (url) { 48974 broadcast(self.app, url, channel, message, function (err) { 48975 if (err) errors++ 48976 if (--pending) return 48977 if (errors === self.urls.length) return cb(err) 48978 cb() 48979 }) 48980 }) 48981} 48982 48983SignalHub.prototype.close = function (cb) { 48984 if (this.closed) return 48985 this.closed = true 48986 48987 if (cb) this.once('close', cb) 48988 var len = this.subscribers.length 48989 if (len > 0) { 48990 var self = this 48991 var closed = 0 48992 this.subscribers.forEach(function (subscriber) { 48993 subscriber.once('close', function () { 48994 if (++closed === len) { 48995 self.emit('close') 48996 } 48997 }) 48998 process.nextTick(function () { 48999 subscriber.destroy() 49000 }) 49001 }) 49002 } else { 49003 this.emit('close') 49004 } 49005} 49006 49007function broadcast (app, url, channel, message, cb) { 49008 return nets({ 49009 method: 'POST', 49010 json: message, 49011 url: url + '/v1/' + app + '/' + channel 49012 }, function (err, res) { 49013 if (err) return cb(err) 49014 if (res.statusCode !== 200) return cb(new Error('Bad status: ' + res.statusCode)) 49015 cb() 49016 }) 49017} 49018 49019function noop () {} 49020 49021}).call(this,require('_process')) 49022},{"_process":84,"event-source-stream":153,"events":154,"inherits":165,"nets":175,"pump":204,"through2":235}],230:[function(require,module,exports){ 49023(function (process){ 49024// Copyright Joyent, Inc. and other Node contributors. 49025// 49026// Permission is hereby granted, free of charge, to any person obtaining a 49027// copy of this software and associated documentation files (the 49028// "Software"), to deal in the Software without restriction, including 49029// without limitation the rights to use, copy, modify, merge, publish, 49030// distribute, sublicense, and/or sell copies of the Software, and to permit 49031// persons to whom the Software is furnished to do so, subject to the 49032// following conditions: 49033// 49034// The above copyright notice and this permission notice shall be included 49035// in all copies or substantial portions of the Software. 49036// 49037// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 49038// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 49039// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 49040// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 49041// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 49042// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 49043// USE OR OTHER DEALINGS IN THE SOFTWARE. 49044 49045// a duplex stream is just a stream that is both readable and writable. 49046// Since JS doesn't have multiple prototypal inheritance, this class 49047// prototypally inherits from Readable, and then parasitically from 49048// Writable. 49049 49050module.exports = Duplex; 49051 49052/*<replacement>*/ 49053var objectKeys = Object.keys || function (obj) { 49054 var keys = []; 49055 for (var key in obj) keys.push(key); 49056 return keys; 49057} 49058/*</replacement>*/ 49059 49060 49061/*<replacement>*/ 49062var util = require('core-util-is'); 49063util.inherits = require('inherits'); 49064/*</replacement>*/ 49065 49066var Readable = require('./_stream_readable'); 49067var Writable = require('./_stream_writable'); 49068 49069util.inherits(Duplex, Readable); 49070 49071forEach(objectKeys(Writable.prototype), function(method) { 49072 if (!Duplex.prototype[method]) 49073 Duplex.prototype[method] = Writable.prototype[method]; 49074}); 49075 49076function Duplex(options) { 49077 if (!(this instanceof Duplex)) 49078 return new Duplex(options); 49079 49080 Readable.call(this, options); 49081 Writable.call(this, options); 49082 49083 if (options && options.readable === false) 49084 this.readable = false; 49085 49086 if (options && options.writable === false) 49087 this.writable = false; 49088 49089 this.allowHalfOpen = true; 49090 if (options && options.allowHalfOpen === false) 49091 this.allowHalfOpen = false; 49092 49093 this.once('end', onend); 49094} 49095 49096// the no-half-open enforcer 49097function onend() { 49098 // if we allow half-open state, or if the writable side ended, 49099 // then we're ok. 49100 if (this.allowHalfOpen || this._writableState.ended) 49101 return; 49102 49103 // no more data can be written. 49104 // But allow more writes to happen in this tick. 49105 process.nextTick(this.end.bind(this)); 49106} 49107 49108function forEach (xs, f) { 49109 for (var i = 0, l = xs.length; i < l; i++) { 49110 f(xs[i], i); 49111 } 49112} 49113 49114}).call(this,require('_process')) 49115},{"./_stream_readable":231,"./_stream_writable":233,"_process":84,"core-util-is":94,"inherits":165}],231:[function(require,module,exports){ 49116(function (process){ 49117// Copyright Joyent, Inc. and other Node contributors. 49118// 49119// Permission is hereby granted, free of charge, to any person obtaining a 49120// copy of this software and associated documentation files (the 49121// "Software"), to deal in the Software without restriction, including 49122// without limitation the rights to use, copy, modify, merge, publish, 49123// distribute, sublicense, and/or sell copies of the Software, and to permit 49124// persons to whom the Software is furnished to do so, subject to the 49125// following conditions: 49126// 49127// The above copyright notice and this permission notice shall be included 49128// in all copies or substantial portions of the Software. 49129// 49130// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 49131// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 49132// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 49133// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 49134// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 49135// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 49136// USE OR OTHER DEALINGS IN THE SOFTWARE. 49137 49138module.exports = Readable; 49139 49140/*<replacement>*/ 49141var isArray = require('isarray'); 49142/*</replacement>*/ 49143 49144 49145/*<replacement>*/ 49146var Buffer = require('buffer').Buffer; 49147/*</replacement>*/ 49148 49149Readable.ReadableState = ReadableState; 49150 49151var EE = require('events').EventEmitter; 49152 49153/*<replacement>*/ 49154if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { 49155 return emitter.listeners(type).length; 49156}; 49157/*</replacement>*/ 49158 49159var Stream = require('stream'); 49160 49161/*<replacement>*/ 49162var util = require('core-util-is'); 49163util.inherits = require('inherits'); 49164/*</replacement>*/ 49165 49166var StringDecoder; 49167 49168util.inherits(Readable, Stream); 49169 49170function ReadableState(options, stream) { 49171 options = options || {}; 49172 49173 // the point at which it stops calling _read() to fill the buffer 49174 // Note: 0 is a valid value, means "don't call _read preemptively ever" 49175 var hwm = options.highWaterMark; 49176 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; 49177 49178 // cast to ints. 49179 this.highWaterMark = ~~this.highWaterMark; 49180 49181 this.buffer = []; 49182 this.length = 0; 49183 this.pipes = null; 49184 this.pipesCount = 0; 49185 this.flowing = false;
49186 this.ended = false; 49187 this.endEmitted = false; 49188 this.reading = false; 49189 49190 // In streams that never have any data, and do push(null) right away, 49191 // the consumer can miss the 'end' event if they do some I/O before 49192 // consuming the stream. So, we don't emit('end') until some reading 49193 // happens. 49194 this.calledRead = false; 49195 49196 // a flag to be able to tell if the onwrite cb is called immediately, 49197 // or on a later tick. We set this to true at first, becuase any 49198 // actions that shouldn't happen until "later" should generally also 49199 // not happen before the first write call. 49200 this.sync = true; 49201 49202 // whenever we return null, then we set a flag to say 49203 // that we're awaiting a 'readable' event emission. 49204 this.needReadable = false; 49205 this.emittedReadable = false; 49206 this.readableListening = false; 49207 49208 49209 // object stream flag. Used to make read(n) ignore n and to 49210 // make all the buffer merging and length checks go away 49211 this.objectMode = !!options.objectMode; 49212 49213 // Crypto is kind of old and crusty. Historically, its default string 49214 // encoding is 'binary' so we have to make this configurable. 49215 // Everything else in the universe uses 'utf8', though. 49216 this.defaultEncoding = options.defaultEncoding || 'utf8'; 49217 49218 // when piping, we only care about 'readable' events that happen 49219 // after read()ing all the bytes and not getting any pushback. 49220 this.ranOut = false; 49221 49222 // the number of writers that are awaiting a drain event in .pipe()s 49223 this.awaitDrain = 0; 49224 49225 // if true, a maybeReadMore has been scheduled 49226 this.readingMore = false; 49227 49228 this.decoder = null; 49229 this.encoding = null; 49230 if (options.encoding) { 49231 if (!StringDecoder) 49232 StringDecoder = require('string_decoder/').StringDecoder; 49233 this.decoder = new StringDecoder(options.encoding); 49234 this.encoding = options.encoding; 49235 } 49236} 49237 49238function Readable(options) { 49239 if (!(this instanceof Readable)) 49240 return new Readable(options); 49241 49242 this._readableState = new ReadableState(options, this); 49243 49244 // legacy 49245 this.readable = true; 49246 49247 Stream.call(this); 49248} 49249 49250// Manually shove something into the read() buffer. 49251// This returns true if the highWaterMark has not been hit yet, 49252// similar to how Writable.write() returns true if you should 49253// write() some more. 49254Readable.prototype.push = function(chunk, encoding) { 49255 var state = this._readableState; 49256 49257 if (typeof chunk === 'string' && !state.objectMode) { 49258 encoding = encoding || state.defaultEncoding; 49259 if (encoding !== state.encoding) { 49260 chunk = new Buffer(chunk, encoding); 49261 encoding = ''; 49262 } 49263 } 49264 49265 return readableAddChunk(this, state, chunk, encoding, false); 49266}; 49267 49268// Unshift should *always* be something directly out of read() 49269Readable.prototype.unshift = function(chunk) { 49270 var state = this._readableState; 49271 return readableAddChunk(this, state, chunk, '', true); 49272}; 49273 49274function readableAddChunk(stream, state, chunk, encoding, addToFront) { 49275 var er = chunkInvalid(state, chunk); 49276 if (er) { 49277 stream.emit('error', er); 49278 } else if (chunk === null || chunk === undefined) { 49279 state.reading = false; 49280 if (!state.ended) 49281 onEofChunk(stream, state); 49282 } else if (state.objectMode || chunk && chunk.length > 0) { 49283 if (state.ended && !addToFront) { 49284 var e = new Error('stream.push() after EOF'); 49285 stream.emit('error', e); 49286 } else if (state.endEmitted && addToFront) { 49287 var e = new Error('stream.unshift() after end event'); 49288 stream.emit('error', e); 49289 } else { 49290 if (state.decoder && !addToFront && !encoding) 49291 chunk = state.decoder.write(chunk); 49292 49293 // update the buffer info. 49294 state.length += state.objectMode ? 1 : chunk.length; 49295 if (addToFront) { 49296 state.buffer.unshift(chunk); 49297 } else { 49298 state.reading = false; 49299 state.buffer.push(chunk); 49300 } 49301 49302 if (state.needReadable) 49303 emitReadable(stream); 49304 49305 maybeReadMore(stream, state); 49306 } 49307 } else if (!addToFront) { 49308 state.reading = false; 49309 } 49310 49311 return needMoreData(state); 49312} 49313 49314 49315 49316// if it's past the high water mark, we can push in some more. 49317// Also, if we have no data yet, we can stand some
49318// more bytes. This is to work around cases where hwm=0, 49319// such as the repl. Also, if the push() triggered a 49320// readable event, and the user called read(largeNumber) such that 49321// needReadable was set, then we ought to push more, so that another 49322// 'readable' event will be triggered. 49323function needMoreData(state) { 49324 return !state.ended && 49325 (state.needReadable || 49326 state.length < state.highWaterMark || 49327 state.length === 0); 49328} 49329 49330// backwards compatibility. 49331Readable.prototype.setEncoding = function(enc) { 49332 if (!StringDecoder) 49333 StringDecoder = require('string_decoder/').StringDecoder; 49334 this._readableState.decoder = new StringDecoder(enc); 49335 this._readableState.encoding = enc; 49336}; 49337 49338// Don't raise the hwm > 128MB 49339var MAX_HWM = 0x800000; 49340function roundUpToNextPowerOf2(n) { 49341 if (n >= MAX_HWM) { 49342 n = MAX_HWM; 49343 } else { 49344 // Get the next highest power of 2 49345 n--; 49346 for (var p = 1; p < 32; p <<= 1) n |= n >> p; 49347 n++; 49348 } 49349 return n; 49350} 49351 49352function howMuchToRead(n, state) { 49353 if (state.length === 0 && state.ended) 49354 return 0; 49355 49356 if (state.objectMode) 49357 return n === 0 ? 0 : 1; 49358 49359 if (n === null || isNaN(n)) { 49360 // only flow one buffer at a time 49361 if (state.flowing && state.buffer.length) 49362 return state.buffer[0].length; 49363 else 49364 return state.length; 49365 } 49366 49367 if (n <= 0) 49368 return 0; 49369 49370 // If we're asking for more than the target buffer level, 49371 // then raise the water mark. Bump up to the next highest 49372 // power of 2, to prevent increasing it excessively in tiny 49373 // amounts. 49374 if (n > state.highWaterMark) 49375 state.highWaterMark = roundUpToNextPowerOf2(n); 49376 49377 // don't have that much. return null, unless we've ended. 49378 if (n > state.length) { 49379 if (!state.ended) { 49380 state.needReadable = true; 49381 return 0; 49382 } else 49383 return state.length; 49384 } 49385 49386 return n; 49387} 49388 49389// you can override either this method, or the async _read(n) below. 49390Readable.prototype.read = function(n) { 49391 var state = this._readableState; 49392 state.calledRead = true; 49393 var nOrig = n; 49394 var ret; 49395 49396 if (typeof n !== 'number' || n > 0) 49397 state.emittedReadable = false; 49398 49399 // if we're doing read(0) to trigger a readable event, but we 49400 // already have a bunch of data in the buffer, then just trigger 49401 // the 'readable' event and move on. 49402 if (n === 0 && 49403 state.needReadable && 49404 (state.length >= state.highWaterMark || state.ended)) { 49405 emitReadable(this); 49406 return null; 49407 } 49408 49409 n = howMuchToRead(n, state); 49410 49411 // if we've ended, and we're now clear, then finish it up. 49412 if (n === 0 && state.ended) { 49413 ret = null; 49414 49415 // In cases where the decoder did not receive enough data 49416 // to produce a full chunk, then immediately received an 49417 // EOF, state.buffer will contain [<Buffer >, <Buffer 00 ...>]. 49418 // howMuchToRead will see this and coerce the amount to 49419 // read to zero (because it's looking at the length of the 49420 // first <Buffer > in state.buffer), and we'll end up here. 49421 // 49422 // This can only happen via state.decoder -- no other venue 49423 // exists for pushing a zero-length chunk into state.buffer 49424 // and triggering this behavior. In this case, we return our 49425 // remaining data and end the stream, if appropriate. 49426 if (state.length > 0 && state.decoder) { 49427 ret = fromList(n, state); 49428 state.length -= ret.length; 49429 } 49430 49431 if (state.length === 0) 49432 endReadable(this); 49433 49434 return ret; 49435 } 49436 49437 // All the actual chunk generation logic needs to be 49438 // *below* the call to _read. The reason is that in certain 49439 // synthetic stream cases, such as passthrough streams, _read 49440 // may be a completely synchronous operation which may change 49441 // the state of the read buffer, providing enough data when 49442 // before there was *not* enough. 49443 // 49444 // So, the steps are: 49445 // 1. Figure out what the state of things will be after we do 49446 // a read from the buffer. 49447 // 49448 // 2. If that resulting state will trigger a _read, then call _read. 49449 // Note that this may be asynchronous, or synchronous. Yes, it is 49450 // deeply ugly to write APIs this way, but that still doesn't mean 49451 // that the Readable class should behave improperly, as streams are 49452 // designed to be sync/async agnostic. 49453 // Take note if the _read call is sync or async (ie, if the read call
49454 // has returned yet), so that we know whether or not it's safe to emit 49455 // 'readable' etc. 49456 // 49457 // 3. Actually pull the requested chunks out of the buffer and return. 49458 49459 // if we need a readable event, then we need to do some reading. 49460 var doRead = state.needReadable; 49461 49462 // if we currently have less than the highWaterMark, then also read some 49463 if (state.length - n <= state.highWaterMark) 49464 doRead = true; 49465 49466 // however, if we've ended, then there's no point, and if we're already 49467 // reading, then it's unnecessary. 49468 if (state.ended || state.reading) 49469 doRead = false; 49470 49471 if (doRead) { 49472 state.reading = true; 49473 state.sync = true; 49474 // if the length is currently zero, then we *need* a readable event. 49475 if (state.length === 0) 49476 state.needReadable = true; 49477 // call internal read method 49478 this._read(state.highWaterMark); 49479 state.sync = false; 49480 } 49481 49482 // If _read called its callback synchronously, then `reading` 49483 // will be false, and we need to re-evaluate how much data we 49484 // can return to the user. 49485 if (doRead && !state.reading) 49486 n = howMuchToRead(nOrig, state); 49487 49488 if (n > 0) 49489 ret = fromList(n, state); 49490 else 49491 ret = null; 49492 49493 if (ret === null) { 49494 state.needReadable = true; 49495 n = 0; 49496 } 49497 49498 state.length -= n; 49499 49500 // If we have nothing in the buffer, then we want to know 49501 // as soon as we *do* get something into the buffer. 49502 if (state.length === 0 && !state.ended) 49503 state.needReadable = true; 49504 49505 // If we happened to read() exactly the remaining amount in the 49506 // buffer, and the EOF has been seen at this point, then make sure 49507 // that we emit 'end' on the very next tick. 49508 if (state.ended && !state.endEmitted && state.length === 0) 49509 endReadable(this); 49510 49511 return ret; 49512}; 49513 49514function chunkInvalid(state, chunk) { 49515 var er = null; 49516 if (!Buffer.isBuffer(chunk) && 49517 'string' !== typeof chunk && 49518 chunk !== null && 49519 chunk !== undefined && 49520 !state.objectMode) { 49521 er = new TypeError('Invalid non-string/buffer chunk'); 49522 } 49523 return er; 49524} 49525 49526 49527function onEofChunk(stream, state) { 49528 if (state.decoder && !state.ended) { 49529 var chunk = state.decoder.end(); 49530 if (chunk && chunk.length) { 49531 state.buffer.push(chunk); 49532 state.length += state.objectMode ? 1 : chunk.length; 49533 } 49534 } 49535 state.ended = true; 49536 49537 // if we've ended and we have some data left, then emit 49538 // 'readable' now to make sure it gets picked up. 49539 if (state.length > 0) 49540 emitReadable(stream); 49541 else 49542 endReadable(stream); 49543} 49544 49545// Don't emit readable right away in sync mode, because this can trigger 49546// another read() call => stack overflow. This way, it might trigger 49547// a nextTick recursion warning, but that's not so bad. 49548function emitReadable(stream) { 49549 var state = stream._readableState; 49550 state.needReadable = false; 49551 if (state.emittedReadable) 49552 return; 49553 49554 state.emittedReadable = true; 49555 if (state.sync) 49556 process.nextTick(function() { 49557 emitReadable_(stream); 49558 }); 49559 else 49560 emitReadable_(stream); 49561} 49562 49563function emitReadable_(stream) { 49564 stream.emit('readable'); 49565} 49566 49567 49568// at this point, the user has presumably seen the 'readable' event, 49569// and called read() to consume some data. that may have triggered 49570// in turn another _read(n) call, in which case reading = true if 49571// it's in progress. 49572// However, if we're not ended, or reading, and the length < hwm, 49573// then go ahead and try to read some more preemptively. 49574function maybeReadMore(stream, state) { 49575 if (!state.readingMore) { 49576 state.readingMore = true; 49577 process.nextTick(function() { 49578 maybeReadMore_(stream, state); 49579 }); 49580 } 49581} 49582 49583function maybeReadMore_(stream, state) { 49584 var len = state.length; 49585 while (!state.reading && !state.flowing && !state.ended && 49586 state.length < state.highWaterMark) { 49587 stream.read(0); 49588 if (len === state.length) 49589 // didn't get any data, stop spinning. 49590 break; 49591 else 49592 len = state.length; 49593 } 49594 state.readingMore = false; 49595} 49596 49597// abstract method. to be overridden in specific implementation classes. 49598// call cb(er, data) where data is <= n in length. 49599// for virtual (non-string, non-buffer) streams, "length" is somewhat 49600// arbitrary, and perhaps not very meaningful. 49601Readable.prototype._read = function(n) {
49602 this.emit('error', new Error('not implemented')); 49603}; 49604 49605Readable.prototype.pipe = function(dest, pipeOpts) { 49606 var src = this; 49607 var state = this._readableState; 49608 49609 switch (state.pipesCount) { 49610 case 0: 49611 state.pipes = dest; 49612 break; 49613 case 1: 49614 state.pipes = [state.pipes, dest]; 49615 break; 49616 default: 49617 state.pipes.push(dest); 49618 break; 49619 } 49620 state.pipesCount += 1; 49621 49622 var doEnd = (!pipeOpts || pipeOpts.end !== false) && 49623 dest !== process.stdout && 49624 dest !== process.stderr; 49625 49626 var endFn = doEnd ? onend : cleanup; 49627 if (state.endEmitted) 49628 process.nextTick(endFn); 49629 else 49630 src.once('end', endFn); 49631 49632 dest.on('unpipe', onunpipe); 49633 function onunpipe(readable) { 49634 if (readable !== src) return; 49635 cleanup(); 49636 } 49637 49638 function onend() { 49639 dest.end(); 49640 } 49641 49642 // when the dest drains, it reduces the awaitDrain counter 49643 // on the source. This would be more elegant with a .once() 49644 // handler in flow(), but adding and removing repeatedly is 49645 // too slow. 49646 var ondrain = pipeOnDrain(src); 49647 dest.on('drain', ondrain); 49648 49649 function cleanup() { 49650 // cleanup event handlers once the pipe is broken 49651 dest.removeListener('close', onclose); 49652 dest.removeListener('finish', onfinish); 49653 dest.removeListener('drain', ondrain); 49654 dest.removeListener('error', onerror); 49655 dest.removeListener('unpipe', onunpipe); 49656 src.removeListener('end', onend); 49657 src.removeListener('end', cleanup); 49658 49659 // if the reader is waiting for a drain event from this 49660 // specific writer, then it would cause it to never start 49661 // flowing again. 49662 // So, if this is awaiting a drain, then we just call it now. 49663 // If we don't know, then assume that we are waiting for one. 49664 if (!dest._writableState || dest._writableState.needDrain) 49665 ondrain(); 49666 } 49667 49668 // if the dest has an error, then stop piping into it. 49669 // however, don't suppress the throwing behavior for this. 49670 function onerror(er) { 49671 unpipe(); 49672 dest.removeListener('error', onerror); 49673 if (EE.listenerCount(dest, 'error') === 0) 49674 dest.emit('error', er); 49675 } 49676 // This is a brutally ugly hack to make sure that our error handler 49677 // is attached before any userland ones. NEVER DO THIS. 49678 if (!dest._events || !dest._events.error) 49679 dest.on('error', onerror); 49680 else if (isArray(dest._events.error)) 49681 dest._events.error.unshift(onerror); 49682 else 49683 dest._events.error = [onerror, dest._events.error]; 49684 49685 49686 49687 // Both close and finish should trigger unpipe, but only once. 49688 function onclose() { 49689 dest.removeListener('finish', onfinish); 49690 unpipe(); 49691 } 49692 dest.once('close', onclose); 49693 function onfinish() { 49694 dest.removeListener('close', onclose); 49695 unpipe(); 49696 } 49697 dest.once('finish', onfinish); 49698 49699 function unpipe() { 49700 src.unpipe(dest); 49701 } 49702 49703 // tell the dest that it's being piped to 49704 dest.emit('pipe', src); 49705 49706 // start the flow if it hasn't been started already. 49707 if (!state.flowing) { 49708 // the handler that waits for readable events after all 49709 // the data gets sucked out in flow. 49710 // This would be easier to follow with a .once() handler 49711 // in flow(), but that is too slow. 49712 this.on('readable', pipeOnReadable); 49713 49714 state.flowing = true; 49715 process.nextTick(function() { 49716 flow(src); 49717 }); 49718 } 49719 49720 return dest; 49721}; 49722 49723function pipeOnDrain(src) { 49724 return function() { 49725 var dest = this; 49726 var state = src._readableState; 49727 state.awaitDrain--; 49728 if (state.awaitDrain === 0) 49729 flow(src); 49730 }; 49731} 49732 49733function flow(src) { 49734 var state = src._readableState; 49735 var chunk; 49736 state.awaitDrain = 0; 49737 49738 function write(dest, i, list) { 49739 var written = dest.write(chunk); 49740 if (false === written) { 49741 state.awaitDrain++; 49742 } 49743 } 49744 49745 while (state.pipesCount && null !== (chunk = src.read())) { 49746 49747 if (state.pipesCount === 1) 49748 write(state.pipes, 0, null); 49749 else 49750 forEach(state.pipes, write); 49751 49752 src.emit('data', chunk); 49753 49754 // if anyone needs a drain, then we have to wait for that. 49755 if (state.awaitDrain > 0) 49756 return; 49757 } 49758 49759 // if every destination was unpiped, either before entering this 49760 // function, or in the while loop, then stop flowing. 49761 // 49762 // NB: This is a pretty rare edge case. 49763 if (state.pipesCount === 0) { 49764 state.flowing = false;
49765 49766 // if there were data event listeners added, then switch to old mode. 49767 if (EE.listenerCount(src, 'data') > 0) 49768 emitDataEvents(src); 49769 return; 49770 } 49771 49772 // at this point, no one needed a drain, so we just ran out of data 49773 // on the next readable event, start it over again. 49774 state.ranOut = true; 49775} 49776 49777function pipeOnReadable() { 49778 if (this._readableState.ranOut) { 49779 this._readableState.ranOut = false; 49780 flow(this); 49781 } 49782} 49783 49784 49785Readable.prototype.unpipe = function(dest) { 49786 var state = this._readableState; 49787 49788 // if we're not piping anywhere, then do nothing. 49789 if (state.pipesCount === 0) 49790 return this; 49791 49792 // just one destination. most common case. 49793 if (state.pipesCount === 1) { 49794 // passed in one, but it's not the right one. 49795 if (dest && dest !== state.pipes) 49796 return this; 49797 49798 if (!dest) 49799 dest = state.pipes; 49800 49801 // got a match. 49802 state.pipes = null; 49803 state.pipesCount = 0; 49804 this.removeListener('readable', pipeOnReadable); 49805 state.flowing = false; 49806 if (dest) 49807 dest.emit('unpipe', this); 49808 return this; 49809 } 49810 49811 // slow case. multiple pipe destinations. 49812 49813 if (!dest) { 49814 // remove all. 49815 var dests = state.pipes; 49816 var len = state.pipesCount; 49817 state.pipes = null; 49818 state.pipesCount = 0; 49819 this.removeListener('readable', pipeOnReadable); 49820 state.flowing = false; 49821 49822 for (var i = 0; i < len; i++) 49823 dests[i].emit('unpipe', this); 49824 return this; 49825 } 49826 49827 // try to find the right one. 49828 var i = indexOf(state.pipes, dest); 49829 if (i === -1) 49830 return this; 49831 49832 state.pipes.splice(i, 1); 49833 state.pipesCount -= 1; 49834 if (state.pipesCount === 1) 49835 state.pipes = state.pipes[0]; 49836 49837 dest.emit('unpipe', this); 49838 49839 return this; 49840}; 49841 49842// set up data events if they are asked for 49843// Ensure readable listeners eventually get something 49844Readable.prototype.on = function(ev, fn) { 49845 var res = Stream.prototype.on.call(this, ev, fn); 49846 49847 if (ev === 'data' && !this._readableState.flowing) 49848 emitDataEvents(this); 49849 49850 if (ev === 'readable' && this.readable) { 49851 var state = this._readableState; 49852 if (!state.readableListening) { 49853 state.readableListening = true; 49854 state.emittedReadable = false; 49855 state.needReadable = true; 49856 if (!state.reading) { 49857 this.read(0); 49858 } else if (state.length) { 49859 emitReadable(this, state); 49860 } 49861 } 49862 } 49863 49864 return res; 49865}; 49866Readable.prototype.addListener = Readable.prototype.on; 49867 49868// pause() and resume() are remnants of the legacy readable stream API 49869// If the user uses them, then switch into old mode. 49870Readable.prototype.resume = function() { 49871 emitDataEvents(this); 49872 this.read(0); 49873 this.emit('resume'); 49874}; 49875 49876Readable.prototype.pause = function() { 49877 emitDataEvents(this, true); 49878 this.emit('pause'); 49879}; 49880 49881function emitDataEvents(stream, startPaused) { 49882 var state = stream._readableState; 49883 49884 if (state.flowing) { 49885 // https://github.com/isaacs/readable-stream/issues/16 49886 throw new Error('Cannot switch to old mode now.'); 49887 } 49888 49889 var paused = startPaused || false; 49890 var readable = false; 49891 49892 // convert to an old-style stream. 49893 stream.readable = true; 49894 stream.pipe = Stream.prototype.pipe; 49895 stream.on = stream.addListener = Stream.prototype.on; 49896 49897 stream.on('readable', function() { 49898 readable = true; 49899 49900 var c; 49901 while (!paused && (null !== (c = stream.read()))) 49902 stream.emit('data', c); 49903 49904 if (c === null) { 49905 readable = false; 49906 stream._readableState.needReadable = true; 49907 } 49908 }); 49909 49910 stream.pause = function() { 49911 paused = true; 49912 this.emit('pause'); 49913 }; 49914 49915 stream.resume = function() { 49916 paused = false; 49917 if (readable) 49918 process.nextTick(function() { 49919 stream.emit('readable'); 49920 }); 49921 else 49922 this.read(0); 49923 this.emit('resume'); 49924 }; 49925 49926 // now make it start, just in case it hadn't already. 49927 stream.emit('readable'); 49928} 49929 49930// wrap an old-style stream as the async data source. 49931// This is *not* part of the readable stream interface. 49932// It is an ugly unfortunate mess of history. 49933Readable.prototype.wrap = function(stream) { 49934 var state = this._readableState; 49935 var paused = false; 49936 49937 var self = this; 49938 stream.on('end', function() { 49939 if (state.decoder && !state.ended) { 49940 var chunk = state.decoder.end(); 49941 if (chunk && chunk.length) 49942 self.push(chunk); 49943 } 49944 49945 self.push(null); 49946 }); 49947 49948 stream.on('data', function(chunk) { 49949 if (state.decoder) 49950 chunk = state.decoder.write(chunk); 49951 49952 // don't skip over falsy values in objectMode 49953 //if (state.objectMode && util.isNullOrUndefined(chunk)) 49954 if (state.objectMode && (chunk === null || chunk === undefined)) 49955 return; 49956 else if (!state.objectMode && (!chunk || !chunk.length)) 49957 return; 49958 49959 var ret = self.push(chunk); 49960 if (!ret) { 49961 paused = true; 49962 stream.pause(); 49963 } 49964 }); 49965 49966 // proxy all the other methods. 49967 // important when wrapping filters and duplexes. 49968 for (var i in stream) { 49969 if (typeof stream[i] === 'function' && 49970 typeof this[i] === 'undefined') { 49971 this[i] = function(method) { return function() { 49972 return stream[method].apply(stream, arguments); 49973 }}(i); 49974 } 49975 } 49976 49977 // proxy certain important events. 49978 var events = ['error', 'close', 'destroy', 'pause', 'resume']; 49979 forEach(events, function(ev) { 49980 stream.on(ev, self.emit.bind(self, ev)); 49981 }); 49982 49983 // when we try to consume some more bytes, simply unpause the 49984 // underlying stream. 49985 self._read = function(n) { 49986 if (paused) { 49987 paused = false;
vendor: 4,839 bytes, lines 49988-50141
49988 stream.resume(); 49989 } 49990 }; 49991 49992 return self; 49993}; 49994 49995 49996 49997// exposed for testing purposes only. 49998Readable._fromList = fromList; 49999 50000// Pluck off n bytes from an array of buffers. 50001// Length is the combined lengths of all the buffers in the list. 50002function fromList(n, state) { 50003 var list = state.buffer; 50004 var length = state.length; 50005 var stringMode = !!state.decoder; 50006 var objectMode = !!state.objectMode; 50007 var ret; 50008 50009 // nothing in the list, definitely empty. 50010 if (list.length === 0) 50011 return null; 50012 50013 if (length === 0) 50014 ret = null; 50015 else if (objectMode) 50016 ret = list.shift(); 50017 else if (!n || n >= length) { 50018 // read it all, truncate the array. 50019 if (stringMode) 50020 ret = list.join(''); 50021 else 50022 ret = Buffer.concat(list, length); 50023 list.length = 0; 50024 } else { 50025 // read just some of it. 50026 if (n < list[0].length) { 50027 // just take a part of the first list item. 50028 // slice is the same for buffers and strings. 50029 var buf = list[0]; 50030 ret = buf.slice(0, n); 50031 list[0] = buf.slice(n); 50032 } else if (n === list[0].length) { 50033 // first list is a perfect match 50034 ret = list.shift(); 50035 } else { 50036 // complex case. 50037 // we have enough to cover it, but it spans past the first buffer. 50038 if (stringMode) 50039 ret = ''; 50040 else 50041 ret = new Buffer(n); 50042 50043 var c = 0; 50044 for (var i = 0, l = list.length; i < l && c < n; i++) { 50045 var buf = list[0]; 50046 var cpy = Math.min(n - c, buf.length); 50047 50048 if (stringMode) 50049 ret += buf.slice(0, cpy); 50050 else 50051 buf.copy(ret, c, 0, cpy); 50052 50053 if (cpy < buf.length) 50054 list[0] = buf.slice(cpy); 50055 else 50056 list.shift(); 50057 50058 c += cpy; 50059 } 50060 } 50061 } 50062 50063 return ret; 50064} 50065 50066function endReadable(stream) { 50067 var state = stream._readableState; 50068 50069 // If we get here before consuming all the bytes, then that is a 50070 // bug in node. Should never happen. 50071 if (state.length > 0) 50072 throw new Error('endReadable called on non-empty stream'); 50073 50074 if (!state.endEmitted && state.calledRead) { 50075 state.ended = true; 50076 process.nextTick(function() { 50077 // Check that we didn't get one last unshift. 50078 if (!state.endEmitted && state.length === 0) { 50079 state.endEmitted = true; 50080 stream.readable = false; 50081 stream.emit('end'); 50082 } 50083 }); 50084 } 50085} 50086 50087function forEach (xs, f) { 50088 for (var i = 0, l = xs.length; i < l; i++) { 50089 f(xs[i], i); 50090 } 50091} 50092 50093function indexOf (xs, x) { 50094 for (var i = 0, l = xs.length; i < l; i++) { 50095 if (xs[i] === x) return i; 50096 } 50097 return -1; 50098} 50099 50100}).call(this,require('_process')) 50101},{"_process":84,"buffer":86,"core-util-is":94,"events":154,"inherits":165,"isarray":170,"stream":237,"string_decoder/":238}],232:[function(require,module,exports){ 50102// Copyright Joyent, Inc. and other Node contributors. 50103// 50104// Permission is hereby granted, free of charge, to any person obtaining a 50105// copy of this software and associated documentation files (the 50106// "Software"), to deal in the Software without restriction, including 50107// without limitation the rights to use, copy, modify, merge, publish, 50108// distribute, sublicense, and/or sell copies of the Software, and to permit 50109// persons to whom the Software is furnished to do so, subject to the 50110// following conditions: 50111// 50112// The above copyright notice and this permission notice shall be included 50113// in all copies or substantial portions of the Software. 50114// 50115// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 50116// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 50117// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 50118// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 50119// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 50120// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 50121// USE OR OTHER DEALINGS IN THE SOFTWARE. 50122 50123 50124// a transform stream is a readable/writable stream where you do 50125// something with the data. Sometimes it's called a "filter", 50126// but that's not a great name for it, since that implies a thing where 50127// some bits pass through, and others are simply ignored. (That would 50128// be a valid example of a transform, of course.) 50129// 50130// While the output is causally related to the input, it's not a 50131// necessarily symmetric or synchronous transformation. For example, 50132// a zlib stream might take multiple plain-text writes(), and then 50133// emit a single compressed chunk some time in the future. 50134// 50135// Here's how this works: 50136// 50137// The Transform stream has all the aspects of the readable and writable 50138// stream classes. When you write(chunk), that calls _write(chunk,cb) 50139// internally, and returns false if there's a lot of pending writes 50140// buffered up. When you call read(), that calls _read(n) until 50141// there's enough pending readable data buffered up.
50142// 50143// In a transform stream, the written data is placed in a buffer. When 50144// _read(n) is called, it transforms the queued up data, calling the 50145// buffered _write cb's as it consumes chunks. If consuming a single 50146// written chunk would result in multiple output chunks, then the first 50147// outputted bit calls the readcb, and subsequent chunks just go into 50148// the read buffer, and will cause it to emit 'readable' if necessary. 50149// 50150// This way, back-pressure is actually determined by the reading side, 50151// since _read has to be called to start processing a new chunk. However, 50152// a pathological inflate type of transform can cause excessive buffering 50153// here. For example, imagine a stream where every byte of input is 50154// interpreted as an integer from 0-255, and then results in that many 50155// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in 50156// 1kb of data being output. In this case, you could write a very small 50157// amount of input, and end up with a very large amount of output. In 50158// such a pathological inflating mechanism, there'd be no way to tell 50159// the system to stop doing the transform. A single 4MB write could 50160// cause the system to run out of memory. 50161// 50162// However, even in such a pathological case, only a single written chunk 50163// would be consumed, and then the rest would wait (un-transformed) until 50164// the results of the previous transformed chunk were consumed. 50165 50166module.exports = Transform; 50167 50168var Duplex = require('./_stream_duplex'); 50169 50170/*<replacement>*/ 50171var util = require('core-util-is'); 50172util.inherits = require('inherits'); 50173/*</replacement>*/ 50174 50175util.inherits(Transform, Duplex); 50176 50177 50178function TransformState(options, stream) { 50179 this.afterTransform = function(er, data) { 50180 return afterTransform(stream, er, data); 50181 }; 50182 50183 this.needTransform = false; 50184 this.transforming = false; 50185 this.writecb = null; 50186 this.writechunk = null; 50187} 50188 50189function afterTransform(stream, er, data) { 50190 var ts = stream._transformState; 50191 ts.transforming = false; 50192 50193 var cb = ts.writecb; 50194 50195 if (!cb) 50196 return stream.emit('error', new Error('no writecb in Transform class')); 50197 50198 ts.writechunk = null; 50199 ts.writecb = null; 50200 50201 if (data !== null && data !== undefined) 50202 stream.push(data); 50203 50204 if (cb) 50205 cb(er); 50206 50207 var rs = stream._readableState; 50208 rs.reading = false; 50209 if (rs.needReadable || rs.length < rs.highWaterMark) { 50210 stream._read(rs.highWaterMark); 50211 } 50212} 50213 50214 50215function Transform(options) { 50216 if (!(this instanceof Transform)) 50217 return new Transform(options); 50218 50219 Duplex.call(this, options); 50220 50221 var ts = this._transformState = new TransformState(options, this); 50222 50223 // when the writable side finishes, then flush out anything remaining. 50224 var stream = this; 50225 50226 // start out asking for a readable event once data is transformed. 50227 this._readableState.needReadable = true; 50228 50229 // we have implemented the _read method, and done the other things 50230 // that Readable wants before the first _read call, so unset the 50231 // sync guard flag. 50232 this._readableState.sync = false; 50233 50234 this.once('finish', function() { 50235 if ('function' === typeof this._flush) 50236 this._flush(function(er) { 50237 done(stream, er); 50238 }); 50239 else 50240 done(stream); 50241 }); 50242} 50243 50244Transform.prototype.push = function(chunk, encoding) { 50245 this._transformState.needTransform = false; 50246 return Duplex.prototype.push.call(this, chunk, encoding); 50247}; 50248 50249// This is the part where you do stuff! 50250// override this function in implementation classes. 50251// 'chunk' is an input chunk. 50252// 50253// Call `push(newChunk)` to pass along transformed output 50254// to the readable side. You may call 'push' zero or more times. 50255// 50256// Call `cb(err)` when you are done with this chunk. If you pass 50257// an error, then that'll put the hurt on the whole operation. If you 50258// never call cb(), then you'll never get another chunk. 50259Transform.prototype._transform = function(chunk, encoding, cb) { 50260 throw new Error('not implemented'); 50261}; 50262 50263Transform.prototype._write = function(chunk, encoding, cb) { 50264 var ts = this._transformState; 50265 ts.writecb = cb; 50266 ts.writechunk = chunk; 50267 ts.writeencoding = encoding; 50268 if (!ts.transforming) { 50269 var rs = this._readableState; 50270 if (ts.needTransform || 50271 rs.needReadable || 50272 rs.length < rs.highWaterMark) 50273 this._read(rs.highWaterMark); 50274 } 50275}; 50276 50277// Doesn't matter what the args are here. 50278// _transform does all the work. 50279// That we got here means that the readable side wants more data. 50280Transform.prototype._read = function(n) { 50281 var ts = this._transformState; 50282 50283 if (ts.writechunk !== null && ts.writecb && !ts.transforming) { 50284 ts.transforming = true; 50285 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); 50286 } else { 50287 // mark that we need a transform, so that any data that comes in 50288 // will get processed, now that we've asked for it. 50289 ts.needTransform = true; 50290 } 50291}; 50292 50293 50294function done(stream, er) { 50295 if (er) 50296 return stream.emit('error', er); 50297 50298 // if there's nothing in the write buffer, then that means 50299 // that nothing more will ever be provided 50300 var ws = stream._writableState; 50301 var rs = stream._readableState; 50302 var ts = stream._transformState; 50303 50304 if (ws.length) 50305 throw new Error('calling transform done when ws.length != 0'); 50306 50307 if (ts.transforming) 50308 throw new Error('calling transform done when still transforming'); 50309 50310 return stream.push(null); 50311} 50312 50313},{"./_stream_duplex":230,"core-util-is":94,"inherits":165}],233:[function(require,module,exports){ 50314(function (process){ 50315// Copyright Joyent, Inc. and other Node contributors. 50316// 50317// Permission is hereby granted, free of charge, to any person obtaining a 50318// copy of this software and associated documentation files (the 50319// "Software"), to deal in the Software without restriction, including 50320// without limitation the rights to use, copy, modify, merge, publish, 50321// distribute, sublicense, and/or sell copies of the Software, and to permit 50322// persons to whom the Software is furnished to do so, subject to the 50323// following conditions: 50324// 50325// The above copyright notice and this permission notice shall be included 50326// in all copies or substantial portions of the Software. 50327// 50328// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 50329// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 50330// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 50331// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 50332// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 50333// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 50334// USE OR OTHER DEALINGS IN THE SOFTWARE. 50335 50336// A bit simpler than readable streams. 50337// Implement an async ._write(chunk, cb), and it'll handle all 50338// the drain event emission and buffering. 50339 50340module.exports = Writable; 50341 50342/*<replacement>*/ 50343var Buffer = require('buffer').Buffer; 50344/*</replacement>*/ 50345 50346Writable.WritableState = WritableState; 50347 50348 50349/*<replacement>*/ 50350var util = require('core-util-is'); 50351util.inherits = require('inherits'); 50352/*</replacement>*/ 50353 50354var Stream = require('stream'); 50355 50356util.inherits(Writable, Stream); 50357 50358function WriteReq(chunk, encoding, cb) { 50359 this.chunk = chunk; 50360 this.encoding = encoding; 50361 this.callback = cb; 50362} 50363 50364function WritableState(options, stream) { 50365 options = options || {}; 50366 50367 // the point at which write() starts returning false 50368 // Note: 0 is a valid value, means that we always return false if 50369 // the entire buffer is not flushed immediately on write() 50370 var hwm = options.highWaterMark; 50371 this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; 50372 50373 // object stream flag to indicate whether or not this stream 50374 // contains buffers or objects. 50375 this.objectMode = !!options.objectMode; 50376 50377 // cast to ints. 50378 this.highWaterMark = ~~this.highWaterMark; 50379 50380 this.needDrain = false;
50381 // at the start of calling end() 50382 this.ending = false; 50383 // when end() has been called, and returned 50384 this.ended = false; 50385 // when 'finish' is emitted 50386 this.finished = false; 50387 50388 // should we decode strings into buffers before passing to _write? 50389 // this is here so that some node-core streams can optimize string 50390 // handling at a lower level. 50391 var noDecode = options.decodeStrings === false; 50392 this.decodeStrings = !noDecode; 50393 50394 // Crypto is kind of old and crusty. Historically, its default string 50395 // encoding is 'binary' so we have to make this configurable. 50396 // Everything else in the universe uses 'utf8', though. 50397 this.defaultEncoding = options.defaultEncoding || 'utf8'; 50398 50399 // not an actual buffer we keep track of, but a measurement 50400 // of how much we're waiting to get pushed to some underlying 50401 // socket or file. 50402 this.length = 0; 50403 50404 // a flag to see when we're in the middle of a write. 50405 this.writing = false; 50406 50407 // a flag to be able to tell if the onwrite cb is called immediately, 50408 // or on a later tick. We set this to true at first, becuase any 50409 // actions that shouldn't happen until "later" should generally also 50410 // not happen before the first write call. 50411 this.sync = true; 50412 50413 // a flag to know if we're processing previously buffered items, which 50414 // may call the _write() callback in the same tick, so that we don't 50415 // end up in an overlapped onwrite situation. 50416 this.bufferProcessing = false; 50417 50418 // the callback that's passed to _write(chunk,cb) 50419 this.onwrite = function(er) { 50420 onwrite(stream, er); 50421 }; 50422 50423 // the callback that the user supplies to write(chunk,encoding,cb) 50424 this.writecb = null; 50425 50426 // the amount that is being written when _write is called. 50427 this.writelen = 0; 50428 50429 this.buffer = []; 50430 50431 // True if the error was already emitted and should not be thrown again 50432 this.errorEmitted = false; 50433} 50434 50435function Writable(options) { 50436 var Duplex = require('./_stream_duplex'); 50437 50438 // Writable ctor is applied to Duplexes, though they're not 50439 // instanceof Writable, they're instanceof Readable. 50440 if (!(this instanceof Writable) && !(this instanceof Duplex)) 50441 return new Writable(options); 50442 50443 this._writableState = new WritableState(options, this); 50444 50445 // legacy. 50446 this.writable = true; 50447 50448 Stream.call(this); 50449} 50450 50451// Otherwise people can pipe Writable streams, which is just wrong. 50452Writable.prototype.pipe = function() { 50453 this.emit('error', new Error('Cannot pipe. Not readable.')); 50454}; 50455 50456 50457function writeAfterEnd(stream, state, cb) { 50458 var er = new Error('write after end'); 50459 // TODO: defer error events consistently everywhere, not just the cb 50460 stream.emit('error', er); 50461 process.nextTick(function() { 50462 cb(er); 50463 }); 50464} 50465 50466// If we get something that is not a buffer, string, null, or undefined, 50467// and we're not in objectMode, then that's an error. 50468// Otherwise stream chunks are all considered to be of length=1, and the 50469// watermarks determine how many objects to keep in the buffer, rather than 50470// how many bytes or characters. 50471function validChunk(stream, state, chunk, cb) { 50472 var valid = true; 50473 if (!Buffer.isBuffer(chunk) && 50474 'string' !== typeof chunk && 50475 chunk !== null && 50476 chunk !== undefined && 50477 !state.objectMode) { 50478 var er = new TypeError('Invalid non-string/buffer chunk'); 50479 stream.emit('error', er); 50480 process.nextTick(function() { 50481 cb(er); 50482 }); 50483 valid = false; 50484 } 50485 return valid; 50486} 50487 50488Writable.prototype.write = function(chunk, encoding, cb) { 50489 var state = this._writableState; 50490 var ret = false;
50491 50492 if (typeof encoding === 'function') { 50493 cb = encoding; 50494 encoding = null; 50495 } 50496 50497 if (Buffer.isBuffer(chunk)) 50498 encoding = 'buffer'; 50499 else if (!encoding) 50500 encoding = state.defaultEncoding; 50501 50502 if (typeof cb !== 'function') 50503 cb = function() {}; 50504 50505 if (state.ended) 50506 writeAfterEnd(this, state, cb); 50507 else if (validChunk(this, state, chunk, cb)) 50508 ret = writeOrBuffer(this, state, chunk, encoding, cb); 50509 50510 return ret; 50511}; 50512 50513function decodeChunk(state, chunk, encoding) { 50514 if (!state.objectMode && 50515 state.decodeStrings !== false && 50516 typeof chunk === 'string') { 50517 chunk = new Buffer(chunk, encoding); 50518 } 50519 return chunk; 50520} 50521 50522// if we're already writing something, then just put this 50523// in the queue, and wait our turn. Otherwise, call _write 50524// If we return false, then we need a drain event, so set that flag. 50525function writeOrBuffer(stream, state, chunk, encoding, cb) { 50526 chunk = decodeChunk(state, chunk, encoding); 50527 if (Buffer.isBuffer(chunk)) 50528 encoding = 'buffer'; 50529 var len = state.objectMode ? 1 : chunk.length; 50530 50531 state.length += len; 50532 50533 var ret = state.length < state.highWaterMark; 50534 // we must ensure that previous needDrain will not be reset to false. 50535 if (!ret) 50536 state.needDrain = true; 50537 50538 if (state.writing) 50539 state.buffer.push(new WriteReq(chunk, encoding, cb)); 50540 else 50541 doWrite(stream, state, len, chunk, encoding, cb); 50542 50543 return ret; 50544} 50545 50546function doWrite(stream, state, len, chunk, encoding, cb) { 50547 state.writelen = len; 50548 state.writecb = cb; 50549 state.writing = true; 50550 state.sync = true; 50551 stream._write(chunk, encoding, state.onwrite); 50552 state.sync = false; 50553} 50554 50555function onwriteError(stream, state, sync, er, cb) { 50556 if (sync) 50557 process.nextTick(function() { 50558 cb(er); 50559 }); 50560 else 50561 cb(er); 50562 50563 stream._writableState.errorEmitted = true; 50564 stream.emit('error', er); 50565} 50566 50567function onwriteStateUpdate(state) { 50568 state.writing = false; 50569 state.writecb = null; 50570 state.length -= state.writelen; 50571 state.writelen = 0; 50572} 50573 50574function onwrite(stream, er) { 50575 var state = stream._writableState; 50576 var sync = state.sync; 50577 var cb = state.writecb; 50578 50579 onwriteStateUpdate(state); 50580 50581 if (er) 50582 onwriteError(stream, state, sync, er, cb); 50583 else { 50584 // Check if we're actually ready to finish, but don't emit yet 50585 var finished = needFinish(stream, state); 50586 50587 if (!finished && !state.bufferProcessing && state.buffer.length) 50588 clearBuffer(stream, state); 50589 50590 if (sync) { 50591 process.nextTick(function() { 50592 afterWrite(stream, state, finished, cb); 50593 }); 50594 } else { 50595 afterWrite(stream, state, finished, cb); 50596 } 50597 } 50598} 50599 50600function afterWrite(stream, state, finished, cb) { 50601 if (!finished) 50602 onwriteDrain(stream, state); 50603 cb(); 50604 if (finished) 50605 finishMaybe(stream, state); 50606} 50607 50608// Must force callback to be called on nextTick, so that we don't 50609// emit 'drain' before the write() consumer gets the 'false' return 50610// value, and has a chance to attach a 'drain' listener. 50611function onwriteDrain(stream, state) { 50612 if (state.length === 0 && state.needDrain) { 50613 state.needDrain = false; 50614 stream.emit('drain'); 50615 } 50616} 50617 50618 50619// if there's something in the buffer waiting, then process it 50620function clearBuffer(stream, state) { 50621 state.bufferProcessing = true; 50622 50623 for (var c = 0; c < state.buffer.length; c++) { 50624 var entry = state.buffer[c]; 50625 var chunk = entry.chunk; 50626 var encoding = entry.encoding; 50627 var cb = entry.callback; 50628 var len = state.objectMode ? 1 : chunk.length; 50629 50630 doWrite(stream, state, len, chunk, encoding, cb); 50631 50632 // if we didn't call the onwrite immediately, then 50633 // it means that we need to wait until it does. 50634 // also, that means that the chunk and cb are currently 50635 // being processed, so move the buffer counter past them. 50636 if (state.writing) { 50637 c++; 50638 break; 50639 } 50640 } 50641 50642 state.bufferProcessing = false; 50643 if (c < state.buffer.length) 50644 state.buffer = state.buffer.slice(c); 50645 else 50646 state.buffer.length = 0; 50647} 50648 50649Writable.prototype._write = function(chunk, encoding, cb) { 50650 cb(new Error('not implemented')); 50651}; 50652 50653Writable.prototype.end = function(chunk, encoding, cb) { 50654 var state = this._writableState; 50655 50656 if (typeof chunk === 'function') { 50657 cb = chunk; 50658 chunk = null; 50659 encoding = null; 50660 } else if (typeof encoding === 'function') { 50661 cb = encoding; 50662 encoding = null; 50663 } 50664 50665 if (typeof chunk !== 'undefined' && chunk !== null) 50666 this.write(chunk, encoding); 50667 50668 // ignore unnecessary end() calls. 50669 if (!state.ending && !state.finished) 50670 endWritable(this, state, cb); 50671}; 50672 50673 50674function needFinish(stream, state) { 50675 return (state.ending && 50676 state.length === 0 && 50677 !state.finished && 50678 !state.writing); 50679} 50680 50681function finishMaybe(stream, state) { 50682 var need = needFinish(stream, state); 50683 if (need) { 50684 state.finished = true; 50685 stream.emit('finish'); 50686 } 50687 return need; 50688} 50689 50690function endWritable(stream, state, cb) { 50691 state.ending = true; 50692 finishMaybe(stream, state); 50693 if (cb) { 50694 if (state.finished) 50695 process.nextTick(cb); 50696 else 50697 stream.once('finish', cb); 50698 } 50699 state.ended = true; 50700} 50701 50702}
50702).call(this,require('_process')) 50703},{"./_stream_duplex":230,"_process":84,"buffer":86,"core-util-is":94,"inherits":165,"stream":237}],234:[function(require,module,exports){ 50704arguments[4][217][0].apply(exports,arguments) 50705},{"./lib/_stream_transform.js":232,"dup":217}],235:[function(require,module,exports){ 50706(function (process){ 50707var Transform = require('readable-stream/transform') 50708 , inherits = require('util').inherits 50709 , xtend = require('xtend') 50710 50711function DestroyableTransform(opts) { 50712 Transform.call(this, opts) 50713 this._destroyed = false 50714} 50715 50716inherits(DestroyableTransform, Transform) 50717 50718DestroyableTransform.prototype.destroy = function(err) { 50719 if (this._destroyed) return 50720 this._destroyed = true 50721 50722 var self = this 50723 process.nextTick(function() { 50724 if (err) 50725 self.emit('error', err) 50726 self.emit('close') 50727 }) 50728} 50729 50730// a noop _transform function 50731function noop (chunk, enc, callback) { 50732 callback(null, chunk) 50733} 50734 50735 50736// create a new export function, used by both the main export and 50737// the .ctor export, contains common logic for dealing with arguments 50738function through2 (construct) { 50739 return function (options, transform, flush) { 50740 if (typeof options == 'function') { 50741 flush = transform 50742 transform = options 50743 options = {} 50744 } 50745 50746 if (typeof transform != 'function') 50747 transform = noop 50748 50749 if (typeof flush != 'function') 50750 flush = null 50751 50752 return construct(options, transform, flush) 50753 } 50754} 50755 50756 50757// main export, just make me a transform stream! 50758module.exports = through2(function (options, transform, flush) { 50759 var t2 = new DestroyableTransform(options) 50760 50761 t2._transform = transform 50762 50763 if (flush) 50764 t2._flush = flush 50765 50766 return t2 50767}) 50768 50769 50770// make me a reusable prototype that I can `new`, or implicitly `new` 50771// with a constructor call 50772module.exports.ctor = through2(function (options, transform, flush) { 50773 function Through2 (override) { 50774 if (!(this instanceof Through2)) 50775 return new Through2(override) 50776 50777 this.options = xtend(options, override) 50778 50779 DestroyableTransform.call(this, this.options) 50780 } 50781 50782 inherits(Through2, DestroyableTransform) 50783 50784 Through2.prototype._transform = transform 50785 50786 if (flush) 50787 Through2.prototype._flush = flush 50788 50789 return Through2 50790}) 50791 50792 50793module.exports.obj = through2(function (options, transform, flush) { 50794 var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options)) 50795 50796 t2._transform = transform 50797 50798 if (flush) 50799 t2._flush = flush 50800 50801 return t2 50802}) 50803 50804}).call(this,require('_process')) 50805},{"_process":84,"readable-stream/transform":234,"util":245,"xtend":251}],236:[function(require,module,exports){ 50806(function (Buffer){ 50807module.exports = Peer 50808 50809var debug = require('debug')('simple-peer') 50810var getBrowserRTC = require('get-browser-rtc') 50811var inherits = require('inherits') 50812var randombytes = require('randombytes') 50813var stream = require('readable-stream') 50814 50815var MAX_BUFFERED_AMOUNT = 64 * 1024 50816 50817inherits(Peer, stream.Duplex) 50818 50819/** 50820 * WebRTC peer connection. Same API as node core `net.Socket`, plus a few extra methods. 50821 * Duplex stream. 50822 * @param {Object} opts 50823 */ 50824function Peer (opts) { 50825 var self = this 50826 if (!(self instanceof Peer)) return new Peer(opts) 50827 50828 self._id = randombytes(4).toString('hex').slice(0, 7) 50829 self._debug('new peer %o', opts) 50830 50831 opts = Object.assign({ 50832 allowHalfOpen: false 50833 }, opts) 50834 50835 stream.Duplex.call(self, opts) 50836 50837 self.channelName = opts.initiator 50838 ? opts.channelName || randombytes(20).toString('hex') 50839 : null 50840 50841 // Needed by _transformConstraints, so set this early 50842 self._isChromium = typeof window !== 'undefined' && !!window.webkitRTCPeerConnection 50843 50844 self.initiator = opts.initiator || false 50845 self.channelConfig = opts.channelConfig || Peer.channelConfig 50846 self.config = opts.config || Peer.config 50847 self.constraints = self._transformConstraints(opts.constraints || Peer.constraints) 50848 self.offerConstraints = self._transformConstraints(opts.offerConstraints || {}) 50849 self.answerConstraints = self._transformConstraints(opts.answerConstraints || {}) 50850 self.reconnectTimer = opts.reconnectTimer || false 50851 self.sdpTransform = opts.sdpTransform || function (sdp) { return sdp } 50852 self.stream = opts.stream || false 50853 self.trickle = opts.trickle !== undefined ? opts.trickle : true 50854 50855 self.destroyed = false 50856 self.connected = false 50857 50858 self.remoteAddress = undefined 50859 self.remoteFamily = undefined 50860 self.remotePort = undefined 50861 self.localAddress = undefined 50862 self.localPort = undefined 50863 50864 self._wrtc = (opts.wrtc && typeof opts.wrtc === 'object') 50865 ? opts.wrtc 50866 : getBrowserRTC() 50867 50868 if (!self._wrtc) { 50869 if (typeof window === 'undefined') { 50870 throw new Error('No WebRTC support: Specify `opts.wrtc` option in this environment') 50871 } else { 50872 throw new Error('No WebRTC support: Not a supported browser') 50873 } 50874 } 50875 50876 self._pcReady = false 50877 self._channelReady = false 50878 self._iceComplete = false // ice candidate trickle done (got null candidate) 50879 self._channel = null 50880 self._pendingCandidates = [] 50881 self._previousStreams = [] 50882 50883 self._chunk = null 50884 self._cb = null 50885 self._interval = null 50886 self._reconnectTimeout = null 50887 50888 self._pc = new (self._wrtc.RTCPeerConnection)(self.config, self.constraints) 50889 50890 // We prefer feature detection whenever possible, but sometimes that's not 50891 // possible for certain implementations. 50892 self._isWrtc = Array.isArray(self._pc.RTCIceConnectionStates) 50893 self._isReactNativeWebrtc = typeof self._pc._peerConnectionId === 'number' 50894 50895 self._pc.oniceconnectionstatechange = function () { 50896 self._onIceConnectionStateChange() 50897 } 50898 self._pc.onsignalingstatechange = function () { 50899 self._onSignalingStateChange() 50900 } 50901 self._pc.onicecandidate = function (event) { 50902 self._onIceCandidate(event) 50903 } 50904 50905 if (self.initiator) { 50906 var createdOffer = false 50907 self._pc.onnegotiationneeded = function () { 50908 if (!createdOffer) self._createOffer() 50909 createdOffer = true 50910 } 50911 50912 self._setupData({
50913 channel: self._pc.createDataChannel(self.channelName, self.channelConfig) 50914 }) 50915 } else { 50916 self._pc.ondatachannel = function (event) { 50917 self._setupData(event) 50918 } 50919 } 50920 50921 if ('addTrack' in self._pc) { 50922 // WebRTC Spec, Firefox 50923 if (self.stream) { 50924 self.stream.getTracks().forEach(function (track) { 50925 self._pc.addTrack(track, self.stream) 50926 }) 50927 } 50928 self._pc.ontrack = function (event) { 50929 self._onTrack(event) 50930 } 50931 } else { 50932 // Chrome, etc. This can be removed once all browsers support `ontrack` 50933 if (self.stream) self._pc.addStream(self.stream) 50934 self._pc.onaddstream = function (event) { 50935 self._onAddStream(event) 50936 } 50937 } 50938 50939 // HACK: wrtc doesn't fire the 'negotionneeded' event 50940 if (self.initiator && self._isWrtc) { 50941 self._pc.onnegotiationneeded() 50942 } 50943 50944 self._onFinishBound = function () { 50945 self._onFinish() 50946 } 50947 self.once('finish', self._onFinishBound) 50948} 50949 50950Peer.WEBRTC_SUPPORT = !!getBrowserRTC() 50951 50952/** 50953 * Expose config, constraints, and data channel config for overriding all Peer 50954 * instances. Otherwise, just set opts.config, opts.constraints, or opts.channelConfig 50955 * when constructing a Peer. 50956 */ 50957Peer.config = { 50958 iceServers: [ 50959 { 50960 urls: 'stun:stun.l.google.com:19302' 50961 }, 50962 { 50963 urls: 'stun:global.stun.twilio.com:3478?transport=udp' 50964 } 50965 ] 50966} 50967Peer.constraints = {} 50968Peer.channelConfig = {} 50969 50970Object.defineProperty(Peer.prototype, 'bufferSize', { 50971 get: function () { 50972 var self = this 50973 return (self._channel && self._channel.bufferedAmount) || 0 50974 } 50975}) 50976 50977Peer.prototype.address = function () { 50978 var self = this 50979 return { port: self.localPort, family: 'IPv4', address: self.localAddress } 50980} 50981 50982Peer.prototype.signal = function (data) { 50983 var self = this 50984 if (self.destroyed) throw new Error('cannot signal after peer is destroyed') 50985 if (typeof data === 'string') { 50986 try { 50987 data = JSON.parse(data) 50988 } catch (err) { 50989 data = {} 50990 } 50991 } 50992 self._debug('signal()') 50993 50994 if (data.candidate) { 50995 if (self._pc.remoteDescription) self._addIceCandidate(data.candidate) 50996 else self._pendingCandidates.push(data.candidate) 50997 } 50998 if (data.sdp) { 50999 self._pc.setRemoteDescription(new (self._wrtc.RTCSessionDescription)(data), function () { 51000 if (self.destroyed) return 51001 51002 self._pendingCandidates.forEach(function (candidate) { 51003 self._addIceCandidate(candidate) 51004 }) 51005 self._pendingCandidates = [] 51006 51007 if (self._pc.remoteDescription.type === 'offer') self._createAnswer() 51008 }, function (err) { self._onError(err) }) 51009 } 51010 if (!data.sdp && !data.candidate) { 51011 self._destroy(new Error('signal() called with invalid signal data')) 51012 } 51013} 51014 51015Peer.prototype._addIceCandidate = function (candidate) { 51016 var self = this 51017 try { 51018 self._pc.addIceCandidate( 51019 new self._wrtc.RTCIceCandidate(candidate), 51020 noop, 51021 function (err) { self._onError(err) } 51022 ) 51023 } catch (err) { 51024 self._destroy(new Error('error adding candidate: ' + err.message)) 51025 } 51026} 51027 51028/** 51029 * Send text/binary data to the remote peer. 51030 * @param {TypedArrayView|ArrayBuffer|Buffer|string|Blob|Object} chunk 51031 */ 51032Peer.prototype.send = function (chunk) { 51033 var self = this 51034 51035 // HACK: `wrtc` module crashes on Node.js Buffer, so convert to Uint8Array 51036 // See: https://github.com/feross/simple-peer/issues/60 51037 if (self._isWrtc && Buffer.isBuffer(chunk)) { 51038 chunk = new Uint8Array(chunk) 51039 } 51040 51041 self._channel.send(chunk) 51042} 51043 51044Peer.prototype.destroy = function (onclose) { 51045 var self = this 51046 self._destroy(null, onclose) 51047} 51048 51049Peer.prototype._destroy = function (err, onclose) { 51050 var self = this 51051 if (self.destroyed) return 51052 if (onclose) self.once('close', onclose) 51053 51054 self._debug('destroy (error: %s)', err && err.message) 51055 51056 self.readable = self.writable = false 51057 51058 if (!self._readableState.ended) self.push(null) 51059 if (!self._writableState.finished) self.end() 51060 51061 self.destroyed = true 51062 self.connected = false 51063 self._pcReady = false 51064 self._channelReady = false 51065 self._previousStreams = null 51066 51067 clearInterval(self._interval) 51068 clearTimeout(self._reconnectTimeout) 51069 self._interval = null 51070 self._reconnectTimeout = null 51071 self._chunk = null 51072 self._cb = null 51073 51074 if (self._onFinishBound) self.removeListener('finish', self._onFinishBound) 51075 self._onFinishBound = null 51076 51077 if (self._pc) { 51078 try { 51079 self._pc.close() 51080 } catch (err) {} 51081 51082 self._pc.oniceconnectionstatechange = null 51083 self._pc.onsignalingstatechange = null 51084 self._pc.onicecandidate = null 51085 if ('addTrack' in self._pc) { 51086 self._pc.ontrack = null 51087 } else { 51088 self._pc.onaddstream = null 51089 } 51090 self._pc.onnegotiationneeded = null 51091 self._pc.ondatachannel = null 51092 } 51093 51094 if (self._channel) { 51095 try { 51096 self._channel.close() 51097 } catch (err) {} 51098 51099 self._channel.onmessage = null 51100 self._channel.onopen = null 51101 self._channel.onclose = null 51102 } 51103 self._pc = null 51104 self._channel = null 51105 51106 if (err) self.emit('error', err) 51107 self.emit('close') 51108} 51109 51110Peer.prototype._setupData = function (event) { 51111 var self = this 51112 self._channel = event.channel 51113 self._channel.binaryType = 'arraybuffer' 51114 51115 if (typeof self._channel.bufferedAmountLowThreshold === 'number') { 51116 self._channel.bufferedAmountLowThreshold = MAX_BUFFERED_AMOUNT 51117 } 51118 51119 self.channelName = self._channel.label 51120 51121 self._channel.onmessage = function (event) { 51122 self._onChannelMessage(event) 51123 } 51124 self._channel.onbufferedamountlow = function () { 51125 self._onChannelBufferedAmountLow() 51126 } 51127 self._channel.onopen = function () { 51128 self._onChannelOpen() 51129 } 51130 self._channel.onclose = function () { 51131 self._onChannelClose() 51132 } 51133} 51134 51135Peer.prototype._read = function () {} 51136 51137Peer.prototype._write = function (chunk, encoding, cb) { 51138 var self = this 51139 if (self.destroyed) return cb(new Error('cannot write after peer is destroyed')) 51140 51141 if (self.connected) { 51142 try { 51143 self.send(chunk) 51144 } catch (err) { 51145 return self._onError(err) 51146 } 51147 if (self._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) { 51148 self._debug('start backpressure: bufferedAmount %d', self._channel.bufferedAmount) 51149 self._cb = cb 51150 } else { 51151 cb(null) 51152 } 51153 } else { 51154 self._debug('write before connect') 51155 self._chunk = chunk 51156 self._cb = cb 51157 } 51158} 51159 51160// When stream finishes writing, close socket. Half open connections are not 51161// supported. 51162Peer.prototype._onFinish = function () { 51163 var self = this 51164 if (self.destroyed) return 51165 51166 if (self.connected) { 51167 destroySoon() 51168 } else { 51169 self.once('connect', destroySoon) 51170 } 51171 51172 // Wait a bit before destroying so the socket flushes. 51173 // TODO: is there a more reliable way to accomplish this? 51174 function destroySoon () { 51175 setTimeout(function () { 51176 self._destroy() 51177 }, 100) 51178 } 51179} 51180 51181Peer.prototype._createOffer = function () { 51182 var self = this 51183 if (self.destroyed) return 51184 51185 self._pc.createOffer(function (offer) { 51186 if (self.destroyed) return 51187 offer.sdp = self.sdpTransform(offer.sdp) 51188 self._pc.setLocalDescription(offer, noop, function (err) { self._onError(err) }) 51189 var sendOffer = function () { 51190 var signal = self._pc.localDescription || offer 51191 self._debug('signal') 51192 self.emit('signal', { 51193 type: signal.type, 51194 sdp: signal.sdp 51195 }) 51196 } 51197 if (self.trickle || self._iceComplete) sendOffer() 51198 else self.once('_iceComplete', sendOffer) // wait for candidates 51199 }, function (err) { self._onError(err) }, self.offerConstraints) 51200} 51201 51202Peer.prototype._createAnswer = function () { 51203 var self = this 51204 if (self.destroyed) return 51205 51206 self._pc.createAnswer(function (answer) { 51207 if (self.destroyed) return 51208 answer.sdp = self.sdpTransform(answer.sdp) 51209 self._pc.setLocalDescription(answer, noop, function (err) { self._onError(err) }) 51210 if (self.trickle || self._iceComplete) sendAnswer() 51211 else self.once('_iceComplete', sendAnswer) 51212 51213 function sendAnswer () { 51214 var signal = self._pc.localDescription || answer 51215 self._debug('signal') 51216 self.emit('signal', { 51217 type: signal.type, 51218 sdp: signal.sdp 51219 }) 51220 } 51221 }, function (err) { self._onError(err) }, self.answerConstraints) 51222} 51223 51224Peer.prototype._onIceConnectionStateChange = function () { 51225 var self = this 51226 if (self.destroyed) return 51227 var iceGatheringState = self._pc.iceGatheringState 51228 var iceConnectionState = self._pc.iceConnectionState 51229 self._debug('iceConnectionStateChange %s %s', iceGatheringState, iceConnectionState) 51230 self.emit('iceConnectionStateChange', iceGatheringState, iceConnectionState) 51231 if (iceConnectionState === 'connected' || iceConnectionState === 'completed') { 51232 clearTimeout(self._reconnectTimeout) 51233 self._pcReady = true 51234 self._maybeReady() 51235 } 51236 if (iceConnectionState === 'disconnected') { 51237 if (self.reconnectTimer) { 51238 // If user has set `opt.reconnectTimer`, allow time for ICE to attempt a reconnect 51239 clearTimeout(self._reconnectTimeout) 51240 self._reconnectTimeout = setTimeout(function () { 51241 self._destroy() 51242 }, self.reconnectTimer) 51243 } else { 51244 self._destroy() 51245 } 51246 } 51247 if (iceConnectionState === 'failed') { 51248 self._destroy(new Error('Ice connection failed.')) 51249 } 51250 if (iceConnectionState === 'closed') { 51251 self._destroy() 51252 } 51253} 51254 51255Peer.prototype.getStats = function (cb) { 51256 var self = this 51257 51258 // Promise-based getStats() (standard) 51259 if (self._pc.getStats.length === 0) { 51260 self._pc.getStats().then(function (res) { 51261 var reports = []
51262 res.forEach(function (report) { 51263 reports.push(report) 51264 }) 51265 cb(reports) 51266 }, function (err) { self._onError(err) }) 51267 51268 // Two-parameter callback-based getStats() (deprecated, former standard) 51269 } else if (self._isReactNativeWebrtc) { 51270 self._pc.getStats(null, function (res) { 51271 var reports = [] 51272 res.forEach(function (report) { 51273 reports.push(report) 51274 }) 51275 cb(reports) 51276 }, function (err) { self._onError(err) }) 51277 51278 // Single-parameter callback-based getStats() (non-standard) 51279 } else if (self._pc.getStats.length > 0) { 51280 self._pc.getStats(function (res) { 51281 var reports = [] 51282 res.result().forEach(function (result) { 51283 var report = {} 51284 result.names().forEach(function (name) { 51285 report[name] = result.stat(name) 51286 }) 51287 report.id = result.id 51288 report.type = result.type 51289 report.timestamp = result.timestamp 51290 reports.push(report) 51291 }) 51292 cb(reports) 51293 }, function (err) { self._onError(err) }) 51294 51295 // Unknown browser, skip getStats() since it's anyone's guess which style of 51296 // getStats() they implement. 51297 } else { 51298 cb([]) 51299 } 51300} 51301 51302Peer.prototype._maybeReady = function () { 51303 var self = this 51304 self._debug('maybeReady pc %s channel %s', self._pcReady, self._channelReady) 51305 if (self.connected || self._connecting || !self._pcReady || !self._channelReady) return 51306 self._connecting = true 51307 51308 self.getStats(function (items) { 51309 self._connecting = false 51310 self.connected = true 51311 51312 var remoteCandidates = {} 51313 var localCandidates = {} 51314 var candidatePairs = {} 51315 51316 items.forEach(function (item) { 51317 // TODO: Once all browsers support the hyphenated stats report types, remove 51318 // the non-hypenated ones 51319 if (item.type === 'remotecandidate' || item.type === 'remote-candidate') { 51320 remoteCandidates[item.id] = item 51321 } 51322 if (item.type === 'localcandidate' || item.type === 'local-candidate') { 51323 localCandidates[item.id] = item 51324 } 51325 if (item.type === 'candidatepair' || item.type === 'candidate-pair') { 51326 candidatePairs[item.id] = item 51327 } 51328 }) 51329 51330 items.forEach(function (item) { 51331 // Spec-compliant 51332 if (item.type === 'transport') { 51333 setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId]) 51334 } 51335 51336 // Old implementations 51337 if ( 51338 (item.type === 'googCandidatePair' && item.googActiveConnection === 'true') || 51339 ((item.type === 'candidatepair' || item.type === 'candidate-pair') && item.selected) 51340 ) { 51341 setSelectedCandidatePair(item) 51342 } 51343 }) 51344 51345 function setSelectedCandidatePair (selectedCandidatePair) { 51346 var local = localCandidates[selectedCandidatePair.localCandidateId] 51347 51348 if (local && local.ip) { 51349 // Spec 51350 self.localAddress = local.ip 51351 self.localPort = Number(local.port) 51352 } else if (local && local.ipAddress) { 51353 // Firefox 51354 self.localAddress = local.ipAddress 51355 self.localPort = Number(local.portNumber) 51356 } else if (typeof selectedCandidatePair.googLocalAddress === 'string') { 51357 // TODO: remove this once Chrome 58 is released 51358 local = selectedCandidatePair.googLocalAddress.split(':') 51359 self.localAddress = local[0] 51360 self.localPort = Number(local[1]) 51361 } 51362 51363 var remote = remoteCandidates[selectedCandidatePair.remoteCandidateId] 51364 51365 if (remote && remote.ip) { 51366 // Spec 51367 self.remoteAddress = remote.ip 51368 self.remotePort = Number(remote.port) 51369 } else if (remote && remote.ipAddress) { 51370 // Firefox 51371 self.remoteAddress = remote.ipAddress 51372 self.remotePort = Number(remote.portNumber) 51373 } else if (typeof selectedCandidatePair.googRemoteAddress === 'string') { 51374 // TODO: remove this once Chrome 58 is released 51375 remote = selectedCandidatePair.googRemoteAddress.split(':') 51376 self.remoteAddress = remote[0] 51377 self.remotePort = Number(remote[1]) 51378 } 51379 self.remoteFamily = 'IPv4' 51380 51381 self._debug( 51382 'connect local: %s:%s remote: %s:%s', 51383 self.localAddress, self.localPort, self.remoteAddress, self.remotePort 51384 ) 51385 } 51386 51387 if (self._chunk) {
51388 try { 51389 self.send(self._chunk) 51390 } catch (err) { 51391 return self._onError(err) 51392 } 51393 self._chunk = null 51394 self._debug('sent chunk from "write before connect"') 51395 51396 var cb = self._cb 51397 self._cb = null 51398 cb(null) 51399 } 51400 51401 // If `bufferedAmountLowThreshold` and 'onbufferedamountlow' are unsupported, 51402 // fallback to using setInterval to implement backpressure. 51403 if (typeof self._channel.bufferedAmountLowThreshold !== 'number') { 51404 self._interval = setInterval(function () { self._onInterval() }, 150) 51405 if (self._interval.unref) self._interval.unref() 51406 } 51407 51408 self._debug('connect') 51409 self.emit('connect') 51410 }) 51411} 51412 51413Peer.prototype._onInterval = function () { 51414 if (!this._cb || !this._channel || this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) { 51415 return 51416 } 51417 this._onChannelBufferedAmountLow() 51418} 51419 51420Peer.prototype._onSignalingStateChange = function () { 51421 var self = this 51422 if (self.destroyed) return 51423 self._debug('signalingStateChange %s', self._pc.signalingState) 51424 self.emit('signalingStateChange', self._pc.signalingState) 51425} 51426 51427Peer.prototype._onIceCandidate = function (event) { 51428 var self = this 51429 if (self.destroyed) return 51430 if (event.candidate && self.trickle) { 51431 self.emit('signal', { 51432 candidate: { 51433 candidate: event.candidate.candidate, 51434 sdpMLineIndex: event.candidate.sdpMLineIndex, 51435 sdpMid: event.candidate.sdpMid 51436 } 51437 }) 51438 } else if (!event.candidate) { 51439 self._iceComplete = true 51440 self.emit('_iceComplete') 51441 } 51442} 51443 51444Peer.prototype._onChannelMessage = function (event) { 51445 var self = this 51446 if (self.destroyed) return 51447 var data = event.data 51448 if (data instanceof ArrayBuffer) data = new Buffer(data) 51449 self.push(data) 51450} 51451 51452Peer.prototype._onChannelBufferedAmountLow = function () { 51453 var self = this 51454 if (self.destroyed || !self._cb) return 51455 self._debug('ending backpressure: bufferedAmount %d', self._channel.bufferedAmount) 51456 var cb = self._cb 51457 self._cb = null 51458 cb(null) 51459} 51460 51461Peer.prototype._onChannelOpen = function () { 51462 var self = this 51463 if (self.connected || self.destroyed) return 51464 self._debug('on channel open') 51465 self._channelReady = true 51466 self._maybeReady() 51467} 51468 51469Peer.prototype._onChannelClose = function () { 51470 var self = this 51471 if (self.destroyed) return 51472 self._debug('on channel close') 51473 self._destroy() 51474} 51475 51476Peer.prototype._onAddStream = function (event) { 51477 var self = this 51478 if (self.destroyed) return 51479 self._debug('on add stream') 51480 self.emit('stream', event.stream) 51481} 51482 51483Peer.prototype._onTrack = function (event) { 51484 var self = this 51485 if (self.destroyed) return 51486 self._debug('on track') 51487 var id = event.streams[0].id 51488 if (self._previousStreams.indexOf(id) !== -1) return // Only fire one 'stream' event, even though there may be multiple tracks per stream 51489 self._previousStreams.push(id) 51490 self.emit('stream', event.streams[0]) 51491} 51492 51493Peer.prototype._onError = function (err) { 51494 var self = this 51495 if (self.destroyed) return 51496 self._debug('error %s', err.message || err) 51497 self._destroy(err) 51498} 51499 51500Peer.prototype._debug = function () { 51501 var self = this 51502 var args = [].slice.call(arguments) 51503 args[0] = '[' + self._id + '] ' + args[0] 51504 debug.apply(null, args) 51505} 51506 51507// Transform constraints objects into the new format (unless Chromium) 51508// TODO: This can be removed when Chromium supports the new format 51509Peer.prototype._transformConstraints = function (constraints) { 51510 var self = this 51511 51512 if (Object.keys(constraints).length === 0) { 51513 return constraints 51514 } 51515 51516 if ((constraints.mandatory || constraints.optional) && !self._isChromium) { 51517 // convert to new format 51518 51519 // Merge mandatory and optional objects, prioritizing mandatory 51520 var newConstraints = Object.assign({}, constraints.optional, constraints.mandatory) 51521 51522 // fix casing 51523 if (newConstraints.OfferToReceiveVideo !== undefined) { 51524 newConstraints.offerToReceiveVideo = newConstraints.OfferToReceiveVideo 51525 delete newConstraints['OfferToReceiveVideo'] 51526 } 51527 51528 if (newConstraints.OfferToReceiveAudio !== undefined) { 51529 newConstraints.offerToReceiveAudio = newConstraints.OfferToReceiveAudio 51530 delete newConstraints['OfferToReceiveAudio'] 51531 } 51532 51533 return newConstraints 51534 } else if (!constraints.mandatory && !constraints.optional && self._isChromium) { 51535 // convert to old format 51536 51537 // fix casing 51538 if (constraints.offerToReceiveVideo !== undefined) { 51539 constraints.OfferToReceiveVideo = constraints.offerToReceiveVideo 51540 delete constraints['offerToReceiveVideo'] 51541 } 51542 51543 if (constraints.offerToReceiveAudio !== undefined) { 51544 constraints.OfferToReceiveAudio = constraints.offerToReceiveAudio 51545 delete constraints['offerToReceiveAudio'] 51546 } 51547 51548 return { 51549 mandatory: constraints // NOTE: All constraints are upgraded to mandatory 51550 } 51551 } 51552 51553 return constraints 51554} 51555 51556function noop () {} 51557 51558}).call(this,require("buffer").Buffer) 51559},{"buffer":86,"debug":97,"get-browser-rtc":156,"inherits":165,"randombytes":206,"readable-stream":216}],237:[function(require,module,exports){ 51560// Copyright Joyent, Inc. and other Node contributors. 51561// 51562// Permission is hereby granted, free of charge, to any person obtaining a 51563// copy of this software and associated documentation files (the 51564// "Software"), to deal in the Software without restriction, including 51565// without limitation the rights to use, copy, modify, merge, publish, 51566// distribute, sublicense, and/or sell copies of the Software, and to permit 51567// persons to whom the Software is furnished to do so, subject to the 51568// following conditions: 51569// 51570// The above copyright notice and this permission notice shall be included 51571// in all copies or substantial portions of the Software. 51572// 51573// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 51574// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 51575// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 51576// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 51577// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 51578// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 51579// USE OR OTHER DEALINGS IN THE SOFTWARE. 51580 51581module.exports = Stream; 51582 51583var EE = require('events').EventEmitter; 51584var inherits = require('inherits'); 51585 51586inherits(Stream, EE); 51587Stream.Readable = require('readable-stream/readable.js'); 51588Stream.Writable = require('readable-stream/writable.js'); 51589Stream.Duplex = require('readable-stream/duplex.js'); 51590Stream.Transform = require('readable-stream/transform.js'); 51591Stream.PassThrough = require('readable-stream/passthrough.js'); 51592 51593// Backwards-compat with node 0.4.x 51594Stream.Stream = Stream; 51595 51596 51597 51598// old-style streams. Note that the pipe method (the only relevant 51599// part of this class) is overridden in the Readable class. 51600 51601function Stream() { 51602 EE.call(this); 51603} 51604 51605Stream.prototype.pipe = function(dest, options) { 51606 var source = this; 51607 51608 function ondata(chunk) { 51609 if (dest.writable) {
vendor: 10,485 bytes, lines 51610-51948
51610 if (false === dest.write(chunk) && source.pause) { 51611 source.pause(); 51612 } 51613 } 51614 } 51615 51616 source.on('data', ondata); 51617 51618 function ondrain() { 51619 if (source.readable && source.resume) { 51620 source.resume(); 51621 } 51622 } 51623 51624 dest.on('drain', ondrain); 51625 51626 // If the 'end' option is not supplied, dest.end() will be called when 51627 // source gets the 'end' or 'close' events. Only dest.end() once. 51628 if (!dest._isStdio && (!options || options.end !== false)) { 51629 source.on('end', onend); 51630 source.on('close', onclose); 51631 } 51632 51633 var didOnEnd = false; 51634 function onend() { 51635 if (didOnEnd) return; 51636 didOnEnd = true; 51637 51638 dest.end(); 51639 } 51640 51641 51642 function onclose() { 51643 if (didOnEnd) return; 51644 didOnEnd = true; 51645 51646 if (typeof dest.destroy === 'function') dest.destroy(); 51647 } 51648 51649 // don't leave dangling pipes when there are errors. 51650 function onerror(er) { 51651 cleanup(); 51652 if (EE.listenerCount(this, 'error') === 0) { 51653 throw er; // Unhandled stream error in pipe. 51654 } 51655 } 51656 51657 source.on('error', onerror); 51658 dest.on('error', onerror); 51659 51660 // remove all the event listeners that were added. 51661 function cleanup() { 51662 source.removeListener('data', ondata); 51663 dest.removeListener('drain', ondrain); 51664 51665 source.removeListener('end', onend); 51666 source.removeListener('close', onclose); 51667 51668 source.removeListener('error', onerror); 51669 dest.removeListener('error', onerror); 51670 51671 source.removeListener('end', cleanup); 51672 source.removeListener('close', cleanup); 51673 51674 dest.removeListener('close', cleanup); 51675 } 51676 51677 source.on('end', cleanup); 51678 source.on('close', cleanup); 51679 51680 dest.on('close', cleanup); 51681 51682 dest.emit('pipe', source); 51683 51684 // Allow for unix-like usage: A.pipe(B).pipe(C) 51685 return dest; 51686}; 51687 51688},{"events":154,"inherits":165,"readable-stream/duplex.js":207,"readable-stream/passthrough.js":215,"readable-stream/readable.js":216,"readable-stream/transform.js":217,"readable-stream/writable.js":218}],238:[function(require,module,exports){ 51689// Copyright Joyent, Inc. and other Node contributors. 51690// 51691// Permission is hereby granted, free of charge, to any person obtaining a 51692// copy of this software and associated documentation files (the 51693// "Software"), to deal in the Software without restriction, including 51694// without limitation the rights to use, copy, modify, merge, publish, 51695// distribute, sublicense, and/or sell copies of the Software, and to permit 51696// persons to whom the Software is furnished to do so, subject to the 51697// following conditions: 51698// 51699// The above copyright notice and this permission notice shall be included 51700// in all copies or substantial portions of the Software. 51701// 51702// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 51703// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 51704// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 51705// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 51706// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 51707// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 51708// USE OR OTHER DEALINGS IN THE SOFTWARE. 51709 51710var Buffer = require('buffer').Buffer; 51711 51712var isBufferEncoding = Buffer.isEncoding 51713 || function(encoding) { 51714 switch (encoding && encoding.toLowerCase()) { 51715 case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; 51716 default: return false; 51717 } 51718 } 51719 51720 51721function assertEncoding(encoding) { 51722 if (encoding && !isBufferEncoding(encoding)) { 51723 throw new Error('Unknown encoding: ' + encoding); 51724 } 51725} 51726 51727// StringDecoder provides an interface for efficiently splitting a series of 51728// buffers into a series of JS strings without breaking apart multi-byte 51729// characters. CESU-8 is handled as part of the UTF-8 encoding. 51730// 51731// @TODO Handling all encodings inside a single object makes it very difficult 51732// to reason about this code, so it should be split up in the future. 51733// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code 51734// points as used by CESU-8. 51735var StringDecoder = exports.StringDecoder = function(encoding) { 51736 this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); 51737 assertEncoding(encoding); 51738 switch (this.encoding) { 51739 case 'utf8': 51740 // CESU-8 represents each of Surrogate Pair by 3-bytes 51741 this.surrogateSize = 3; 51742 break; 51743 case 'ucs2': 51744 case 'utf16le': 51745 // UTF-16 represents each of Surrogate Pair by 2-bytes 51746 this.surrogateSize = 2; 51747 this.detectIncompleteChar = utf16DetectIncompleteChar; 51748 break; 51749 case 'base64': 51750 // Base-64 stores 3 bytes in 4 chars, and pads the remainder. 51751 this.surrogateSize = 3; 51752 this.detectIncompleteChar = base64DetectIncompleteChar; 51753 break; 51754 default: 51755 this.write = passThroughWrite; 51756 return; 51757 } 51758 51759 // Enough space to store all bytes of a single character. UTF-8 needs 4 51760 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). 51761 this.charBuffer = new Buffer(6); 51762 // Number of bytes received for the current incomplete multi-byte character. 51763 this.charReceived = 0; 51764 // Number of bytes expected for the current incomplete multi-byte character. 51765 this.charLength = 0; 51766}; 51767 51768 51769// write decodes the given buffer and returns it as JS string that is 51770// guaranteed to not contain any partial multi-byte characters. Any partial 51771// character found at the end of the buffer is buffered up, and will be 51772// returned when calling write again with the remaining bytes. 51773// 51774// Note: Converting a Buffer containing an orphan surrogate to a String 51775// currently works, but converting a String to a Buffer (via `new Buffer`, or 51776// Buffer#write) will replace incomplete surrogates with the unicode 51777// replacement character. See https://codereview.chromium.org/121173009/ . 51778StringDecoder.prototype.write = function(buffer) { 51779 var charStr = ''; 51780 // if our last write ended with an incomplete multibyte character 51781 while (this.charLength) { 51782 // determine how many remaining bytes this buffer has to offer for this char 51783 var available = (buffer.length >= this.charLength - this.charReceived) ? 51784 this.charLength - this.charReceived : 51785 buffer.length; 51786 51787 // add the new bytes to the char buffer 51788 buffer.copy(this.charBuffer, this.charReceived, 0, available); 51789 this.charReceived += available; 51790 51791 if (this.charReceived < this.charLength) { 51792 // still not enough chars in this buffer? wait for more ... 51793 return ''; 51794 } 51795 51796 // remove bytes belonging to the current character from the buffer 51797 buffer = buffer.slice(available, buffer.length); 51798 51799 // get the character that was split 51800 charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); 51801 51802 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character 51803 var charCode = charStr.charCodeAt(charStr.length - 1); 51804 if (charCode >= 0xD800 && charCode <= 0xDBFF) { 51805 this.charLength += this.surrogateSize; 51806 charStr = ''; 51807 continue; 51808 } 51809 this.charReceived = this.charLength = 0; 51810 51811 // if there are no more bytes in this buffer, just emit our char 51812 if (buffer.length === 0) { 51813 return charStr; 51814 } 51815 break; 51816 } 51817 51818 // determine and set charLength / charReceived 51819 this.detectIncompleteChar(buffer); 51820 51821 var end = buffer.length; 51822 if (this.charLength) { 51823 // buffer the incomplete character bytes we got 51824 buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); 51825 end -= this.charReceived; 51826 } 51827 51828 charStr += buffer.toString(this.encoding, 0, end); 51829 51830 var end = charStr.length - 1; 51831 var charCode = charStr.charCodeAt(end); 51832 // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character 51833 if (charCode >= 0xD800 && charCode <= 0xDBFF) { 51834 var size = this.surrogateSize; 51835 this.charLength += size; 51836 this.charReceived += size; 51837 this.charBuffer.copy(this.charBuffer, size, 0, size); 51838 buffer.copy(this.charBuffer, 0, 0, size); 51839 return charStr.substring(0, end); 51840 } 51841 51842 // or just emit the charStr 51843 return charStr; 51844}; 51845 51846// detectIncompleteChar determines if there is an incomplete UTF-8 character at 51847// the end of the given buffer. If so, it sets this.charLength to the byte 51848// length that character, and sets this.charReceived to the number of bytes 51849// that are available for this character. 51850StringDecoder.prototype.detectIncompleteChar = function(buffer) { 51851 // determine how many bytes we have to check at the end of this buffer 51852 var i = (buffer.length >= 3) ? 3 : buffer.length; 51853 51854 // Figure out if one of the last i bytes of our buffer announces an 51855 // incomplete char. 51856 for (; i > 0; i--) { 51857 var c = buffer[buffer.length - i]; 51858 51859 // See http://en.wikipedia.org/wiki/UTF-8#Description 51860 51861 // 110XXXXX 51862 if (i == 1 && c >> 5 == 0x06) { 51863 this.charLength = 2; 51864 break; 51865 } 51866 51867 // 1110XXXX 51868 if (i <= 2 && c >> 4 == 0x0E) { 51869 this.charLength = 3; 51870 break; 51871 } 51872 51873 // 11110XXX 51874 if (i <= 3 && c >> 3 == 0x1E) { 51875 this.charLength = 4; 51876 break; 51877 } 51878 } 51879 this.charReceived = i; 51880}; 51881 51882StringDecoder.prototype.end = function(buffer) { 51883 var res = ''; 51884 if (buffer && buffer.length) 51885 res = this.write(buffer); 51886 51887 if (this.charReceived) { 51888 var cr = this.charReceived; 51889 var buf = this.charBuffer; 51890 var enc = this.encoding; 51891 res += buf.slice(0, cr).toString(enc); 51892 } 51893 51894 return res; 51895}; 51896 51897function passThroughWrite(buffer) { 51898 return buffer.toString(this.encoding); 51899} 51900 51901function utf16DetectIncompleteChar(buffer) { 51902 this.charReceived = buffer.length % 2; 51903 this.charLength = this.charReceived ? 2 : 0; 51904} 51905 51906function base64DetectIncompleteChar(buffer) { 51907 this.charReceived = buffer.length % 3; 51908 this.charLength = this.charReceived ? 3 : 0; 51909} 51910 51911},{"buffer":86}],239:[function(require,module,exports){ 51912arguments[4][235][0].apply(exports,arguments) 51913},{"_process":84,"dup":235,"readable-stream/transform":217,"util":245,"xtend":251}],240:[function(require,module,exports){ 51914 51915exports = module.exports = trim; 51916 51917function trim(str){ 51918 return str.replace(/^\s*|\s*$/g, ''); 51919} 51920 51921exports.left = function(str){ 51922 return str.replace(/^\s*/, ''); 51923}; 51924 51925exports.right = function(str){ 51926 return str.replace(/\s*$/, ''); 51927}; 51928 51929},{}],241:[function(require,module,exports){ 51930/** 51931 * Export `uid` 51932 */ 51933 51934module.exports = uid; 51935 51936/** 51937 * Create a `uid` 51938 * 51939 * @param {String} len 51940 * @return {String} uid 51941 */ 51942 51943function uid(len) { 51944 len = len || 7; 51945 return Math.random().toString(35).substr(2, len); 51946} 51947 51948},{}
vendor: 2,170 bytes, lines 51948-52028
51948],242:[function(require,module,exports){ 51949(function (global){ 51950 51951/** 51952 * Module exports. 51953 */ 51954 51955module.exports = deprecate; 51956 51957/** 51958 * Mark that a method should not be used. 51959 * Returns a modified function which warns once by default. 51960 * 51961 * If `localStorage.noDeprecation = true` is set, then it is a no-op. 51962 * 51963 * If `localStorage.throwDeprecation = true` is set, then deprecated functions 51964 * will throw an Error when invoked. 51965 * 51966 * If `localStorage.traceDeprecation = true` is set, then deprecated functions 51967 * will invoke `console.trace()` instead of `console.error()`. 51968 * 51969 * @param {Function} fn - the function to deprecate 51970 * @param {String} msg - the string to print to the console when `fn` is invoked 51971 * @returns {Function} a new "deprecated" version of `fn` 51972 * @api public 51973 */ 51974 51975function deprecate (fn, msg) { 51976 if (config('noDeprecation')) { 51977 return fn; 51978 } 51979 51980 var warned = false; 51981 function deprecated() { 51982 if (!warned) { 51983 if (config('throwDeprecation')) { 51984 throw new Error(msg); 51985 } else if (config('traceDeprecation')) { 51986 console.trace(msg); 51987 } else { 51988 console.warn(msg); 51989 } 51990 warned = true; 51991 } 51992 return fn.apply(this, arguments); 51993 } 51994 51995 return deprecated; 51996} 51997 51998/** 51999 * Checks `localStorage` for boolean values for the given `name`. 52000 * 52001 * @param {String} name 52002 * @returns {Boolean} 52003 * @api private 52004 */ 52005 52006function config (name) { 52007 // accessing global.localStorage can trigger a DOMException in sandboxed iframes 52008 try { 52009 if (!global.localStorage) return false; 52010 } catch (_) { 52011 return false; 52012 } 52013 var val = global.localStorage[name]; 52014 if (null == val) return false; 52015 return String(val).toLowerCase() === 'true'; 52016} 52017 52018}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 52019},{}],243:[function(require,module,exports){ 52020arguments[4][165][0].apply(exports,arguments) 52021},{"dup":165}],244:[function(require,module,exports){ 52022module.exports = function isBuffer(arg) { 52023 return arg && typeof arg === 'object' 52024 && typeof arg.copy === 'function' 52025 && typeof arg.fill === 'function' 52026 && typeof arg.readUInt8 === 'function'; 52027} 52028},{}],245
vendor: 15,808 bytes, lines 52028-52618
52028:[function(require,module,exports){ 52029(function (process,global){ 52030// Copyright Joyent, Inc. and other Node contributors. 52031// 52032// Permission is hereby granted, free of charge, to any person obtaining a 52033// copy of this software and associated documentation files (the 52034// "Software"), to deal in the Software without restriction, including 52035// without limitation the rights to use, copy, modify, merge, publish, 52036// distribute, sublicense, and/or sell copies of the Software, and to permit 52037// persons to whom the Software is furnished to do so, subject to the 52038// following conditions: 52039// 52040// The above copyright notice and this permission notice shall be included 52041// in all copies or substantial portions of the Software. 52042// 52043// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 52044// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 52045// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 52046// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 52047// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 52048// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 52049// USE OR OTHER DEALINGS IN THE SOFTWARE. 52050 52051var formatRegExp = /%[sdj%]/g; 52052exports.format = function(f) { 52053 if (!isString(f)) { 52054 var objects = []; 52055 for (var i = 0; i < arguments.length; i++) { 52056 objects.push(inspect(arguments[i])); 52057 } 52058 return objects.join(' '); 52059 } 52060 52061 var i = 1; 52062 var args = arguments; 52063 var len = args.length; 52064 var str = String(f).replace(formatRegExp, function(x) { 52065 if (x === '%%') return '%'; 52066 if (i >= len) return x; 52067 switch (x) { 52068 case '%s': return String(args[i++]); 52069 case '%d': return Number(args[i++]); 52070 case '%j': 52071 try { 52072 return JSON.stringify(args[i++]); 52073 } catch (_) { 52074 return '[Circular]'; 52075 } 52076 default: 52077 return x; 52078 } 52079 }); 52080 for (var x = args[i]; i < len; x = args[++i]) { 52081 if (isNull(x) || !isObject(x)) { 52082 str += ' ' + x; 52083 } else { 52084 str += ' ' + inspect(x); 52085 } 52086 } 52087 return str; 52088}; 52089 52090 52091// Mark that a method should not be used. 52092// Returns a modified function which warns once by default. 52093// If --no-deprecation is set, then it is a no-op. 52094exports.deprecate = function(fn, msg) { 52095 // Allow for deprecating things in the process of starting up. 52096 if (isUndefined(global.process)) { 52097 return function() { 52098 return exports.deprecate(fn, msg).apply(this, arguments); 52099 }; 52100 } 52101 52102 if (process.noDeprecation === true) { 52103 return fn; 52104 } 52105 52106 var warned = false; 52107 function deprecated() { 52108 if (!warned) { 52109 if (process.throwDeprecation) { 52110 throw new Error(msg); 52111 } else if (process.traceDeprecation) { 52112 console.trace(msg); 52113 } else { 52114 console.error(msg); 52115 } 52116 warned = true; 52117 } 52118 return fn.apply(this, arguments); 52119 } 52120 52121 return deprecated; 52122}; 52123 52124 52125var debugs = {}; 52126var debugEnviron; 52127exports.debuglog = function(set) { 52128 if (isUndefined(debugEnviron)) 52129 debugEnviron = process.env.NODE_DEBUG || ''; 52130 set = set.toUpperCase(); 52131 if (!debugs[set]) { 52132 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { 52133 var pid = process.pid; 52134 debugs[set] = function() { 52135 var msg = exports.format.apply(exports, arguments); 52136 console.error('%s %d: %s', set, pid, msg); 52137 }; 52138 } else { 52139 debugs[set] = function() {}; 52140 } 52141 } 52142 return debugs[set]; 52143}; 52144 52145 52146/** 52147 * Echos the value of a value. Trys to print the value out 52148 * in the best way possible given the different types. 52149 * 52150 * @param {Object} obj The object to print out. 52151 * @param {Object} opts Optional options object that alters the output. 52152 */ 52153/* legacy: obj, showHidden, depth, colors*/ 52154function inspect(obj, opts) { 52155 // default options 52156 var ctx = { 52157 seen: [], 52158 stylize: stylizeNoColor 52159 }; 52160 // legacy... 52161 if (arguments.length >= 3) ctx.depth = arguments[2]; 52162 if (arguments.length >= 4) ctx.colors = arguments[3]; 52163 if (isBoolean(opts)) { 52164 // legacy... 52165 ctx.showHidden = opts; 52166 } else if (opts) { 52167 // got an "options" object 52168 exports._extend(ctx, opts); 52169 } 52170 // set default options 52171 if (isUndefined(ctx.showHidden)) ctx.showHidden = false; 52172 if (isUndefined(ctx.depth)) ctx.depth = 2; 52173 if (isUndefined(ctx.colors)) ctx.colors = false; 52174 if (isUndefined(ctx.customInspect)) ctx.customInspect = true; 52175 if (ctx.colors) ctx.stylize = stylizeWithColor; 52176 return formatValue(ctx, obj, ctx.depth); 52177} 52178exports.inspect = inspect; 52179 52180 52181// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics 52182inspect.colors = { 52183 'bold' : [1, 22], 52184 'italic' : [3, 23], 52185 'underline' : [4, 24], 52186 'inverse' : [7, 27], 52187 'white' : [37, 39], 52188 'grey' : [90, 39], 52189 'black' : [30, 39], 52190 'blue' : [34, 39], 52191 'cyan' : [36, 39], 52192 'green' : [32, 39], 52193 'magenta' : [35, 39], 52194 'red' : [31, 39], 52195 'yellow' : [33, 39] 52196}; 52197 52198// Don't use 'blue' not visible on cmd.exe 52199inspect.styles = { 52200 'special': 'cyan', 52201 'number': 'yellow', 52202 'boolean': 'yellow', 52203 'undefined': 'grey', 52204 'null': 'bold', 52205 'string': 'green', 52206 'date': 'magenta', 52207 // "name": intentionally not styling 52208 'regexp': 'red' 52209}; 52210 52211 52212function stylizeWithColor(str, styleType) { 52213 var style = inspect.styles[styleType]; 52214 52215 if (style) { 52216 return '\u001b[' + inspect.colors[style][0] + 'm' + str + 52217 '\u001b[' + inspect.colors[style][1] + 'm'; 52218 } else { 52219 return str; 52220 } 52221} 52222 52223 52224function stylizeNoColor(str, styleType) { 52225 return str; 52226} 52227 52228 52229function arrayToHash(array) { 52230 var hash = {}; 52231 52232 array.forEach(function(val, idx) { 52233 hash[val] = true; 52234 }); 52235 52236 return hash; 52237} 52238 52239 52240function formatValue(ctx, value, recurseTimes) { 52241 // Provide a hook for user-specified inspect functions. 52242 // Check that value is an object with an inspect function on it 52243 if (ctx.customInspect && 52244 value && 52245 isFunction(value.inspect) && 52246 // Filter out the util module, it's inspect function is special 52247 value.inspect !== exports.inspect && 52248 // Also filter out any prototype objects using the circular check. 52249 !(value.constructor && value.constructor.prototype === value)) { 52250 var ret = value.inspect(recurseTimes, ctx); 52251 if (!isString(ret)) { 52252 ret = formatValue(ctx, ret, recurseTimes); 52253 } 52254 return ret; 52255 } 52256 52257 // Primitive types cannot have properties 52258 var primitive = formatPrimitive(ctx, value); 52259 if (primitive) { 52260 return primitive; 52261 } 52262 52263 // Look up the keys of the object. 52264 var keys = Object.keys(value); 52265 var visibleKeys = arrayToHash(keys); 52266 52267 if (ctx.showHidden) { 52268 keys = Object.getOwnPropertyNames(value); 52269 } 52270 52271 // IE doesn't make error fields non-enumerable 52272 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx 52273 if (isError(value) 52274 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { 52275 return formatError(value); 52276 } 52277 52278 // Some type of object without properties can be shortcutted. 52279 if (keys.length === 0) { 52280 if (isFunction(value)) { 52281 var name = value.name ? ': ' + value.name : ''; 52282 return ctx.stylize('[Function' + name + ']', 'special'); 52283 } 52284 if (isRegExp(value)) { 52285 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); 52286 } 52287 if (isDate(value)) { 52288 return ctx.stylize(Date.prototype.toString.call(value), 'date'); 52289 } 52290 if (isError(value)) { 52291 return formatError(value); 52292 } 52293 } 52294 52295 var base = '', array = false, braces = ['{', '}']; 52296 52297 // Make Array say that they are Array 52298 if (isArray(value)) { 52299 array = true; 52300 braces = ['[', ']']; 52301 } 52302 52303 // Make functions say that they are functions 52304 if (isFunction(value)) { 52305 var n = value.name ? ': ' + value.name : ''; 52306 base = ' [Function' + n + ']'; 52307 } 52308 52309 // Make RegExps say that they are RegExps 52310 if (isRegExp(value)) { 52311 base = ' ' + RegExp.prototype.toString.call(value); 52312 } 52313 52314 // Make dates with properties first say the date 52315 if (isDate(value)) { 52316 base = ' ' + Date.prototype.toUTCString.call(value); 52317 } 52318 52319 // Make error with message first say the error 52320 if (isError(value)) { 52321 base = ' ' + formatError(value); 52322 } 52323 52324 if (keys.length === 0 && (!array || value.length == 0)) { 52325 return braces[0] + base + braces[1]; 52326 } 52327 52328 if (recurseTimes < 0) { 52329 if (isRegExp(value)) { 52330 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); 52331 } else { 52332 return ctx.stylize('[Object]', 'special'); 52333 } 52334 } 52335 52336 ctx.seen.push(value); 52337 52338 var output; 52339 if (array) { 52340 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); 52341 } else { 52342 output = keys.map(function(key) { 52343 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); 52344 }); 52345 } 52346 52347 ctx.seen.pop(); 52348 52349 return reduceToSingleString(output, base, braces); 52350} 52351 52352 52353function formatPrimitive(ctx, value) { 52354 if (isUndefined(value)) 52355 return ctx.stylize('undefined', 'undefined'); 52356 if (isString(value)) { 52357 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') 52358 .replace(/'/g, "\\'") 52359 .replace(/\\"/g, '"') + '\''; 52360 return ctx.stylize(simple, 'string'); 52361 } 52362 if (isNumber(value)) 52363 return ctx.stylize('' + value, 'number'); 52364 if (isBoolean(value)) 52365 return ctx.stylize('' + value, 'boolean'); 52366 // For some reason typeof null is "object", so special case here. 52367 if (isNull(value)) 52368 return ctx.stylize('null', 'null'); 52369} 52370 52371 52372function formatError(value) { 52373 return '[' + Error.prototype.toString.call(value) + ']'; 52374} 52375 52376 52377function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { 52378 var output = []; 52379 for (var i = 0, l = value.length; i < l; ++i) { 52380 if (hasOwnProperty(value, String(i))) { 52381 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, 52382 String(i), true)); 52383 } else { 52384 output.push(''); 52385 } 52386 } 52387 keys.forEach(function(key) { 52388 if (!key.match(/^\d+$/)) { 52389 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, 52390 key, true)); 52391 } 52392 }); 52393 return output; 52394} 52395 52396 52397function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { 52398 var name, str, desc; 52399 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; 52400 if (desc.get) { 52401 if (desc.set) { 52402 str = ctx.stylize('[Getter/Setter]', 'special'); 52403 } else { 52404 str = ctx.stylize('[Getter]', 'special'); 52405 } 52406 } else { 52407 if (desc.set) { 52408 str = ctx.stylize('[Setter]', 'special'); 52409 } 52410 } 52411 if (!hasOwnProperty(visibleKeys, key)) { 52412 name = '[' + key + ']'; 52413 } 52414 if (!str) { 52415 if (ctx.seen.indexOf(desc.value) < 0) { 52416 if (isNull(recurseTimes)) { 52417 str = formatValue(ctx, desc.value, null); 52418 } else { 52419 str = formatValue(ctx, desc.value, recurseTimes - 1); 52420 } 52421 if (str.indexOf('\n') > -1) { 52422 if (array) { 52423 str = str.split('\n').map(function(line) { 52424 return ' ' + line; 52425 }).join('\n').substr(2); 52426 } else { 52427 str = '\n' + str.split('\n').map(function(line) { 52428 return ' ' + line; 52429 }).join('\n'); 52430 } 52431 } 52432 } else { 52433 str = ctx.stylize('[Circular]', 'special'); 52434 } 52435 } 52436 if (isUndefined(name)) { 52437 if (array && key.match(/^\d+$/)) { 52438 return str; 52439 } 52440 name = JSON.stringify('' + key); 52441 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { 52442 name = name.substr(1, name.length - 2); 52443 name = ctx.stylize(name, 'name'); 52444 } else { 52445 name = name.replace(/'/g, "\\'") 52446 .replace(/\\"/g, '"') 52447 .replace(/(^"|"$)/g, "'"); 52448 name = ctx.stylize(name, 'string'); 52449 } 52450 } 52451 52452 return name + ': ' + str; 52453} 52454 52455 52456function reduceToSingleString(output, base, braces) { 52457 var numLinesEst = 0; 52458 var length = output.reduce(function(prev, cur) { 52459 numLinesEst++; 52460 if (cur.indexOf('\n') >= 0) numLinesEst++; 52461 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; 52462 }, 0); 52463 52464 if (length > 60) { 52465 return braces[0] + 52466 (base === '' ? '' : base + '\n ') + 52467 ' ' + 52468 output.join(',\n ') + 52469 ' ' + 52470 braces[1]; 52471 } 52472 52473 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; 52474} 52475 52476 52477// NOTE: These type checking functions intentionally don't use `instanceof` 52478// because it is fragile and can be easily faked with `Object.create()`. 52479function isArray(ar) { 52480 return Array.isArray(ar); 52481} 52482exports.isArray = isArray; 52483 52484function isBoolean(arg) { 52485 return typeof arg === 'boolean'; 52486} 52487exports.isBoolean = isBoolean; 52488 52489function isNull(arg) { 52490 return arg === null; 52491} 52492exports.isNull = isNull; 52493 52494function isNullOrUndefined(arg) { 52495 return arg == null; 52496} 52497exports.isNullOrUndefined = isNullOrUndefined; 52498 52499function isNumber(arg) { 52500 return typeof arg === 'number'; 52501} 52502exports.isNumber = isNumber; 52503 52504function isString(arg) { 52505 return typeof arg === 'string'; 52506} 52507exports.isString = isString; 52508 52509function isSymbol(arg) { 52510 return typeof arg === 'symbol'; 52511} 52512exports.isSymbol = isSymbol; 52513 52514function isUndefined(arg) { 52515 return arg === void 0; 52516} 52517exports.isUndefined = isUndefined; 52518 52519function isRegExp(re) { 52520 return isObject(re) && objectToString(re) === '[object RegExp]'; 52521} 52522exports.isRegExp = isRegExp; 52523 52524function isObject(arg) { 52525 return typeof arg === 'object' && arg !== null; 52526} 52527exports.isObject = isObject; 52528 52529function isDate(d) { 52530 return isObject(d) && objectToString(d) === '[object Date]'; 52531} 52532exports.isDate = isDate; 52533 52534function isError(e) { 52535 return isObject(e) && 52536 (objectToString(e) === '[object Error]' || e instanceof Error); 52537} 52538exports.isError = isError; 52539 52540function isFunction(arg) { 52541 return typeof arg === 'function'; 52542} 52543exports.isFunction = isFunction; 52544 52545function isPrimitive(arg) { 52546 return arg === null || 52547 typeof arg === 'boolean' || 52548 typeof arg === 'number' || 52549 typeof arg === 'string' || 52550 typeof arg === 'symbol' || // ES6 symbol 52551 typeof arg === 'undefined'; 52552} 52553exports.isPrimitive = isPrimitive; 52554 52555exports.isBuffer = require('./support/isBuffer'); 52556 52557function objectToString(o) { 52558 return Object.prototype.toString.call(o); 52559} 52560 52561 52562function pad(n) { 52563 return n < 10 ? '0' + n.toString(10) : n.toString(10); 52564} 52565 52566 52567var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 52568 'Oct', 'Nov', 'Dec']; 52569 52570// 26 Feb 16:19:34 52571function timestamp() { 52572 var d = new Date(); 52573 var time = [pad(d.getHours()), 52574 pad(d.getMinutes()), 52575 pad(d.getSeconds())].join(':'); 52576 return [d.getDate(), months[d.getMonth()], time].join(' '); 52577} 52578 52579 52580// log is just a thin wrapper to console.log that prepends a timestamp 52581exports.log = function() { 52582 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); 52583}; 52584 52585 52586/** 52587 * Inherit the prototype methods from one constructor into another. 52588 * 52589 * The Function.prototype.inherits from lang.js rewritten as a standalone 52590 * function (not on Function.prototype). NOTE: If this file is to be loaded 52591 * during bootstrapping this function needs to be rewritten using some native 52592 * functions as prototype setup using normal JavaScript does not work as 52593 * expected during bootstrapping (see mirror.js in r114903). 52594 * 52595 * @param {function} ctor Constructor function which needs to inherit the 52596 * prototype. 52597 * @param {function} superCtor Constructor function to inherit prototype from. 52598 */ 52599exports.inherits = require('inherits'); 52600 52601exports._extend = function(origin, add) { 52602 // Don't do anything if add isn't an object 52603 if (!add || !isObject(add)) return origin; 52604 52605 var keys = Object.keys(add); 52606 var i = keys.length; 52607 while (i--) { 52608 origin[keys[i]] = add[keys[i]]; 52609 } 52610 return origin; 52611}; 52612 52613function hasOwnProperty(obj, prop) { 52614 return Object.prototype.hasOwnProperty.call(obj, prop); 52615} 52616 52617}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) 52618},{"./support/isBuffer":
52618244,"_process":84,"inherits":243}],246:[function(require,module,exports){ 52619var assert = require('assert') 52620var trie = require('./trie') 52621 52622module.exports = Wayfarer 52623 52624// create a router 52625// str -> obj 52626function Wayfarer (dft) { 52627 if (!(this instanceof Wayfarer)) return new Wayfarer(dft) 52628 52629 var _default = (dft || '').replace(/^\//, '') 52630 var _trie = trie() 52631 52632 emit._trie = _trie 52633 emit.emit = emit 52634 emit.on = on 52635 emit._wayfarer = true 52636 52637 return emit 52638 52639 // define a route 52640 // (str, fn) -> obj 52641 function on (route, cb) { 52642 assert.equal(typeof route, 'string') 52643 assert.equal(typeof cb, 'function') 52644 52645 route = route || '/' 52646 52647 if (cb && cb._wayfarer && cb._trie) { 52648 _trie.mount(route, cb._trie.trie) 52649 } else { 52650 var node = _trie.create(route) 52651 node.cb = cb 52652 } 52653 52654 return emit 52655 } 52656 52657 // match and call a route 52658 // (str, obj?) -> null 52659 function emit (route) { 52660 assert.notEqual(route, undefined, "'route' must be defined") 52661 var args = new Array(arguments.length) 52662 for (var i = 1; i < args.length; i++) { 52663 args[i] = arguments[i] 52664 } 52665 52666 var node = _trie.match(route) 52667 if (node && node.cb) { 52668 args[0] = node.params 52669 return node.cb.apply(null, args) 52670 } 52671 52672 var dft = _trie.match(_default) 52673 if (dft && dft.cb) { 52674 args[0] = dft.params 52675 return dft.cb.apply(null, args) 52676 } 52677 52678 throw new Error("route '" + route + "' did not match") 52679 } 52680} 52681 52682},{"./trie":247,"assert":78}],247:[function(require,module,exports){ 52683var mutate = require('xtend/mutable') 52684var assert = require('assert') 52685var xtend = require('xtend') 52686 52687module.exports = Trie 52688 52689// create a new trie 52690// null -> obj 52691function Trie () { 52692 if (!(this instanceof Trie)) return new Trie() 52693 this.trie = { nodes: {} } 52694} 52695 52696// create a node on the trie at route 52697// and return a node 52698// str -> null 52699Trie.prototype.create = function (route) { 52700 assert.equal(typeof route, 'string', 'route should be a string') 52701 // strip leading '/' and split routes 52702 var routes = route.replace(/^\//, '').split('/') 52703 return (function createNode (index, trie) { 52704 var thisRoute = routes[index] 52705 52706 if (thisRoute === undefined) return trie 52707 52708 var node = null 52709 if (/^:|^\*/.test(thisRoute)) { 52710 // if node is a name match, set name and append to ':' node 52711 if (!trie.nodes['$$']) { 52712 node = { nodes: {} } 52713 trie.nodes['$$'] = node 52714 } else { 52715 node = trie.nodes['$$'] 52716 } 52717 52718 if (thisRoute[0] === '*') { 52719 trie.wildcard = true 52720 } 52721 52722 trie.name = thisRoute.replace(/^:|^\*/, '') 52723 } else if (!trie.nodes[thisRoute]) { 52724 node = { nodes: {} } 52725 trie.nodes[thisRoute] = node 52726 } else { 52727 node = trie.nodes[thisRoute] 52728 } 52729 52730 // we must recurse deeper 52731 return createNode(index + 1, node) 52732 })(0, this.trie) 52733} 52734 52735// match a route on the trie 52736// and return the node 52737// str -> obj 52738Trie.prototype.match = function (route) { 52739 assert.equal(typeof route, 'string', 'route should be a string') 52740 52741 var routes = route.replace(/^\//, '').split('/') 52742 var params = {} 52743 52744 var node = (function search (index, trie) { 52745 // either there's no match, or we're done searching 52746 if (trie === undefined) return undefined 52747 var thisRoute = routes[index] 52748 if (thisRoute === undefined) return trie 52749 52750 if (trie.nodes[thisRoute]) { 52751 // match regular routes first 52752 return search(index + 1, trie.nodes[thisRoute]) 52753 } else if (trie.wildcard) { 52754 // match wildcards 52755 params['wildcard'] = decodeURIComponent(routes.slice(index).join('/')) 52756 // return early, or else search may keep recursing through the wildcard 52757 return trie.nodes['$$'] 52758 } else if (trie.name) { 52759 // match named routes 52760 params[trie.name] = decodeURIComponent(thisRoute) 52761 return search(index + 1, trie.nodes['$$']) 52762 } else { 52763 // no matches found 52764 return search(index + 1) 52765 } 52766 })(0, this.trie) 52767 52768 if (!node) return undefined 52769 node = xtend(node) 52770 node.params = params 52771 return node 52772} 52773 52774// mount a trie onto a node at route 52775// (str, obj) -> null 52776Trie.prototype.mount = function (route, trie) { 52777 assert.equal(typeof route, 'string', 'route should be a string') 52778 assert.equal(typeof trie, 'object', 'trie should be a object') 52779 52780 var split = route.replace(/^\//, '').split('/') 52781 var node = null 52782 var key = null 52783 52784 if (split.length === 1) { 52785 key = split[0] 52786 node = this.create(key) 52787 } else { 52788 var headArr = split.splice(0, split.length - 1) 52789 var head = headArr.join('/') 52790 key = split[0] 52791 node = this.create(head) 52792 } 52793 52794 mutate(node.nodes, trie.nodes) 52795 if (trie.name) node.name = trie.name 52796 52797 // delegate properties from '/' to the new node 52798 // '/' cannot be reached once mounted 52799 if (node.nodes['']) {
52800 Object.keys(node.nodes['']).forEach(function (key) { 52801 if (key === 'nodes') return 52802 node[key] = node.nodes[''][key] 52803 }) 52804 mutate(node.nodes, node.nodes[''].nodes) 52805 delete node.nodes[''].nodes 52806 } 52807} 52808 52809},{"assert":78,"xtend":251,"xtend/mutable":252}],248:[function(require,module,exports){ 52810var assert = require('assert') 52811 52812module.exports = walk 52813 52814// walk a wayfarer trie 52815// (obj, fn) -> null 52816function walk (router, transform) { 52817 assert.equal(typeof router, 'function', 'wayfarer.walk: router should be an function') 52818 assert.equal(typeof transform, 'function', 'wayfarer.walk: transform should be a function') 52819 52820 var trie = router._trie 52821 assert.equal(typeof trie, 'object', 'wayfarer.walk: trie should be an object') 52822 52823 // (str, obj) -> null 52824 ;(function walk (route, trie) { 52825 if (trie.cb) { 52826 trie.cb = transform(route, trie.cb) 52827 } 52828 52829 if (trie.nodes) { 52830 var nodes = trie.nodes 52831 Object.keys(nodes).forEach(function (key) { 52832 var node = nodes[key] 52833 var newRoute = (key === '$$') 52834 ? route + '/:' + trie.name 52835 : route + '/' + key 52836 walk(newRoute, node) 52837 }) 52838 } 52839 })('', trie.trie) 52840} 52841 52842},{"assert":78}],249:[function(require,module,exports){ 52843// Returns a wrapper function that returns a wrapped callback 52844// The wrapper function should do some stuff, and return a 52845// presumably different callback function. 52846// This makes sure that own properties are retained, so that 52847// decorations and such are not lost along the way. 52848module.exports = wrappy 52849function wrappy (fn, cb) { 52850 if (fn && cb) return wrappy(fn)(cb) 52851 52852 if (typeof fn !== 'function') 52853 throw new TypeError('need wrapper function') 52854 52855 Object.keys(fn).forEach(function (k) { 52856 wrapper[k] = fn[k] 52857 }) 52858 52859 return wrapper 52860 52861 function wrapper() { 52862 var args = new Array(arguments.length) 52863 for (var i = 0; i < args.length; i++) { 52864 args[i] = arguments[i] 52865 } 52866 var ret = fn.apply(this, args) 52867 var cb = args[args.length-1] 52868 if (typeof ret === 'function' && ret !== cb) { 52869 Object.keys(cb).forEach(function (k) { 52870 ret[k] = cb[k] 52871 }) 52872 } 52873 return ret 52874 } 52875} 52876 52877},{}],250:[function(require,module,exports){ 52878"use strict"; 52879var window = require("global/window") 52880var isFunction = require("is-function") 52881var parseHeaders = require("parse-headers") 52882var xtend = require("xtend") 52883 52884module.exports = createXHR 52885createXHR.XMLHttpRequest = window.XMLHttpRequest || noop 52886createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest 52887 52888forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) { 52889 createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) { 52890 options = initParams(uri, options, callback) 52891 options.method = method.toUpperCase() 52892 return _createXHR(options) 52893 } 52894}) 52895 52896function forEachArray(array, iterator) { 52897 for (var i = 0; i < array.length; i++) { 52898 iterator(array[i]) 52899 } 52900} 52901 52902function isEmpty(obj){ 52903 for(var i in obj){ 52904 if(obj.hasOwnProperty(i)) return false 52905 } 52906 return true 52907} 52908 52909function initParams(uri, options, callback) { 52910 var params = uri 52911 52912 if (isFunction(options)) { 52913 callback = options 52914 if (typeof uri === "string") { 52915 params = {uri:uri} 52916 } 52917 } else { 52918 params = xtend(options, {uri: uri}) 52919 } 52920 52921 params.callback = callback 52922 return params 52923} 52924 52925function createXHR(uri, options, callback) { 52926 options = initParams(uri, options, callback) 52927 return _createXHR(options) 52928} 52929 52930function _createXHR(options) { 52931 if(typeof options.callback === "undefined"){ 52932 throw new Error("callback argument missing") 52933 } 52934 52935 var called = false 52936 var callback = function cbOnce(err, response, body){ 52937 if(!called){ 52938 called = true 52939 options.callback(err, response, body) 52940 } 52941 } 52942 52943 function readystatechange() { 52944 if (xhr.readyState === 4) { 52945 setTimeout(loadFunc, 0) 52946 } 52947 } 52948 52949 function getBody() { 52950 // Chrome with requestType=blob throws errors arround when even testing access to responseText 52951 var body = undefined 52952 52953 if (xhr.response) { 52954 body = xhr.response 52955 } else { 52956 body = xhr.responseText || getXml(xhr) 52957 } 52958 52959 if (isJson) { 52960 try { 52961 body = JSON.parse(body) 52962 } catch (e) {} 52963 } 52964 52965 return body 52966 } 52967 52968 function errorFunc(evt) { 52969 clearTimeout(timeoutTimer) 52970 if(!(evt instanceof Error)){ 52971 evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) 52972 } 52973 evt.statusCode = 0 52974 return callback(evt, failureResponse) 52975 } 52976 52977 // will load the data & process the response in a special response object 52978 function loadFunc() { 52979 if (aborted) return 52980 var status 52981 clearTimeout(timeoutTimer) 52982 if(options.useXDR && xhr.status===undefined) { 52983 //IE8 CORS GET successful response doesn't have a status field, but body is fine 52984 status = 200 52985 } else { 52986 status = (xhr.status === 1223 ? 204 : xhr.status) 52987 } 52988 var response = failureResponse 52989 var err = null 52990 52991 if (status !== 0){ 52992 response = { 52993 body: getBody(), 52994 statusCode: status, 52995 method: method, 52996 headers: {},
vendor: 4,942 bytes, lines 52997-53161
52997 url: uri, 52998 rawRequest: xhr 52999 } 53000 if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE 53001 response.headers = parseHeaders(xhr.getAllResponseHeaders()) 53002 } 53003 } else { 53004 err = new Error("Internal XMLHttpRequest Error") 53005 } 53006 return callback(err, response, response.body) 53007 } 53008 53009 var xhr = options.xhr || null 53010 53011 if (!xhr) { 53012 if (options.cors || options.useXDR) { 53013 xhr = new createXHR.XDomainRequest() 53014 }else{ 53015 xhr = new createXHR.XMLHttpRequest() 53016 } 53017 } 53018 53019 var key 53020 var aborted 53021 var uri = xhr.url = options.uri || options.url 53022 var method = xhr.method = options.method || "GET" 53023 var body = options.body || options.data 53024 var headers = xhr.headers = options.headers || {} 53025 var sync = !!options.sync 53026 var isJson = false 53027 var timeoutTimer 53028 var failureResponse = { 53029 body: undefined, 53030 headers: {}, 53031 statusCode: 0, 53032 method: method, 53033 url: uri, 53034 rawRequest: xhr 53035 } 53036 53037 if ("json" in options && options.json !== false) { 53038 isJson = true 53039 headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user 53040 if (method !== "GET" && method !== "HEAD") { 53041 headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user 53042 body = JSON.stringify(options.json === true ? body : options.json) 53043 } 53044 } 53045 53046 xhr.onreadystatechange = readystatechange 53047 xhr.onload = loadFunc 53048 xhr.onerror = errorFunc 53049 // IE9 must have onprogress be set to a unique function. 53050 xhr.onprogress = function () { 53051 // IE must die 53052 } 53053 xhr.onabort = function(){ 53054 aborted = true; 53055 } 53056 xhr.ontimeout = errorFunc 53057 xhr.open(method, uri, !sync, options.username, options.password) 53058 //has to be after open 53059 if(!sync) { 53060 xhr.withCredentials = !!options.withCredentials 53061 } 53062 // Cannot set timeout with sync request 53063 // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly 53064 // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent 53065 if (!sync && options.timeout > 0 ) { 53066 timeoutTimer = setTimeout(function(){ 53067 if (aborted) return 53068 aborted = true//IE9 may still call readystatechange 53069 xhr.abort("timeout") 53070 var e = new Error("XMLHttpRequest timeout") 53071 e.code = "ETIMEDOUT" 53072 errorFunc(e) 53073 }, options.timeout ) 53074 } 53075 53076 if (xhr.setRequestHeader) { 53077 for(key in headers){ 53078 if(headers.hasOwnProperty(key)){ 53079 xhr.setRequestHeader(key, headers[key]) 53080 } 53081 } 53082 } else if (options.headers && !isEmpty(options.headers)) { 53083 throw new Error("Headers cannot be set on an XDomainRequest object") 53084 } 53085 53086 if ("responseType" in options) { 53087 xhr.responseType = options.responseType 53088 } 53089 53090 if ("beforeSend" in options && 53091 typeof options.beforeSend === "function" 53092 ) { 53093 options.beforeSend(xhr) 53094 } 53095 53096 // Microsoft Edge browser sends "undefined" when send is called with undefined value. 53097 // XMLHttpRequest spec says to pass null as body to indicate no body 53098 // See https://github.com/naugtur/xhr/issues/100. 53099 xhr.send(body || null) 53100 53101 return xhr 53102 53103 53104} 53105 53106function getXml(xhr) { 53107 if (xhr.responseType === "document") { 53108 return xhr.responseXML 53109 } 53110 var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror" 53111 if (xhr.responseType === "" && !firefoxBugTakenEffect) { 53112 return xhr.responseXML 53113 } 53114 53115 return null 53116} 53117 53118function noop() {} 53119 53120},{"global/window":158,"is-function":169,"parse-headers":178,"xtend":251}],251:[function(require,module,exports){ 53121module.exports = extend 53122 53123var hasOwnProperty = Object.prototype.hasOwnProperty; 53124 53125function extend() { 53126 var target = {} 53127 53128 for (var i = 0; i < arguments.length; i++) { 53129 var source = arguments[i] 53130 53131 for (var key in source) { 53132 if (hasOwnProperty.call(source, key)) { 53133 target[key] = source[key] 53134 } 53135 } 53136 } 53137 53138 return target 53139} 53140 53141},{}],252:[function(require,module,exports){ 53142module.exports = extend 53143 53144var hasOwnProperty = Object.prototype.hasOwnProperty; 53145 53146function extend(target) { 53147 for (var i = 1; i < arguments.length; i++) { 53148 var source = arguments[i] 53149 53150 for (var key in source) { 53151 if (hasOwnProperty.call(source, key)) { 53152 target[key] = source[key] 53153 } 53154 } 53155 } 53156 53157 return target 53158} 53159 53160},{}],253:[function(require,module,exports){ 53161var bel = require('bel') // turns template tag into DOM elements
53162var morphdom = require('morphdom') // efficiently diffs + morphs two DOM elements 53163var defaultEvents = require('./update-events.js') // default events to be copied when dom elements update 53164 53165module.exports = bel 53166 53167// TODO move this + defaultEvents to a new module once we receive more feedback 53168module.exports.update = function (fromNode, toNode, opts) { 53169 if (!opts) opts = {} 53170 if (opts.events !== false) { 53171 if (!opts.onBeforeElUpdated) opts.onBeforeElUpdated = copier 53172 } 53173 53174 return morphdom(fromNode, toNode, opts) 53175 53176 // morphdom only copies attributes. we decided we also wanted to copy events 53177 // that can be set via attributes 53178 function copier (f, t) { 53179 // copy events: 53180 var events = opts.events || defaultEvents 53181 for (var i = 0; i < events.length; i++) { 53182 var ev = events[i] 53183 if (t[ev]) { // if new element has a whitelisted attribute 53184 f[ev] = t[ev] // update existing element 53185 } else if (f[ev]) { // if existing element has it and new one doesnt 53186 f[ev] = undefined // remove it from existing element 53187 } 53188 } 53189 var oldValue = f.value 53190 var newValue = t.value 53191 // copy values for form elements 53192 if ((f.nodeName === 'INPUT' && f.type !== 'file') || f.nodeName === 'SELECT') { 53193 if (!newValue) { 53194 t.value = f.value 53195 } else if (newValue !== oldValue) { 53196 f.value = newValue 53197 } 53198 } else if (f.nodeName === 'TEXTAREA') { 53199 if (t.getAttribute('value') === null) f.value = t.value 53200 } 53201 } 53202} 53203 53204},{"./update-events.js":254,"bel":82,"morphdom":172}],254:[function(require,module,exports){ 53205module.exports = [ 53206 // attribute events (can be set with attributes) 53207 'onclick', 53208 'ondblclick', 53209 'onmousedown', 53210 'onmouseup', 53211 'onmouseover', 53212 'onmousemove', 53213 'onmouseout', 53214 'ondragstart', 53215 'ondrag', 53216 'ondragenter', 53217 'ondragleave', 53218 'ondragover', 53219 'ondrop', 53220 'ondragend', 53221 'onkeydown', 53222 'onkeypress', 53223 'onkeyup', 53224 'onunload', 53225 'onabort', 53226 'onerror', 53227 'onresize', 53228 'onscroll', 53229 'onselect', 53230 'onchange', 53231 'onsubmit', 53232 'onreset', 53233 'onfocus', 53234 'onblur', 53235 'oninput', 53236 // other common events 53237 'oncontextmenu', 53238 'onfocusin', 53239 'onfocusout' 53240] 53241 53242},{}],255:[function(require,module,exports){ 53243module.exports = function yoyoifyAppendChild (el, childs) { 53244 for (var i = 0; i < childs.length; i++) { 53245 var node = childs[i] 53246 if (Array.isArray(node)) { 53247 yoyoifyAppendChild(el, node) 53248 continue 53249 } 53250 if (typeof node === 'number' || 53251 typeof node === 'boolean' || 53252 node instanceof Date || 53253 node instanceof RegExp) { 53254 node = node.toString() 53255 } 53256 if (typeof node === 'string') { 53257 if (/^[\n\r\s]+$/.test(node)) continue 53258 if (el.lastChild && el.lastChild.nodeName === '#text') { 53259 el.lastChild.nodeValue += node 53260 continue 53261 } 53262 node = document.createTextNode(node) 53263 } 53264 if (node && node.nodeType) { 53265 el.appendChild(node) 53266 } 53267 } 53268} 53269 53270},{}],256:[function(require,module,exports){ 53271module.exports = function yoyoifySetAttribute (el, attr, value) { 53272 if (typeof attr === 'object') { 53273 for (var i in attr) { 53274 if (attr.hasOwnProperty(i)) { 53275 yoyoifySetAttribute(el, i, attr[i]) 53276 } 53277 } 53278 return 53279 } 53280 if (!attr) return 53281 if (attr === 'className') attr = 'class' 53282 if (attr === 'htmlFor') attr = 'for' 53283 if (attr.slice(0, 2) === 'on') { 53284 el[attr] = value 53285 } else { 53286 // assume a boolean attribute if the value === true 53287 // no need to do typeof because "false" would've caused an early return 53288 if (value === true) value = attr 53289 el.setAttribute(attr, value) 53290 } 53291} 53292 53293},{}],257:[function(require,module,exports){ 53294'use strict'; 53295 53296var _templateObject = _taggedTemplateLiteral([''], ['']); 53297 53298function _taggedTemplateLiteral(strings, raw) { return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } 53299 53300var html = {}; 53301var sf = 0; 53302var _ = require('lodash'); 53303var team = require('./team'); 53304 53305var prefix = (require('sheetify/insert')("._44606cd3 {\n color: #404040;\n height: 100%;\n width: 100%;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n overflow-x: hidden;\n }
53305\n \n ._44606cd3 div {\n align-items: center;\n margin-bottom: 25px;\n } \n \n ._44606cd3 > .logo {\n width: 100%;\n height: 15%;\n min-height: 250px;\n background-image: url('assets/icons/robotopia.svg');\n background-size: contain;\n background-position: center;\n background-repeat: no-repeat;\n margin-bottom: 0;\n }\n\n ._44606cd3 > .people > .person {\n display: flex;\n flex-direction: row;\n width: 70%;\n margin: 0 auto;\n margin-bottom: 20px;\n }\n \n .person > .personImg {\n width: 100px;\n border-radius: 10px;\n margin-right: 20px;\n }\n \n .person > .personInfo {\n display: flex;\n flex-direction: column;\n align-items: flex-start;\n width: 100%;\n margin-bottom: 0;\n }\n \n .personInfo h2 {\n margin:0;\n margin-bottom: 7px;\n padding: 0;\n }\n \n .personInfo h4 {\n color: #808080;\n margin:0;\n margin-bottom: 10px;\n padding: 0;\n } \n \n .person .links {\n display: flex;\n flex-direction: row;\n margin-bottom: 0;\n }\n \n .links > a {\n color: #404040;\n text-decoration: none;\n margin-right: 25px;\n }\n \n .links > a:hover {\n color: #dddddd;\n }\n \n .links > .githubLink:before {\n background-image: url('assets/icons/github.png');\n background-size: contain;\n background-position: center;\n background-repeat: no-repeat;\n content: '';\n width: 25px;\n height: 25px;\n padding-left: 30px;\n }\n \n .personInfo > p {\n color: #808080;\n }") || true) && "_44606cd3"; 53306 53307var creditsView = function creditsView(state, prev, send) { 53308 return function () { 53309 53310 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53311 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 53312 var bel2 = document.createElement("div"); 53313 bel2.setAttribute("class", arguments[1]); 53314 var bel0 = document.createElement("div"); 53315 bel0.setAttribute("class", "logo"); 53316 var bel1 = document.createElement("div"); 53317 bel1.setAttribute("class", "people"); 53318 ac(bel1, ["\n ", arguments[0], "\n "]); 53319 ac(bel2, ["\n ", bel0, "\n ", bel1, "\n "]); 53320 return bel2; 53321 }(_.map(team, function (person) { 53322 return personDiv(person); 53323 }), prefix); 53324}; 53325 53326function personDiv(_ref) { 53327 var name = _ref.name, 53328 role = _ref.role, 53329 img = _ref.img, 53330 github = _ref.github, 53331 homepage = _ref.homepage, 53332 desc = _ref.desc; 53333 53334 var githubName = github.split('/').pop(); 53335 53336 return function () { 53337 53338 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53339 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 53340 var bel7 = document.createElement("div"); 53341 bel7.setAttribute("class", "person"); 53342 var bel0 = document.createElement("img"); 53343 bel0.setAttribute("src", arguments[0]); 53344 bel0.setAttribute("class", "personImg"); 53345 var bel6 = document.createElement("div"); 53346 bel6.setAttribute("class", "personInfo"); 53347 var bel1 = document.createElement("h2"); 53348 ac(bel1, [arguments[1]]); 53349 var bel2 = document.createElement("h4"); 53350 ac(bel2, [arguments[2]]); 53351 var bel4 = document.createElement("div"); 53352 bel4.setAttribute("class", "links"); 53353 var bel3 = document.createElement("a"); 53354 bel3.setAttribute("href", arguments[3]); 53355 bel3.setAttribute("class", "githubLink"); 53356 ac(bel3, [arguments[4]]); 53357 ac(bel4, ["\n ", bel3, "\n ", arguments[5], "\n "]); 53358 var bel5 = document.createElement("p"); 53359 ac(bel5, [arguments[6]]); 53360 ac(bel6, ["\n ", bel1, "\n ", bel2, "\n ", bel4, "\n ", bel5, "\n "]); 53361 ac(bel7, ["\n ", bel0, "\n ", bel6, "\n "]); 53362 return bel7; 53363 }(img, name, role, github, githubName, homepage ? function () { 53364 53365 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53366 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 53367 var bel0 = document.createElement("a"); 53368 bel0.setAttribute("href", arguments[0]); 53369 ac(bel0, [arguments[1]]); 53370 return bel0; 53371 }
53371(homepage, homepage) : html(_templateObject), desc); 53372} 53373 53374module.exports = creditsView; 53375 53376},{"./team":258,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"lodash":171,"sheetify/insert":227}],258:[function(require,module,exports){ 53377'use strict'; 53378 53379module.exports = [{ 53380 name: 'Per Guth', 53381 role: 'Project Manager / P2P-Guru / Scrummy Thing', 53382 img: 'https://avatars1.githubusercontent.com/u/85259?v=3&s=400', 53383 github: 'https://github.com/pguth', 53384 homepage: 'https://pguth.js.org', 53385 desc: '"Can we teach people, not just to code, but to demand the right to participate in shaping society?"' 53386}, { 53387 name: 'Paul Sonnentag', 53388 role: 'Technical Lead / Mr. JavaScript', 53389 img: 'https://avatars1.githubusercontent.com/u/650540?v=3&s=400', 53390 github: 'https://github.com/paulsonnentag', 53391 homepage: 'http://paulsonnentag.com', 53392 desc: 'Passionate developer, studying computer science. At home on the web. Building things with JavaScript, Elm and Clojure.' 53393}, { 53394 name: 'Johannes Kahlhöfer', 53395 role: 'Developer / Evil Mind', 53396 img: 'https://avatars1.githubusercontent.com/u/5808849?v=3&s=400', 53397 github: 'https://github.com/H3rby7', 53398 desc: '' 53399}, { 53400 name: 'Tim GroÃmann', 53401 role: 'Developer', 53402 img: 'https://avatars3.githubusercontent.com/u/16529337?v=3&s=400', 53403 github: 'https://github.com/timgrossmann', 53404 desc: 'Passionate learner and developer. Studying computer science at the Media University. Looking forward to work with ingenious teams on challenging projects.' 53405}, { 53406 name: 'David ReeÃ', 53407 role: 'Consultant', 53408 img: 'https://avatars2.githubusercontent.com/u/4615516?v=3&s=400', 53409 github: 'https://github.com/queicherius', 53410 homepage: 'https://david-reess.de', 53411 desc: 'Full stack developer, currently in love with JavaScript. Main pet project is @gw2efficiency' 53412}, { 53413 name: 'Emre Kecik', 53414 role: 'User Testing', 53415 img: '../assets/img/emre.jpg', 53416 github: 'https://github.com/robotopia-x/robotopia', 53417 desc: '' 53418}, { 53419 name: 'Lorena Müller', 53420 role: 'Robot Designer', 53421 img: '../assets/img/dragon.png', 53422 github: 'https://github.com/robotopia-x/robotopia', 53423 desc: 'Animation & Game Student' 53424}]; 53425 53426},{}],259:[function(require,module,exports){ 53427'use strict'; 53428 53429/* globals localStorage */ 53430var html = {}; 53431var initialState = require('./initial-state'); 53432var button = require('../../elements/button'); 53433var blocklyWidget = require('../../elements/blockly'); 53434var pageLayout = require('../../elements/page-layout'); 53435var gameRunnerView = require('../../elements/game-runner'); 53436var clientDialogView = require('../../elements/client-dialog'); 53437 53438var DEV_MODE = false; // set to true to dev on the editor and not be bothered with multiplayer 53439 53440var blocklyView = blocklyWidget(); 53441 53442function editorView(state, prev, send) { 53443 var clock = state.clock, 53444 editor = state.editor, 53445 game = state.game, 53446 client = state.client; 53447 53448 53449 var blocklyHtml = blocklyView({ 53450 toolbox: initialState.editor.toolbox, 53451 workspace: localStorage.getItem('workspace') || initialState.editor.workspace || editor.workspace, 53452 onChange: function onChange(_ref) { 53453 var code = _ref.code, 53454 workspace = _ref.workspace; 53455 53456 localStorage.setItem('workspace', workspace); 53457 send('editor:update', { code: code, workspace: workspace }); 53458 } 53459 }); 53460 53461 var gameRunnerHtml = gameRunnerView({ 53462 game: game, 53463 clock: clock, 53464 onStart: function onStart() { 53465 send('runtime:commitCode', { code: editor.code, groupId: 1 }); 53466 send('clock:start'); 53467 }, 53468 onStop: init, 53469 onChangeSpeed: function onChangeSpeed(value) { 53470 return send('clock:setIntervalDuration', { intervalDuration: value }); 53471 } 53472 }); 53473 53474 var commitButtonHtml = button({ 53475 onClick: function onClick() { 53476 send('client:sendCode', { code: editor.code }); 53477 }, 53478 icon: 'upload', 53479 label: 'Upload' 53480 }); 53481 53482 var clientDialogHtml = clientDialogView({ 53483 client: client, 53484 onSetUsername: function onSetUsername(username) { 53485 return send('client:setUsername', { username: username }); 53486 }, 53487 onJoinGroup: function onJoinGroup(groupId) { 53488 return send('client:joinGroup', { groupId: groupId }); 53489 }, 53490 onDisconnect: function onDisconnect() { 53491 return send('client:disconnect'); 53492 }, 53493 onDenyRecovery: function onDenyRecovery() { 53494 return send('client:denyRecovery'); 53495 } 53496 }); 53497 53498 var pageHtml = pageLayout({ 53499 id: 'editor-page', 53500 context: [state, prev, send], 53501 panels: [{ view: gameRunnerHtml, size: 1 }, { view: blocklyHtml, size: 1 }], 53502 menu: [commitButtonHtml] 53503 }); 53504 53505 return function () { 53506 53507 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53508 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 53509 var bel0 = document.createElement("div"); 53510 bel0["onload"] = arguments[0]; 53511 ac(bel0, ["\n ", arguments[1], "\n ", arguments[2], "\n "]); 53512 return bel0; 53513 }(init, pageHtml, DEV_MODE ? '' : clientDialogHtml); 53514
53515 function init() { 53516 send('clock:stop'); 53517 send('runtime:reset'); 53518 send('game:loadGameState', { loadState: initialState.game }); 53519 send('game:initializeResourceSpots', { numberOfSpots: 10, value: 100, chunks: 10, color: 'BLUE', requiredDistance: 5 }); 53520 } 53521} 53522 53523module.exports = editorView; 53524 53525},{"../../elements/blockly":20,"../../elements/button":22,"../../elements/client-dialog":24,"../../elements/game-runner":26,"../../elements/page-layout":35,"./initial-state":260,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256}],260:[function(require,module,exports){ 53526'use strict'; 53527 53528var entities = require('../../models/game/entities'); 53529var blockColors = require('../../elements/blockly/colors'); 53530 53531var game = { 53532 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1], [1, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1], [1, 3, 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 1, 1], [1, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 3, 3, 3, 1], [1, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 3, 3, 1], [1, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 1], [1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 4, 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 1], [1, 1, 1, 1, 1, 1, 3, 3, 3, 1, 1, 3, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 1], [1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 1], [1, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1], [1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 53533 53534 entities: [entities.base({ x: 17, y: 17, teamId: 1 })], 53535 53536 teams: { 53537 1: { resources: 0, points: 0 } 53538 } 53539}; 53540 53541var editor = { 53542 workspace: '\n <xml xmlns="http://www.w3.org/1999/xhtml">\n <block type="start_handler" id="!o0D0w#D7c3RJ_[d[KgX" x="50" y="50" deletable="false"></block>\n </xml>\n ', 53543 53544 toolbox: '\n <xml id="toolbox" style="display: none">\n <category name="Logic" colour="' + blockColors.LOGIC_COLOR + '">\n <block type="logic_boolean"></block> \n <block type="logic_negate"></block>\n <block type="logic_compare"></block>\n <block type="controls_if"></block>\n <block type="logic_compare"></block>\n </category>\n \n <sep gap="8"></sep>
53544\n \n <category name="Loops" colour="' + blockColors.LOOPS_COLOR + '">\n <block type="controls_repeat"></block>\n <block type="controls_repeat_ext"></block>\n <block type="controls_whileUntil"></block>\n </category>\n \n <sep gap="8"></sep>\n \n <category name="Math" colour="' + blockColors.MATH_COLOR + '">\n <block type="math_number"></block>\n <block type="random_number"></block>\n <block type="random_number_ext"></block>\n <block type="math_arithmetic"></block>\n </category>\n \n <sep gap="8"></sep>\n \n <category name="Movement" colour="' + blockColors.MOVEMENT_COLOR + '">\n <block type="move"></block>\n <block type="rotate"></block>\n <block type="move_to"></block>\n <block type="move_to_ext"></block>\n <block type="move_to_entity"></block>\n </category>\n \n <sep gap="8"></sep>\n \n <category name="Actions" colour="' + blockColors.ACTION_COLOR + '">\n <block type="collect_resource"></block>\n <block type="deposit_resource"></block>\n <block type="collected_resources"></block>\n <block type="place_marker"></block>\n <block type="place_marker_ext"></block> \n </category>\n \n <sep gap="8"></sep>\n \n <category name="Events" colour="' + blockColors.EVENT_COLOR + '">\n <block type="resource_event_handler"></block>\n <block type="marker_event_handler"></block>\n </category>\n </xml>' 53545}; 53546 53547module.exports = { 53548 game: game, 53549 editor: editor 53550}; 53551 53552},{"../../elements/blockly/colors":19,"../../models/game/entities":56}],261:[function(require,module,exports){ 53553'use strict'; 53554 53555var html = {}; 53556var sf = 0; 53557var _ = require('lodash'); 53558var tutorials = require('../assets/tutorial'); 53559var buttonView = require('../elements/button'); 53560 53561var prefix = (require('sheetify/insert')("._1985df32 {\n color: #404040;\n height: 100%;\n width: 100%;\n overflow-y: scroll;\n }\n \n ._1985df32 > div {\n margin-bottom: 25px;\n } \n \n ._1985df32 > .logo {\n width: 100%;\n height: 35%;\n background-image: url('assets/icons/robotopia.svg');\n background-size: contain;\n background-position: center;\n background-repeat: no-repeat;\n margin-bottom: 0;\n }\n \n ._1985df32 h2 {\n color: #03a9f4;\n text-align: center;\n }\n \n ._1985df32 .editor {\n text-align: center;\n }\n \n ._1985df32 ol {\n padding-top: 0;\n margin-top: 0;\n }\n \n li {\n font-size: 1.5em;\n padding: 3px;\n }\n \n ._1985df32 a {\n color: #404040;\n }\n \n ._1985df32 a:hover {\n color: #dddddd;\n }\n \n ._1985df32 > .credits {\n margin-top: 50px;\n text-decoration: underline;\n text-align: center;\n }\n \n ._1985df32 .category {\n max-width: 950px;\n border-bottom: 1px solid black;\n margin: 20px auto;\n padding: 1em;\n }\n \n ._1985df32 .category:first-child {\n border-top: 1px solid black;\n }\n \n ._1985df32 .name {\n text-align: left;\n font-size: 150%;\n font-weight: 600;\n }\n \n ._1985df32 .level {\n width: 250px;\n overflow: hidden;\n display: inline-block;\n position: relative;\n margin: 20px;\n text-decoration: none;\n }\n \n ._1985df32 .level:hover {\n opacity: 0.8;\n color: #404040;\n }\n \n ._1985df32 .level > div{\n width: 100%;\n position: relative;\n text-align: center;\n }\n \n ._1985df32 .levelImage {\n width: 250px;\n height: 250px;\n background-size: contain;\n background-position: center;\n background-repeat: no-repeat;\n margin-bottom: 5px;\n }\n \n ._1985df32 .levelName {\n font-weight: 600;\n line-height: 150%;\n }") || true) && "_1985df32"; 53562 53563var overviewView = function overviewView(state, prev, send) { 53564 var editorButton = buttonView({ 53565 label: 'Open Editor', 53566 onClick: function onClick() { 53567 return send('location:set', '#editor'); 53568 } 53569 }); 53570 53571 var presenterButton = buttonView({ 53572 label: 'Open Presenter', 53573 onClick: function onClick() { 53574 return send('location:set', '#presenter'); 53575 } 53576 }); 53577 53578 return function () { 53579 53580 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53581 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js');
53582 var bel7 = document.createElement("div"); 53583 bel7.setAttribute("class", arguments[3]); 53584 var bel0 = document.createElement("div"); 53585 bel0.setAttribute("class", "logo"); 53586 var bel2 = document.createElement("div"); 53587 bel2.setAttribute("class", "tutorials"); 53588 var bel1 = document.createElement("h2"); 53589 ac(bel1, ["Tutorials"]); 53590 ac(bel2, ["\n ", bel1, "\n ", arguments[0], "\n "]); 53591 var bel4 = document.createElement("div"); 53592 bel4.setAttribute("class", "editor"); 53593 var bel3 = document.createElement("h2"); 53594 ac(bel3, ["Competitive Mode"]); 53595 ac(bel4, ["\n ", bel3, "\n ", arguments[1], "\n ", arguments[2], "\n "]); 53596 var bel6 = document.createElement("div"); 53597 bel6.setAttribute("class", "credits"); 53598 var bel5 = document.createElement("a"); 53599 bel5.setAttribute("href", "#credits"); 53600 ac(bel5, ["© Credits"]); 53601 ac(bel6, [bel5]); 53602 ac(bel7, ["\n ", bel0, "\n ", arguments[4], "\n ", bel2, "\n ", bel4, " \n ", bel6, "\n "]); 53603 return bel7; 53604 }(getAllTutorials(tutorials), editorButton, presenterButton, prefix, githubButtons()); 53605}; 53606 53607function githubButtons() { 53608 return function () { 53609 53610 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53611 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 53612 var bel4 = document.createElement("div"); 53613 bel4.setAttribute("style", "display: flex; justify-content: center"); 53614 var bel0 = document.createElement("a"); 53615 bel0.setAttribute("data-size", "large"); 53616 bel0.setAttribute("href", "http://github.com/robotopia-x/robotopia"); 53617 bel0.setAttribute("class", "github-button"); 53618 ac(bel0, ["View on github"]); 53619 var bel3 = document.createElement("div"); 53620 bel3.setAttribute("style", "margin: 0 10px;"); 53621 var bel1 = document.createElement("a"); 53622 bel1.setAttribute("href", "https://github.com/robotopia-x/robotopia"); 53623 bel1.setAttribute("data-icon", "octicon-star"); 53624 bel1.setAttribute("data-size", "large"); 53625 bel1.setAttribute("data-count-href", "/robotopia-x/robotopia/stargazers"); 53626 bel1.setAttribute("data-show-count", "true"); 53627 bel1.setAttribute("data-count-aria-label", "# stargazers on GitHub"); 53628 bel1.setAttribute("aria-label", "Star robotopia-x/robotopia on GitHub"); 53629 bel1.setAttribute("class", "github-button"); 53630 ac(bel1, ["Star"]); 53631 var bel2 = document.createElement("script"); 53632 bel2.setAttribute("async", "async"); 53633 bel2.setAttribute("defer", "defer"); 53634 bel2.setAttribute("src", "https://buttons.github.io/buttons.js"); 53635 ac(bel3, ["\n ", bel1, " \n ", bel2, "\n "]); 53636 ac(bel4, ["\n ", bel0, "\n ", bel3, "\n "]); 53637 return bel4; 53638 }(); 53639} 53640 53641function getAllTutorials(tutorials) { 53642 return function () { 53643 53644 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53645 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 53646 var bel0 = document.createElement("div"); 53647 bel0.setAttribute("class", "tutorials"); 53648 ac(bel0, ["\n ", arguments[0], "\n"]); 53649 return bel0; 53650 }(_.map(tutorials, getTutorialCategory)); 53651 53652 function getTutorialCategory(category) { 53653 var categoryName = category.categoryName; 53654 return function () { 53655 53656 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53657 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 53658 var bel1 = document.createElement("div"); 53659 bel1.setAttribute("class", "category"); 53660 var bel0 = document.createElement("div"); 53661 bel0.setAttribute("class", "name"); 53662 ac(bel0, [arguments[0]]); 53663 ac(bel1, ["\n ", bel0, "\n ", arguments[1], "\n "]); 53664 return bel1; 53665 }(categoryName, _.map(category.levels, getTutorial)); 53666 53667 function getTutorial(level, index) { 53668 var oneIndex = index + 1; 53669 return function () { 53670 53671 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53672 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 53673 var bel2 = document.createElement("a"); 53674 bel2.setAttribute("href", "#tutorial/" + arguments[3] + "/" + arguments[4]); 53675 bel2.setAttribute("class", "level"); 53676 var bel0 = document.createElement("div"); 53677 bel0.setAttribute("style", "background-image: url('assets/tutorial/level-images/" + arguments[0] + arguments[1] + ".png');"); 53678 bel0.setAttribute("class", "levelImage"); 53679 var bel1 = document.createElement("div"); 53680 bel1.setAttribute("class", "levelName"); 53681 ac(bel1, [arguments[2]]); 53682 ac(bel2, ["\n ", bel0, "\n ", bel1, "\n "]); 53683 return bel2; 53684 }(categoryName.toLowerCase(), index + 1, level().label, categoryName, oneIndex); 53685 } 53686 } 53687} 53688 53689module.exports = overviewView; 53690 53691},{"../assets/tutorial":16,"../elements/button":22,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"lodash":171,"sheetify/insert":227}],262:[function(require,module,exports){ 53692'use strict'; 53693 53694var html = {}; 53695 53696var timerDisplay = require('../../elements/timer'); 53697var overlayView = require('../../elements/overlay'); 53698 53699var gameRunnerView = require('../../elements/game-runner'); 53700var pageLayout = require('../../elements/page-layout'); 53701 53702var presenterModalView = require('../../elements/presenter-dialog'); 53703var clientsList = require('../../elements/clients-list'); 53704var prepfight = require('action-overlay')('prepfight').view; 53705var initialState = require('./initial-state'); 53706 53707var DEV_MODE = false;
53708 53709module.exports = function (state, prev, send) { 53710 var presenter = state.presenter; 53711 var game = state.game; 53712 var clock = state.clock; 53713 53714 if (presenter.groupId === null) { 53715 if (DEV_MODE) { 53716 send('presenter:joinGroup', { groupId: 'asd' }); 53717 send('presenter:_testMode'); 53718 } 53719 } 53720 53721 var presenterDialog = presenterModalView({ 53722 presenter: presenter, 53723 currentGame: game.current, 53724 onJoinGroup: function onJoinGroup(groupId) { 53725 send('presenter:joinGroup', { groupId: groupId }); 53726 }, 53727 onPlayersPicked: function onPlayersPicked(players) { 53728 send('presenter:setPlayers', players); 53729 send('presenter:startMatch'); 53730 }, 53731 onCancelPlayerPicking: function onCancelPlayerPicking() { 53732 send('presenter:pickPlayers', false); 53733 send('presenter:setTime', 0); 53734 }, 53735 onCloseWinModal: function onCloseWinModal() { 53736 send('presenter:showWinDialog', false); 53737 } 53738 }); 53739 53740 var gameRunnerHtml = gameRunnerView({ 53741 game: game, 53742 clock: clock, 53743 onStart: function onStart() { 53744 send('presenter:setTime', 120); 53745 send('presenter:pickPlayers', { playerCount: 2, selectionMode: 'pick' }); 53746 }, 53747 onStop: function onStop() { 53748 return send('presenter:stopMatch'); 53749 }, 53750 onChangeSpeed: function onChangeSpeed(value) { 53751 return send('clock:setIntervalDuration', { intervalDuration: value }); 53752 } 53753 }); 53754 53755 var timerHtml = overlayView({ 53756 position: 'bottom right', 53757 hasFrame: false, 53758 content: timerDisplay({ seconds: presenter.time }) 53759 }); 53760 53761 var prepfightHtml = prepfight(state, prev, send); 53762 53763 var clientsListHtml = overlayView({ 53764 position: 'bottom left', 53765 content: clientsList({ 53766 clients: presenter.clients, 53767 playerNumbers: presenter.playerNumbers 53768 }) 53769 }); 53770 53771 var pageHtml = pageLayout({ 53772 id: 'presenter-page', 53773 context: [state, prev, send], 53774 panels: [{ view: gameRunnerHtml, size: 1 }] 53775 }); 53776 53777 return function () { 53778 53779 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53780 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 53781 var bel0 = document.createElement("div"); 53782 bel0["onload"] = arguments[0]; 53783 ac(bel0, ["\n ", arguments[1], "\n ", arguments[2], "\n ", arguments[3], "\n ", arguments[4], "\n ", arguments[5], "\n "]); 53784 return bel0; 53785 }(init, pageHtml, presenterDialog, presenter.time === 0 && !presenter.displayWinDialog && !presenter.displayPlayerPickScreen ? clientsListHtml : '', timerHtml, prepfightHtml); 53786 53787 function init() { 53788 send('clock:stop'); 53789 send('game:loadGameState', { loadState: initialState.game }); 53790 send('prepfight:setLeft', { img: '' }); 53791 send('prepfight:setRight', { img: '' }); 53792 send('prepfight:setVS', { img: 'http://vignette2.wikia.nocookie.net/mortalkombat/images/6/64/Vs.png/revision/latest?cb=20150319161124&path-prefix=de' }); 53793 send('prepfight:setDurations', { up: 1000, down: 1000, stay: 1500 }); 53794 } 53795}; 53796 53797},{"../../elements/clients-list":25,"../../elements/game-runner":26,"../../elements/overlay":34,"../../elements/page-layout":35,"../../elements/presenter-dialog":36,"../../elements/timer":38,"./initial-state":263,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256,"action-overlay":75}],263:[function(require,module,exports){ 53798'use strict'; 53799 53800var entities = require('../../models/game/entities'); 53801 53802var game = { 53803 tiles: [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1], [1, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 3, 3, 3, 4, 5, 4, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 1, 1], [1, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 1, 1, 3, 3, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 1, 1, 3, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 1], [1, 1, 1, 3, 3, 3, 3, 1, 1, 1, 1, 3, 3, 3, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 1], [1, 1, 1, 3, 3, 3, 3, 3, 3, 1, 1, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 1], [1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 2, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 2, 2, 2, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 2, 2, 2, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1], [1, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 3, 3, 3, 1], [1, 3, 3, 3, 3, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 4, 3, 3, 3, 1], [1, 1, 3, 3, 3, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 3, 3, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1], [1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1], [1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 53804 53805 entities: [entities.base({ x: 5, y: 5, teamId: 1 }), entities.base({ x: 29, y: 29, teamId: 2 })], 53806 53807 teams: { 53808 1: { resources: 0, points: 0 }, 53809 2: { resources: 0, points: 0 } 53810 }, 53811 53812 resources: {}, 53813 gamePoints: {} 53814}; 53815 53816module.exports = { 53817 game: game 53818}; 53819 53820},{"../../models/game/entities":56}],264:[function(require,module,exports){ 53821'use strict'; 53822 53823var html = {}; 53824var pageLayout = require('../elements/page-layout'); 53825var gameRunnerView = require('../elements/game-runner'); 53826var tutorialDialogView = require('../elements/tutorial/tutorialDialog'); 53827var blocklyWidget = require('../elements/blockly'); 53828 53829var _require = require('../elements/instructions'), 53830 instructionView = _require.instructionView; 53831 53832var blocklyView = blocklyWidget(); 53833 53834var tutorialView = function tutorialView(state, prev, send) { 53835 var game = state.game, 53836 clock = state.clock,
53837 editor = state.editor, 53838 tutorial = state.tutorial, 53839 location = state.location; 53840 53841 // we need to check if level param has changed because onLoad will not be triggered if tutorial page 53842 // has already been loaded 53843 53844 if (prev !== null && (location.params.category !== prev.location.params.category || location.params.level !== prev.location.params.level)) { 53845 init(); 53846 } 53847 53848 var instructionHtml = instructionView(game, tutorial); 53849 53850 var blocklyHtml = blocklyView({ 53851 toolbox: tutorial.level && tutorial.level.editor.toolbox, 53852 workspace: tutorial.level && tutorial.level.editor.workspace, 53853 onChange: function onChange(_ref) { 53854 var code = _ref.code, 53855 workspace = _ref.workspace; 53856 53857 send('runtime:commitCode', { code: code, groupId: 1 }); 53858 send('editor:update', { code: code, workspace: workspace }); 53859 } 53860 }); 53861 53862 var gameRunnerHtml = gameRunnerView({ 53863 game: game, 53864 clock: clock, 53865 onStart: function onStart() { 53866 send('game:loadGameState', { loadState: tutorial.level.game }); 53867 var otherRobots = tutorial.level.otherRobots; 53868 var res = tutorial.level.resources; 53869 if (res && res.numberOfSpots && res.value && res.chunks && res.color) { 53870 send('game:initializeResourceSpots', res); 53871 } 53872 send('runtime:destroyRobot', { id: 'ROBOT' }); 53873 send('runtime:createRobot', { id: 'ROBOT', groupId: 1 }); 53874 if (otherRobots) { 53875 var i = void 0; 53876 for (i in otherRobots) { 53877 send('runtime:destroyRobot', { id: otherRobots[i].id }); 53878 send('runtime:createRobot', otherRobots[i]); 53879 } 53880 } 53881 send('clock:start'); 53882 send('tutorial:resetEvents'); 53883 }, 53884 onStop: function onStop() { 53885 send('clock:stop'); 53886 send('runtime:destroyRobot', { id: 'ROBOT' }); 53887 var otherRobots = tutorial.level.otherRobots; 53888 if (otherRobots) { 53889 var i = void 0; 53890 for (i in otherRobots) { 53891 send('runtime:destroyRobot', { id: otherRobots[i].id }); 53892 } 53893 } 53894 send('game:loadGameState', { loadState: tutorial.level.game }); 53895 }, 53896 onChangeSpeed: function onChangeSpeed(value) { 53897 return send('clock:setIntervalDuration', { intervalDuration: value }); 53898 } 53899 }); 53900 53901 var pageLayoutHtml = pageLayout({ 53902 id: 'tutorial-page', 53903 context: [state, prev, send], 53904 panels: [{ view: instructionHtml, size: 1 }, { view: gameRunnerHtml, size: 2 }, { view: blocklyHtml, size: 2 }] 53905 }); 53906 53907 return function () { 53908 53909 var ac = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js'); 53910 var sa = require('/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js'); 53911 var bel0 = document.createElement("div"); 53912 bel0["onload"] = arguments[0]; 53913 ac(bel0, ["\n ", arguments[1], "\n ", arguments[2], "\n "]); 53914 return bel0; 53915 }(init, pageLayoutHtml, tutorialDialogView(game, tutorial, editor.workspace, send)); 53916 53917 function init() { 53918 send('clock:stop'); 53919 send('tutorial:loadLevel', { category: location.params.category, index: location.params.level }); 53920 } 53921}; 53922 53923module.exports = tutorialView; 53924 53925},{"../elements/blockly":20,"../elements/game-runner":26,"../elements/instructions":32,"../elements/page-layout":35,"../elements/tutorial/tutorialDialog":39,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/appendChild.js":255,"/Users/paul/repos/robotopia/node_modules/yo-yoify/lib/setAttribute.js":256}]},{},[40]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.