Socket
Socket
Sign inDemoInstall

resource-loader

Package Overview
Dependencies
Maintainers
1
Versions
57
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

resource-loader - npm Package Compare versions

Comparing version 2.0.3 to 2.0.4

2

dist/resource-loader.min.js

@@ -1,1 +0,1 @@

(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Loader=f()}})(function(){var define,module,exports;return 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){"use strict";exports.__esModule=true;var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};var _miniSignals=require("mini-signals");var _miniSignals2=_interopRequireDefault(_miniSignals);var _parseUri=require("parse-uri");var _parseUri2=_interopRequireDefault(_parseUri);var _async=require("./async");var async=_interopRequireWildcard(_async);var _Resource=require("./Resource");var _Resource2=_interopRequireDefault(_Resource);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var MAX_PROGRESS=100;var rgxExtractUrlHash=/(#[\w\-]+)?$/;var Loader=function(){function Loader(){var _this=this;var baseUrl=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";var concurrency=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;_classCallCheck(this,Loader);this.baseUrl=baseUrl;this.progress=0;this.loading=false;this.defaultQueryString="";this._beforeMiddleware=[];this._afterMiddleware=[];this._boundLoadResource=function(r,d){return _this._loadResource(r,d)};this._queue=async.queue(this._boundLoadResource,concurrency);this._queue.pause();this.resources={};this.onProgress=new _miniSignals2.default;this.onError=new _miniSignals2.default;this.onLoad=new _miniSignals2.default;this.onStart=new _miniSignals2.default;this.onComplete=new _miniSignals2.default}Loader.prototype.add=function add(name,url,options,cb){if(Array.isArray(name)){for(var i=0;i<name.length;++i){this.add(name[i])}return this}if((typeof name==="undefined"?"undefined":_typeof(name))==="object"){cb=url||name.callback||name.onComplete;options=name;url=name.url;name=name.name||name.key||name.url}if(typeof url!=="string"){cb=options;options=url;url=name}if(typeof url!=="string"){throw new Error("No url passed to add resource to loader.")}if(typeof options==="function"){cb=options;options=null}if(this.loading&&(!options||!options.parentResource)){throw new Error("Cannot add resources while the loader is running.")}if(this.resources[name]){throw new Error('Resource named "'+name+'" already exists.')}url=this._prepareUrl(url);this.resources[name]=new _Resource2.default(name,url,options);if(typeof cb==="function"){this.resources[name].onAfterMiddleware.once(cb)}if(this.loading){var parent=options.parentResource;var fullChunk=parent.progressChunk*(parent.children.length+1);var eachChunk=fullChunk/(parent.children.length+2);parent.children.push(this.resources[name]);parent.progressChunk=eachChunk;for(var _i=0;_i<parent.children.length;++_i){parent.children[_i].progressChunk=eachChunk}}this._queue.push(this.resources[name]);return this};Loader.prototype.pre=function pre(fn){this._beforeMiddleware.push(fn);return this};Loader.prototype.use=function use(fn){this._afterMiddleware.push(fn);return this};Loader.prototype.reset=function reset(){this.progress=0;this.loading=false;this._queue.kill();this._queue.pause();for(var k in this.resources){var res=this.resources[k];if(res._onLoadBinding){res._onLoadBinding.detach()}if(res.isLoading){res.abort()}}this.resources={};return this};Loader.prototype.load=function load(cb){if(typeof cb==="function"){this.onComplete.once(cb)}if(this.loading){return this}var chunk=100/this._queue._tasks.length;for(var i=0;i<this._queue._tasks.length;++i){this._queue._tasks[i].data.progressChunk=chunk}this.loading=true;this.onStart.dispatch(this);this._queue.resume();return this};Loader.prototype._prepareUrl=function _prepareUrl(url){var parsedUrl=(0,_parseUri2.default)(url,{strictMode:true});var result=void 0;if(parsedUrl.protocol||!parsedUrl.path||url.indexOf("//")===0){result=url}else if(this.baseUrl.length&&this.baseUrl.lastIndexOf("/")!==this.baseUrl.length-1&&url.charAt(0)!=="/"){result=this.baseUrl+"/"+url}else{result=this.baseUrl+url}if(this.defaultQueryString){var hash=rgxExtractUrlHash.exec(result)[0];result=result.substr(0,result.length-hash.length);if(result.indexOf("?")!==-1){result+="&"+this.defaultQueryString}else{result+="?"+this.defaultQueryString}result+=hash}return result};Loader.prototype._loadResource=function _loadResource(resource,dequeue){var _this2=this;resource._dequeue=dequeue;async.eachSeries(this._beforeMiddleware,function(fn,next){fn.call(_this2,resource,function(){next(resource.isComplete?{}:null)})},function(){if(resource.isComplete){_this2._onLoad(resource)}else{resource._onLoadBinding=resource.onComplete.once(_this2._onLoad,_this2);resource.load()}})};Loader.prototype._onComplete=function _onComplete(){this.loading=false;this.onComplete.dispatch(this,this.resources)};Loader.prototype._onLoad=function _onLoad(resource){var _this3=this;resource._onLoadBinding=null;async.eachSeries(this._afterMiddleware,function(fn,next){fn.call(_this3,resource,next)},function(){resource.onAfterMiddleware.dispatch(resource);_this3.progress+=resource.progressChunk;_this3.onProgress.dispatch(_this3,resource);if(resource.error){_this3.onError.dispatch(resource.error,_this3,resource)}else{_this3.onLoad.dispatch(_this3,resource)}resource._dequeue();if(_this3._queue.idle()){_this3.progress=MAX_PROGRESS;_this3._onComplete()}})};return Loader}();exports.default=Loader},{"./Resource":2,"./async":3,"mini-signals":6,"parse-uri":7}],2:[function(require,module,exports){"use strict";exports.__esModule=true;var _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}}();var _parseUri=require("parse-uri");var _parseUri2=_interopRequireDefault(_parseUri);var _miniSignals=require("mini-signals");var _miniSignals2=_interopRequireDefault(_miniSignals);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var useXdr=!!(window.XDomainRequest&&!("withCredentials"in new XMLHttpRequest));var tempAnchor=null;var STATUS_NONE=0;var STATUS_OK=200;var STATUS_EMPTY=204;function _noop(){}var Resource=function(){Resource.setExtensionLoadType=function setExtensionLoadType(extname,loadType){setExtMap(Resource._loadTypeMap,extname,loadType)};Resource.setExtensionXhrType=function setExtensionXhrType(extname,xhrType){setExtMap(Resource._xhrTypeMap,extname,xhrType)};function Resource(name,url,options){_classCallCheck(this,Resource);if(typeof name!=="string"||typeof url!=="string"){throw new Error("Both name and url are required for constructing a resource.")}options=options||{};this._flags=0;this._setFlag(Resource.STATUS_FLAGS.DATA_URL,url.indexOf("data:")===0);this.name=name;this.url=url;this.data=null;this.crossOrigin=options.crossOrigin===true?"anonymous":options.crossOrigin;this.loadType=options.loadType||this._determineLoadType();this.xhrType=options.xhrType;this.metadata=options.metadata||{};this.error=null;this.xhr=null;this.children=[];this.type=Resource.TYPE.UNKNOWN;this.progressChunk=0;this._dequeue=_noop;this._onLoadBinding=null;this._boundComplete=this.complete.bind(this);this._boundOnError=this._onError.bind(this);this._boundOnProgress=this._onProgress.bind(this);this._boundXhrOnError=this._xhrOnError.bind(this);this._boundXhrOnAbort=this._xhrOnAbort.bind(this);this._boundXhrOnLoad=this._xhrOnLoad.bind(this);this._boundXdrOnTimeout=this._xdrOnTimeout.bind(this);this.onStart=new _miniSignals2.default;this.onProgress=new _miniSignals2.default;this.onComplete=new _miniSignals2.default;this.onAfterMiddleware=new _miniSignals2.default}Resource.prototype.complete=function complete(){if(this.data&&this.data.removeEventListener){this.data.removeEventListener("error",this._boundOnError,false);this.data.removeEventListener("load",this._boundComplete,false);this.data.removeEventListener("progress",this._boundOnProgress,false);this.data.removeEventListener("canplaythrough",this._boundComplete,false)}if(this.xhr){if(this.xhr.removeEventListener){this.xhr.removeEventListener("error",this._boundXhrOnError,false);this.xhr.removeEventListener("abort",this._boundXhrOnAbort,false);this.xhr.removeEventListener("progress",this._boundOnProgress,false);this.xhr.removeEventListener("load",this._boundXhrOnLoad,false)}else{this.xhr.onerror=null;this.xhr.ontimeout=null;this.xhr.onprogress=null;this.xhr.onload=null}}if(this.isComplete){throw new Error("Complete called again for an already completed resource.")}this._setFlag(Resource.STATUS_FLAGS.COMPLETE,true);this._setFlag(Resource.STATUS_FLAGS.LOADING,false);this.onComplete.dispatch(this)};Resource.prototype.abort=function abort(message){if(this.error){return}this.error=new Error(message);if(this.xhr){this.xhr.abort()}else if(this.xdr){this.xdr.abort()}else if(this.data){if(this.data.src){this.data.src=Resource.EMPTY_GIF}else{while(this.data.firstChild){this.data.removeChild(this.data.firstChild)}}}this.complete()};Resource.prototype.load=function load(cb){var _this=this;if(this.isLoading){return}if(this.isComplete){if(cb){setTimeout(function(){return cb(_this)},1)}return}else if(cb){this.onComplete.once(cb)}this._setFlag(Resource.STATUS_FLAGS.LOADING,true);this.onStart.dispatch(this);if(this.crossOrigin===false||typeof this.crossOrigin!=="string"){this.crossOrigin=this._determineCrossOrigin(this.url)}switch(this.loadType){case Resource.LOAD_TYPE.IMAGE:this.type=Resource.TYPE.IMAGE;this._loadElement("image");break;case Resource.LOAD_TYPE.AUDIO:this.type=Resource.TYPE.AUDIO;this._loadSourceElement("audio");break;case Resource.LOAD_TYPE.VIDEO:this.type=Resource.TYPE.VIDEO;this._loadSourceElement("video");break;case Resource.LOAD_TYPE.XHR:default:if(useXdr&&this.crossOrigin){this._loadXdr()}else{this._loadXhr()}break}};Resource.prototype._hasFlag=function _hasFlag(flag){return!!(this._flags&flag)};Resource.prototype._setFlag=function _setFlag(flag,value){this._flags=value?this._flags|flag:this._flags&~flag};Resource.prototype._loadElement=function _loadElement(type){if(this.metadata.loadElement){this.data=this.metadata.loadElement}else if(type==="image"&&typeof window.Image!=="undefined"){this.data=new Image}else{this.data=document.createElement(type)}if(this.crossOrigin){this.data.crossOrigin=this.crossOrigin}if(!this.metadata.skipSource){this.data.src=this.url}this.data.addEventListener("error",this._boundOnError,false);this.data.addEventListener("load",this._boundComplete,false);this.data.addEventListener("progress",this._boundOnProgress,false)};Resource.prototype._loadSourceElement=function _loadSourceElement(type){if(this.metadata.loadElement){this.data=this.metadata.loadElement}else if(type==="audio"&&typeof window.Audio!=="undefined"){this.data=new Audio}else{this.data=document.createElement(type)}if(this.data===null){this.abort("Unsupported element: "+type);return}if(!this.metadata.skipSource){if(navigator.isCocoonJS){this.data.src=Array.isArray(this.url)?this.url[0]:this.url}else if(Array.isArray(this.url)){for(var i=0;i<this.url.length;++i){this.data.appendChild(this._createSource(type,this.url[i]))}}else{this.data.appendChild(this._createSource(type,this.url))}}this.data.addEventListener("error",this._boundOnError,false);this.data.addEventListener("load",this._boundComplete,false);this.data.addEventListener("progress",this._boundOnProgress,false);this.data.addEventListener("canplaythrough",this._boundComplete,false);this.data.load()};Resource.prototype._loadXhr=function _loadXhr(){if(typeof this.xhrType!=="string"){this.xhrType=this._determineXhrType()}var xhr=this.xhr=new XMLHttpRequest;xhr.open("GET",this.url,true);if(this.xhrType===Resource.XHR_RESPONSE_TYPE.JSON||this.xhrType===Resource.XHR_RESPONSE_TYPE.DOCUMENT){xhr.responseType=Resource.XHR_RESPONSE_TYPE.TEXT}else{xhr.responseType=this.xhrType}xhr.addEventListener("error",this._boundXhrOnError,false);xhr.addEventListener("abort",this._boundXhrOnAbort,false);xhr.addEventListener("progress",this._boundOnProgress,false);xhr.addEventListener("load",this._boundXhrOnLoad,false);xhr.send()};Resource.prototype._loadXdr=function _loadXdr(){if(typeof this.xhrType!=="string"){this.xhrType=this._determineXhrType()}var xdr=this.xhr=new XDomainRequest;xdr.timeout=5e3;xdr.onerror=this._boundXhrOnError;xdr.ontimeout=this._boundXdrOnTimeout;xdr.onprogress=this._boundOnProgress;xdr.onload=this._boundXhrOnLoad;xdr.open("GET",this.url,true);setTimeout(function(){return xdr.send()},1)};Resource.prototype._createSource=function _createSource(type,url,mime){if(!mime){mime=type+"/"+url.substr(url.lastIndexOf(".")+1)}var source=document.createElement("source");source.src=url;source.type=mime;return source};Resource.prototype._onError=function _onError(event){this.abort("Failed to load element using: "+event.target.nodeName)};Resource.prototype._onProgress=function _onProgress(event){if(event&&event.lengthComputable){this.onProgress.dispatch(this,event.loaded/event.total)}};Resource.prototype._xhrOnError=function _xhrOnError(){var xhr=this.xhr;this.abort(reqType(xhr)+" Request failed. Status: "+xhr.status+', text: "'+xhr.statusText+'"')};Resource.prototype._xhrOnAbort=function _xhrOnAbort(){this.abort(reqType(this.xhr)+" Request was aborted by the user.")};Resource.prototype._xdrOnTimeout=function _xdrOnTimeout(){this.abort(reqType(this.xhr)+" Request timed out.")};Resource.prototype._xhrOnLoad=function _xhrOnLoad(){var xhr=this.xhr;var status=typeof xhr.status==="undefined"?xhr.status:STATUS_OK;if(status===STATUS_OK||status===STATUS_EMPTY||status===STATUS_NONE&&xhr.responseText.length>0){if(this.xhrType===Resource.XHR_RESPONSE_TYPE.TEXT){this.data=xhr.responseText;this.type=Resource.TYPE.TEXT}else if(this.xhrType===Resource.XHR_RESPONSE_TYPE.JSON){try{this.data=JSON.parse(xhr.responseText);this.type=Resource.TYPE.JSON}catch(e){this.abort("Error trying to parse loaded json: "+e);return}}else if(this.xhrType===Resource.XHR_RESPONSE_TYPE.DOCUMENT){try{if(window.DOMParser){var domparser=new DOMParser;this.data=domparser.parseFromString(xhr.responseText,"text/xml")}else{var div=document.createElement("div");div.innerHTML=xhr.responseText;this.data=div}this.type=Resource.TYPE.XML}catch(e){this.abort("Error trying to parse loaded xml: "+e);return}}else{this.data=xhr.response||xhr.responseText}}else{this.abort("["+xhr.status+"] "+xhr.statusText+": "+xhr.responseURL);return}this.complete()};Resource.prototype._determineCrossOrigin=function _determineCrossOrigin(url,loc){if(url.indexOf("data:")===0){return""}loc=loc||window.location;if(!tempAnchor){tempAnchor=document.createElement("a")}tempAnchor.href=url;url=(0,_parseUri2.default)(tempAnchor.href,{strictMode:true});var samePort=!url.port&&loc.port===""||url.port===loc.port;var protocol=url.protocol?url.protocol+":":"";if(url.host!==loc.hostname||!samePort||protocol!==loc.protocol){return"anonymous"}return""};Resource.prototype._determineXhrType=function _determineXhrType(){return Resource._xhrTypeMap[this._getExtension()]||Resource.XHR_RESPONSE_TYPE.TEXT};Resource.prototype._determineLoadType=function _determineLoadType(){return Resource._loadTypeMap[this._getExtension()]||Resource.LOAD_TYPE.XHR};Resource.prototype._getExtension=function _getExtension(){var url=this.url;var ext="";if(this.isDataUrl){var slashIndex=url.indexOf("/");ext=url.substring(slashIndex+1,url.indexOf(";",slashIndex))}else{var queryStart=url.indexOf("?");if(queryStart!==-1){url=url.substring(0,queryStart)}ext=url.substring(url.lastIndexOf(".")+1)}return ext.toLowerCase()};Resource.prototype._getMimeFromXhrType=function _getMimeFromXhrType(type){switch(type){case Resource.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case Resource.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case Resource.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case Resource.XHR_RESPONSE_TYPE.JSON:return"application/json";case Resource.XHR_RESPONSE_TYPE.DEFAULT:case Resource.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}};_createClass(Resource,[{key:"isDataUrl",get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.LOADING)}}]);return Resource}();exports.default=Resource;Resource.STATUS_FLAGS={NONE:0,DATA_URL:1<<0,COMPLETE:1<<1,LOADING:1<<2};Resource.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6};Resource.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4};Resource.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"};Resource._loadTypeMap={gif:Resource.LOAD_TYPE.IMAGE,png:Resource.LOAD_TYPE.IMAGE,bmp:Resource.LOAD_TYPE.IMAGE,jpg:Resource.LOAD_TYPE.IMAGE,jpeg:Resource.LOAD_TYPE.IMAGE,tif:Resource.LOAD_TYPE.IMAGE,tiff:Resource.LOAD_TYPE.IMAGE,webp:Resource.LOAD_TYPE.IMAGE,tga:Resource.LOAD_TYPE.IMAGE,svg:Resource.LOAD_TYPE.IMAGE,"svg+xml":Resource.LOAD_TYPE.IMAGE,mp3:Resource.LOAD_TYPE.AUDIO,ogg:Resource.LOAD_TYPE.AUDIO,wav:Resource.LOAD_TYPE.AUDIO,mp4:Resource.LOAD_TYPE.VIDEO,webm:Resource.LOAD_TYPE.VIDEO};Resource._xhrTypeMap={xhtml:Resource.XHR_RESPONSE_TYPE.DOCUMENT,html:Resource.XHR_RESPONSE_TYPE.DOCUMENT,htm:Resource.XHR_RESPONSE_TYPE.DOCUMENT,xml:Resource.XHR_RESPONSE_TYPE.DOCUMENT,tmx:Resource.XHR_RESPONSE_TYPE.DOCUMENT,svg:Resource.XHR_RESPONSE_TYPE.DOCUMENT,tsx:Resource.XHR_RESPONSE_TYPE.DOCUMENT,gif:Resource.XHR_RESPONSE_TYPE.BLOB,png:Resource.XHR_RESPONSE_TYPE.BLOB,bmp:Resource.XHR_RESPONSE_TYPE.BLOB,jpg:Resource.XHR_RESPONSE_TYPE.BLOB,jpeg:Resource.XHR_RESPONSE_TYPE.BLOB,tif:Resource.XHR_RESPONSE_TYPE.BLOB,tiff:Resource.XHR_RESPONSE_TYPE.BLOB,webp:Resource.XHR_RESPONSE_TYPE.BLOB,tga:Resource.XHR_RESPONSE_TYPE.BLOB,json:Resource.XHR_RESPONSE_TYPE.JSON,text:Resource.XHR_RESPONSE_TYPE.TEXT,txt:Resource.XHR_RESPONSE_TYPE.TEXT,ttf:Resource.XHR_RESPONSE_TYPE.BUFFER,otf:Resource.XHR_RESPONSE_TYPE.BUFFER};Resource.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";function setExtMap(map,extname,val){if(extname&&extname.indexOf(".")===0){extname=extname.substring(1)}if(!extname){return}map[extname]=val}function reqType(xhr){return xhr.toString().replace("object ","")}},{"mini-signals":6,"parse-uri":7}],3:[function(require,module,exports){"use strict";exports.__esModule=true;exports.eachSeries=eachSeries;exports.queue=queue;function _noop(){}function eachSeries(array,iterator,callback){var i=0;var len=array.length;(function next(err){if(err||i===len){if(callback){callback(err)}return}iterator(array[i++],next)})()}function onlyOnce(fn){return function onceWrapper(){if(fn===null){throw new Error("Callback was already called.")}var callFn=fn;fn=null;callFn.apply(this,arguments)}}function queue(worker,concurrency){if(concurrency==null){concurrency=1}else if(concurrency===0){throw new Error("Concurrency must not be zero")}var workers=0;var q={_tasks:[],concurrency:concurrency,saturated:_noop,unsaturated:_noop,buffer:concurrency/4,empty:_noop,drain:_noop,error:_noop,started:false,paused:false,push:function push(data,callback){_insert(data,false,callback)},kill:function kill(){workers=0;q.drain=_noop;q.started=false;q._tasks=[]},unshift:function unshift(data,callback){_insert(data,true,callback)},process:function process(){while(!q.paused&&workers<q.concurrency&&q._tasks.length){var task=q._tasks.shift();if(q._tasks.length===0){q.empty()}workers+=1;if(workers===q.concurrency){q.saturated()}worker(task.data,onlyOnce(_next(task)))}},length:function length(){return q._tasks.length},running:function running(){return workers},idle:function idle(){return q._tasks.length+workers===0},pause:function pause(){if(q.paused===true){return}q.paused=true},resume:function resume(){if(q.paused===false){return}q.paused=false;for(var w=1;w<=q.concurrency;w++){q.process()}}};function _insert(data,insertAtFront,callback){if(callback!=null&&typeof callback!=="function"){throw new Error("task callback must be a function")}q.started=true;if(data==null&&q.idle()){setTimeout(function(){return q.drain()},1);return}var item={data:data,callback:typeof callback==="function"?callback:_noop};if(insertAtFront){q._tasks.unshift(item)}else{q._tasks.push(item)}setTimeout(function(){return q.process()},1)}function _next(task){return function next(){workers-=1;task.callback.apply(task,arguments);if(arguments[0]!=null){q.error(arguments[0],task.data)}if(workers<=q.concurrency-q.buffer){q.unsaturated()}if(q.idle()){q.drain()}q.process()}}return q}},{}],4:[function(require,module,exports){"use strict";exports.__esModule=true;exports.encodeBinary=encodeBinary;var _keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function encodeBinary(input){var output="";var inx=0;while(inx<input.length){var bytebuffer=[0,0,0];var encodedCharIndexes=[0,0,0,0];for(var jnx=0;jnx<bytebuffer.length;++jnx){if(inx<input.length){bytebuffer[jnx]=input.charCodeAt(inx++)&255}else{bytebuffer[jnx]=0}}encodedCharIndexes[0]=bytebuffer[0]>>2;encodedCharIndexes[1]=(bytebuffer[0]&3)<<4|bytebuffer[1]>>4;encodedCharIndexes[2]=(bytebuffer[1]&15)<<2|bytebuffer[2]>>6;encodedCharIndexes[3]=bytebuffer[2]&63;var paddingBytes=inx-(input.length-1);switch(paddingBytes){case 2:encodedCharIndexes[3]=64;encodedCharIndexes[2]=64;break;case 1:encodedCharIndexes[3]=64;break;default:break}for(var _jnx=0;_jnx<encodedCharIndexes.length;++_jnx){output+=_keyStr.charAt(encodedCharIndexes[_jnx])}}return output}},{}],5:[function(require,module,exports){"use strict";exports.__esModule=true;var _Loader=require("./Loader");var _Loader2=_interopRequireDefault(_Loader);var _Resource=require("./Resource");var _Resource2=_interopRequireDefault(_Resource);var _async=require("./async");var async=_interopRequireWildcard(_async);var _b=require("./b64");var b64=_interopRequireWildcard(_b);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}_Loader2.default.Resource=_Resource2.default;_Loader2.default.async=async;_Loader2.default.base64=b64;module.exports=_Loader2.default;exports.default=_Loader2.default},{"./Loader":1,"./Resource":2,"./async":3,"./b64":4}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _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}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var MiniSignalBinding=function(){function MiniSignalBinding(fn,once,thisArg){if(once===undefined)once=false;_classCallCheck(this,MiniSignalBinding);this._fn=fn;this._once=once;this._thisArg=thisArg;this._next=this._prev=this._owner=null}_createClass(MiniSignalBinding,[{key:"detach",value:function detach(){if(this._owner===null)return false;this._owner.detach(this);return true}}]);return MiniSignalBinding}();function _addMiniSignalBinding(self,node){if(!self._head){self._head=node;self._tail=node}else{self._tail._next=node;node._prev=self._tail;self._tail=node}node._owner=self;return node}var MiniSignal=function(){function MiniSignal(){_classCallCheck(this,MiniSignal);this._head=this._tail=undefined}_createClass(MiniSignal,[{key:"handlers",value:function handlers(){var exists=arguments.length<=0||arguments[0]===undefined?false:arguments[0];var node=this._head;if(exists)return!!node;var ee=[];while(node){ee.push(node);node=node._next}return ee}},{key:"has",value:function has(node){if(!(node instanceof MiniSignalBinding)){throw new Error("MiniSignal#has(): First arg must be a MiniSignalBinding object.")}return node._owner===this}},{key:"dispatch",value:function dispatch(){var node=this._head;if(!node)return false;while(node){if(node._once)this.detach(node);node._fn.apply(node._thisArg,arguments);node=node._next}return true}},{key:"add",value:function add(fn){var thisArg=arguments.length<=1||arguments[1]===undefined?null:arguments[1];if(typeof fn!=="function"){throw new Error("MiniSignal#add(): First arg must be a Function.")}return _addMiniSignalBinding(this,new MiniSignalBinding(fn,false,thisArg))}},{key:"once",value:function once(fn){var thisArg=arguments.length<=1||arguments[1]===undefined?null:arguments[1];if(typeof fn!=="function"){throw new Error("MiniSignal#once(): First arg must be a Function.")}return _addMiniSignalBinding(this,new MiniSignalBinding(fn,true,thisArg))}},{key:"detach",value:function detach(node){if(!(node instanceof MiniSignalBinding)){throw new Error("MiniSignal#detach(): First arg must be a MiniSignalBinding object.")}if(node._owner!==this)return this;if(node._prev)node._prev._next=node._next;if(node._next)node._next._prev=node._prev;if(node===this._head){this._head=node._next;if(node._next===null){this._tail=null}}else if(node===this._tail){this._tail=node._prev;this._tail._next=null}node._owner=null;return this}},{key:"detachAll",value:function detachAll(){var node=this._head;if(!node)return this;this._head=this._tail=null;while(node){node._owner=null;node=node._next}return this}}]);return MiniSignal}();MiniSignal.MiniSignalBinding=MiniSignalBinding;exports["default"]=MiniSignal;module.exports=exports["default"]},{}],7:[function(require,module,exports){"use strict";module.exports=function parseURI(str,opts){opts=opts||{};var o={key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var m=o.parser[opts.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--)uri[o.key[i]]=m[i]||"";uri[o.q.name]={};uri[o.key[12]].replace(o.q.parser,function($0,$1,$2){if($1)uri[o.q.name][$1]=$2});return uri}},{}]},{},[5])(5)});
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Loader=f()}})(function(){var define,module,exports;return 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){"use strict";exports.__esModule=true;var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};var _miniSignals=require("mini-signals");var _miniSignals2=_interopRequireDefault(_miniSignals);var _parseUri=require("parse-uri");var _parseUri2=_interopRequireDefault(_parseUri);var _async=require("./async");var async=_interopRequireWildcard(_async);var _Resource=require("./Resource");var _Resource2=_interopRequireDefault(_Resource);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var MAX_PROGRESS=100;var rgxExtractUrlHash=/(#[\w-]+)?$/;var Loader=function(){function Loader(){var _this=this;var baseUrl=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";var concurrency=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;_classCallCheck(this,Loader);this.baseUrl=baseUrl;this.progress=0;this.loading=false;this.defaultQueryString="";this._beforeMiddleware=[];this._afterMiddleware=[];this._resourcesParsing=[];this._boundLoadResource=function(r,d){return _this._loadResource(r,d)};this._queue=async.queue(this._boundLoadResource,concurrency);this._queue.pause();this.resources={};this.onProgress=new _miniSignals2.default;this.onError=new _miniSignals2.default;this.onLoad=new _miniSignals2.default;this.onStart=new _miniSignals2.default;this.onComplete=new _miniSignals2.default}Loader.prototype.add=function add(name,url,options,cb){if(Array.isArray(name)){for(var i=0;i<name.length;++i){this.add(name[i])}return this}if((typeof name==="undefined"?"undefined":_typeof(name))==="object"){cb=url||name.callback||name.onComplete;options=name;url=name.url;name=name.name||name.key||name.url}if(typeof url!=="string"){cb=options;options=url;url=name}if(typeof url!=="string"){throw new Error("No url passed to add resource to loader.")}if(typeof options==="function"){cb=options;options=null}if(this.loading&&(!options||!options.parentResource)){throw new Error("Cannot add resources while the loader is running.")}if(this.resources[name]){throw new Error('Resource named "'+name+'" already exists.')}url=this._prepareUrl(url);this.resources[name]=new _Resource2.default(name,url,options);if(typeof cb==="function"){this.resources[name].onAfterMiddleware.once(cb)}if(this.loading){var parent=options.parentResource;var incompleteChildren=[];for(var _i=0;_i<parent.children.length;++_i){if(!parent.children[_i].isComplete){incompleteChildren.push(parent.children[_i])}}var fullChunk=parent.progressChunk*(incompleteChildren.length+1);var eachChunk=fullChunk/(incompleteChildren.length+2);parent.children.push(this.resources[name]);parent.progressChunk=eachChunk;for(var _i2=0;_i2<incompleteChildren.length;++_i2){incompleteChildren[_i2].progressChunk=eachChunk}}this._queue.push(this.resources[name]);return this};Loader.prototype.pre=function pre(fn){this._beforeMiddleware.push(fn);return this};Loader.prototype.use=function use(fn){this._afterMiddleware.push(fn);return this};Loader.prototype.reset=function reset(){this.progress=0;this.loading=false;this._queue.kill();this._queue.pause();for(var k in this.resources){var res=this.resources[k];if(res._onLoadBinding){res._onLoadBinding.detach()}if(res.isLoading){res.abort()}}this.resources={};return this};Loader.prototype.load=function load(cb){if(typeof cb==="function"){this.onComplete.once(cb)}if(this.loading){return this}var chunk=100/this._queue._tasks.length;for(var i=0;i<this._queue._tasks.length;++i){this._queue._tasks[i].data.progressChunk=chunk}this.loading=true;this.onStart.dispatch(this);this._queue.resume();return this};Loader.prototype._prepareUrl=function _prepareUrl(url){var parsedUrl=(0,_parseUri2.default)(url,{strictMode:true});var result=void 0;if(parsedUrl.protocol||!parsedUrl.path||url.indexOf("//")===0){result=url}else if(this.baseUrl.length&&this.baseUrl.lastIndexOf("/")!==this.baseUrl.length-1&&url.charAt(0)!=="/"){result=this.baseUrl+"/"+url}else{result=this.baseUrl+url}if(this.defaultQueryString){var hash=rgxExtractUrlHash.exec(result)[0];result=result.substr(0,result.length-hash.length);if(result.indexOf("?")!==-1){result+="&"+this.defaultQueryString}else{result+="?"+this.defaultQueryString}result+=hash}return result};Loader.prototype._loadResource=function _loadResource(resource,dequeue){var _this2=this;resource._dequeue=dequeue;async.eachSeries(this._beforeMiddleware,function(fn,next){fn.call(_this2,resource,function(){next(resource.isComplete?{}:null)})},function(){if(resource.isComplete){_this2._onLoad(resource)}else{resource._onLoadBinding=resource.onComplete.once(_this2._onLoad,_this2);resource.load()}})};Loader.prototype._onComplete=function _onComplete(){this.loading=false;this.onComplete.dispatch(this,this.resources)};Loader.prototype._onLoad=function _onLoad(resource){var _this3=this;resource._onLoadBinding=null;resource._dequeue();this._resourcesParsing.push(resource);async.eachSeries(this._afterMiddleware,function(fn,next){fn.call(_this3,resource,next)},function(){resource.onAfterMiddleware.dispatch(resource);_this3.progress+=resource.progressChunk;_this3.onProgress.dispatch(_this3,resource);if(resource.error){_this3.onError.dispatch(resource.error,_this3,resource)}else{_this3.onLoad.dispatch(_this3,resource)}_this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource),1);if(_this3._queue.idle()&&_this3._resourcesParsing.length===0){_this3.progress=MAX_PROGRESS;_this3._onComplete()}})};return Loader}();exports.default=Loader},{"./Resource":2,"./async":3,"mini-signals":6,"parse-uri":7}],2:[function(require,module,exports){"use strict";exports.__esModule=true;var _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}}();var _parseUri=require("parse-uri");var _parseUri2=_interopRequireDefault(_parseUri);var _miniSignals=require("mini-signals");var _miniSignals2=_interopRequireDefault(_miniSignals);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var useXdr=!!(window.XDomainRequest&&!("withCredentials"in new XMLHttpRequest));var tempAnchor=null;var STATUS_NONE=0;var STATUS_OK=200;var STATUS_EMPTY=204;function _noop(){}var Resource=function(){Resource.setExtensionLoadType=function setExtensionLoadType(extname,loadType){setExtMap(Resource._loadTypeMap,extname,loadType)};Resource.setExtensionXhrType=function setExtensionXhrType(extname,xhrType){setExtMap(Resource._xhrTypeMap,extname,xhrType)};function Resource(name,url,options){_classCallCheck(this,Resource);if(typeof name!=="string"||typeof url!=="string"){throw new Error("Both name and url are required for constructing a resource.")}options=options||{};this._flags=0;this._setFlag(Resource.STATUS_FLAGS.DATA_URL,url.indexOf("data:")===0);this.name=name;this.url=url;this.data=null;this.crossOrigin=options.crossOrigin===true?"anonymous":options.crossOrigin;this.loadType=options.loadType||this._determineLoadType();this.xhrType=options.xhrType;this.metadata=options.metadata||{};this.error=null;this.xhr=null;this.children=[];this.type=Resource.TYPE.UNKNOWN;this.progressChunk=0;this._dequeue=_noop;this._onLoadBinding=null;this._boundComplete=this.complete.bind(this);this._boundOnError=this._onError.bind(this);this._boundOnProgress=this._onProgress.bind(this);this._boundXhrOnError=this._xhrOnError.bind(this);this._boundXhrOnAbort=this._xhrOnAbort.bind(this);this._boundXhrOnLoad=this._xhrOnLoad.bind(this);this._boundXdrOnTimeout=this._xdrOnTimeout.bind(this);this.onStart=new _miniSignals2.default;this.onProgress=new _miniSignals2.default;this.onComplete=new _miniSignals2.default;this.onAfterMiddleware=new _miniSignals2.default}Resource.prototype.complete=function complete(){if(this.data&&this.data.removeEventListener){this.data.removeEventListener("error",this._boundOnError,false);this.data.removeEventListener("load",this._boundComplete,false);this.data.removeEventListener("progress",this._boundOnProgress,false);this.data.removeEventListener("canplaythrough",this._boundComplete,false)}if(this.xhr){if(this.xhr.removeEventListener){this.xhr.removeEventListener("error",this._boundXhrOnError,false);this.xhr.removeEventListener("abort",this._boundXhrOnAbort,false);this.xhr.removeEventListener("progress",this._boundOnProgress,false);this.xhr.removeEventListener("load",this._boundXhrOnLoad,false)}else{this.xhr.onerror=null;this.xhr.ontimeout=null;this.xhr.onprogress=null;this.xhr.onload=null}}if(this.isComplete){throw new Error("Complete called again for an already completed resource.")}this._setFlag(Resource.STATUS_FLAGS.COMPLETE,true);this._setFlag(Resource.STATUS_FLAGS.LOADING,false);this.onComplete.dispatch(this)};Resource.prototype.abort=function abort(message){if(this.error){return}this.error=new Error(message);if(this.xhr){this.xhr.abort()}else if(this.xdr){this.xdr.abort()}else if(this.data){if(this.data.src){this.data.src=Resource.EMPTY_GIF}else{while(this.data.firstChild){this.data.removeChild(this.data.firstChild)}}}this.complete()};Resource.prototype.load=function load(cb){var _this=this;if(this.isLoading){return}if(this.isComplete){if(cb){setTimeout(function(){return cb(_this)},1)}return}else if(cb){this.onComplete.once(cb)}this._setFlag(Resource.STATUS_FLAGS.LOADING,true);this.onStart.dispatch(this);if(this.crossOrigin===false||typeof this.crossOrigin!=="string"){this.crossOrigin=this._determineCrossOrigin(this.url)}switch(this.loadType){case Resource.LOAD_TYPE.IMAGE:this.type=Resource.TYPE.IMAGE;this._loadElement("image");break;case Resource.LOAD_TYPE.AUDIO:this.type=Resource.TYPE.AUDIO;this._loadSourceElement("audio");break;case Resource.LOAD_TYPE.VIDEO:this.type=Resource.TYPE.VIDEO;this._loadSourceElement("video");break;case Resource.LOAD_TYPE.XHR:default:if(useXdr&&this.crossOrigin){this._loadXdr()}else{this._loadXhr()}break}};Resource.prototype._hasFlag=function _hasFlag(flag){return!!(this._flags&flag)};Resource.prototype._setFlag=function _setFlag(flag,value){this._flags=value?this._flags|flag:this._flags&~flag};Resource.prototype._loadElement=function _loadElement(type){if(this.metadata.loadElement){this.data=this.metadata.loadElement}else if(type==="image"&&typeof window.Image!=="undefined"){this.data=new Image}else{this.data=document.createElement(type)}if(this.crossOrigin){this.data.crossOrigin=this.crossOrigin}if(!this.metadata.skipSource){this.data.src=this.url}this.data.addEventListener("error",this._boundOnError,false);this.data.addEventListener("load",this._boundComplete,false);this.data.addEventListener("progress",this._boundOnProgress,false)};Resource.prototype._loadSourceElement=function _loadSourceElement(type){if(this.metadata.loadElement){this.data=this.metadata.loadElement}else if(type==="audio"&&typeof window.Audio!=="undefined"){this.data=new Audio}else{this.data=document.createElement(type)}if(this.data===null){this.abort("Unsupported element: "+type);return}if(!this.metadata.skipSource){if(navigator.isCocoonJS){this.data.src=Array.isArray(this.url)?this.url[0]:this.url}else if(Array.isArray(this.url)){for(var i=0;i<this.url.length;++i){this.data.appendChild(this._createSource(type,this.url[i]))}}else{this.data.appendChild(this._createSource(type,this.url))}}this.data.addEventListener("error",this._boundOnError,false);this.data.addEventListener("load",this._boundComplete,false);this.data.addEventListener("progress",this._boundOnProgress,false);this.data.addEventListener("canplaythrough",this._boundComplete,false);this.data.load()};Resource.prototype._loadXhr=function _loadXhr(){if(typeof this.xhrType!=="string"){this.xhrType=this._determineXhrType()}var xhr=this.xhr=new XMLHttpRequest;xhr.open("GET",this.url,true);if(this.xhrType===Resource.XHR_RESPONSE_TYPE.JSON||this.xhrType===Resource.XHR_RESPONSE_TYPE.DOCUMENT){xhr.responseType=Resource.XHR_RESPONSE_TYPE.TEXT}else{xhr.responseType=this.xhrType}xhr.addEventListener("error",this._boundXhrOnError,false);xhr.addEventListener("abort",this._boundXhrOnAbort,false);xhr.addEventListener("progress",this._boundOnProgress,false);xhr.addEventListener("load",this._boundXhrOnLoad,false);xhr.send()};Resource.prototype._loadXdr=function _loadXdr(){if(typeof this.xhrType!=="string"){this.xhrType=this._determineXhrType()}var xdr=this.xhr=new XDomainRequest;xdr.timeout=5e3;xdr.onerror=this._boundXhrOnError;xdr.ontimeout=this._boundXdrOnTimeout;xdr.onprogress=this._boundOnProgress;xdr.onload=this._boundXhrOnLoad;xdr.open("GET",this.url,true);setTimeout(function(){return xdr.send()},1)};Resource.prototype._createSource=function _createSource(type,url,mime){if(!mime){mime=type+"/"+url.substr(url.lastIndexOf(".")+1)}var source=document.createElement("source");source.src=url;source.type=mime;return source};Resource.prototype._onError=function _onError(event){this.abort("Failed to load element using: "+event.target.nodeName)};Resource.prototype._onProgress=function _onProgress(event){if(event&&event.lengthComputable){this.onProgress.dispatch(this,event.loaded/event.total)}};Resource.prototype._xhrOnError=function _xhrOnError(){var xhr=this.xhr;this.abort(reqType(xhr)+" Request failed. Status: "+xhr.status+', text: "'+xhr.statusText+'"')};Resource.prototype._xhrOnAbort=function _xhrOnAbort(){this.abort(reqType(this.xhr)+" Request was aborted by the user.")};Resource.prototype._xdrOnTimeout=function _xdrOnTimeout(){this.abort(reqType(this.xhr)+" Request timed out.")};Resource.prototype._xhrOnLoad=function _xhrOnLoad(){var xhr=this.xhr;var status=typeof xhr.status==="undefined"?xhr.status:STATUS_OK;if(status===STATUS_OK||status===STATUS_EMPTY||status===STATUS_NONE&&xhr.responseText.length>0){if(this.xhrType===Resource.XHR_RESPONSE_TYPE.TEXT){this.data=xhr.responseText;this.type=Resource.TYPE.TEXT}else if(this.xhrType===Resource.XHR_RESPONSE_TYPE.JSON){try{this.data=JSON.parse(xhr.responseText);this.type=Resource.TYPE.JSON}catch(e){this.abort("Error trying to parse loaded json: "+e);return}}else if(this.xhrType===Resource.XHR_RESPONSE_TYPE.DOCUMENT){try{if(window.DOMParser){var domparser=new DOMParser;this.data=domparser.parseFromString(xhr.responseText,"text/xml")}else{var div=document.createElement("div");div.innerHTML=xhr.responseText;this.data=div}this.type=Resource.TYPE.XML}catch(e){this.abort("Error trying to parse loaded xml: "+e);return}}else{this.data=xhr.response||xhr.responseText}}else{this.abort("["+xhr.status+"] "+xhr.statusText+": "+xhr.responseURL);return}this.complete()};Resource.prototype._determineCrossOrigin=function _determineCrossOrigin(url,loc){if(url.indexOf("data:")===0){return""}loc=loc||window.location;if(!tempAnchor){tempAnchor=document.createElement("a")}tempAnchor.href=url;url=(0,_parseUri2.default)(tempAnchor.href,{strictMode:true});var samePort=!url.port&&loc.port===""||url.port===loc.port;var protocol=url.protocol?url.protocol+":":"";if(url.host!==loc.hostname||!samePort||protocol!==loc.protocol){return"anonymous"}return""};Resource.prototype._determineXhrType=function _determineXhrType(){return Resource._xhrTypeMap[this._getExtension()]||Resource.XHR_RESPONSE_TYPE.TEXT};Resource.prototype._determineLoadType=function _determineLoadType(){return Resource._loadTypeMap[this._getExtension()]||Resource.LOAD_TYPE.XHR};Resource.prototype._getExtension=function _getExtension(){var url=this.url;var ext="";if(this.isDataUrl){var slashIndex=url.indexOf("/");ext=url.substring(slashIndex+1,url.indexOf(";",slashIndex))}else{var queryStart=url.indexOf("?");if(queryStart!==-1){url=url.substring(0,queryStart)}ext=url.substring(url.lastIndexOf(".")+1)}return ext.toLowerCase()};Resource.prototype._getMimeFromXhrType=function _getMimeFromXhrType(type){switch(type){case Resource.XHR_RESPONSE_TYPE.BUFFER:return"application/octet-binary";case Resource.XHR_RESPONSE_TYPE.BLOB:return"application/blob";case Resource.XHR_RESPONSE_TYPE.DOCUMENT:return"application/xml";case Resource.XHR_RESPONSE_TYPE.JSON:return"application/json";case Resource.XHR_RESPONSE_TYPE.DEFAULT:case Resource.XHR_RESPONSE_TYPE.TEXT:default:return"text/plain"}};_createClass(Resource,[{key:"isDataUrl",get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL)}},{key:"isComplete",get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE)}},{key:"isLoading",get:function get(){return this._hasFlag(Resource.STATUS_FLAGS.LOADING)}}]);return Resource}();exports.default=Resource;Resource.STATUS_FLAGS={NONE:0,DATA_URL:1<<0,COMPLETE:1<<1,LOADING:1<<2};Resource.TYPE={UNKNOWN:0,JSON:1,XML:2,IMAGE:3,AUDIO:4,VIDEO:5,TEXT:6};Resource.LOAD_TYPE={XHR:1,IMAGE:2,AUDIO:3,VIDEO:4};Resource.XHR_RESPONSE_TYPE={DEFAULT:"text",BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json",TEXT:"text"};Resource._loadTypeMap={gif:Resource.LOAD_TYPE.IMAGE,png:Resource.LOAD_TYPE.IMAGE,bmp:Resource.LOAD_TYPE.IMAGE,jpg:Resource.LOAD_TYPE.IMAGE,jpeg:Resource.LOAD_TYPE.IMAGE,tif:Resource.LOAD_TYPE.IMAGE,tiff:Resource.LOAD_TYPE.IMAGE,webp:Resource.LOAD_TYPE.IMAGE,tga:Resource.LOAD_TYPE.IMAGE,svg:Resource.LOAD_TYPE.IMAGE,"svg+xml":Resource.LOAD_TYPE.IMAGE,mp3:Resource.LOAD_TYPE.AUDIO,ogg:Resource.LOAD_TYPE.AUDIO,wav:Resource.LOAD_TYPE.AUDIO,mp4:Resource.LOAD_TYPE.VIDEO,webm:Resource.LOAD_TYPE.VIDEO};Resource._xhrTypeMap={xhtml:Resource.XHR_RESPONSE_TYPE.DOCUMENT,html:Resource.XHR_RESPONSE_TYPE.DOCUMENT,htm:Resource.XHR_RESPONSE_TYPE.DOCUMENT,xml:Resource.XHR_RESPONSE_TYPE.DOCUMENT,tmx:Resource.XHR_RESPONSE_TYPE.DOCUMENT,svg:Resource.XHR_RESPONSE_TYPE.DOCUMENT,tsx:Resource.XHR_RESPONSE_TYPE.DOCUMENT,gif:Resource.XHR_RESPONSE_TYPE.BLOB,png:Resource.XHR_RESPONSE_TYPE.BLOB,bmp:Resource.XHR_RESPONSE_TYPE.BLOB,jpg:Resource.XHR_RESPONSE_TYPE.BLOB,jpeg:Resource.XHR_RESPONSE_TYPE.BLOB,tif:Resource.XHR_RESPONSE_TYPE.BLOB,tiff:Resource.XHR_RESPONSE_TYPE.BLOB,webp:Resource.XHR_RESPONSE_TYPE.BLOB,tga:Resource.XHR_RESPONSE_TYPE.BLOB,json:Resource.XHR_RESPONSE_TYPE.JSON,text:Resource.XHR_RESPONSE_TYPE.TEXT,txt:Resource.XHR_RESPONSE_TYPE.TEXT,ttf:Resource.XHR_RESPONSE_TYPE.BUFFER,otf:Resource.XHR_RESPONSE_TYPE.BUFFER};Resource.EMPTY_GIF="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";function setExtMap(map,extname,val){if(extname&&extname.indexOf(".")===0){extname=extname.substring(1)}if(!extname){return}map[extname]=val}function reqType(xhr){return xhr.toString().replace("object ","")}},{"mini-signals":6,"parse-uri":7}],3:[function(require,module,exports){"use strict";exports.__esModule=true;exports.eachSeries=eachSeries;exports.queue=queue;function _noop(){}function eachSeries(array,iterator,callback){var i=0;var len=array.length;(function next(err){if(err||i===len){if(callback){callback(err)}return}iterator(array[i++],next)})()}function onlyOnce(fn){return function onceWrapper(){if(fn===null){throw new Error("Callback was already called.")}var callFn=fn;fn=null;callFn.apply(this,arguments)}}function queue(worker,concurrency){if(concurrency==null){concurrency=1}else if(concurrency===0){throw new Error("Concurrency must not be zero")}var workers=0;var q={_tasks:[],concurrency:concurrency,saturated:_noop,unsaturated:_noop,buffer:concurrency/4,empty:_noop,drain:_noop,error:_noop,started:false,paused:false,push:function push(data,callback){_insert(data,false,callback)},kill:function kill(){workers=0;q.drain=_noop;q.started=false;q._tasks=[]},unshift:function unshift(data,callback){_insert(data,true,callback)},process:function process(){while(!q.paused&&workers<q.concurrency&&q._tasks.length){var task=q._tasks.shift();if(q._tasks.length===0){q.empty()}workers+=1;if(workers===q.concurrency){q.saturated()}worker(task.data,onlyOnce(_next(task)))}},length:function length(){return q._tasks.length},running:function running(){return workers},idle:function idle(){return q._tasks.length+workers===0},pause:function pause(){if(q.paused===true){return}q.paused=true},resume:function resume(){if(q.paused===false){return}q.paused=false;for(var w=1;w<=q.concurrency;w++){q.process()}}};function _insert(data,insertAtFront,callback){if(callback!=null&&typeof callback!=="function"){throw new Error("task callback must be a function")}q.started=true;if(data==null&&q.idle()){setTimeout(function(){return q.drain()},1);return}var item={data:data,callback:typeof callback==="function"?callback:_noop};if(insertAtFront){q._tasks.unshift(item)}else{q._tasks.push(item)}setTimeout(function(){return q.process()},1)}function _next(task){return function next(){workers-=1;task.callback.apply(task,arguments);if(arguments[0]!=null){q.error(arguments[0],task.data)}if(workers<=q.concurrency-q.buffer){q.unsaturated()}if(q.idle()){q.drain()}q.process()}}return q}},{}],4:[function(require,module,exports){"use strict";exports.__esModule=true;exports.encodeBinary=encodeBinary;var _keyStr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";function encodeBinary(input){var output="";var inx=0;while(inx<input.length){var bytebuffer=[0,0,0];var encodedCharIndexes=[0,0,0,0];for(var jnx=0;jnx<bytebuffer.length;++jnx){if(inx<input.length){bytebuffer[jnx]=input.charCodeAt(inx++)&255}else{bytebuffer[jnx]=0}}encodedCharIndexes[0]=bytebuffer[0]>>2;encodedCharIndexes[1]=(bytebuffer[0]&3)<<4|bytebuffer[1]>>4;encodedCharIndexes[2]=(bytebuffer[1]&15)<<2|bytebuffer[2]>>6;encodedCharIndexes[3]=bytebuffer[2]&63;var paddingBytes=inx-(input.length-1);switch(paddingBytes){case 2:encodedCharIndexes[3]=64;encodedCharIndexes[2]=64;break;case 1:encodedCharIndexes[3]=64;break;default:break}for(var _jnx=0;_jnx<encodedCharIndexes.length;++_jnx){output+=_keyStr.charAt(encodedCharIndexes[_jnx])}}return output}},{}],5:[function(require,module,exports){"use strict";exports.__esModule=true;var _Loader=require("./Loader");var _Loader2=_interopRequireDefault(_Loader);var _Resource=require("./Resource");var _Resource2=_interopRequireDefault(_Resource);var _async=require("./async");var async=_interopRequireWildcard(_async);var _b=require("./b64");var b64=_interopRequireWildcard(_b);function _interopRequireWildcard(obj){if(obj&&obj.__esModule){return obj}else{var newObj={};if(obj!=null){for(var key in obj){if(Object.prototype.hasOwnProperty.call(obj,key))newObj[key]=obj[key]}}newObj.default=obj;return newObj}}function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}_Loader2.default.Resource=_Resource2.default;_Loader2.default.async=async;_Loader2.default.base64=b64;module.exports=_Loader2.default;exports.default=_Loader2.default},{"./Loader":1,"./Resource":2,"./async":3,"./b64":4}],6:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});var _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}}();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var MiniSignalBinding=function(){function MiniSignalBinding(fn,once,thisArg){if(once===undefined)once=false;_classCallCheck(this,MiniSignalBinding);this._fn=fn;this._once=once;this._thisArg=thisArg;this._next=this._prev=this._owner=null}_createClass(MiniSignalBinding,[{key:"detach",value:function detach(){if(this._owner===null)return false;this._owner.detach(this);return true}}]);return MiniSignalBinding}();function _addMiniSignalBinding(self,node){if(!self._head){self._head=node;self._tail=node}else{self._tail._next=node;node._prev=self._tail;self._tail=node}node._owner=self;return node}var MiniSignal=function(){function MiniSignal(){_classCallCheck(this,MiniSignal);this._head=this._tail=undefined}_createClass(MiniSignal,[{key:"handlers",value:function handlers(){var exists=arguments.length<=0||arguments[0]===undefined?false:arguments[0];var node=this._head;if(exists)return!!node;var ee=[];while(node){ee.push(node);node=node._next}return ee}},{key:"has",value:function has(node){if(!(node instanceof MiniSignalBinding)){throw new Error("MiniSignal#has(): First arg must be a MiniSignalBinding object.")}return node._owner===this}},{key:"dispatch",value:function dispatch(){var node=this._head;if(!node)return false;while(node){if(node._once)this.detach(node);node._fn.apply(node._thisArg,arguments);node=node._next}return true}},{key:"add",value:function add(fn){var thisArg=arguments.length<=1||arguments[1]===undefined?null:arguments[1];if(typeof fn!=="function"){throw new Error("MiniSignal#add(): First arg must be a Function.")}return _addMiniSignalBinding(this,new MiniSignalBinding(fn,false,thisArg))}},{key:"once",value:function once(fn){var thisArg=arguments.length<=1||arguments[1]===undefined?null:arguments[1];if(typeof fn!=="function"){throw new Error("MiniSignal#once(): First arg must be a Function.")}return _addMiniSignalBinding(this,new MiniSignalBinding(fn,true,thisArg))}},{key:"detach",value:function detach(node){if(!(node instanceof MiniSignalBinding)){throw new Error("MiniSignal#detach(): First arg must be a MiniSignalBinding object.")}if(node._owner!==this)return this;if(node._prev)node._prev._next=node._next;if(node._next)node._next._prev=node._prev;if(node===this._head){this._head=node._next;if(node._next===null){this._tail=null}}else if(node===this._tail){this._tail=node._prev;this._tail._next=null}node._owner=null;return this}},{key:"detachAll",value:function detachAll(){var node=this._head;if(!node)return this;this._head=this._tail=null;while(node){node._owner=null;node=node._next}return this}}]);return MiniSignal}();MiniSignal.MiniSignalBinding=MiniSignalBinding;exports["default"]=MiniSignal;module.exports=exports["default"]},{}],7:[function(require,module,exports){"use strict";module.exports=function parseURI(str,opts){opts=opts||{};var o={key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var m=o.parser[opts.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--)uri[o.key[i]]=m[i]||"";uri[o.q.name]={};uri[o.key[12]].replace(o.q.parser,function($0,$1,$2){if($1)uri[o.q.name][$1]=$2});return uri}},{}]},{},[5])(5)});

@@ -31,3 +31,3 @@ 'use strict';

var MAX_PROGRESS = 100;
var rgxExtractUrlHash = /(#[\w\-]+)?$/;
var rgxExtractUrlHash = /(#[\w-]+)?$/;

@@ -114,2 +114,9 @@ /**

/**
* The tracks the resources we are currently completing parsing for.
*
* @member {Resource[]}
*/
this._resourcesParsing = [];
/**
* The `_loadResource` function bound with this object context.

@@ -350,13 +357,21 @@ *

// if loading make sure to adjust progress chunks for that parent and its children
// if actively loading, make sure to adjust progress chunks for that parent and its children
if (this.loading) {
var parent = options.parentResource;
var fullChunk = parent.progressChunk * (parent.children.length + 1); // +1 for parent
var eachChunk = fullChunk / (parent.children.length + 2); // +2 for parent & new child
var incompleteChildren = [];
for (var _i = 0; _i < parent.children.length; ++_i) {
if (!parent.children[_i].isComplete) {
incompleteChildren.push(parent.children[_i]);
}
}
var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent
var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child
parent.children.push(this.resources[name]);
parent.progressChunk = eachChunk;
for (var _i = 0; _i < parent.children.length; ++_i) {
parent.children[_i].progressChunk = eachChunk;
for (var _i2 = 0; _i2 < incompleteChildren.length; ++_i2) {
incompleteChildren[_i2].progressChunk = eachChunk;
}

@@ -573,2 +588,6 @@ }

// remove this resource from the async queue, and add it to our list of resources that are being parsed
resource._dequeue();
this._resourcesParsing.push(resource);
// run middleware, this *must* happen before dequeue so sub-assets get added properly

@@ -589,7 +608,6 @@ async.eachSeries(this._afterMiddleware, function (fn, next) {

// remove this resource from the async queue
resource._dequeue();
_this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1);
// do completion check
if (_this3._queue.idle()) {
if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) {
_this3.progress = MAX_PROGRESS;

@@ -596,0 +614,0 @@ _this3._onComplete();

{
"name": "resource-loader",
"version": "2.0.3",
"version": "2.0.4",
"main": "./lib/index.js",
"jsnext:main": "./src/index.js",
"description": "A generic asset loader, made with web games in mind.",

@@ -28,4 +27,6 @@ "author": "Chad Engler <chad@pantherdev.com>",

"scripts": {
"clean": "rm -rf ./dist ./lib && mkdir dist && mkdir lib",
"prebuild": "npm run lib",
"clean": "rm -rf ./dist ./lib && npm run setup",
"setup": "mkdirp dist lib",
"full-build": "npm run clean && npm run build && npm run minify",
"prebuild": "npm run setup && npm run lib",
"build": "browserify -d -s Loader -e ./lib/index.js -o ./dist/resource-loader.js",

@@ -36,8 +37,8 @@ "lib": "babel src --out-dir lib -s",

"lint": "eslint src/ test/",
"start": "npm run build",
"pretest": "npm run build",
"start": "npm run full-build",
"pretest": "npm run full-build",
"test": "npm run test-dev -- --single-run",
"test-dev": "karma start test/karma.conf.js",
"docs": "jsdoc -c jsdoc.conf.json -R README.md",
"prepublish": "npm run build && npm run minify"
"prepublish": "npm run full-build"
},

@@ -63,2 +64,3 @@ "dependencies": {

"karma-sinon-chai": "^1.2.4",
"mkdirp": "^0.5.1",
"mocha": "^3.2.0",

@@ -65,0 +67,0 @@ "sinon": "^1.17.6",

@@ -8,3 +8,3 @@ import Signal from 'mini-signals';

const MAX_PROGRESS = 100;
const rgxExtractUrlHash = /(#[\w\-]+)?$/;
const rgxExtractUrlHash = /(#[\w-]+)?$/;

@@ -83,2 +83,9 @@ /**

/**
* The tracks the resources we are currently completing parsing for.
*
* @member {Resource[]}
*/
this._resourcesParsing = [];
/**
* The `_loadResource` function bound with this object context.

@@ -315,13 +322,21 @@ *

// if loading make sure to adjust progress chunks for that parent and its children
// if actively loading, make sure to adjust progress chunks for that parent and its children
if (this.loading) {
const parent = options.parentResource;
const fullChunk = parent.progressChunk * (parent.children.length + 1); // +1 for parent
const eachChunk = fullChunk / (parent.children.length + 2); // +2 for parent & new child
const incompleteChildren = [];
for (let i = 0; i < parent.children.length; ++i) {
if (!parent.children[i].isComplete) {
incompleteChildren.push(parent.children[i]);
}
}
const fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent
const eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child
parent.children.push(this.resources[name]);
parent.progressChunk = eachChunk;
for (let i = 0; i < parent.children.length; ++i) {
parent.children[i].progressChunk = eachChunk;
for (let i = 0; i < incompleteChildren.length; ++i) {
incompleteChildren[i].progressChunk = eachChunk;
}

@@ -528,2 +543,6 @@ }

// remove this resource from the async queue, and add it to our list of resources that are being parsed
resource._dequeue();
this._resourcesParsing.push(resource);
// run middleware, this *must* happen before dequeue so sub-assets get added properly

@@ -548,7 +567,6 @@ async.eachSeries(

// remove this resource from the async queue
resource._dequeue();
this._resourcesParsing.splice(this._resourcesParsing.indexOf(resource), 1);
// do completion check
if (this._queue.idle()) {
if (this._queue.idle() && this._resourcesParsing.length === 0) {
this.progress = MAX_PROGRESS;

@@ -555,0 +573,0 @@ this._onComplete();

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc