diff --git a/.github/workflows/moodle-ci.yml b/.github/workflows/moodle-ci.yml index 670a2fb..31288a6 100644 --- a/.github/workflows/moodle-ci.yml +++ b/.github/workflows/moodle-ci.yml @@ -28,9 +28,15 @@ jobs: fail-fast: false matrix: include: - - php: '8.1' + - php: '8.3' moodle-branch: 'master' database: 'pgsql' + - php: '8.2' + moodle-branch: 'master' + database: 'mariadb' + - php: '8.1' + moodle-branch: 'MOODLE_404_STABLE' + database: 'mariadb' - php: '8.1' moodle-branch: 'MOODLE_403_STABLE' database: 'pgsql' @@ -39,7 +45,7 @@ jobs: database: 'mariadb' - php: '8.0' moodle-branch: 'MOODLE_401_STABLE' - database: 'mariadb' + database: 'pgsql' steps: - name: Check out repository code diff --git a/classes/media_manager.php b/classes/media_manager.php index b4634e3..97a3dbd 100644 --- a/classes/media_manager.php +++ b/classes/media_manager.php @@ -45,11 +45,14 @@ */ class media_manager implements renderable, templatable { /** @var array $media List of media resources to display */ - protected $media; + protected $media = null; /** @var int $page Paging offset */ protected int $page = 0; + /** @var $source Source manager */ + protected $source = null; + /** @var $page Search form */ protected $search = null; @@ -71,7 +74,6 @@ public function __construct(string $source, ?stdClass $record = null, int $page require_capability('tool/mediatime:view', context_system::instance()); if ($record) { $source = $record->source; - $record->content = json_decode($record->content); } $plugins = plugininfo\mediatimesrc::get_enabled_plugins(); @@ -98,7 +100,7 @@ public function __construct(string $source, ?stdClass $record = null, int $page $rs = self::search((array)$this->search->get_data()); foreach ($rs as $media) { if (in_array($media->source, $plugins)) { - $media->content = json_decode($media->content); + $media->content = $media->content ?? '{}'; $this->media[] = $media; } } @@ -136,7 +138,8 @@ public function export_for_template(renderer_base $output): array { 'imageurl' => $resource->image_url($output), 'tags' => $resource->tags($output), 'url' => $url->out(), - 'content' => $record->content, + 'name' => $record->name, + 'title' => $resource->get_title(), 'removeurl' => $removeurl->out(), ]; } diff --git a/classes/output/media_resource.php b/classes/output/media_resource.php index 8730533..c00ca40 100644 --- a/classes/output/media_resource.php +++ b/classes/output/media_resource.php @@ -121,4 +121,16 @@ public function image_url($output) { public function video_file_content($output) { return $this->resource->video_file_content($output); } + + /** + * Return resource title + * + * @return string + */ + public function get_title() { + if (method_exists($this->resource, 'get_title')) { + return $this->resource->get_title(); + } + return json_decode($this->record->content)->title ?? ''; + } } diff --git a/lang/en/tool_mediatime.php b/lang/en/tool_mediatime.php index 041ab61..daff3fc 100644 --- a/lang/en/tool_mediatime.php +++ b/lang/en/tool_mediatime.php @@ -49,3 +49,5 @@ $string['tagarea_tool_mediatime'] = 'Media resources'; $string['title'] = 'Title'; $string['title_help'] = 'The title may be displayed by the video player when used'; +$string['subplugintype_mediatimesrc_plural'] = 'Media Time sources'; +$string['filelinks'] = 'File links'; diff --git a/source/streamio/classes/form/delete_resource.php b/source/streamio/classes/form/delete_resource.php index 64fbfab..c9eb4c9 100644 --- a/source/streamio/classes/form/delete_resource.php +++ b/source/streamio/classes/form/delete_resource.php @@ -36,7 +36,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class delete_resource extends \tool_mediatime\form\delete_resource { - /** * Definition */ diff --git a/source/streamio/classes/form/edit_resource.php b/source/streamio/classes/form/edit_resource.php index b8eacad..23dc230 100644 --- a/source/streamio/classes/form/edit_resource.php +++ b/source/streamio/classes/form/edit_resource.php @@ -40,7 +40,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class edit_resource extends \tool_mediatime\form\edit_resource { - /** * Definition */ @@ -93,7 +92,7 @@ public function definition_after_data() { $record = $DB->get_record('tool_mediatime', ['id' => $id]); $context = context_system::instance(); if ($record) { - $record->content = json_decode($record->content); + $content = json_decode($record->content); $resource = new media_resource($record); $videourl = $resource->video_url($OUTPUT); diff --git a/source/streamio/classes/manager.php b/source/streamio/classes/manager.php index 7f77e39..fb61c81 100644 --- a/source/streamio/classes/manager.php +++ b/source/streamio/classes/manager.php @@ -234,13 +234,13 @@ protected function save_file($id, $video) { 'tool_mediatime', 'm3u8', $id, - 'id DESC', false + 'id DESC', + false ); foreach ($files as $file) { $file->delete(); } if ($video->transcodings) { - $fileinfo = [ 'contextid' => SYSCONTEXTID, 'component' => 'tool_mediatime', diff --git a/source/streamio/classes/output/media_resource.php b/source/streamio/classes/output/media_resource.php index f163f54..ced7fad 100644 --- a/source/streamio/classes/output/media_resource.php +++ b/source/streamio/classes/output/media_resource.php @@ -61,7 +61,6 @@ public function __construct(stdClass $record) { */ public function export_for_template(renderer_base $output) { global $DB, $USER; - $content = (array)$this->record->content; $context = \context_system::instance(); $videourl = $this->video_url($output); @@ -96,7 +95,7 @@ public function export_for_template(renderer_base $output) { * @return string url */ public function image_url(renderer_base $output) { - return 'https://' . $this->record->content->screenshot->normal; + return 'https://' . json_decode($this->record->content)->screenshot->normal; } /** @@ -108,7 +107,7 @@ public function image_url(renderer_base $output) { public function video_url($output) { $this->videourl = ''; - $id = $this->record->content->id; + $id = json_decod($this->record->content)->id; return "https://streamio.com/api/v1/videos/$id/public_show.m3u8"; } diff --git a/source/streamio/classes/privacy/provider.php b/source/streamio/classes/privacy/provider.php index 815576e..7ca8224 100644 --- a/source/streamio/classes/privacy/provider.php +++ b/source/streamio/classes/privacy/provider.php @@ -31,14 +31,13 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class provider implements \core_privacy\local\metadata\null_provider { - /** * Get the language string identifier with the component's language * file to explain why this plugin stores no data. * * @return string */ - public static function get_reason() : string { + public static function get_reason(): string { return 'privacy:metadata'; } } diff --git a/source/streamio/lang/en/mediatimesrc_streamio.php b/source/streamio/lang/en/mediatimesrc_streamio.php index 6a0d15d..3305c78 100644 --- a/source/streamio/lang/en/mediatimesrc_streamio.php +++ b/source/streamio/lang/en/mediatimesrc_streamio.php @@ -25,22 +25,22 @@ defined('MOODLE_INTERNAL') || die(); -$string['pluginname'] = 'Streamio'; $string['event_resource_created'] = 'Streamio resource created'; $string['event_resource_deleted'] = 'Streamio resource deleted'; $string['event_resource_updated'] = 'Streamio resource updated'; $string['keepstreamiofiles'] = 'Keep Streamio files'; $string['password'] = 'Password'; $string['password_help'] = 'Streamio password for administrative access'; +$string['pluginname'] = 'Streamio'; +$string['privacy:metadata'] = 'The Streamio plugin for Media Time does not store personal data. It does transmit files associated with educational video content that normally does not contain user data. If it is used for personal data, a separate agreement with the provider may be required.'; $string['removestreamiofiles'] = 'Remove Streamio files'; $string['selectexistingfile'] = 'Select existing file'; -$string['streamiofileaction'] = 'Streamio file action'; -$string['streamiofileaction_help'] = 'Select whether the file should be deleted on Streamio when the local content is deleted. If the file is used in other local resources, it will no longer be available to users.'; $string['streamio:upload'] = 'Upload files to Streamio'; $string['streamio:viewall'] = 'View all files available'; +$string['streamiofileaction'] = 'Streamio file action'; +$string['streamiofileaction_help'] = 'Select whether the file should be deleted on Streamio when the local content is deleted. If the file is used in other local resources, it will no longer be available to users.'; $string['uploadnewfile'] = 'Upload new file'; $string['username'] = 'Username'; $string['username_help'] = 'Streamio user name for administrative access found in Streamio settings'; $string['videofile'] = 'Video file'; $string['videofile_help'] = 'Choose to upload a new video, or choose to use an existing one that you select'; -$string['privacy:metadata'] = 'The Streamio plugin for Media Time does not store personal data. It does transmit files associated with educational video content that normally does not contain user data. If it is used for personal data, a separate agreement with the provider may be required.'; diff --git a/source/streamio/templates/file_upload.mustache b/source/streamio/templates/file_upload.mustache index b71bdb3..41bac31 100644 --- a/source/streamio/templates/file_upload.mustache +++ b/source/streamio/templates/file_upload.mustache @@ -42,7 +42,7 @@
- +
diff --git a/source/videotime/classes/form/delete_resource.php b/source/videotime/classes/form/delete_resource.php index 567b712..c6c677c 100644 --- a/source/videotime/classes/form/delete_resource.php +++ b/source/videotime/classes/form/delete_resource.php @@ -36,7 +36,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class delete_resource extends \tool_mediatime\form\delete_resource { - /** * Definition */ diff --git a/source/videotime/classes/form/edit_resource.php b/source/videotime/classes/form/edit_resource.php index f2a6069..d7c69d0 100644 --- a/source/videotime/classes/form/edit_resource.php +++ b/source/videotime/classes/form/edit_resource.php @@ -38,7 +38,6 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class edit_resource extends \tool_mediatime\form\edit_resource { - /** * Definition */ diff --git a/source/videotime/classes/manager.php b/source/videotime/classes/manager.php index 839d679..646bbaa 100644 --- a/source/videotime/classes/manager.php +++ b/source/videotime/classes/manager.php @@ -68,7 +68,7 @@ public function __construct($record = null) { } if ($record) { - $this->content = $record->content; + $this->content = json_decode($record->content); } $maxbytes = get_config('mediatimesrc_videotime', 'maxbytes'); diff --git a/source/videotime/classes/output/media_resource.php b/source/videotime/classes/output/media_resource.php index 66192a4..5da70de 100644 --- a/source/videotime/classes/output/media_resource.php +++ b/source/videotime/classes/output/media_resource.php @@ -41,9 +41,18 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class media_resource implements renderable, templatable { + /** @var $context System context */ + protected $context = null; + + /** @var $context Poster image url */ + protected $poster = null; + /** @var ?stdClass $record Media Time resource record */ protected $record; + /** @var $context Video url */ + protected $videourl = null; + /** * Constructor * @@ -83,7 +92,7 @@ public function export_for_template(renderer_base $output) { 'canedit' => has_capability('moodle/tag:edit', $this->context) || $USER->id == $this->record->usermodified, 'id' => $this->record->id, 'libraryhome' => new moodle_url('/admin/tool/mediatime/index.php'), - 'resource' => $this->record->content, + 'resource' => json_decode($this->record->content), 'video' => $output->render_from_template('mediatimesrc_videotime/video', $content), ]; } diff --git a/source/videotime/classes/privacy/provider.php b/source/videotime/classes/privacy/provider.php index 73cd310..15873d5 100644 --- a/source/videotime/classes/privacy/provider.php +++ b/source/videotime/classes/privacy/provider.php @@ -31,14 +31,13 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class provider implements \core_privacy\local\metadata\null_provider { - /** * Get the language string identifier with the component's language * file to explain why this plugin stores no data. * * @return string */ - public static function get_reason() : string { + public static function get_reason(): string { return 'privacy:metadata'; } } diff --git a/source/videotime/lang/en/mediatimesrc_videotime.php b/source/videotime/lang/en/mediatimesrc_videotime.php index f67d0ef..474f82f 100644 --- a/source/videotime/lang/en/mediatimesrc_videotime.php +++ b/source/videotime/lang/en/mediatimesrc_videotime.php @@ -25,14 +25,14 @@ defined('MOODLE_INTERNAL') || die(); -$string['pluginname'] = 'Video Time resource'; +$string['configmaxbytes'] = 'Default maximum file size for all files uploaded'; $string['event_resource_created'] = 'Video Time resource created'; $string['event_resource_deleted'] = 'Video Time resource deleted'; $string['event_resource_updated'] = 'Video Time resource updated'; $string['maxbytes'] = 'Maximum size of file uploads'; +$string['pluginname'] = 'Video Time resource'; $string['posterimage'] = 'Poster image'; $string['posterimage_help'] = 'Select an image to displayed before the video is played or as a thumbnail image.'; +$string['privacy:metadata'] = 'The Video Time resource does not store or transmit any personal data.'; $string['videofile'] = 'Video file'; $string['videofile_help'] = 'Video file to be displayed'; -$string['configmaxbytes'] = 'Default maximum file size for all files uploaded'; -$string['privacy:metadata'] = 'The Video Time resource does not store or transmit any personal data.'; diff --git a/source/videotime/lib.php b/source/videotime/lib.php index 92d753f..d9dddbb 100644 --- a/source/videotime/lib.php +++ b/source/videotime/lib.php @@ -38,25 +38,29 @@ * @param array $options additional options affecting the file serving * @return bool false if the file was not found, just send the file otherwise and do not return anything */ -function mediatimesrc_videotime_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=[]) { +function mediatimesrc_videotime_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = []) { if ($context->contextlevel != CONTEXT_SYSTEM) { return false; } - require_login(); - - if (in_array($filearea, [ - 'posterimage', + if ( + in_array($filearea, [ 'videofile', - ])) { + ]) + ) { $itemid = array_shift($args); + $contenthash = array_shift($args); $relativepath = implode('/', $args); $fullpath = "/$context->id/mediatimesrc_videotime/$filearea/$itemid/$relativepath"; $fs = get_file_storage(); - if ((!$file = $fs->get_file_by_hash(sha1($fullpath))) || $file->is_directory()) { + if ( + (!$file = $fs->get_file_by_hash(sha1($fullpath))) + || $file->is_directory() + || $file->get_contenthash() != $contenthash + ) { return false; } @@ -72,6 +76,6 @@ function mediatimesrc_videotime_pluginfile($course, $cm, $context, $filearea, $a function mediatimesrc_videotime_config_file_areas() { return [ 'posterimage', - 'videotile', + 'videofile', ]; } diff --git a/source/vimeo/amd/build/file_upload.min.js b/source/vimeo/amd/build/file_upload.min.js new file mode 100644 index 0000000..a99941c --- /dev/null +++ b/source/vimeo/amd/build/file_upload.min.js @@ -0,0 +1,3 @@ +define("mediatimesrc_vimeo/file_upload",["exports","core/ajax","core/config","core/log","core/notification"],(function(_exports,_ajax,_config,_log,_notification){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_ajax=_interopRequireDefault(_ajax),_config=_interopRequireDefault(_config),_log=_interopRequireDefault(_log),_notification=_interopRequireDefault(_notification);const upload=async resource=>{const file=document.querySelector('input[name="videofile"]').files[0],url=new URL(_config.default.wwwroot+"/admin/tool/mediatime/index.php");let response;url.searchParams.set("id",resource.id);do{const request=new Request(resource.uploadurl,{body:file,headers:{"Tus-Resumable":"1.0.0","Upload-Offset":String(0),"Content-Type":"application/offset+octet-stream"},method:"PATCH"});response=await fetch(request),document.querySelector(".progress").style.width=response.headers.get("Upload-Offset")/file.size*100+"%",_log.default.debug(response.headers.get("Upload-Offset"))}while(response.headers.get("Upload-Offset") {\n const file = document.querySelector('input[name=\"videofile\"]').files[0];\n const url = new URL(Config.wwwroot + '/admin/tool/mediatime/index.php');\n let offset = 0;\n let response;\n\n url.searchParams.set('id', resource.id);\n\n do {\n const request = new Request(resource.uploadurl, {\n body: file,\n headers: {\n 'Tus-Resumable': '1.0.0',\n 'Upload-Offset': String(offset),\n 'Content-Type': 'application/offset+octet-stream'\n },\n method: 'PATCH'\n });\n response = await fetch(request);\n document.querySelector('.progress').style.width = (response.headers.get('Upload-Offset') / file.size * 100) + '%';\n Log.debug(response.headers.get('Upload-Offset'));\n } while (response.headers.get('Upload-Offset') < file.size);\n window.location.href = url;\n};\n\nexport default {\n init: function() {\n document.body.removeEventListener('click', this.handleClick);\n document.body.addEventListener('click', this.handleClick);\n },\n\n handleClick: function(e) {\n const button = e.target.closest('button[name=\"upload\"]');\n if (button) {\n const file = document.querySelector('input[name=\"videofile\"]').files[0];\n e.preventDefault();\n Ajax.call([{\n args: {\n filesize: Number(file.size),\n description: document.querySelector('input[name=\"description\"]').value,\n name: document.querySelector('input[name=\"name\"]').value,\n tags: document.querySelector('input[name=\"tags\"]').value,\n title: document.querySelector('input[name=\"title\"]').value\n },\n contextid: 1,\n done: upload,\n fail: Notification.exception,\n methodname: 'mediatimesrc_vimeo_create_token'\n }]);\n Log.debug(file.size);\n }\n }\n};\n"],"names":["upload","async","file","document","querySelector","files","url","URL","Config","wwwroot","response","searchParams","set","resource","id","request","Request","uploadurl","body","headers","String","method","fetch","style","width","get","size","debug","window","location","href","init","removeEventListener","this","handleClick","addEventListener","e","target","closest","preventDefault","call","args","filesize","Number","description","value","name","tags","title","contextid","done","fail","Notification","exception","methodname"],"mappings":"4eAKMA,OAASC,MAAAA,iBACLC,KAAOC,SAASC,cAAc,2BAA2BC,MAAM,GAC/DC,IAAM,IAAIC,IAAIC,gBAAOC,QAAU,uCAEjCC,SAEJJ,IAAIK,aAAaC,IAAI,KAAMC,SAASC,MAEjC,OACOC,QAAU,IAAIC,QAAQH,SAASI,UAAW,CAC5CC,KAAMhB,KACNiB,QAAS,iBACY,wBACAC,OAVhB,kBAWe,mCAEpBC,OAAQ,UAEZX,eAAiBY,MAAMP,SACvBZ,SAASC,cAAc,aAAamB,MAAMC,MAASd,SAASS,QAAQM,IAAI,iBAAmBvB,KAAKwB,KAAO,IAAO,iBAC1GC,MAAMjB,SAASS,QAAQM,IAAI,wBAC1Bf,SAASS,QAAQM,IAAI,iBAAmBvB,KAAKwB,MACtDE,OAAOC,SAASC,KAAOxB,kBAGZ,CACXyB,KAAM,WACF5B,SAASe,KAAKc,oBAAoB,QAASC,KAAKC,aAChD/B,SAASe,KAAKiB,iBAAiB,QAASF,KAAKC,cAGjDA,YAAa,SAASE,MACHA,EAAEC,OAAOC,QAAQ,yBACpB,OACFpC,KAAOC,SAASC,cAAc,2BAA2BC,MAAM,GACrE+B,EAAEG,+BACGC,KAAK,CAAC,CACPC,KAAM,CACFC,SAAUC,OAAOzC,KAAKwB,MACtBkB,YAAazC,SAASC,cAAc,6BAA6ByC,MACjEC,KAAM3C,SAASC,cAAc,sBAAsByC,MACnDE,KAAM5C,SAASC,cAAc,sBAAsByC,MACnDG,MAAO7C,SAASC,cAAc,uBAAuByC,OAEzDI,UAAW,EACXC,KAAMlD,OACNmD,KAAMC,sBAAaC,UACnBC,WAAY,kDAEZ3B,MAAMzB,KAAKwB"} \ No newline at end of file diff --git a/source/vimeo/amd/build/tus.min.js b/source/vimeo/amd/build/tus.min.js new file mode 100644 index 0000000..caf79bd --- /dev/null +++ b/source/vimeo/amd/build/tus.min.js @@ -0,0 +1,3 @@ +!function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define("mediatimesrc_vimeo/tus",[],f);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).tus=f()}}((function(){return function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){return o(e[i][1][r]||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return handle("end");if(i.tryLoc<=this.prev){var c=n.call(i,"catchLoc"),u=n.call(i,"finallyLoc");if(c&&u){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),resetTryEntry(r),y}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;resetTryEntry(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:values(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),y}},e}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _defineProperties(target,props){for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:null;return new Promise((function(resolve,reject){_this._xhr.onload=function(){resolve(new Response(_this._xhr))},_this._xhr.onerror=function(err){reject(err)},_this._xhr.send(body)}))}},{key:"abort",value:function(){return this._xhr.abort(),Promise.resolve()}},{key:"getUnderlyingObject",value:function(){return this._xhr}}]),Request}(),Response=function(){function Response(xhr){_classCallCheck(this,Response),this._xhr=xhr}return _createClass(Response,[{key:"getStatus",value:function(){return this._xhr.status}},{key:"getHeader",value:function(header){return this._xhr.getResponseHeader(header)}},{key:"getBody",value:function(){return this._xhr.responseText}},{key:"getUnderlyingObject",value:function(){return this._xhr}}]),Response}()},{}],4:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"DefaultHttpStack",{enumerable:!0,get:function(){return _httpStack.default}}),Object.defineProperty(exports,"DetailedError",{enumerable:!0,get:function(){return _error.default}}),exports.Upload=void 0,Object.defineProperty(exports,"canStoreURLs",{enumerable:!0,get:function(){return _urlStorage.canStoreURLs}}),exports.defaultOptions=void 0,Object.defineProperty(exports,"enableDebugLog",{enumerable:!0,get:function(){return _logger.enableDebugLog}}),exports.isSupported=void 0;var _upload=_interopRequireDefault(require("../upload.js")),_noopUrlStorage=_interopRequireDefault(require("../noopUrlStorage.js")),_logger=require("../logger.js"),_error=_interopRequireDefault(require("../error.js")),_urlStorage=require("./urlStorage.js"),_httpStack=_interopRequireDefault(require("./httpStack.js")),_fileReader=_interopRequireDefault(require("./fileReader.js")),_fileSignature=_interopRequireDefault(require("./fileSignature.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(o){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:null,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return _classCallCheck(this,Upload),options=_objectSpread(_objectSpread({},defaultOptions),options),_super.call(this,file,options)}return Constructor=Upload,staticProps=[{key:"terminate",value:function(url){var options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return options=_objectSpread(_objectSpread({},defaultOptions),options),_upload.default.terminate(url,options)}}],(protoProps=null)&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),Upload}(_upload.default),exports.isSupported="function"==typeof XMLHttpRequest&&"function"==typeof Blob&&"function"==typeof Blob.prototype.slice},{"../error.js":12,"../logger.js":13,"../noopUrlStorage.js":14,"../upload.js":15,"./fileReader.js":1,"./fileSignature.js":2,"./httpStack.js":3,"./urlStorage.js":11}],5:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(){return"undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase()}},{}],6:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _isCordova=_interopRequireDefault(require("./isCordova.js")),_readAsByteArray=_interopRequireDefault(require("./readAsByteArray.js"));function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _typeof(o){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _defineProperties(target,props){for(var i=0;i=this.size;return Promise.resolve({value:value,done:done})}},{key:"close",value:function(){}}])&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),FileSource}()},{"./isCordova.js":8,"./readAsByteArray.js":9}],7:[function(require,module,exports){function _typeof(o){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _defineProperties(target,props){for(var i=0;ithis._bufferOffset&&(this._buffer=this._buffer.slice(start-this._bufferOffset),this._bufferOffset=start);var hasAllDataBeenRead=0===len(this._buffer);return this._done&&hasAllDataBeenRead?null:this._buffer.slice(0,end-start)}},{key:"close",value:function(){this._reader.cancel&&this._reader.cancel()}}])&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),StreamSource}()},{}],8:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;exports.default=function(){return"undefined"!=typeof window&&(void 0!==window.PhoneGap||void 0!==window.Cordova||void 0!==window.cordova)}},{}],9:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(chunk){return new Promise((function(resolve,reject){var reader=new FileReader;reader.onload=function(){var value=new Uint8Array(reader.result);resolve({value:value})},reader.onerror=function(err){reject(err)},reader.readAsArrayBuffer(chunk)}))}},{}],10:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(uri){return new Promise((function(resolve,reject){var xhr=new XMLHttpRequest;xhr.responseType="blob",xhr.onload=function(){var blob=xhr.response;resolve(blob)},xhr.onerror=function(err){reject(err)},xhr.open("GET",uri),xhr.send()}))}},{}],11:[function(require,module,exports){function _typeof(o){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _defineProperties(target,props){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:null,req=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,res=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(_classCallCheck(this,DetailedError),(_this=_super.call(this,message)).originalRequest=req,_this.originalResponse=res,_this.causingError=causingErr,null!=causingErr&&(message+=", caused by ".concat(causingErr.toString())),null!=req){var requestId=req.getHeader("X-Request-ID")||"n/a",method=req.getMethod(),url=req.getURL(),status=res?res.getStatus():"n/a",body=res?res.getBody()||"":"n/a";message+=", originated from request (method: ".concat(method,", url: ").concat(url,", response code: ").concat(status,", response text: ").concat(body,", request id: ").concat(requestId,")")}return _this.message=message,_this}return Constructor=DetailedError,protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}(_wrapNativeSuper(Error));exports.default=DetailedError},{}],13:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.enableDebugLog=function(){isEnabled=!0},exports.log=function(msg){if(!isEnabled)return;console.log(msg)};var isEnabled=!1},{}],14:[function(require,module,exports){function _typeof(o){return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function _defineProperties(target,props){for(var i=0;i=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return handle("end");if(i.tryLoc<=this.prev){var c=n.call(i,"catchLoc"),u=n.call(i,"finallyLoc");if(c&&u){if(this.prev=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),resetTryEntry(r),y}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;resetTryEntry(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:values(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),y}},e}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise((function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)}))}}function _slicedToArray(arr,i){return function(arr){if(Array.isArray(arr))return arr}(arr)||function(r,l){var t=null==r?null:"undefined"!=typeof Symbol&&r[Symbol.iterator]||r["@@iterator"];if(null!=t){var e,n,i,u,a=[],f=!0,o=!1;try{if(i=(t=t.call(r)).next,0===l){if(Object(t)!==t)return;f=!1}else for(;!(f=(e=i.call(t)).done)&&(a.push(e.value),a.length!==l);f=!0);}catch(r){o=!0,n=r}finally{try{if(!f&&null!=t.return&&(u=t.return(),Object(u)!==u))return}finally{if(o)throw n}}return a}}(arr,i)||function(o,minLen){if(!o)return;if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}(arr,i)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i1)for(var _i=0,_arr=["uploadUrl","uploadSize","uploadLengthDeferred"];_i<_arr.length;_i++){var optionName=_arr[_i];if(this.options[optionName])return void this._emitError(new Error("tus: cannot use the ".concat(optionName," option when parallelUploads is enabled")))}if(this.options.parallelUploadBoundaries){if(this.options.parallelUploads<=1)return void this._emitError(new Error("tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled"));if(this.options.parallelUploads!==this.options.parallelUploadBoundaries.length)return void this._emitError(new Error("tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`"))}this.options.fingerprint(file,this.options).then((function(fingerprint){return null==fingerprint?(0,_logger.log)("No fingerprint was calculated meaning that the upload cannot be stored in the URL storage."):(0,_logger.log)("Calculated fingerprint: ".concat(fingerprint)),_this2._fingerprint=fingerprint,_this2._source?_this2._source:_this2.options.fileReader.openFile(file,_this2.options.chunkSize)})).then((function(source){if(_this2._source=source,_this2.options.uploadLengthDeferred)_this2._size=null;else if(null!=_this2.options.uploadSize){if(_this2._size=Number(_this2.options.uploadSize),Number.isNaN(_this2._size))return void _this2._emitError(new Error("tus: cannot convert `uploadSize` option into a number"))}else if(_this2._size=_this2._source.size,null==_this2._size)return void _this2._emitError(new Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option"));_this2.options.parallelUploads>1||null!=_this2._parallelUploadUrls?_this2._startParallelUpload():_this2._startSingleUpload()})).catch((function(err){_this2._emitError(err)}))}else this._emitError(new Error("tus: the `retryDelays` option must either be an array or null"))}else this._emitError(new Error("tus: neither an endpoint or an upload URL is provided"));else this._emitError(new Error("tus: no file or stream to upload provided"))}},{key:"_startParallelUpload",value:function(){var _this$options$paralle,_this3=this,totalSize=this._size,totalProgress=0;this._parallelUploads=[];var partCount=null!=this._parallelUploadUrls?this._parallelUploadUrls.length:this.options.parallelUploads,parts=null!==(_this$options$paralle=this.options.parallelUploadBoundaries)&&void 0!==_this$options$paralle?_this$options$paralle:function(totalSize,partCount){for(var partSize=Math.floor(totalSize/partCount),parts=[],i=0;ithis._offsetBeforeRetry&&(this._retryAttempt=0),shouldRetry(err,this._retryAttempt,this.options))){var delay=this.options.retryDelays[this._retryAttempt++];return this._offsetBeforeRetry=this._offset,void(this._retryTimeout=setTimeout((function(){_this5.start()}),delay))}if("function"!=typeof this.options.onError)throw err;this.options.onError(err)}}},{key:"_emitSuccess",value:function(){this.options.removeFingerprintOnSuccess&&this._removeFromUrlStorage(),"function"==typeof this.options.onSuccess&&this.options.onSuccess()}},{key:"_emitProgress",value:function(bytesSent,bytesTotal){"function"==typeof this.options.onProgress&&this.options.onProgress(bytesSent,bytesTotal)}},{key:"_emitChunkComplete",value:function(chunkSize,bytesAccepted,bytesTotal){"function"==typeof this.options.onChunkComplete&&this.options.onChunkComplete(chunkSize,bytesAccepted,bytesTotal)}},{key:"_createUpload",value:function(){var _this6=this;if(this.options.endpoint){var req=this._openRequest("POST",this.options.endpoint);this.options.uploadLengthDeferred?req.setHeader("Upload-Defer-Length",1):req.setHeader("Upload-Length",this._size);var promise,metadata=encodeMetadata(this.options.metadata);""!==metadata&&req.setHeader("Upload-Metadata",metadata),this.options.uploadDataDuringCreation&&!this.options.uploadLengthDeferred?(this._offset=0,promise=this._addChunkToRequest(req)):promise=this._sendRequest(req,null),promise.then((function(res){if(inStatusCategory(res.getStatus(),200)){var location=res.getHeader("Location");if(null!=location){if(_this6.url=resolveUrl(_this6.options.endpoint,location),(0,_logger.log)("Created upload at ".concat(_this6.url)),"function"==typeof _this6.options.onUploadUrlAvailable&&_this6.options.onUploadUrlAvailable(),0===_this6._size)return _this6._emitSuccess(),void _this6._source.close();_this6._saveUploadInUrlStorage().then((function(){_this6.options.uploadDataDuringCreation?_this6._handleUploadResponse(req,res):(_this6._offset=0,_this6._performUpload())}))}else _this6._emitHttpError(req,res,"tus: invalid or missing Location header")}else _this6._emitHttpError(req,res,"tus: unexpected response while creating upload")})).catch((function(err){_this6._emitHttpError(req,null,"tus: failed to create upload",err)}))}else this._emitError(new Error("tus: unable to create upload because no endpoint is provided"))}},{key:"_resumeUpload",value:function(){var _this7=this,req=this._openRequest("HEAD",this.url);this._sendRequest(req,null).then((function(res){var status=res.getStatus();if(!inStatusCategory(status,200))return 423===status?void _this7._emitHttpError(req,res,"tus: upload is currently locked; retry later"):(inStatusCategory(status,400)&&_this7._removeFromUrlStorage(),_this7.options.endpoint?(_this7.url=null,void _this7._createUpload()):void _this7._emitHttpError(req,res,"tus: unable to resume upload (new upload cannot be created without an endpoint)"));var offset=parseInt(res.getHeader("Upload-Offset"),10);if(Number.isNaN(offset))_this7._emitHttpError(req,res,"tus: invalid or missing offset value");else{var length=parseInt(res.getHeader("Upload-Length"),10);!Number.isNaN(length)||_this7.options.uploadLengthDeferred?("function"==typeof _this7.options.onUploadUrlAvailable&&_this7.options.onUploadUrlAvailable(),_this7._saveUploadInUrlStorage().then((function(){if(offset===length)return _this7._emitProgress(length,length),void _this7._emitSuccess();_this7._offset=offset,_this7._performUpload()}))):_this7._emitHttpError(req,res,"tus: invalid or missing length value")}})).catch((function(err){_this7._emitHttpError(req,null,"tus: failed to resume upload",err)}))}},{key:"_performUpload",value:function(){var req,_this8=this;this._aborted||(this.options.overridePatchMethod?(req=this._openRequest("POST",this.url)).setHeader("X-HTTP-Method-Override","PATCH"):req=this._openRequest("PATCH",this.url),req.setHeader("Upload-Offset",this._offset),this._addChunkToRequest(req).then((function(res){inStatusCategory(res.getStatus(),200)?_this8._handleUploadResponse(req,res):_this8._emitHttpError(req,res,"tus: unexpected response while uploading chunk")})).catch((function(err){_this8._aborted||_this8._emitHttpError(req,null,"tus: failed to upload chunk at offset ".concat(_this8._offset),err)})))}},{key:"_addChunkToRequest",value:function(req){var _this9=this,start=this._offset,end=this._offset+this.options.chunkSize;return req.setProgressHandler((function(bytesSent){_this9._emitProgress(start+bytesSent,_this9._size)})),req.setHeader("Content-Type","application/offset+octet-stream"),(end===1/0||end>this._size)&&!this.options.uploadLengthDeferred&&(end=this._size),this._source.slice(start,end).then((function(_ref2){var value=_ref2.value,done=_ref2.done,valueSize=value&&value.size?value.size:0;_this9.options.uploadLengthDeferred&&done&&(_this9._size=_this9._offset+valueSize,req.setHeader("Upload-Length",_this9._size));var newSize=_this9._offset+valueSize;return!_this9.options.uploadLengthDeferred&&done&&newSize!==_this9._size?Promise.reject(new Error("upload was configured with a size of ".concat(_this9._size," bytes, but the source is done after ").concat(newSize," bytes"))):null===value?_this9._sendRequest(req):(_this9._emitProgress(_this9._offset,_this9._size),_this9._sendRequest(req,value))}))}},{key:"_handleUploadResponse",value:function(req,res){var offset=parseInt(res.getHeader("Upload-Offset"),10);if(Number.isNaN(offset))this._emitHttpError(req,res,"tus: invalid or missing offset value");else{if(this._emitProgress(offset,this._size),this._emitChunkComplete(offset-this._offset,offset,this._size),this._offset=offset,offset===this._size)return this._emitSuccess(),void this._source.close();this._performUpload()}}},{key:"_openRequest",value:function(method,url){var req=openRequest(method,url,this.options);return this._req=req,req}},{key:"_removeFromUrlStorage",value:function(){var _this10=this;this._urlStorageKey&&(this._urlStorage.removeUpload(this._urlStorageKey).catch((function(err){_this10._emitError(err)})),this._urlStorageKey=null)}},{key:"_saveUploadInUrlStorage",value:function(){var _this11=this;if(!this.options.storeFingerprintForResuming||!this._fingerprint||null!==this._urlStorageKey)return Promise.resolve();var storedUpload={size:this._size,metadata:this.options.metadata,creationTime:(new Date).toString()};return this._parallelUploads?storedUpload.parallelUploadUrls=this._parallelUploadUrls:storedUpload.uploadUrl=this.url,this._urlStorage.addUpload(this._fingerprint,storedUpload).then((function(urlStorageKey){_this11._urlStorageKey=urlStorageKey}))}},{key:"_sendRequest",value:function(req){var body=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return sendRequest(req,body,this.options)}}],staticProps=[{key:"terminate",value:function(url){var options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},req=openRequest("DELETE",url,options);return sendRequest(req,null,options).then((function(res){if(204!==res.getStatus())throw new _error.default("tus: unexpected response while terminating upload",null,req,res)})).catch((function(err){if(err instanceof _error.default||(err=new _error.default("tus: failed to terminate upload",err,req,null)),!shouldRetry(err,0,options))throw err;var delay=options.retryDelays[0],remainingDelays=options.retryDelays.slice(1),newOptions=_objectSpread(_objectSpread({},options),{},{retryDelays:remainingDelays});return new Promise((function(resolve){return setTimeout(resolve,delay)})).then((function(){return BaseUpload.terminate(url,newOptions)}))}))}}],protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),BaseUpload}();function encodeMetadata(metadata){return Object.entries(metadata).map((function(_ref3){var _ref4=_slicedToArray(_ref3,2),key=_ref4[0],value=_ref4[1];return"".concat(key," ").concat(_jsBase.Base64.encode(String(value)))})).join(",")}function inStatusCategory(status,category){return status>=category&&status=options.retryDelays.length||null==err.originalRequest)&&(options&&"function"==typeof options.onShouldRetry?options.onShouldRetry(err,retryAttempt,options):defaultOnShouldRetry(err))}function defaultOnShouldRetry(err){var online,status=err.originalResponse?err.originalResponse.getStatus():0;return(!inStatusCategory(status,400)||409===status||423===status)&&(online=!0,"undefined"!=typeof navigator&&!1===navigator.onLine&&(online=!1),online)}function resolveUrl(origin,link){return new _urlParse.default(link,origin).toString()}BaseUpload.defaultOptions=defaultOptions;exports.default=BaseUpload},{"./error.js":12,"./logger.js":13,"./uuid.js":16,"js-base64":20,"url-parse":23}],16:[function(require,module,exports){Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(c){var r=16*Math.random()|0;return("x"===c?r:3&r|8).toString(16)}))}},{}],17:[function(require,module,exports){exports.byteLength=function(b64){var lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1];return 3*(validLen+placeHoldersLen)/4-placeHoldersLen},exports.toByteArray=function(b64){var tmp,i,lens=getLens(b64),validLen=lens[0],placeHoldersLen=lens[1],arr=new Arr(function(b64,validLen,placeHoldersLen){return 3*(validLen+placeHoldersLen)/4-placeHoldersLen}(0,validLen,placeHoldersLen)),curByte=0,len=placeHoldersLen>0?validLen-4:validLen;for(i=0;i>16&255,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp;2===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4,arr[curByte++]=255&tmp);1===placeHoldersLen&&(tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2,arr[curByte++]=tmp>>8&255,arr[curByte++]=255&tmp);return arr},exports.fromByteArray=function(uint8){for(var tmp,len=uint8.length,extraBytes=len%3,parts=[],i=0,len2=len-extraBytes;ilen2?len2:i+16383));1===extraBytes?(tmp=uint8[len-1],parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")):2===extraBytes&&(tmp=(uint8[len-2]<<8)+uint8[len-1],parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"="));return parts.join("")};for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i0)throw new Error("Invalid string. Length must be a multiple of 4");var validLen=b64.indexOf("=");return-1===validLen&&(validLen=len),[validLen,validLen===len?0:4-validLen%4]}function encodeChunk(uint8,start,end){for(var tmp,num,output=[],i=start;i>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[63&num]);return output.join("")}revLookup["-".charCodeAt(0)]=62,revLookup["_".charCodeAt(0)]=63},{}],18:[function(require,module,exports){(function(Buffer){(function(){var base64=require("base64-js"),ieee754=require("ieee754");exports.Buffer=Buffer,exports.SlowBuffer=function(length){+length!=length&&(length=0);return Buffer.alloc(+length)},exports.INSPECT_MAX_BYTES=50;function createBuffer(length){if(length>2147483647)throw new RangeError('The value "'+length+'" is invalid for option "size"');var buf=new Uint8Array(length);return buf.__proto__=Buffer.prototype,buf}function Buffer(arg,encodingOrOffset,length){if("number"==typeof arg){if("string"==typeof encodingOrOffset)throw new TypeError('The "string" argument must be of type string. Received type number');return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}function from(value,encodingOrOffset,length){if("string"==typeof value)return function(string,encoding){"string"==typeof encoding&&""!==encoding||(encoding="utf8");if(!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=0|byteLength(string,encoding),buf=createBuffer(length),actual=buf.write(string,encoding);actual!==length&&(buf=buf.slice(0,actual));return buf}(value,encodingOrOffset);if(ArrayBuffer.isView(value))return fromArrayLike(value);if(null==value)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer))return function(array,byteOffset,length){if(byteOffset<0||array.byteLength=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647..toString(16)+" bytes");return 0|length}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof string);var len=string.length,mustMatch=arguments.length>2&&!0===arguments[2];if(!mustMatch&&0===len)return 0;for(var loweredCase=!1;;)switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*len;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return mustMatch?-1:utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase(),loweredCase=!0}}function slowToString(encoding,start,end){var loweredCase=!1;if((void 0===start||start<0)&&(start=0),start>this.length)return"";if((void 0===end||end>this.length)&&(end=this.length),end<=0)return"";if((end>>>=0)<=(start>>>=0))return"";for(encoding||(encoding="utf8");;)switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase(),loweredCase=!0}}function swap(b,n,m){var i=b[n];b[n]=b[m],b[m]=i}function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){if(0===buffer.length)return-1;if("string"==typeof byteOffset?(encoding=byteOffset,byteOffset=0):byteOffset>2147483647?byteOffset=2147483647:byteOffset<-2147483648&&(byteOffset=-2147483648),numberIsNaN(byteOffset=+byteOffset)&&(byteOffset=dir?0:buffer.length-1),byteOffset<0&&(byteOffset=buffer.length+byteOffset),byteOffset>=buffer.length){if(dir)return-1;byteOffset=buffer.length-1}else if(byteOffset<0){if(!dir)return-1;byteOffset=0}if("string"==typeof val&&(val=Buffer.from(val,encoding)),Buffer.isBuffer(val))return 0===val.length?-1:arrayIndexOf(buffer,val,byteOffset,encoding,dir);if("number"==typeof val)return val&=255,"function"==typeof Uint8Array.prototype.indexOf?dir?Uint8Array.prototype.indexOf.call(buffer,val,byteOffset):Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset):arrayIndexOf(buffer,[val],byteOffset,encoding,dir);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var i,indexSize=1,arrLength=arr.length,valLength=val.length;if(void 0!==encoding&&("ucs2"===(encoding=String(encoding).toLowerCase())||"ucs-2"===encoding||"utf16le"===encoding||"utf-16le"===encoding)){if(arr.length<2||val.length<2)return-1;indexSize=2,arrLength/=2,valLength/=2,byteOffset/=2}function read(buf,i){return 1===indexSize?buf[i]:buf.readUInt16BE(i*indexSize)}if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength&&(byteOffset=arrLength-valLength),i=byteOffset;i>=0;i--){for(var found=!0,j=0;jremaining&&(length=remaining):length=remaining;var strLen=string.length;length>strLen/2&&(length=strLen/2);for(var i=0;i>8,lo=c%256,byteArray.push(lo),byteArray.push(hi);return byteArray}(string,buf.length-offset),buf,offset,length)}function base64Slice(buf,start,end){return 0===start&&end===buf.length?base64.fromByteArray(buf):base64.fromByteArray(buf.slice(start,end))}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);for(var res=[],i=start;i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end)switch(bytesPerSequence){case 1:firstByte<128&&(codePoint=firstByte);break;case 2:128==(192&(secondByte=buf[i+1]))&&(tempCodePoint=(31&firstByte)<<6|63&secondByte)>127&&(codePoint=tempCodePoint);break;case 3:secondByte=buf[i+1],thirdByte=buf[i+2],128==(192&secondByte)&&128==(192&thirdByte)&&(tempCodePoint=(15&firstByte)<<12|(63&secondByte)<<6|63&thirdByte)>2047&&(tempCodePoint<55296||tempCodePoint>57343)&&(codePoint=tempCodePoint);break;case 4:secondByte=buf[i+1],thirdByte=buf[i+2],fourthByte=buf[i+3],128==(192&secondByte)&&128==(192&thirdByte)&&128==(192&fourthByte)&&(tempCodePoint=(15&firstByte)<<18|(63&secondByte)<<12|(63&thirdByte)<<6|63&fourthByte)>65535&&tempCodePoint<1114112&&(codePoint=tempCodePoint)}null===codePoint?(codePoint=65533,bytesPerSequence=1):codePoint>65535&&(codePoint-=65536,res.push(codePoint>>>10&1023|55296),codePoint=56320|1023&codePoint),res.push(codePoint),i+=bytesPerSequence}return function(codePoints){var len=codePoints.length;if(len<=4096)return String.fromCharCode.apply(String,codePoints);var res="",i=0;for(;imax&&(str+=" ... "),""},Buffer.prototype.compare=function(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)&&(target=Buffer.from(target,target.offset,target.byteLength)),!Buffer.isBuffer(target))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof target);if(void 0===start&&(start=0),void 0===end&&(end=target?target.length:0),void 0===thisStart&&(thisStart=0),void 0===thisEnd&&(thisEnd=this.length),start<0||end>target.length||thisStart<0||thisEnd>this.length)throw new RangeError("out of range index");if(thisStart>=thisEnd&&start>=end)return 0;if(thisStart>=thisEnd)return-1;if(start>=end)return 1;if(this===target)return 0;for(var x=(thisEnd>>>=0)-(thisStart>>>=0),y=(end>>>=0)-(start>>>=0),len=Math.min(x,y),thisCopy=this.slice(thisStart,thisEnd),targetCopy=target.slice(start,end),i=0;i>>=0,isFinite(length)?(length>>>=0,void 0===encoding&&(encoding="utf8")):(encoding=length,length=void 0)}var remaining=this.length-offset;if((void 0===length||length>remaining)&&(length=remaining),string.length>0&&(length<0||offset<0)||offset>this.length)throw new RangeError("Attempt to write outside buffer bounds");encoding||(encoding="utf8");for(var loweredCase=!1;;)switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase(),loweredCase=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;ilen)&&(end=len);for(var out="",i=start;ilength)throw new RangeError("Trying to access beyond buffer length")}function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,0,offset,4),ieee754.write(buf,value,offset,littleEndian,23,4),offset+4}function writeDouble(buf,value,offset,littleEndian,noAssert){return value=+value,offset>>>=0,noAssert||checkIEEE754(buf,0,offset,8),ieee754.write(buf,value,offset,littleEndian,52,8),offset+8}Buffer.prototype.slice=function(start,end){var len=this.length;(start=~~start)<0?(start+=len)<0&&(start=0):start>len&&(start=len),(end=void 0===end?len:~~end)<0?(end+=len)<0&&(end=0):end>len&&(end=len),end>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset+--byteLength],mul=1;byteLength>0&&(mul*=256);)val+=this[offset+--byteLength]*mul;return val},Buffer.prototype.readUInt8=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),this[offset]},Buffer.prototype.readUInt16LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]|this[offset+1]<<8},Buffer.prototype.readUInt16BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,2,this.length),this[offset]<<8|this[offset+1]},Buffer.prototype.readUInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+16777216*this[offset+3]},Buffer.prototype.readUInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),16777216*this[offset]+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])},Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var val=this[offset],mul=1,i=0;++i=(mul*=128)&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset>>>=0,byteLength>>>=0,noAssert||checkOffset(offset,byteLength,this.length);for(var i=byteLength,mul=1,val=this[offset+--i];i>0&&(mul*=256);)val+=this[offset+--i]*mul;return val>=(mul*=128)&&(val-=Math.pow(2,8*byteLength)),val},Buffer.prototype.readInt8=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,1,this.length),128&this[offset]?-1*(255-this[offset]+1):this[offset]},Buffer.prototype.readInt16LE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt16BE=function(offset,noAssert){offset>>>=0,noAssert||checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return 32768&val?4294901760|val:val},Buffer.prototype.readInt32LE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24},Buffer.prototype.readInt32BE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]},Buffer.prototype.readFloatLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!0,23,4)},Buffer.prototype.readFloatBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,4,this.length),ieee754.read(this,offset,!1,23,4)},Buffer.prototype.readDoubleLE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!0,52,8)},Buffer.prototype.readDoubleBE=function(offset,noAssert){return offset>>>=0,noAssert||checkOffset(offset,8,this.length),ieee754.read(this,offset,!1,52,8)},Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){(value=+value,offset>>>=0,byteLength>>>=0,noAssert)||checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0);var mul=1,i=0;for(this[offset]=255&value;++i>>=0,byteLength>>>=0,noAssert)||checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength)-1,0);var i=byteLength-1,mul=1;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)this[offset+i]=value/mul&255;return offset+byteLength},Buffer.prototype.writeUInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,255,0),this[offset]=255&value,offset+1},Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,65535,0),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset+3]=value>>>24,this[offset+2]=value>>>16,this[offset+1]=value>>>8,this[offset]=255&value,offset+4},Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,4294967295,0),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0,mul=1,sub=0;for(this[offset]=255&value;++i>0)-sub&255;return offset+byteLength},Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){if(value=+value,offset>>>=0,!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1,mul=1,sub=0;for(this[offset+i]=255&value;--i>=0&&(mul*=256);)value<0&&0===sub&&0!==this[offset+i+1]&&(sub=1),this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength},Buffer.prototype.writeInt8=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,1,127,-128),value<0&&(value=255+value+1),this[offset]=255&value,offset+1},Buffer.prototype.writeInt16LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=255&value,this[offset+1]=value>>>8,offset+2},Buffer.prototype.writeInt16BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,2,32767,-32768),this[offset]=value>>>8,this[offset+1]=255&value,offset+2},Buffer.prototype.writeInt32LE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),this[offset]=255&value,this[offset+1]=value>>>8,this[offset+2]=value>>>16,this[offset+3]=value>>>24,offset+4},Buffer.prototype.writeInt32BE=function(value,offset,noAssert){return value=+value,offset>>>=0,noAssert||checkInt(this,value,offset,4,2147483647,-2147483648),value<0&&(value=4294967295+value+1),this[offset]=value>>>24,this[offset+1]=value>>>16,this[offset+2]=value>>>8,this[offset+3]=255&value,offset+4},Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,!0,noAssert)},Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,!1,noAssert)},Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,!0,noAssert)},Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,!1,noAssert)},Buffer.prototype.copy=function(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(start||(start=0),end||0===end||(end=this.length),targetStart>=target.length&&(targetStart=target.length),targetStart||(targetStart=0),end>0&&end=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");end>this.length&&(end=this.length),target.length-targetStart=0;--i)target[i+targetStart]=this[i+start];else Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart);return len},Buffer.prototype.fill=function(val,start,end,encoding){if("string"==typeof val){if("string"==typeof start?(encoding=start,start=0,end=this.length):"string"==typeof end&&(encoding=end,end=this.length),void 0!==encoding&&"string"!=typeof encoding)throw new TypeError("encoding must be a string");if("string"==typeof encoding&&!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);if(1===val.length){var code=val.charCodeAt(0);("utf8"===encoding&&code<128||"latin1"===encoding)&&(val=code)}}else"number"==typeof val&&(val&=255);if(start<0||this.length>>=0,end=void 0===end?this.length:end>>>0,val||(val=0),"number"==typeof val)for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){(units-=3)>-1&&bytes.push(239,191,189);continue}if(i+1===length){(units-=3)>-1&&bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){(units-=3)>-1&&bytes.push(239,191,189),leadSurrogate=codePoint;continue}codePoint=65536+(leadSurrogate-55296<<10|codePoint-56320)}else leadSurrogate&&(units-=3)>-1&&bytes.push(239,191,189);if(leadSurrogate=null,codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,63&codePoint|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,63&codePoint|128)}else{if(!(codePoint<1114112))throw new Error("Invalid code point");if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,63&codePoint|128)}}return bytes}function base64ToBytes(str){return base64.toByteArray(function(str){if((str=(str=str.split("=")[0]).trim().replace(INVALID_BASE64_RE,"")).length<2)return"";for(;str.length%4!=0;)str+="=";return str}(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length);++i)dst[i+offset]=src[i];return i}function isInstance(obj,type){return obj instanceof type||null!=obj&&null!=obj.constructor&&null!=obj.constructor.name&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!=obj}}).call(this)}).call(this,require("buffer").Buffer)},{"base64-js":17,buffer:18,ieee754:19}],19:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=8*nBytes-mLen-1,eMax=(1<>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];for(i+=d,e=s&(1<<-nBits)-1,s>>=-nBits,nBits+=eLen;nBits>0;e=256*e+buffer[offset+i],i+=d,nBits-=8);for(m=e&(1<<-nBits)-1,e>>=-nBits,nBits+=mLen;nBits>0;m=256*m+buffer[offset+i],i+=d,nBits-=8);if(0===e)e=1-eBias;else{if(e===eMax)return m?NaN:1/0*(s?-1:1);m+=Math.pow(2,mLen),e-=eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)},exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=8*nBytes-mLen-1,eMax=(1<>1,rt=23===mLen?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||0===value&&1/value<0?1:0;for(value=Math.abs(value),isNaN(value)||value===1/0?(m=isNaN(value)?1:0,e=eMax):(e=Math.floor(Math.log(value)/Math.LN2),value*(c=Math.pow(2,-e))<1&&(e--,c*=2),(value+=e+eBias>=1?rt/c:rt*Math.pow(2,1-eBias))*c>=2&&(e++,c/=2),e+eBias>=eMax?(m=0,e=eMax):e+eBias>=1?(m=(value*c-1)*Math.pow(2,mLen),e+=eBias):(m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen),e=0));mLen>=8;buffer[offset+i]=255&m,i+=d,m/=256,mLen-=8);for(e=e<0;buffer[offset+i]=255&e,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=128*s}},{}],20:[function(require,module,exports){(function(global,Buffer){(function(){!function(global,factory){var _Base64,gBase64;"object"==typeof exports&&void 0!==module?module.exports=factory():(_Base64=global.Base64,(gBase64=factory()).noConflict=function(){return global.Base64=_Base64,gBase64},global.Meteor&&(Base64=gBase64),global.Base64=gBase64)}("undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==global?global:this,(function(){var tab,_hasatob="function"==typeof atob,_hasbtoa="function"==typeof btoa,_hasBuffer="function"==typeof Buffer,_TD="function"==typeof TextDecoder?new TextDecoder:void 0,_TE="function"==typeof TextEncoder?new TextEncoder:void 0,b64chs=Array.prototype.slice.call("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="),b64tab=(tab={},b64chs.forEach((function(c,i){return tab[c]=i})),tab),b64re=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,_fromCC=String.fromCharCode.bind(String),_U8Afrom="function"==typeof Uint8Array.from?Uint8Array.from.bind(Uint8Array):function(it){return new Uint8Array(Array.prototype.slice.call(it,0))},_mkUriSafe=function(src){return src.replace(/=/g,"").replace(/[+\/]/g,(function(m0){return"+"==m0?"-":"_"}))},_tidyB64=function(s){return s.replace(/[^A-Za-z0-9\+\/]/g,"")},btoaPolyfill=function(bin){for(var u32,c0,c1,c2,asc="",pad=bin.length%3,i=0;i255||(c1=bin.charCodeAt(i++))>255||(c2=bin.charCodeAt(i++))>255)throw new TypeError("invalid character found");asc+=b64chs[(u32=c0<<16|c1<<8|c2)>>18&63]+b64chs[u32>>12&63]+b64chs[u32>>6&63]+b64chs[63&u32]}return pad?asc.slice(0,pad-3)+"===".substring(pad):asc},_btoa=_hasbtoa?function(bin){return btoa(bin)}:_hasBuffer?function(bin){return Buffer.from(bin,"binary").toString("base64")}:btoaPolyfill,_fromUint8Array=_hasBuffer?function(u8a){return Buffer.from(u8a).toString("base64")}:function(u8a){for(var strs=[],i=0,l=u8a.length;i>>6)+_fromCC(128|63&cc):_fromCC(224|cc>>>12&15)+_fromCC(128|cc>>>6&63)+_fromCC(128|63&cc);var cc=65536+1024*(c.charCodeAt(0)-55296)+(c.charCodeAt(1)-56320);return _fromCC(240|cc>>>18&7)+_fromCC(128|cc>>>12&63)+_fromCC(128|cc>>>6&63)+_fromCC(128|63&cc)},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,utob=function(u){return u.replace(re_utob,cb_utob)},_encode=_hasBuffer?function(s){return Buffer.from(s,"utf8").toString("base64")}:_TE?function(s){return _fromUint8Array(_TE.encode(s))}:function(s){return _btoa(utob(s))},encode=function(src,urlsafe){return void 0===urlsafe&&(urlsafe=!1),urlsafe?_mkUriSafe(_encode(src)):_encode(src)},encodeURI=function(src){return encode(src,!0)},re_btou=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,cb_btou=function(cccc){switch(cccc.length){case 4:var offset=((7&cccc.charCodeAt(0))<<18|(63&cccc.charCodeAt(1))<<12|(63&cccc.charCodeAt(2))<<6|63&cccc.charCodeAt(3))-65536;return _fromCC(55296+(offset>>>10))+_fromCC(56320+(1023&offset));case 3:return _fromCC((15&cccc.charCodeAt(0))<<12|(63&cccc.charCodeAt(1))<<6|63&cccc.charCodeAt(2));default:return _fromCC((31&cccc.charCodeAt(0))<<6|63&cccc.charCodeAt(1))}},btou=function(b){return b.replace(re_btou,cb_btou)},atobPolyfill=function(asc){if(asc=asc.replace(/\s+/g,""),!b64re.test(asc))throw new TypeError("malformed base64.");asc+="==".slice(2-(3&asc.length));for(var u24,r1,r2,bin="",i=0;i>16&255):64===r2?_fromCC(u24>>16&255,u24>>8&255):_fromCC(u24>>16&255,u24>>8&255,255&u24);return bin},_atob=_hasatob?function(asc){return atob(_tidyB64(asc))}:_hasBuffer?function(asc){return Buffer.from(asc,"base64").toString("binary")}:atobPolyfill,_toUint8Array=_hasBuffer?function(a){return _U8Afrom(Buffer.from(a,"base64"))}:function(a){return _U8Afrom(_atob(a).split("").map((function(c){return c.charCodeAt(0)})))},toUint8Array=function(a){return _toUint8Array(_unURI(a))},_decode=_hasBuffer?function(a){return Buffer.from(a,"base64").toString("utf8")}:_TD?function(a){return _TD.decode(_toUint8Array(a))}:function(a){return btou(_atob(a))},_unURI=function(a){return _tidyB64(a.replace(/[-_]/g,(function(m0){return"-"==m0?"+":"/"})))},decode=function(src){return _decode(_unURI(src))},_noEnum=function(v){return{value:v,enumerable:!1,writable:!0,configurable:!0}},extendString=function(){var _add=function(name,body){return Object.defineProperty(String.prototype,name,_noEnum(body))};_add("fromBase64",(function(){return decode(this)})),_add("toBase64",(function(urlsafe){return encode(this,urlsafe)})),_add("toBase64URI",(function(){return encode(this,!0)})),_add("toBase64URL",(function(){return encode(this,!0)})),_add("toUint8Array",(function(){return toUint8Array(this)}))},extendUint8Array=function(){var _add=function(name,body){return Object.defineProperty(Uint8Array.prototype,name,_noEnum(body))};_add("toBase64",(function(urlsafe){return fromUint8Array(this,urlsafe)})),_add("toBase64URI",(function(){return fromUint8Array(this,!0)})),_add("toBase64URL",(function(){return fromUint8Array(this,!0)}))},gBase64={version:"3.7.5",VERSION:"3.7.5",atob:_atob,atobPolyfill:atobPolyfill,btoa:_btoa,btoaPolyfill:btoaPolyfill,fromBase64:decode,toBase64:encode,encode:encode,encodeURI:encodeURI,encodeURL:encodeURI,utob:utob,btou:btou,decode:decode,isValid:function(src){if("string"!=typeof src)return!1;var s=src.replace(/\s+/g,"").replace(/={0,2}$/,"");return!/[^\s0-9a-zA-Z\+/]/.test(s)||!/[^\s0-9a-zA-Z\-_]/.test(s)},fromUint8Array:fromUint8Array,toUint8Array:toUint8Array,extendString:extendString,extendUint8Array:extendUint8Array,extendBuiltins:function(){extendString(),extendUint8Array()},Base64:{}};return Object.keys(gBase64).forEach((function(k){return gBase64.Base64[k]=gBase64[k]})),gBase64}))}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},require("buffer").Buffer)},{buffer:18}],21:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;function decode(input){try{return decodeURIComponent(input.replace(/\+/g," "))}catch(e){return null}}function encode(input){try{return encodeURIComponent(input)}catch(e){return null}}exports.stringify=function(obj,prefix){prefix=prefix||"";var value,key,pairs=[];for(key in"string"!=typeof prefix&&(prefix="?"),obj)if(has.call(obj,key)){if((value=obj[key])||null!=value&&!isNaN(value)||(value=""),key=encode(key),value=encode(value),null===key||null===value)continue;pairs.push(key+"="+value)}return pairs.length?prefix+pairs.join("&"):""},exports.parse=function(query){for(var part,parser=/([^=?#&]+)=?([^&]*)/g,result={};part=parser.exec(query);){var key=decode(part[1]),value=decode(part[2]);null===key||null===value||key in result||(result[key]=value)}return result}},{}],22:[function(require,module,exports){module.exports=function(port,protocol){if(protocol=protocol.split(":")[0],!(port=+port))return!1;switch(protocol){case"http":case"ws":return 80!==port;case"https":case"wss":return 443!==port;case"ftp":return 21!==port;case"gopher":return 70!==port;case"file":return!1}return 0!==port}},{}],23:[function(require,module,exports){(function(global){(function(){var required=require("requires-port"),qs=require("querystringify"),controlOrWhitespace=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/,CRHTLF=/[\n\r\t]/g,slashes=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,port=/:\d+$/,protocolre=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,windowsDriveLetter=/^[a-zA-Z]:/;function trimLeft(str){return(str||"").toString().replace(controlOrWhitespace,"")}var rules=[["#","hash"],["?","query"],function(address,url){return isSpecial(url.protocol)?address.replace(/\\/g,"/"):address},["/","pathname"],["@","auth",1],[NaN,"host",void 0,1,1],[/:(\d*)$/,"port",void 0,1],[NaN,"hostname",void 0,1,1]],ignore={hash:1,query:1};function lolcation(loc){var key,location=("undefined"!=typeof window?window:void 0!==global?global:"undefined"!=typeof self?self:{}).location||{},finaldestination={},type=typeof(loc=loc||location);if("blob:"===loc.protocol)finaldestination=new Url(unescape(loc.pathname),{});else if("string"===type)for(key in finaldestination=new Url(loc,{}),ignore)delete finaldestination[key];else if("object"===type){for(key in loc)key in ignore||(finaldestination[key]=loc[key]);void 0===finaldestination.slashes&&(finaldestination.slashes=slashes.test(loc.href))}return finaldestination}function isSpecial(scheme){return"file:"===scheme||"ftp:"===scheme||"http:"===scheme||"https:"===scheme||"ws:"===scheme||"wss:"===scheme}function extractProtocol(address,location){address=(address=trimLeft(address)).replace(CRHTLF,""),location=location||{};var rest,match=protocolre.exec(address),protocol=match[1]?match[1].toLowerCase():"",forwardSlashes=!!match[2],otherSlashes=!!match[3],slashesCount=0;return forwardSlashes?otherSlashes?(rest=match[2]+match[3]+match[4],slashesCount=match[2].length+match[3].length):(rest=match[2]+match[4],slashesCount=match[2].length):otherSlashes?(rest=match[3]+match[4],slashesCount=match[3].length):rest=match[4],"file:"===protocol?slashesCount>=2&&(rest=rest.slice(2)):isSpecial(protocol)?rest=match[4]:protocol?forwardSlashes&&(rest=rest.slice(2)):slashesCount>=2&&isSpecial(location.protocol)&&(rest=match[4]),{protocol:protocol,slashes:forwardSlashes||isSpecial(protocol),slashesCount:slashesCount,rest:rest}}function Url(address,location,parser){if(address=(address=trimLeft(address)).replace(CRHTLF,""),!(this instanceof Url))return new Url(address,location,parser);var relative,extracted,parse,instruction,index,key,instructions=rules.slice(),type=typeof location,url=this,i=0;for("object"!==type&&"string"!==type&&(parser=location,location=null),parser&&"function"!=typeof parser&&(parser=qs.parse),relative=!(extracted=extractProtocol(address||"",location=lolcation(location))).protocol&&!extracted.slashes,url.slashes=extracted.slashes||relative&&location.slashes,url.protocol=extracted.protocol||location.protocol||"",address=extracted.rest,("file:"===extracted.protocol&&(2!==extracted.slashesCount||windowsDriveLetter.test(address))||!extracted.slashes&&(extracted.protocol||extracted.slashesCount<2||!isSpecial(url.protocol)))&&(instructions[3]=[/(.*)/,"pathname"]);i= 0; --o) { var i = this.tryEntries[o], a = i.completion; if (\"root\" === i.tryLoc) return handle(\"end\"); if (i.tryLoc <= this.prev) { var c = n.call(i, \"catchLoc\"), u = n.call(i, \"finallyLoc\"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error(\"try statement without catch or finally\"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, \"finallyLoc\") && this.prev < o.finallyLoc) { var i = o; break; } } i && (\"break\" === t || \"continue\" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = \"next\", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if (\"throw\" === t.type) throw t.arg; return \"break\" === t.type || \"continue\" === t.type ? this.next = t.arg : \"return\" === t.type ? (this.rval = this.arg = t.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, \"catch\": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if (\"throw\" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, \"next\" === this.method && (this.arg = t), y; } }, e; }\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar FileReader = exports[\"default\"] = /*#__PURE__*/function () {\n function FileReader() {\n _classCallCheck(this, FileReader);\n }\n _createClass(FileReader, [{\n key: \"openFile\",\n value: function () {\n var _openFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(input, chunkSize) {\n var blob;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n if (!((0, _isReactNative[\"default\"])() && input && typeof input.uri !== 'undefined')) {\n _context.next = 11;\n break;\n }\n _context.prev = 1;\n _context.next = 4;\n return (0, _uriToBlob[\"default\"])(input.uri);\n case 4:\n blob = _context.sent;\n return _context.abrupt(\"return\", new _FileSource[\"default\"](blob));\n case 8:\n _context.prev = 8;\n _context.t0 = _context[\"catch\"](1);\n throw new Error(\"tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. \".concat(_context.t0));\n case 11:\n if (!(typeof input.slice === 'function' && typeof input.size !== 'undefined')) {\n _context.next = 13;\n break;\n }\n return _context.abrupt(\"return\", Promise.resolve(new _FileSource[\"default\"](input)));\n case 13:\n if (!(typeof input.read === 'function')) {\n _context.next = 18;\n break;\n }\n chunkSize = Number(chunkSize);\n if (Number.isFinite(chunkSize)) {\n _context.next = 17;\n break;\n }\n return _context.abrupt(\"return\", Promise.reject(new Error('cannot create source for stream without a finite value for the `chunkSize` option')));\n case 17:\n return _context.abrupt(\"return\", Promise.resolve(new _StreamSource[\"default\"](input, chunkSize)));\n case 18:\n return _context.abrupt(\"return\", Promise.reject(new Error('source object may only be an instance of File, Blob, or Reader in this environment')));\n case 19:\n case \"end\":\n return _context.stop();\n }\n }, _callee, null, [[1, 8]]);\n }));\n function openFile(_x, _x2) {\n return _openFile.apply(this, arguments);\n }\n return openFile;\n }()\n }]);\n return FileReader;\n}();\n\n},{\"./isReactNative.js\":5,\"./sources/FileSource.js\":6,\"./sources/StreamSource.js\":7,\"./uriToBlob.js\":10}],2:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = fingerprint;\nvar _isReactNative = _interopRequireDefault(require(\"./isReactNative.js\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n// TODO: Differenciate between input types\n\n/**\n * Generate a fingerprint for a file which will be used the store the endpoint\n *\n * @param {File} file\n * @param {Object} options\n * @param {Function} callback\n */\nfunction fingerprint(file, options) {\n if ((0, _isReactNative[\"default\"])()) {\n return Promise.resolve(reactNativeFingerprint(file, options));\n }\n return Promise.resolve(['tus-br', file.name, file.type, file.size, file.lastModified, options.endpoint].join('-'));\n}\nfunction reactNativeFingerprint(file, options) {\n var exifHash = file.exif ? hashCode(JSON.stringify(file.exif)) : 'noexif';\n return ['tus-rn', file.name || 'noname', file.size || 'nosize', exifHash, options.endpoint].join('/');\n}\nfunction hashCode(str) {\n /* eslint-disable no-bitwise */\n // from https://stackoverflow.com/a/8831937/151666\n var hash = 0;\n if (str.length === 0) {\n return hash;\n }\n for (var i = 0; i < str.length; i++) {\n var _char = str.charCodeAt(i);\n hash = (hash << 5) - hash + _char;\n hash &= hash; // Convert to 32bit integer\n }\n return hash;\n}\n\n},{\"./isReactNative.js\":5}],3:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/* eslint-disable max-classes-per-file */\nvar XHRHttpStack = exports[\"default\"] = /*#__PURE__*/function () {\n function XHRHttpStack() {\n _classCallCheck(this, XHRHttpStack);\n }\n _createClass(XHRHttpStack, [{\n key: \"createRequest\",\n value: function createRequest(method, url) {\n return new Request(method, url);\n }\n }, {\n key: \"getName\",\n value: function getName() {\n return 'XHRHttpStack';\n }\n }]);\n return XHRHttpStack;\n}();\nvar Request = /*#__PURE__*/function () {\n function Request(method, url) {\n _classCallCheck(this, Request);\n this._xhr = new XMLHttpRequest();\n this._xhr.open(method, url, true);\n this._method = method;\n this._url = url;\n this._headers = {};\n }\n _createClass(Request, [{\n key: \"getMethod\",\n value: function getMethod() {\n return this._method;\n }\n }, {\n key: \"getURL\",\n value: function getURL() {\n return this._url;\n }\n }, {\n key: \"setHeader\",\n value: function setHeader(header, value) {\n this._xhr.setRequestHeader(header, value);\n this._headers[header] = value;\n }\n }, {\n key: \"getHeader\",\n value: function getHeader(header) {\n return this._headers[header];\n }\n }, {\n key: \"setProgressHandler\",\n value: function setProgressHandler(progressHandler) {\n // Test support for progress events before attaching an event listener\n if (!('upload' in this._xhr)) {\n return;\n }\n this._xhr.upload.onprogress = function (e) {\n if (!e.lengthComputable) {\n return;\n }\n progressHandler(e.loaded);\n };\n }\n }, {\n key: \"send\",\n value: function send() {\n var _this = this;\n var body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n return new Promise(function (resolve, reject) {\n _this._xhr.onload = function () {\n resolve(new Response(_this._xhr));\n };\n _this._xhr.onerror = function (err) {\n reject(err);\n };\n _this._xhr.send(body);\n });\n }\n }, {\n key: \"abort\",\n value: function abort() {\n this._xhr.abort();\n return Promise.resolve();\n }\n }, {\n key: \"getUnderlyingObject\",\n value: function getUnderlyingObject() {\n return this._xhr;\n }\n }]);\n return Request;\n}();\nvar Response = /*#__PURE__*/function () {\n function Response(xhr) {\n _classCallCheck(this, Response);\n this._xhr = xhr;\n }\n _createClass(Response, [{\n key: \"getStatus\",\n value: function getStatus() {\n return this._xhr.status;\n }\n }, {\n key: \"getHeader\",\n value: function getHeader(header) {\n return this._xhr.getResponseHeader(header);\n }\n }, {\n key: \"getBody\",\n value: function getBody() {\n return this._xhr.responseText;\n }\n }, {\n key: \"getUnderlyingObject\",\n value: function getUnderlyingObject() {\n return this._xhr;\n }\n }]);\n return Response;\n}();\n\n},{}],4:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"DefaultHttpStack\", {\n enumerable: true,\n get: function get() {\n return _httpStack[\"default\"];\n }\n});\nObject.defineProperty(exports, \"DetailedError\", {\n enumerable: true,\n get: function get() {\n return _error[\"default\"];\n }\n});\nexports.Upload = void 0;\nObject.defineProperty(exports, \"canStoreURLs\", {\n enumerable: true,\n get: function get() {\n return _urlStorage.canStoreURLs;\n }\n});\nexports.defaultOptions = void 0;\nObject.defineProperty(exports, \"enableDebugLog\", {\n enumerable: true,\n get: function get() {\n return _logger.enableDebugLog;\n }\n});\nexports.isSupported = void 0;\nvar _upload = _interopRequireDefault(require(\"../upload.js\"));\nvar _noopUrlStorage = _interopRequireDefault(require(\"../noopUrlStorage.js\"));\nvar _logger = require(\"../logger.js\");\nvar _error = _interopRequireDefault(require(\"../error.js\"));\nvar _urlStorage = require(\"./urlStorage.js\");\nvar _httpStack = _interopRequireDefault(require(\"./httpStack.js\"));\nvar _fileReader = _interopRequireDefault(require(\"./fileReader.js\"));\nvar _fileSignature = _interopRequireDefault(require(\"./fileSignature.js\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar defaultOptions = exports.defaultOptions = _objectSpread(_objectSpread({}, _upload[\"default\"].defaultOptions), {}, {\n httpStack: new _httpStack[\"default\"](),\n fileReader: new _fileReader[\"default\"](),\n urlStorage: _urlStorage.canStoreURLs ? new _urlStorage.WebStorageUrlStorage() : new _noopUrlStorage[\"default\"](),\n fingerprint: _fileSignature[\"default\"]\n});\nvar Upload = exports.Upload = /*#__PURE__*/function (_BaseUpload) {\n _inherits(Upload, _BaseUpload);\n var _super = _createSuper(Upload);\n function Upload() {\n var file = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n _classCallCheck(this, Upload);\n options = _objectSpread(_objectSpread({}, defaultOptions), options);\n return _super.call(this, file, options);\n }\n _createClass(Upload, null, [{\n key: \"terminate\",\n value: function terminate(url) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n options = _objectSpread(_objectSpread({}, defaultOptions), options);\n return _upload[\"default\"].terminate(url, options);\n }\n }]);\n return Upload;\n}(_upload[\"default\"]); // Note: We don't reference `window` here because these classes also exist in a Web Worker's context.\nvar isSupported = exports.isSupported = typeof XMLHttpRequest === 'function' && typeof Blob === 'function' && typeof Blob.prototype.slice === 'function';\n\n},{\"../error.js\":12,\"../logger.js\":13,\"../noopUrlStorage.js\":14,\"../upload.js\":15,\"./fileReader.js\":1,\"./fileSignature.js\":2,\"./httpStack.js\":3,\"./urlStorage.js\":11}],5:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar isReactNative = function isReactNative() {\n return typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative';\n};\nvar _default = exports[\"default\"] = isReactNative;\n\n},{}],6:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar _isCordova = _interopRequireDefault(require(\"./isCordova.js\"));\nvar _readAsByteArray = _interopRequireDefault(require(\"./readAsByteArray.js\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar FileSource = exports[\"default\"] = /*#__PURE__*/function () {\n // Make this.size a method\n function FileSource(file) {\n _classCallCheck(this, FileSource);\n this._file = file;\n this.size = file.size;\n }\n _createClass(FileSource, [{\n key: \"slice\",\n value: function slice(start, end) {\n // In Apache Cordova applications, a File must be resolved using\n // FileReader instances, see\n // https://cordova.apache.org/docs/en/8.x/reference/cordova-plugin-file/index.html#read-a-file\n if ((0, _isCordova[\"default\"])()) {\n return (0, _readAsByteArray[\"default\"])(this._file.slice(start, end));\n }\n var value = this._file.slice(start, end);\n var done = end >= this.size;\n return Promise.resolve({\n value: value,\n done: done\n });\n }\n }, {\n key: \"close\",\n value: function close() {\n // Nothing to do here since we don't need to release any resources.\n }\n }]);\n return FileSource;\n}();\n\n},{\"./isCordova.js\":8,\"./readAsByteArray.js\":9}],7:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction len(blobOrArray) {\n if (blobOrArray === undefined) return 0;\n if (blobOrArray.size !== undefined) return blobOrArray.size;\n return blobOrArray.length;\n}\n\n/*\n Typed arrays and blobs don't have a concat method.\n This function helps StreamSource accumulate data to reach chunkSize.\n*/\nfunction concat(a, b) {\n if (a.concat) {\n // Is `a` an Array?\n return a.concat(b);\n }\n if (a instanceof Blob) {\n return new Blob([a, b], {\n type: a.type\n });\n }\n if (a.set) {\n // Is `a` a typed array?\n var c = new a.constructor(a.length + b.length);\n c.set(a);\n c.set(b, a.length);\n return c;\n }\n throw new Error('Unknown data type');\n}\nvar StreamSource = exports[\"default\"] = /*#__PURE__*/function () {\n function StreamSource(reader) {\n _classCallCheck(this, StreamSource);\n this._buffer = undefined;\n this._bufferOffset = 0;\n this._reader = reader;\n this._done = false;\n }\n _createClass(StreamSource, [{\n key: \"slice\",\n value: function slice(start, end) {\n if (start < this._bufferOffset) {\n return Promise.reject(new Error(\"Requested data is before the reader's current offset\"));\n }\n return this._readUntilEnoughDataOrDone(start, end);\n }\n }, {\n key: \"_readUntilEnoughDataOrDone\",\n value: function _readUntilEnoughDataOrDone(start, end) {\n var _this = this;\n var hasEnoughData = end <= this._bufferOffset + len(this._buffer);\n if (this._done || hasEnoughData) {\n var value = this._getDataFromBuffer(start, end);\n var done = value == null ? this._done : false;\n return Promise.resolve({\n value: value,\n done: done\n });\n }\n return this._reader.read().then(function (_ref) {\n var value = _ref.value,\n done = _ref.done;\n if (done) {\n _this._done = true;\n } else if (_this._buffer === undefined) {\n _this._buffer = value;\n } else {\n _this._buffer = concat(_this._buffer, value);\n }\n return _this._readUntilEnoughDataOrDone(start, end);\n });\n }\n }, {\n key: \"_getDataFromBuffer\",\n value: function _getDataFromBuffer(start, end) {\n // Remove data from buffer before `start`.\n // Data might be reread from the buffer if an upload fails, so we can only\n // safely delete data when it comes *before* what is currently being read.\n if (start > this._bufferOffset) {\n this._buffer = this._buffer.slice(start - this._bufferOffset);\n this._bufferOffset = start;\n }\n // If the buffer is empty after removing old data, all data has been read.\n var hasAllDataBeenRead = len(this._buffer) === 0;\n if (this._done && hasAllDataBeenRead) {\n return null;\n }\n // We already removed data before `start`, so we just return the first\n // chunk from the buffer.\n return this._buffer.slice(0, end - start);\n }\n }, {\n key: \"close\",\n value: function close() {\n if (this._reader.cancel) {\n this._reader.cancel();\n }\n }\n }]);\n return StreamSource;\n}();\n\n},{}],8:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar isCordova = function isCordova() {\n return typeof window !== 'undefined' && (typeof window.PhoneGap !== 'undefined' || typeof window.Cordova !== 'undefined' || typeof window.cordova !== 'undefined');\n};\nvar _default = exports[\"default\"] = isCordova;\n\n},{}],9:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = readAsByteArray;\n/**\n * readAsByteArray converts a File object to a Uint8Array.\n * This function is only used on the Apache Cordova platform.\n * See https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html#read-a-file\n */\nfunction readAsByteArray(chunk) {\n return new Promise(function (resolve, reject) {\n var reader = new FileReader();\n reader.onload = function () {\n var value = new Uint8Array(reader.result);\n resolve({\n value: value\n });\n };\n reader.onerror = function (err) {\n reject(err);\n };\n reader.readAsArrayBuffer(chunk);\n });\n}\n\n},{}],10:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = uriToBlob;\n/**\n * uriToBlob resolves a URI to a Blob object. This is used for\n * React Native to retrieve a file (identified by a file://\n * URI) as a blob.\n */\nfunction uriToBlob(uri) {\n return new Promise(function (resolve, reject) {\n var xhr = new XMLHttpRequest();\n xhr.responseType = 'blob';\n xhr.onload = function () {\n var blob = xhr.response;\n resolve(blob);\n };\n xhr.onerror = function (err) {\n reject(err);\n };\n xhr.open('GET', uri);\n xhr.send();\n });\n}\n\n},{}],11:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.canStoreURLs = exports.WebStorageUrlStorage = void 0;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar hasStorage = false;\ntry {\n // Note: localStorage does not exist in the Web Worker's context, so we must use window here.\n hasStorage = 'localStorage' in window;\n\n // Attempt to store and read entries from the local storage to detect Private\n // Mode on Safari on iOS (see #49)\n // If the key was not used before, we remove it from local storage again to\n // not cause confusion where the entry came from.\n var key = 'tusSupport';\n var originalValue = localStorage.getItem(key);\n localStorage.setItem(key, originalValue);\n if (originalValue === null) localStorage.removeItem(key);\n} catch (e) {\n // If we try to access localStorage inside a sandboxed iframe, a SecurityError\n // is thrown. When in private mode on iOS Safari, a QuotaExceededError is\n // thrown (see #49)\n if (e.code === e.SECURITY_ERR || e.code === e.QUOTA_EXCEEDED_ERR) {\n hasStorage = false;\n } else {\n throw e;\n }\n}\nvar canStoreURLs = exports.canStoreURLs = hasStorage;\nvar WebStorageUrlStorage = exports.WebStorageUrlStorage = /*#__PURE__*/function () {\n function WebStorageUrlStorage() {\n _classCallCheck(this, WebStorageUrlStorage);\n }\n _createClass(WebStorageUrlStorage, [{\n key: \"findAllUploads\",\n value: function findAllUploads() {\n var results = this._findEntries('tus::');\n return Promise.resolve(results);\n }\n }, {\n key: \"findUploadsByFingerprint\",\n value: function findUploadsByFingerprint(fingerprint) {\n var results = this._findEntries(\"tus::\".concat(fingerprint, \"::\"));\n return Promise.resolve(results);\n }\n }, {\n key: \"removeUpload\",\n value: function removeUpload(urlStorageKey) {\n localStorage.removeItem(urlStorageKey);\n return Promise.resolve();\n }\n }, {\n key: \"addUpload\",\n value: function addUpload(fingerprint, upload) {\n var id = Math.round(Math.random() * 1e12);\n var key = \"tus::\".concat(fingerprint, \"::\").concat(id);\n localStorage.setItem(key, JSON.stringify(upload));\n return Promise.resolve(key);\n }\n }, {\n key: \"_findEntries\",\n value: function _findEntries(prefix) {\n var results = [];\n for (var i = 0; i < localStorage.length; i++) {\n var _key = localStorage.key(i);\n if (_key.indexOf(prefix) !== 0) continue;\n try {\n var upload = JSON.parse(localStorage.getItem(_key));\n upload.urlStorageKey = _key;\n results.push(upload);\n } catch (e) {\n // The JSON parse error is intentionally ignored here, so a malformed\n // entry in the storage cannot prevent an upload.\n }\n }\n return results;\n }\n }]);\n return WebStorageUrlStorage;\n}();\n\n},{}],12:[function(require,module,exports){\n\"use strict\";\n\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, \"prototype\", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } else if (call !== void 0) { throw new TypeError(\"Derived constructors may only return object or undefined\"); } return _assertThisInitialized(self); }\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\nfunction _wrapNativeSuper(Class) { var _cache = typeof Map === \"function\" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== \"function\") { throw new TypeError(\"Super expression must either be null or a function\"); } if (typeof _cache !== \"undefined\") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }\nfunction _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }\nfunction _isNativeFunction(fn) { try { return Function.toString.call(fn).indexOf(\"[native code]\") !== -1; } catch (e) { return typeof fn === \"function\"; } }\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\nvar DetailedError = /*#__PURE__*/function (_Error) {\n _inherits(DetailedError, _Error);\n var _super = _createSuper(DetailedError);\n function DetailedError(message) {\n var _this;\n var causingErr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n var req = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;\n var res = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;\n _classCallCheck(this, DetailedError);\n _this = _super.call(this, message);\n _this.originalRequest = req;\n _this.originalResponse = res;\n _this.causingError = causingErr;\n if (causingErr != null) {\n message += \", caused by \".concat(causingErr.toString());\n }\n if (req != null) {\n var requestId = req.getHeader('X-Request-ID') || 'n/a';\n var method = req.getMethod();\n var url = req.getURL();\n var status = res ? res.getStatus() : 'n/a';\n var body = res ? res.getBody() || '' : 'n/a';\n message += \", originated from request (method: \".concat(method, \", url: \").concat(url, \", response code: \").concat(status, \", response text: \").concat(body, \", request id: \").concat(requestId, \")\");\n }\n _this.message = message;\n return _this;\n }\n return _createClass(DetailedError);\n}( /*#__PURE__*/_wrapNativeSuper(Error));\nvar _default = exports[\"default\"] = DetailedError;\n\n},{}],13:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.enableDebugLog = enableDebugLog;\nexports.log = log;\n/* eslint no-console: \"off\" */\n\nvar isEnabled = false;\nfunction enableDebugLog() {\n isEnabled = true;\n}\nfunction log(msg) {\n if (!isEnabled) return;\n console.log(msg);\n}\n\n},{}],14:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/* eslint no-unused-vars: \"off\" */\nvar NoopUrlStorage = exports[\"default\"] = /*#__PURE__*/function () {\n function NoopUrlStorage() {\n _classCallCheck(this, NoopUrlStorage);\n }\n _createClass(NoopUrlStorage, [{\n key: \"listAllUploads\",\n value: function listAllUploads() {\n return Promise.resolve([]);\n }\n }, {\n key: \"findUploadsByFingerprint\",\n value: function findUploadsByFingerprint(fingerprint) {\n return Promise.resolve([]);\n }\n }, {\n key: \"removeUpload\",\n value: function removeUpload(urlStorageKey) {\n return Promise.resolve();\n }\n }, {\n key: \"addUpload\",\n value: function addUpload(fingerprint, upload) {\n return Promise.resolve(null);\n }\n }]);\n return NoopUrlStorage;\n}();\n\n},{}],15:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = void 0;\nvar _jsBase = require(\"js-base64\");\nvar _urlParse = _interopRequireDefault(require(\"url-parse\"));\nvar _error = _interopRequireDefault(require(\"./error.js\"));\nvar _logger = require(\"./logger.js\");\nvar _uuid = _interopRequireDefault(require(\"./uuid.js\"));\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\nfunction _regeneratorRuntime() { \"use strict\"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = \"function\" == typeof Symbol ? Symbol : {}, a = i.iterator || \"@@iterator\", c = i.asyncIterator || \"@@asyncIterator\", u = i.toStringTag || \"@@toStringTag\"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, \"\"); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, \"_invoke\", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: \"normal\", arg: t.call(e, r) }; } catch (t) { return { type: \"throw\", arg: t }; } } e.wrap = wrap; var h = \"suspendedStart\", l = \"suspendedYield\", f = \"executing\", s = \"completed\", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { [\"next\", \"throw\", \"return\"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if (\"throw\" !== c.type) { var u = c.arg, h = u.value; return h && \"object\" == _typeof(h) && n.call(h, \"__await\") ? e.resolve(h.__await).then(function (t) { invoke(\"next\", t, i, a); }, function (t) { invoke(\"throw\", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke(\"throw\", t, i, a); }); } a(c.arg); } var r; o(this, \"_invoke\", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error(\"Generator is already running\"); if (o === s) { if (\"throw\" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if (\"next\" === n.method) n.sent = n._sent = n.arg;else if (\"throw\" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else \"return\" === n.method && n.abrupt(\"return\", n.arg); o = f; var p = tryCatch(e, r, n); if (\"normal\" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } \"throw\" === p.type && (o = s, n.method = \"throw\", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, \"throw\" === n && e.iterator[\"return\"] && (r.method = \"return\", r.arg = t, maybeInvokeDelegate(e, r), \"throw\" === r.method) || \"return\" !== n && (r.method = \"throw\", r.arg = new TypeError(\"The iterator does not provide a '\" + n + \"' method\")), y; var i = tryCatch(o, e.iterator, r.arg); if (\"throw\" === i.type) return r.method = \"throw\", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, \"return\" !== r.method && (r.method = \"next\", r.arg = t), r.delegate = null, y) : a : (r.method = \"throw\", r.arg = new TypeError(\"iterator result is not an object\"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = \"normal\", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: \"root\" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || \"\" === e) { var r = e[a]; if (r) return r.call(e); if (\"function\" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + \" is not iterable\"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, \"constructor\", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, \"constructor\", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, \"GeneratorFunction\"), e.isGeneratorFunction = function (t) { var e = \"function\" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || \"GeneratorFunction\" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, \"GeneratorFunction\")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, \"Generator\"), define(g, a, function () { return this; }), define(g, \"toString\", function () { return \"[object Generator]\"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) \"t\" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if (\"throw\" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = \"throw\", a.arg = e, r.next = n, o && (r.method = \"next\", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if (\"root\" === i.tryLoc) return handle(\"end\"); if (i.tryLoc <= this.prev) { var c = n.call(i, \"catchLoc\"), u = n.call(i, \"finallyLoc\"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error(\"try statement without catch or finally\"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, \"finallyLoc\") && this.prev < o.finallyLoc) { var i = o; break; } } i && (\"break\" === t || \"continue\" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = \"next\", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if (\"throw\" === t.type) throw t.arg; return \"break\" === t.type || \"continue\" === t.type ? this.next = t.arg : \"return\" === t.type ? (this.rval = this.arg = t.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, \"catch\": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if (\"throw\" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error(\"illegal catch attempt\"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, \"next\" === this.method && (this.arg = t), y; } }, e; }\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }\nfunction _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err); } _next(undefined); }); }; }\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }\nfunction _iterableToArrayLimit(r, l) { var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t[\"return\"] && (u = t[\"return\"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\nfunction _typeof(o) { \"@babel/helpers - typeof\"; return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o; }, _typeof(o); }\nfunction ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }\nfunction _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\nfunction _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, _toPropertyKey(descriptor.key), descriptor); } }\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, \"prototype\", { writable: false }); return Constructor; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return _typeof(key) === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (_typeof(input) !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (_typeof(res) !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\nvar defaultOptions = {\n endpoint: null,\n uploadUrl: null,\n metadata: {},\n fingerprint: null,\n uploadSize: null,\n onProgress: null,\n onChunkComplete: null,\n onSuccess: null,\n onError: null,\n onUploadUrlAvailable: null,\n overridePatchMethod: false,\n headers: {},\n addRequestId: false,\n onBeforeRequest: null,\n onAfterResponse: null,\n onShouldRetry: defaultOnShouldRetry,\n chunkSize: Infinity,\n retryDelays: [0, 1000, 3000, 5000],\n parallelUploads: 1,\n parallelUploadBoundaries: null,\n storeFingerprintForResuming: true,\n removeFingerprintOnSuccess: false,\n uploadLengthDeferred: false,\n uploadDataDuringCreation: false,\n urlStorage: null,\n fileReader: null,\n httpStack: null\n};\nvar BaseUpload = /*#__PURE__*/function () {\n function BaseUpload(file, options) {\n _classCallCheck(this, BaseUpload);\n // Warn about removed options from previous versions\n if ('resume' in options) {\n // eslint-disable-next-line no-console\n console.log('tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead.');\n }\n\n // The default options will already be added from the wrapper classes.\n this.options = options;\n\n // Cast chunkSize to integer\n this.options.chunkSize = Number(this.options.chunkSize);\n\n // The storage module used to store URLs\n this._urlStorage = this.options.urlStorage;\n\n // The underlying File/Blob object\n this.file = file;\n\n // The URL against which the file will be uploaded\n this.url = null;\n\n // The underlying request object for the current PATCH request\n this._req = null;\n\n // The fingerpinrt for the current file (set after start())\n this._fingerprint = null;\n\n // The key that the URL storage returned when saving an URL with a fingerprint,\n this._urlStorageKey = null;\n\n // The offset used in the current PATCH request\n this._offset = null;\n\n // True if the current PATCH request has been aborted\n this._aborted = false;\n\n // The file's size in bytes\n this._size = null;\n\n // The Source object which will wrap around the given file and provides us\n // with a unified interface for getting its size and slice chunks from its\n // content allowing us to easily handle Files, Blobs, Buffers and Streams.\n this._source = null;\n\n // The current count of attempts which have been made. Zero indicates none.\n this._retryAttempt = 0;\n\n // The timeout's ID which is used to delay the next retry\n this._retryTimeout = null;\n\n // The offset of the remote upload before the latest attempt was started.\n this._offsetBeforeRetry = 0;\n\n // An array of BaseUpload instances which are used for uploading the different\n // parts, if the parallelUploads option is used.\n this._parallelUploads = null;\n\n // An array of upload URLs which are used for uploading the different\n // parts, if the parallelUploads option is used.\n this._parallelUploadUrls = null;\n }\n\n /**\n * Use the Termination extension to delete an upload from the server by sending a DELETE\n * request to the specified upload URL. This is only possible if the server supports the\n * Termination extension. If the `options.retryDelays` property is set, the method will\n * also retry if an error ocurrs.\n *\n * @param {String} url The upload's URL which will be terminated.\n * @param {object} options Optional options for influencing HTTP requests.\n * @return {Promise} The Promise will be resolved/rejected when the requests finish.\n */\n _createClass(BaseUpload, [{\n key: \"findPreviousUploads\",\n value: function findPreviousUploads() {\n var _this = this;\n return this.options.fingerprint(this.file, this.options).then(function (fingerprint) {\n return _this._urlStorage.findUploadsByFingerprint(fingerprint);\n });\n }\n }, {\n key: \"resumeFromPreviousUpload\",\n value: function resumeFromPreviousUpload(previousUpload) {\n this.url = previousUpload.uploadUrl || null;\n this._parallelUploadUrls = previousUpload.parallelUploadUrls || null;\n this._urlStorageKey = previousUpload.urlStorageKey;\n }\n }, {\n key: \"start\",\n value: function start() {\n var _this2 = this;\n var file = this.file;\n if (!file) {\n this._emitError(new Error('tus: no file or stream to upload provided'));\n return;\n }\n if (!this.options.endpoint && !this.options.uploadUrl && !this.url) {\n this._emitError(new Error('tus: neither an endpoint or an upload URL is provided'));\n return;\n }\n var retryDelays = this.options.retryDelays;\n if (retryDelays != null && Object.prototype.toString.call(retryDelays) !== '[object Array]') {\n this._emitError(new Error('tus: the `retryDelays` option must either be an array or null'));\n return;\n }\n if (this.options.parallelUploads > 1) {\n // Test which options are incompatible with parallel uploads.\n for (var _i = 0, _arr = ['uploadUrl', 'uploadSize', 'uploadLengthDeferred']; _i < _arr.length; _i++) {\n var optionName = _arr[_i];\n if (this.options[optionName]) {\n this._emitError(new Error(\"tus: cannot use the \".concat(optionName, \" option when parallelUploads is enabled\")));\n return;\n }\n }\n }\n if (this.options.parallelUploadBoundaries) {\n if (this.options.parallelUploads <= 1) {\n this._emitError(new Error('tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled'));\n return;\n }\n if (this.options.parallelUploads !== this.options.parallelUploadBoundaries.length) {\n this._emitError(new Error('tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`'));\n return;\n }\n }\n this.options.fingerprint(file, this.options).then(function (fingerprint) {\n if (fingerprint == null) {\n (0, _logger.log)('No fingerprint was calculated meaning that the upload cannot be stored in the URL storage.');\n } else {\n (0, _logger.log)(\"Calculated fingerprint: \".concat(fingerprint));\n }\n _this2._fingerprint = fingerprint;\n if (_this2._source) {\n return _this2._source;\n }\n return _this2.options.fileReader.openFile(file, _this2.options.chunkSize);\n }).then(function (source) {\n _this2._source = source;\n\n // First, we look at the uploadLengthDeferred option.\n // Next, we check if the caller has supplied a manual upload size.\n // Finally, we try to use the calculated size from the source object.\n if (_this2.options.uploadLengthDeferred) {\n _this2._size = null;\n } else if (_this2.options.uploadSize != null) {\n _this2._size = Number(_this2.options.uploadSize);\n if (Number.isNaN(_this2._size)) {\n _this2._emitError(new Error('tus: cannot convert `uploadSize` option into a number'));\n return;\n }\n } else {\n _this2._size = _this2._source.size;\n if (_this2._size == null) {\n _this2._emitError(new Error(\"tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option\"));\n return;\n }\n }\n\n // If the upload was configured to use multiple requests or if we resume from\n // an upload which used multiple requests, we start a parallel upload.\n if (_this2.options.parallelUploads > 1 || _this2._parallelUploadUrls != null) {\n _this2._startParallelUpload();\n } else {\n _this2._startSingleUpload();\n }\n })[\"catch\"](function (err) {\n _this2._emitError(err);\n });\n }\n\n /**\n * Initiate the uploading procedure for a parallelized upload, where one file is split into\n * multiple request which are run in parallel.\n *\n * @api private\n */\n }, {\n key: \"_startParallelUpload\",\n value: function _startParallelUpload() {\n var _this$options$paralle,\n _this3 = this;\n var totalSize = this._size;\n var totalProgress = 0;\n this._parallelUploads = [];\n var partCount = this._parallelUploadUrls != null ? this._parallelUploadUrls.length : this.options.parallelUploads;\n\n // The input file will be split into multiple slices which are uploaded in separate\n // requests. Here we get the start and end position for the slices.\n var parts = (_this$options$paralle = this.options.parallelUploadBoundaries) !== null && _this$options$paralle !== void 0 ? _this$options$paralle : splitSizeIntoParts(this._source.size, partCount);\n\n // Attach URLs from previous uploads, if available.\n if (this._parallelUploadUrls) {\n parts.forEach(function (part, index) {\n part.uploadUrl = _this3._parallelUploadUrls[index] || null;\n });\n }\n\n // Create an empty list for storing the upload URLs\n this._parallelUploadUrls = new Array(parts.length);\n\n // Generate a promise for each slice that will be resolve if the respective\n // upload is completed.\n var uploads = parts.map(function (part, index) {\n var lastPartProgress = 0;\n return _this3._source.slice(part.start, part.end).then(function (_ref) {\n var value = _ref.value;\n return new Promise(function (resolve, reject) {\n // Merge with the user supplied options but overwrite some values.\n var options = _objectSpread(_objectSpread({}, _this3.options), {}, {\n // If available, the partial upload should be resumed from a previous URL.\n uploadUrl: part.uploadUrl || null,\n // We take manually care of resuming for partial uploads, so they should\n // not be stored in the URL storage.\n storeFingerprintForResuming: false,\n removeFingerprintOnSuccess: false,\n // Reset the parallelUploads option to not cause recursion.\n parallelUploads: 1,\n // Reset this option as we are not doing a parallel upload.\n parallelUploadBoundaries: null,\n metadata: {},\n // Add the header to indicate the this is a partial upload.\n headers: _objectSpread(_objectSpread({}, _this3.options.headers), {}, {\n 'Upload-Concat': 'partial'\n }),\n // Reject or resolve the promise if the upload errors or completes.\n onSuccess: resolve,\n onError: reject,\n // Based in the progress for this partial upload, calculate the progress\n // for the entire final upload.\n onProgress: function onProgress(newPartProgress) {\n totalProgress = totalProgress - lastPartProgress + newPartProgress;\n lastPartProgress = newPartProgress;\n _this3._emitProgress(totalProgress, totalSize);\n },\n // Wait until every partial upload has an upload URL, so we can add\n // them to the URL storage.\n onUploadUrlAvailable: function onUploadUrlAvailable() {\n _this3._parallelUploadUrls[index] = upload.url;\n // Test if all uploads have received an URL\n if (_this3._parallelUploadUrls.filter(function (u) {\n return Boolean(u);\n }).length === parts.length) {\n _this3._saveUploadInUrlStorage();\n }\n }\n });\n var upload = new BaseUpload(value, options);\n upload.start();\n\n // Store the upload in an array, so we can later abort them if necessary.\n _this3._parallelUploads.push(upload);\n });\n });\n });\n var req;\n // Wait until all partial uploads are finished and we can send the POST request for\n // creating the final upload.\n Promise.all(uploads).then(function () {\n req = _this3._openRequest('POST', _this3.options.endpoint);\n req.setHeader('Upload-Concat', \"final;\".concat(_this3._parallelUploadUrls.join(' ')));\n\n // Add metadata if values have been added\n var metadata = encodeMetadata(_this3.options.metadata);\n if (metadata !== '') {\n req.setHeader('Upload-Metadata', metadata);\n }\n return _this3._sendRequest(req, null);\n }).then(function (res) {\n if (!inStatusCategory(res.getStatus(), 200)) {\n _this3._emitHttpError(req, res, 'tus: unexpected response while creating upload');\n return;\n }\n var location = res.getHeader('Location');\n if (location == null) {\n _this3._emitHttpError(req, res, 'tus: invalid or missing Location header');\n return;\n }\n _this3.url = resolveUrl(_this3.options.endpoint, location);\n (0, _logger.log)(\"Created upload at \".concat(_this3.url));\n _this3._emitSuccess();\n })[\"catch\"](function (err) {\n _this3._emitError(err);\n });\n }\n\n /**\n * Initiate the uploading procedure for a non-parallel upload. Here the entire file is\n * uploaded in a sequential matter.\n *\n * @api private\n */\n }, {\n key: \"_startSingleUpload\",\n value: function _startSingleUpload() {\n // Reset the aborted flag when the upload is started or else the\n // _performUpload will stop before sending a request if the upload has been\n // aborted previously.\n this._aborted = false;\n\n // The upload had been started previously and we should reuse this URL.\n if (this.url != null) {\n (0, _logger.log)(\"Resuming upload from previous URL: \".concat(this.url));\n this._resumeUpload();\n return;\n }\n\n // A URL has manually been specified, so we try to resume\n if (this.options.uploadUrl != null) {\n (0, _logger.log)(\"Resuming upload from provided URL: \".concat(this.options.uploadUrl));\n this.url = this.options.uploadUrl;\n this._resumeUpload();\n return;\n }\n\n // An upload has not started for the file yet, so we start a new one\n (0, _logger.log)('Creating a new upload');\n this._createUpload();\n }\n\n /**\n * Abort any running request and stop the current upload. After abort is called, no event\n * handler will be invoked anymore. You can use the `start` method to resume the upload\n * again.\n * If `shouldTerminate` is true, the `terminate` function will be called to remove the\n * current upload from the server.\n *\n * @param {boolean} shouldTerminate True if the upload should be deleted from the server.\n * @return {Promise} The Promise will be resolved/rejected when the requests finish.\n */\n }, {\n key: \"abort\",\n value: function abort(shouldTerminate) {\n var _this4 = this;\n // Stop any parallel partial uploads, that have been started in _startParallelUploads.\n if (this._parallelUploads != null) {\n this._parallelUploads.forEach(function (upload) {\n upload.abort(shouldTerminate);\n });\n }\n\n // Stop any current running request.\n if (this._req !== null) {\n this._req.abort();\n // Note: We do not close the file source here, so the user can resume in the future.\n }\n this._aborted = true;\n\n // Stop any timeout used for initiating a retry.\n if (this._retryTimeout != null) {\n clearTimeout(this._retryTimeout);\n this._retryTimeout = null;\n }\n if (!shouldTerminate || this.url == null) {\n return Promise.resolve();\n }\n return BaseUpload.terminate(this.url, this.options)\n // Remove entry from the URL storage since the upload URL is no longer valid.\n .then(function () {\n return _this4._removeFromUrlStorage();\n });\n }\n }, {\n key: \"_emitHttpError\",\n value: function _emitHttpError(req, res, message, causingErr) {\n this._emitError(new _error[\"default\"](message, causingErr, req, res));\n }\n }, {\n key: \"_emitError\",\n value: function _emitError(err) {\n var _this5 = this;\n // Do not emit errors, e.g. from aborted HTTP requests, if the upload has been stopped.\n if (this._aborted) return;\n\n // Check if we should retry, when enabled, before sending the error to the user.\n if (this.options.retryDelays != null) {\n // We will reset the attempt counter if\n // - we were already able to connect to the server (offset != null) and\n // - we were able to upload a small chunk of data to the server\n var shouldResetDelays = this._offset != null && this._offset > this._offsetBeforeRetry;\n if (shouldResetDelays) {\n this._retryAttempt = 0;\n }\n if (shouldRetry(err, this._retryAttempt, this.options)) {\n var delay = this.options.retryDelays[this._retryAttempt++];\n this._offsetBeforeRetry = this._offset;\n this._retryTimeout = setTimeout(function () {\n _this5.start();\n }, delay);\n return;\n }\n }\n if (typeof this.options.onError === 'function') {\n this.options.onError(err);\n } else {\n throw err;\n }\n }\n\n /**\n * Publishes notification if the upload has been successfully completed.\n *\n * @api private\n */\n }, {\n key: \"_emitSuccess\",\n value: function _emitSuccess() {\n if (this.options.removeFingerprintOnSuccess) {\n // Remove stored fingerprint and corresponding endpoint. This causes\n // new uploads of the same file to be treated as a different file.\n this._removeFromUrlStorage();\n }\n if (typeof this.options.onSuccess === 'function') {\n this.options.onSuccess();\n }\n }\n\n /**\n * Publishes notification when data has been sent to the server. This\n * data may not have been accepted by the server yet.\n *\n * @param {number} bytesSent Number of bytes sent to the server.\n * @param {number} bytesTotal Total number of bytes to be sent to the server.\n * @api private\n */\n }, {\n key: \"_emitProgress\",\n value: function _emitProgress(bytesSent, bytesTotal) {\n if (typeof this.options.onProgress === 'function') {\n this.options.onProgress(bytesSent, bytesTotal);\n }\n }\n\n /**\n * Publishes notification when a chunk of data has been sent to the server\n * and accepted by the server.\n * @param {number} chunkSize Size of the chunk that was accepted by the server.\n * @param {number} bytesAccepted Total number of bytes that have been\n * accepted by the server.\n * @param {number} bytesTotal Total number of bytes to be sent to the server.\n * @api private\n */\n }, {\n key: \"_emitChunkComplete\",\n value: function _emitChunkComplete(chunkSize, bytesAccepted, bytesTotal) {\n if (typeof this.options.onChunkComplete === 'function') {\n this.options.onChunkComplete(chunkSize, bytesAccepted, bytesTotal);\n }\n }\n\n /**\n * Create a new upload using the creation extension by sending a POST\n * request to the endpoint. After successful creation the file will be\n * uploaded\n *\n * @api private\n */\n }, {\n key: \"_createUpload\",\n value: function _createUpload() {\n var _this6 = this;\n if (!this.options.endpoint) {\n this._emitError(new Error('tus: unable to create upload because no endpoint is provided'));\n return;\n }\n var req = this._openRequest('POST', this.options.endpoint);\n if (this.options.uploadLengthDeferred) {\n req.setHeader('Upload-Defer-Length', 1);\n } else {\n req.setHeader('Upload-Length', this._size);\n }\n\n // Add metadata if values have been added\n var metadata = encodeMetadata(this.options.metadata);\n if (metadata !== '') {\n req.setHeader('Upload-Metadata', metadata);\n }\n var promise;\n if (this.options.uploadDataDuringCreation && !this.options.uploadLengthDeferred) {\n this._offset = 0;\n promise = this._addChunkToRequest(req);\n } else {\n promise = this._sendRequest(req, null);\n }\n promise.then(function (res) {\n if (!inStatusCategory(res.getStatus(), 200)) {\n _this6._emitHttpError(req, res, 'tus: unexpected response while creating upload');\n return;\n }\n var location = res.getHeader('Location');\n if (location == null) {\n _this6._emitHttpError(req, res, 'tus: invalid or missing Location header');\n return;\n }\n _this6.url = resolveUrl(_this6.options.endpoint, location);\n (0, _logger.log)(\"Created upload at \".concat(_this6.url));\n if (typeof _this6.options.onUploadUrlAvailable === 'function') {\n _this6.options.onUploadUrlAvailable();\n }\n if (_this6._size === 0) {\n // Nothing to upload and file was successfully created\n _this6._emitSuccess();\n _this6._source.close();\n return;\n }\n _this6._saveUploadInUrlStorage().then(function () {\n if (_this6.options.uploadDataDuringCreation) {\n _this6._handleUploadResponse(req, res);\n } else {\n _this6._offset = 0;\n _this6._performUpload();\n }\n });\n })[\"catch\"](function (err) {\n _this6._emitHttpError(req, null, 'tus: failed to create upload', err);\n });\n }\n\n /*\n * Try to resume an existing upload. First a HEAD request will be sent\n * to retrieve the offset. If the request fails a new upload will be\n * created. In the case of a successful response the file will be uploaded.\n *\n * @api private\n */\n }, {\n key: \"_resumeUpload\",\n value: function _resumeUpload() {\n var _this7 = this;\n var req = this._openRequest('HEAD', this.url);\n var promise = this._sendRequest(req, null);\n promise.then(function (res) {\n var status = res.getStatus();\n if (!inStatusCategory(status, 200)) {\n // If the upload is locked (indicated by the 423 Locked status code), we\n // emit an error instead of directly starting a new upload. This way the\n // retry logic can catch the error and will retry the upload. An upload\n // is usually locked for a short period of time and will be available\n // afterwards.\n if (status === 423) {\n _this7._emitHttpError(req, res, 'tus: upload is currently locked; retry later');\n return;\n }\n if (inStatusCategory(status, 400)) {\n // Remove stored fingerprint and corresponding endpoint,\n // on client errors since the file can not be found\n _this7._removeFromUrlStorage();\n }\n if (!_this7.options.endpoint) {\n // Don't attempt to create a new upload if no endpoint is provided.\n _this7._emitHttpError(req, res, 'tus: unable to resume upload (new upload cannot be created without an endpoint)');\n return;\n }\n\n // Try to create a new upload\n _this7.url = null;\n _this7._createUpload();\n return;\n }\n var offset = parseInt(res.getHeader('Upload-Offset'), 10);\n if (Number.isNaN(offset)) {\n _this7._emitHttpError(req, res, 'tus: invalid or missing offset value');\n return;\n }\n var length = parseInt(res.getHeader('Upload-Length'), 10);\n if (Number.isNaN(length) && !_this7.options.uploadLengthDeferred) {\n _this7._emitHttpError(req, res, 'tus: invalid or missing length value');\n return;\n }\n if (typeof _this7.options.onUploadUrlAvailable === 'function') {\n _this7.options.onUploadUrlAvailable();\n }\n _this7._saveUploadInUrlStorage().then(function () {\n // Upload has already been completed and we do not need to send additional\n // data to the server\n if (offset === length) {\n _this7._emitProgress(length, length);\n _this7._emitSuccess();\n return;\n }\n _this7._offset = offset;\n _this7._performUpload();\n });\n })[\"catch\"](function (err) {\n _this7._emitHttpError(req, null, 'tus: failed to resume upload', err);\n });\n }\n\n /**\n * Start uploading the file using PATCH requests. The file will be divided\n * into chunks as specified in the chunkSize option. During the upload\n * the onProgress event handler may be invoked multiple times.\n *\n * @api private\n */\n }, {\n key: \"_performUpload\",\n value: function _performUpload() {\n var _this8 = this;\n // If the upload has been aborted, we will not send the next PATCH request.\n // This is important if the abort method was called during a callback, such\n // as onChunkComplete or onProgress.\n if (this._aborted) {\n return;\n }\n var req;\n\n // Some browser and servers may not support the PATCH method. For those\n // cases, you can tell tus-js-client to use a POST request with the\n // X-HTTP-Method-Override header for simulating a PATCH request.\n if (this.options.overridePatchMethod) {\n req = this._openRequest('POST', this.url);\n req.setHeader('X-HTTP-Method-Override', 'PATCH');\n } else {\n req = this._openRequest('PATCH', this.url);\n }\n req.setHeader('Upload-Offset', this._offset);\n var promise = this._addChunkToRequest(req);\n promise.then(function (res) {\n if (!inStatusCategory(res.getStatus(), 200)) {\n _this8._emitHttpError(req, res, 'tus: unexpected response while uploading chunk');\n return;\n }\n _this8._handleUploadResponse(req, res);\n })[\"catch\"](function (err) {\n // Don't emit an error if the upload was aborted manually\n if (_this8._aborted) {\n return;\n }\n _this8._emitHttpError(req, null, \"tus: failed to upload chunk at offset \".concat(_this8._offset), err);\n });\n }\n\n /**\n * _addChunktoRequest reads a chunk from the source and sends it using the\n * supplied request object. It will not handle the response.\n *\n * @api private\n */\n }, {\n key: \"_addChunkToRequest\",\n value: function _addChunkToRequest(req) {\n var _this9 = this;\n var start = this._offset;\n var end = this._offset + this.options.chunkSize;\n req.setProgressHandler(function (bytesSent) {\n _this9._emitProgress(start + bytesSent, _this9._size);\n });\n req.setHeader('Content-Type', 'application/offset+octet-stream');\n\n // The specified chunkSize may be Infinity or the calcluated end position\n // may exceed the file's size. In both cases, we limit the end position to\n // the input's total size for simpler calculations and correctness.\n if ((end === Infinity || end > this._size) && !this.options.uploadLengthDeferred) {\n end = this._size;\n }\n return this._source.slice(start, end).then(function (_ref2) {\n var value = _ref2.value,\n done = _ref2.done;\n var valueSize = value && value.size ? value.size : 0;\n\n // If the upload length is deferred, the upload size was not specified during\n // upload creation. So, if the file reader is done reading, we know the total\n // upload size and can tell the tus server.\n if (_this9.options.uploadLengthDeferred && done) {\n _this9._size = _this9._offset + valueSize;\n req.setHeader('Upload-Length', _this9._size);\n }\n\n // The specified uploadSize might not match the actual amount of data that a source\n // provides. In these cases, we cannot successfully complete the upload, so we\n // rather error out and let the user know. If not, tus-js-client will be stuck\n // in a loop of repeating empty PATCH requests.\n // See https://community.transloadit.com/t/how-to-abort-hanging-companion-uploads/16488/13\n var newSize = _this9._offset + valueSize;\n if (!_this9.options.uploadLengthDeferred && done && newSize !== _this9._size) {\n return Promise.reject(new Error(\"upload was configured with a size of \".concat(_this9._size, \" bytes, but the source is done after \").concat(newSize, \" bytes\")));\n }\n if (value === null) {\n return _this9._sendRequest(req);\n }\n _this9._emitProgress(_this9._offset, _this9._size);\n return _this9._sendRequest(req, value);\n });\n }\n\n /**\n * _handleUploadResponse is used by requests that haven been sent using _addChunkToRequest\n * and already have received a response.\n *\n * @api private\n */\n }, {\n key: \"_handleUploadResponse\",\n value: function _handleUploadResponse(req, res) {\n var offset = parseInt(res.getHeader('Upload-Offset'), 10);\n if (Number.isNaN(offset)) {\n this._emitHttpError(req, res, 'tus: invalid or missing offset value');\n return;\n }\n this._emitProgress(offset, this._size);\n this._emitChunkComplete(offset - this._offset, offset, this._size);\n this._offset = offset;\n if (offset === this._size) {\n // Yay, finally done :)\n this._emitSuccess();\n this._source.close();\n return;\n }\n this._performUpload();\n }\n\n /**\n * Create a new HTTP request object with the given method and URL.\n *\n * @api private\n */\n }, {\n key: \"_openRequest\",\n value: function _openRequest(method, url) {\n var req = openRequest(method, url, this.options);\n this._req = req;\n return req;\n }\n\n /**\n * Remove the entry in the URL storage, if it has been saved before.\n *\n * @api private\n */\n }, {\n key: \"_removeFromUrlStorage\",\n value: function _removeFromUrlStorage() {\n var _this10 = this;\n if (!this._urlStorageKey) return;\n this._urlStorage.removeUpload(this._urlStorageKey)[\"catch\"](function (err) {\n _this10._emitError(err);\n });\n this._urlStorageKey = null;\n }\n\n /**\n * Add the upload URL to the URL storage, if possible.\n *\n * @api private\n */\n }, {\n key: \"_saveUploadInUrlStorage\",\n value: function _saveUploadInUrlStorage() {\n var _this11 = this;\n // We do not store the upload URL\n // - if it was disabled in the option, or\n // - if no fingerprint was calculated for the input (i.e. a stream), or\n // - if the URL is already stored (i.e. key is set alread).\n if (!this.options.storeFingerprintForResuming || !this._fingerprint || this._urlStorageKey !== null) {\n return Promise.resolve();\n }\n var storedUpload = {\n size: this._size,\n metadata: this.options.metadata,\n creationTime: new Date().toString()\n };\n if (this._parallelUploads) {\n // Save multiple URLs if the parallelUploads option is used ...\n storedUpload.parallelUploadUrls = this._parallelUploadUrls;\n } else {\n // ... otherwise we just save the one available URL.\n storedUpload.uploadUrl = this.url;\n }\n return this._urlStorage.addUpload(this._fingerprint, storedUpload).then(function (urlStorageKey) {\n _this11._urlStorageKey = urlStorageKey;\n });\n }\n\n /**\n * Send a request with the provided body.\n *\n * @api private\n */\n }, {\n key: \"_sendRequest\",\n value: function _sendRequest(req) {\n var body = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;\n return sendRequest(req, body, this.options);\n }\n }], [{\n key: \"terminate\",\n value: function terminate(url) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var req = openRequest('DELETE', url, options);\n return sendRequest(req, null, options).then(function (res) {\n // A 204 response indicates a successfull request\n if (res.getStatus() === 204) {\n return;\n }\n throw new _error[\"default\"]('tus: unexpected response while terminating upload', null, req, res);\n })[\"catch\"](function (err) {\n if (!(err instanceof _error[\"default\"])) {\n err = new _error[\"default\"]('tus: failed to terminate upload', err, req, null);\n }\n if (!shouldRetry(err, 0, options)) {\n throw err;\n }\n\n // Instead of keeping track of the retry attempts, we remove the first element from the delays\n // array. If the array is empty, all retry attempts are used up and we will bubble up the error.\n // We recursively call the terminate function will removing elements from the retryDelays array.\n var delay = options.retryDelays[0];\n var remainingDelays = options.retryDelays.slice(1);\n var newOptions = _objectSpread(_objectSpread({}, options), {}, {\n retryDelays: remainingDelays\n });\n return new Promise(function (resolve) {\n return setTimeout(resolve, delay);\n }).then(function () {\n return BaseUpload.terminate(url, newOptions);\n });\n });\n }\n }]);\n return BaseUpload;\n}();\nfunction encodeMetadata(metadata) {\n return Object.entries(metadata).map(function (_ref3) {\n var _ref4 = _slicedToArray(_ref3, 2),\n key = _ref4[0],\n value = _ref4[1];\n return \"\".concat(key, \" \").concat(_jsBase.Base64.encode(String(value)));\n }).join(',');\n}\n\n/**\n * Checks whether a given status is in the range of the expected category.\n * For example, only a status between 200 and 299 will satisfy the category 200.\n *\n * @api private\n */\nfunction inStatusCategory(status, category) {\n return status >= category && status < category + 100;\n}\n\n/**\n * Create a new HTTP request with the specified method and URL.\n * The necessary headers that are included in every request\n * will be added, including the request ID.\n *\n * @api private\n */\nfunction openRequest(method, url, options) {\n var req = options.httpStack.createRequest(method, url);\n req.setHeader('Tus-Resumable', '1.0.0');\n var headers = options.headers || {};\n Object.entries(headers).forEach(function (_ref5) {\n var _ref6 = _slicedToArray(_ref5, 2),\n name = _ref6[0],\n value = _ref6[1];\n req.setHeader(name, value);\n });\n if (options.addRequestId) {\n var requestId = (0, _uuid[\"default\"])();\n req.setHeader('X-Request-ID', requestId);\n }\n return req;\n}\n\n/**\n * Send a request with the provided body while invoking the onBeforeRequest\n * and onAfterResponse callbacks.\n *\n * @api private\n */\nfunction sendRequest(_x, _x2, _x3) {\n return _sendRequest2.apply(this, arguments);\n}\n/**\n * Checks whether the browser running this code has internet access.\n * This function will always return true in the node.js environment\n *\n * @api private\n */\nfunction _sendRequest2() {\n _sendRequest2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, body, options) {\n var res;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n if (!(typeof options.onBeforeRequest === 'function')) {\n _context.next = 3;\n break;\n }\n _context.next = 3;\n return options.onBeforeRequest(req);\n case 3:\n _context.next = 5;\n return req.send(body);\n case 5:\n res = _context.sent;\n if (!(typeof options.onAfterResponse === 'function')) {\n _context.next = 9;\n break;\n }\n _context.next = 9;\n return options.onAfterResponse(req, res);\n case 9:\n return _context.abrupt(\"return\", res);\n case 10:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return _sendRequest2.apply(this, arguments);\n}\nfunction isOnline() {\n var online = true;\n // Note: We don't reference `window` here because the navigator object also exists\n // in a Web Worker's context.\n // eslint-disable-next-line no-undef\n if (typeof navigator !== 'undefined' && navigator.onLine === false) {\n online = false;\n }\n return online;\n}\n\n/**\n * Checks whether or not it is ok to retry a request.\n * @param {Error|DetailedError} err the error returned from the last request\n * @param {number} retryAttempt the number of times the request has already been retried\n * @param {object} options tus Upload options\n *\n * @api private\n */\nfunction shouldRetry(err, retryAttempt, options) {\n // We only attempt a retry if\n // - retryDelays option is set\n // - we didn't exceed the maxium number of retries, yet, and\n // - this error was caused by a request or it's response and\n // - the error is server error (i.e. not a status 4xx except a 409 or 423) or\n // a onShouldRetry is specified and returns true\n // - the browser does not indicate that we are offline\n if (options.retryDelays == null || retryAttempt >= options.retryDelays.length || err.originalRequest == null) {\n return false;\n }\n if (options && typeof options.onShouldRetry === 'function') {\n return options.onShouldRetry(err, retryAttempt, options);\n }\n return defaultOnShouldRetry(err);\n}\n\n/**\n * determines if the request should be retried. Will only retry if not a status 4xx except a 409 or 423\n * @param {DetailedError} err\n * @returns {boolean}\n */\nfunction defaultOnShouldRetry(err) {\n var status = err.originalResponse ? err.originalResponse.getStatus() : 0;\n return (!inStatusCategory(status, 400) || status === 409 || status === 423) && isOnline();\n}\n\n/**\n * Resolve a relative link given the origin as source. For example,\n * if a HTTP request to http://example.com/files/ returns a Location\n * header with the value /upload/abc, the resolved URL will be:\n * http://example.com/upload/abc\n */\nfunction resolveUrl(origin, link) {\n return new _urlParse[\"default\"](link, origin).toString();\n}\n\n/**\n * Calculate the start and end positions for the parts if an upload\n * is split into multiple parallel requests.\n *\n * @param {number} totalSize The byte size of the upload, which will be split.\n * @param {number} partCount The number in how many parts the upload will be split.\n * @return {object[]}\n * @api private\n */\nfunction splitSizeIntoParts(totalSize, partCount) {\n var partSize = Math.floor(totalSize / partCount);\n var parts = [];\n for (var i = 0; i < partCount; i++) {\n parts.push({\n start: partSize * i,\n end: partSize * (i + 1)\n });\n }\n parts[partCount - 1].end = totalSize;\n return parts;\n}\nBaseUpload.defaultOptions = defaultOptions;\nvar _default = exports[\"default\"] = BaseUpload;\n\n},{\"./error.js\":12,\"./logger.js\":13,\"./uuid.js\":16,\"js-base64\":20,\"url-parse\":23}],16:[function(require,module,exports){\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = uuid;\n/**\n * Generate a UUID v4 based on random numbers. We intentioanlly use the less\n * secure Math.random function here since the more secure crypto.getRandomNumbers\n * is not available on all platforms.\n * This is not a problem for us since we use the UUID only for generating a\n * request ID, so we can correlate server logs to client errors.\n *\n * This function is taken from following site:\n * https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript\n *\n * @return {string} The generate UUID\n */\nfunction uuid() {\n /* eslint-disable no-bitwise */\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n var r = Math.random() * 16 | 0;\n var v = c === 'x' ? r : r & 0x3 | 0x8;\n return v.toString(16);\n });\n}\n\n},{}],17:[function(require,module,exports){\n'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n\n},{}],18:[function(require,module,exports){\n(function (Buffer){(function (){\n/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\n// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\nif (typeof Symbol !== 'undefined' && Symbol.species != null &&\n Buffer[Symbol.species] === Buffer) {\n Object.defineProperty(Buffer, Symbol.species, {\n value: null,\n configurable: true,\n enumerable: false,\n writable: false\n })\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayLike(value)\n }\n\n if (value == null) {\n throw TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nBuffer.prototype.__proto__ = Uint8Array.prototype\nBuffer.__proto__ = Uint8Array\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n buf.__proto__ = Buffer.prototype\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n buf = Buffer.from(buf)\n }\n if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n newBuf.__proto__ = Buffer.prototype\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (var i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n}).call(this)}).call(this,require(\"buffer\").Buffer)\n\n},{\"base64-js\":17,\"buffer\":18,\"ieee754\":19}],19:[function(require,module,exports){\n/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n\n},{}],20:[function(require,module,exports){\n(function (global,Buffer){(function (){\n//\n// THIS FILE IS AUTOMATICALLY GENERATED! DO NOT EDIT BY HAND!\n//\n;\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n ? module.exports = factory()\n : typeof define === 'function' && define.amd\n ? define(factory) :\n // cf. https://github.com/dankogai/js-base64/issues/119\n (function () {\n // existing version for noConflict()\n var _Base64 = global.Base64;\n var gBase64 = factory();\n gBase64.noConflict = function () {\n global.Base64 = _Base64;\n return gBase64;\n };\n if (global.Meteor) { // Meteor.js\n Base64 = gBase64;\n }\n global.Base64 = gBase64;\n })();\n}((typeof self !== 'undefined' ? self\n : typeof window !== 'undefined' ? window\n : typeof global !== 'undefined' ? global\n : this), function () {\n 'use strict';\n /**\n * base64.ts\n *\n * Licensed under the BSD 3-Clause License.\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * References:\n * http://en.wikipedia.org/wiki/Base64\n *\n * @author Dan Kogai (https://github.com/dankogai)\n */\n var version = '3.7.5';\n /**\n * @deprecated use lowercase `version`.\n */\n var VERSION = version;\n var _hasatob = typeof atob === 'function';\n var _hasbtoa = typeof btoa === 'function';\n var _hasBuffer = typeof Buffer === 'function';\n var _TD = typeof TextDecoder === 'function' ? new TextDecoder() : undefined;\n var _TE = typeof TextEncoder === 'function' ? new TextEncoder() : undefined;\n var b64ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';\n var b64chs = Array.prototype.slice.call(b64ch);\n var b64tab = (function (a) {\n var tab = {};\n a.forEach(function (c, i) { return tab[c] = i; });\n return tab;\n })(b64chs);\n var b64re = /^(?:[A-Za-z\\d+\\/]{4})*?(?:[A-Za-z\\d+\\/]{2}(?:==)?|[A-Za-z\\d+\\/]{3}=?)?$/;\n var _fromCC = String.fromCharCode.bind(String);\n var _U8Afrom = typeof Uint8Array.from === 'function'\n ? Uint8Array.from.bind(Uint8Array)\n : function (it) { return new Uint8Array(Array.prototype.slice.call(it, 0)); };\n var _mkUriSafe = function (src) { return src\n .replace(/=/g, '').replace(/[+\\/]/g, function (m0) { return m0 == '+' ? '-' : '_'; }); };\n var _tidyB64 = function (s) { return s.replace(/[^A-Za-z0-9\\+\\/]/g, ''); };\n /**\n * polyfill version of `btoa`\n */\n var btoaPolyfill = function (bin) {\n // console.log('polyfilled');\n var u32, c0, c1, c2, asc = '';\n var pad = bin.length % 3;\n for (var i = 0; i < bin.length;) {\n if ((c0 = bin.charCodeAt(i++)) > 255 ||\n (c1 = bin.charCodeAt(i++)) > 255 ||\n (c2 = bin.charCodeAt(i++)) > 255)\n throw new TypeError('invalid character found');\n u32 = (c0 << 16) | (c1 << 8) | c2;\n asc += b64chs[u32 >> 18 & 63]\n + b64chs[u32 >> 12 & 63]\n + b64chs[u32 >> 6 & 63]\n + b64chs[u32 & 63];\n }\n return pad ? asc.slice(0, pad - 3) + \"===\".substring(pad) : asc;\n };\n /**\n * does what `window.btoa` of web browsers do.\n * @param {String} bin binary string\n * @returns {string} Base64-encoded string\n */\n var _btoa = _hasbtoa ? function (bin) { return btoa(bin); }\n : _hasBuffer ? function (bin) { return Buffer.from(bin, 'binary').toString('base64'); }\n : btoaPolyfill;\n var _fromUint8Array = _hasBuffer\n ? function (u8a) { return Buffer.from(u8a).toString('base64'); }\n : function (u8a) {\n // cf. https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string/12713326#12713326\n var maxargs = 0x1000;\n var strs = [];\n for (var i = 0, l = u8a.length; i < l; i += maxargs) {\n strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));\n }\n return _btoa(strs.join(''));\n };\n /**\n * converts a Uint8Array to a Base64 string.\n * @param {boolean} [urlsafe] URL-and-filename-safe a la RFC4648 §5\n * @returns {string} Base64 string\n */\n var fromUint8Array = function (u8a, urlsafe) {\n if (urlsafe === void 0) { urlsafe = false; }\n return urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a);\n };\n // This trick is found broken https://github.com/dankogai/js-base64/issues/130\n // const utob = (src: string) => unescape(encodeURIComponent(src));\n // reverting good old fationed regexp\n var cb_utob = function (c) {\n if (c.length < 2) {\n var cc = c.charCodeAt(0);\n return cc < 0x80 ? c\n : cc < 0x800 ? (_fromCC(0xc0 | (cc >>> 6))\n + _fromCC(0x80 | (cc & 0x3f)))\n : (_fromCC(0xe0 | ((cc >>> 12) & 0x0f))\n + _fromCC(0x80 | ((cc >>> 6) & 0x3f))\n + _fromCC(0x80 | (cc & 0x3f)));\n }\n else {\n var cc = 0x10000\n + (c.charCodeAt(0) - 0xD800) * 0x400\n + (c.charCodeAt(1) - 0xDC00);\n return (_fromCC(0xf0 | ((cc >>> 18) & 0x07))\n + _fromCC(0x80 | ((cc >>> 12) & 0x3f))\n + _fromCC(0x80 | ((cc >>> 6) & 0x3f))\n + _fromCC(0x80 | (cc & 0x3f)));\n }\n };\n var re_utob = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFFF]|[^\\x00-\\x7F]/g;\n /**\n * @deprecated should have been internal use only.\n * @param {string} src UTF-8 string\n * @returns {string} UTF-16 string\n */\n var utob = function (u) { return u.replace(re_utob, cb_utob); };\n //\n var _encode = _hasBuffer\n ? function (s) { return Buffer.from(s, 'utf8').toString('base64'); }\n : _TE\n ? function (s) { return _fromUint8Array(_TE.encode(s)); }\n : function (s) { return _btoa(utob(s)); };\n /**\n * converts a UTF-8-encoded string to a Base64 string.\n * @param {boolean} [urlsafe] if `true` make the result URL-safe\n * @returns {string} Base64 string\n */\n var encode = function (src, urlsafe) {\n if (urlsafe === void 0) { urlsafe = false; }\n return urlsafe\n ? _mkUriSafe(_encode(src))\n : _encode(src);\n };\n /**\n * converts a UTF-8-encoded string to URL-safe Base64 RFC4648 §5.\n * @returns {string} Base64 string\n */\n var encodeURI = function (src) { return encode(src, true); };\n // This trick is found broken https://github.com/dankogai/js-base64/issues/130\n // const btou = (src: string) => decodeURIComponent(escape(src));\n // reverting good old fationed regexp\n var re_btou = /[\\xC0-\\xDF][\\x80-\\xBF]|[\\xE0-\\xEF][\\x80-\\xBF]{2}|[\\xF0-\\xF7][\\x80-\\xBF]{3}/g;\n var cb_btou = function (cccc) {\n switch (cccc.length) {\n case 4:\n var cp = ((0x07 & cccc.charCodeAt(0)) << 18)\n | ((0x3f & cccc.charCodeAt(1)) << 12)\n | ((0x3f & cccc.charCodeAt(2)) << 6)\n | (0x3f & cccc.charCodeAt(3)), offset = cp - 0x10000;\n return (_fromCC((offset >>> 10) + 0xD800)\n + _fromCC((offset & 0x3FF) + 0xDC00));\n case 3:\n return _fromCC(((0x0f & cccc.charCodeAt(0)) << 12)\n | ((0x3f & cccc.charCodeAt(1)) << 6)\n | (0x3f & cccc.charCodeAt(2)));\n default:\n return _fromCC(((0x1f & cccc.charCodeAt(0)) << 6)\n | (0x3f & cccc.charCodeAt(1)));\n }\n };\n /**\n * @deprecated should have been internal use only.\n * @param {string} src UTF-16 string\n * @returns {string} UTF-8 string\n */\n var btou = function (b) { return b.replace(re_btou, cb_btou); };\n /**\n * polyfill version of `atob`\n */\n var atobPolyfill = function (asc) {\n // console.log('polyfilled');\n asc = asc.replace(/\\s+/g, '');\n if (!b64re.test(asc))\n throw new TypeError('malformed base64.');\n asc += '=='.slice(2 - (asc.length & 3));\n var u24, bin = '', r1, r2;\n for (var i = 0; i < asc.length;) {\n u24 = b64tab[asc.charAt(i++)] << 18\n | b64tab[asc.charAt(i++)] << 12\n | (r1 = b64tab[asc.charAt(i++)]) << 6\n | (r2 = b64tab[asc.charAt(i++)]);\n bin += r1 === 64 ? _fromCC(u24 >> 16 & 255)\n : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255)\n : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);\n }\n return bin;\n };\n /**\n * does what `window.atob` of web browsers do.\n * @param {String} asc Base64-encoded string\n * @returns {string} binary string\n */\n var _atob = _hasatob ? function (asc) { return atob(_tidyB64(asc)); }\n : _hasBuffer ? function (asc) { return Buffer.from(asc, 'base64').toString('binary'); }\n : atobPolyfill;\n //\n var _toUint8Array = _hasBuffer\n ? function (a) { return _U8Afrom(Buffer.from(a, 'base64')); }\n : function (a) { return _U8Afrom(_atob(a).split('').map(function (c) { return c.charCodeAt(0); })); };\n /**\n * converts a Base64 string to a Uint8Array.\n */\n var toUint8Array = function (a) { return _toUint8Array(_unURI(a)); };\n //\n var _decode = _hasBuffer\n ? function (a) { return Buffer.from(a, 'base64').toString('utf8'); }\n : _TD\n ? function (a) { return _TD.decode(_toUint8Array(a)); }\n : function (a) { return btou(_atob(a)); };\n var _unURI = function (a) { return _tidyB64(a.replace(/[-_]/g, function (m0) { return m0 == '-' ? '+' : '/'; })); };\n /**\n * converts a Base64 string to a UTF-8 string.\n * @param {String} src Base64 string. Both normal and URL-safe are supported\n * @returns {string} UTF-8 string\n */\n var decode = function (src) { return _decode(_unURI(src)); };\n /**\n * check if a value is a valid Base64 string\n * @param {String} src a value to check\n */\n var isValid = function (src) {\n if (typeof src !== 'string')\n return false;\n var s = src.replace(/\\s+/g, '').replace(/={0,2}$/, '');\n return !/[^\\s0-9a-zA-Z\\+/]/.test(s) || !/[^\\s0-9a-zA-Z\\-_]/.test(s);\n };\n //\n var _noEnum = function (v) {\n return {\n value: v, enumerable: false, writable: true, configurable: true\n };\n };\n /**\n * extend String.prototype with relevant methods\n */\n var extendString = function () {\n var _add = function (name, body) { return Object.defineProperty(String.prototype, name, _noEnum(body)); };\n _add('fromBase64', function () { return decode(this); });\n _add('toBase64', function (urlsafe) { return encode(this, urlsafe); });\n _add('toBase64URI', function () { return encode(this, true); });\n _add('toBase64URL', function () { return encode(this, true); });\n _add('toUint8Array', function () { return toUint8Array(this); });\n };\n /**\n * extend Uint8Array.prototype with relevant methods\n */\n var extendUint8Array = function () {\n var _add = function (name, body) { return Object.defineProperty(Uint8Array.prototype, name, _noEnum(body)); };\n _add('toBase64', function (urlsafe) { return fromUint8Array(this, urlsafe); });\n _add('toBase64URI', function () { return fromUint8Array(this, true); });\n _add('toBase64URL', function () { return fromUint8Array(this, true); });\n };\n /**\n * extend Builtin prototypes with relevant methods\n */\n var extendBuiltins = function () {\n extendString();\n extendUint8Array();\n };\n var gBase64 = {\n version: version,\n VERSION: VERSION,\n atob: _atob,\n atobPolyfill: atobPolyfill,\n btoa: _btoa,\n btoaPolyfill: btoaPolyfill,\n fromBase64: decode,\n toBase64: encode,\n encode: encode,\n encodeURI: encodeURI,\n encodeURL: encodeURI,\n utob: utob,\n btou: btou,\n decode: decode,\n isValid: isValid,\n fromUint8Array: fromUint8Array,\n toUint8Array: toUint8Array,\n extendString: extendString,\n extendUint8Array: extendUint8Array,\n extendBuiltins: extendBuiltins\n };\n //\n // export Base64 to the namespace\n //\n // ES5 is yet to have Object.assign() that may make transpilers unhappy.\n // gBase64.Base64 = Object.assign({}, gBase64);\n gBase64.Base64 = {};\n Object.keys(gBase64).forEach(function (k) { return gBase64.Base64[k] = gBase64[k]; });\n return gBase64;\n}));\n\n}).call(this)}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {},require(\"buffer\").Buffer)\n\n},{\"buffer\":18}],21:[function(require,module,exports){\n'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , undef;\n\n/**\n * Decode a URI encoded string.\n *\n * @param {String} input The URI encoded string.\n * @returns {String|Null} The decoded string.\n * @api private\n */\nfunction decode(input) {\n try {\n return decodeURIComponent(input.replace(/\\+/g, ' '));\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Attempts to encode a given input.\n *\n * @param {String} input The string that needs to be encoded.\n * @returns {String|Null} The encoded string.\n * @api private\n */\nfunction encode(input) {\n try {\n return encodeURIComponent(input);\n } catch (e) {\n return null;\n }\n}\n\n/**\n * Simple query string parser.\n *\n * @param {String} query The query string that needs to be parsed.\n * @returns {Object}\n * @api public\n */\nfunction querystring(query) {\n var parser = /([^=?#&]+)=?([^&]*)/g\n , result = {}\n , part;\n\n while (part = parser.exec(query)) {\n var key = decode(part[1])\n , value = decode(part[2]);\n\n //\n // Prevent overriding of existing properties. This ensures that build-in\n // methods like `toString` or __proto__ are not overriden by malicious\n // querystrings.\n //\n // In the case if failed decoding, we want to omit the key/value pairs\n // from the result.\n //\n if (key === null || value === null || key in result) continue;\n result[key] = value;\n }\n\n return result;\n}\n\n/**\n * Transform a query string to an object.\n *\n * @param {Object} obj Object that should be transformed.\n * @param {String} prefix Optional prefix.\n * @returns {String}\n * @api public\n */\nfunction querystringify(obj, prefix) {\n prefix = prefix || '';\n\n var pairs = []\n , value\n , key;\n\n //\n // Optionally prefix with a '?' if needed\n //\n if ('string' !== typeof prefix) prefix = '?';\n\n for (key in obj) {\n if (has.call(obj, key)) {\n value = obj[key];\n\n //\n // Edge cases where we actually want to encode the value to an empty\n // string instead of the stringified value.\n //\n if (!value && (value === null || value === undef || isNaN(value))) {\n value = '';\n }\n\n key = encode(key);\n value = encode(value);\n\n //\n // If we failed to encode the strings, we should bail out as we don't\n // want to add invalid strings to the query.\n //\n if (key === null || value === null) continue;\n pairs.push(key +'='+ value);\n }\n }\n\n return pairs.length ? prefix + pairs.join('&') : '';\n}\n\n//\n// Expose the module.\n//\nexports.stringify = querystringify;\nexports.parse = querystring;\n\n},{}],22:[function(require,module,exports){\n'use strict';\n\n/**\n * Check if we're required to add a port number.\n *\n * @see https://url.spec.whatwg.org/#default-port\n * @param {Number|String} port Port number we need to check\n * @param {String} protocol Protocol we need to check against.\n * @returns {Boolean} Is it a default port for the given protocol\n * @api private\n */\nmodule.exports = function required(port, protocol) {\n protocol = protocol.split(':')[0];\n port = +port;\n\n if (!port) return false;\n\n switch (protocol) {\n case 'http':\n case 'ws':\n return port !== 80;\n\n case 'https':\n case 'wss':\n return port !== 443;\n\n case 'ftp':\n return port !== 21;\n\n case 'gopher':\n return port !== 70;\n\n case 'file':\n return false;\n }\n\n return port !== 0;\n};\n\n},{}],23:[function(require,module,exports){\n(function (global){(function (){\n'use strict';\n\nvar required = require('requires-port')\n , qs = require('querystringify')\n , controlOrWhitespace = /^[\\x00-\\x20\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000\\ufeff]+/\n , CRHTLF = /[\\n\\r\\t]/g\n , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\\/\\//\n , port = /:\\d+$/\n , protocolre = /^([a-z][a-z0-9.+-]*:)?(\\/\\/)?([\\\\/]+)?([\\S\\s]*)/i\n , windowsDriveLetter = /^[a-zA-Z]:/;\n\n/**\n * Remove control characters and whitespace from the beginning of a string.\n *\n * @param {Object|String} str String to trim.\n * @returns {String} A new string representing `str` stripped of control\n * characters and whitespace from its beginning.\n * @public\n */\nfunction trimLeft(str) {\n return (str ? str : '').toString().replace(controlOrWhitespace, '');\n}\n\n/**\n * These are the parse rules for the URL parser, it informs the parser\n * about:\n *\n * 0. The char it Needs to parse, if it's a string it should be done using\n * indexOf, RegExp using exec and NaN means set as current value.\n * 1. The property we should set when parsing this value.\n * 2. Indication if it's backwards or forward parsing, when set as number it's\n * the value of extra chars that should be split off.\n * 3. Inherit from location if non existing in the parser.\n * 4. `toLowerCase` the resulting value.\n */\nvar rules = [\n ['#', 'hash'], // Extract from the back.\n ['?', 'query'], // Extract from the back.\n function sanitize(address, url) { // Sanitize what is left of the address\n return isSpecial(url.protocol) ? address.replace(/\\\\/g, '/') : address;\n },\n ['/', 'pathname'], // Extract from the back.\n ['@', 'auth', 1], // Extract from the front.\n [NaN, 'host', undefined, 1, 1], // Set left over value.\n [/:(\\d*)$/, 'port', undefined, 1], // RegExp the back.\n [NaN, 'hostname', undefined, 1, 1] // Set left over.\n];\n\n/**\n * These properties should not be copied or inherited from. This is only needed\n * for all non blob URL's as a blob URL does not include a hash, only the\n * origin.\n *\n * @type {Object}\n * @private\n */\nvar ignore = { hash: 1, query: 1 };\n\n/**\n * The location object differs when your code is loaded through a normal page,\n * Worker or through a worker using a blob. And with the blobble begins the\n * trouble as the location object will contain the URL of the blob, not the\n * location of the page where our code is loaded in. The actual origin is\n * encoded in the `pathname` so we can thankfully generate a good \"default\"\n * location from it so we can generate proper relative URL's again.\n *\n * @param {Object|String} loc Optional default location object.\n * @returns {Object} lolcation object.\n * @public\n */\nfunction lolcation(loc) {\n var globalVar;\n\n if (typeof window !== 'undefined') globalVar = window;\n else if (typeof global !== 'undefined') globalVar = global;\n else if (typeof self !== 'undefined') globalVar = self;\n else globalVar = {};\n\n var location = globalVar.location || {};\n loc = loc || location;\n\n var finaldestination = {}\n , type = typeof loc\n , key;\n\n if ('blob:' === loc.protocol) {\n finaldestination = new Url(unescape(loc.pathname), {});\n } else if ('string' === type) {\n finaldestination = new Url(loc, {});\n for (key in ignore) delete finaldestination[key];\n } else if ('object' === type) {\n for (key in loc) {\n if (key in ignore) continue;\n finaldestination[key] = loc[key];\n }\n\n if (finaldestination.slashes === undefined) {\n finaldestination.slashes = slashes.test(loc.href);\n }\n }\n\n return finaldestination;\n}\n\n/**\n * Check whether a protocol scheme is special.\n *\n * @param {String} The protocol scheme of the URL\n * @return {Boolean} `true` if the protocol scheme is special, else `false`\n * @private\n */\nfunction isSpecial(scheme) {\n return (\n scheme === 'file:' ||\n scheme === 'ftp:' ||\n scheme === 'http:' ||\n scheme === 'https:' ||\n scheme === 'ws:' ||\n scheme === 'wss:'\n );\n}\n\n/**\n * @typedef ProtocolExtract\n * @type Object\n * @property {String} protocol Protocol matched in the URL, in lowercase.\n * @property {Boolean} slashes `true` if protocol is followed by \"//\", else `false`.\n * @property {String} rest Rest of the URL that is not part of the protocol.\n */\n\n/**\n * Extract protocol information from a URL with/without double slash (\"//\").\n *\n * @param {String} address URL we want to extract from.\n * @param {Object} location\n * @return {ProtocolExtract} Extracted information.\n * @private\n */\nfunction extractProtocol(address, location) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n location = location || {};\n\n var match = protocolre.exec(address);\n var protocol = match[1] ? match[1].toLowerCase() : '';\n var forwardSlashes = !!match[2];\n var otherSlashes = !!match[3];\n var slashesCount = 0;\n var rest;\n\n if (forwardSlashes) {\n if (otherSlashes) {\n rest = match[2] + match[3] + match[4];\n slashesCount = match[2].length + match[3].length;\n } else {\n rest = match[2] + match[4];\n slashesCount = match[2].length;\n }\n } else {\n if (otherSlashes) {\n rest = match[3] + match[4];\n slashesCount = match[3].length;\n } else {\n rest = match[4]\n }\n }\n\n if (protocol === 'file:') {\n if (slashesCount >= 2) {\n rest = rest.slice(2);\n }\n } else if (isSpecial(protocol)) {\n rest = match[4];\n } else if (protocol) {\n if (forwardSlashes) {\n rest = rest.slice(2);\n }\n } else if (slashesCount >= 2 && isSpecial(location.protocol)) {\n rest = match[4];\n }\n\n return {\n protocol: protocol,\n slashes: forwardSlashes || isSpecial(protocol),\n slashesCount: slashesCount,\n rest: rest\n };\n}\n\n/**\n * Resolve a relative URL pathname against a base URL pathname.\n *\n * @param {String} relative Pathname of the relative URL.\n * @param {String} base Pathname of the base URL.\n * @return {String} Resolved pathname.\n * @private\n */\nfunction resolve(relative, base) {\n if (relative === '') return base;\n\n var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))\n , i = path.length\n , last = path[i - 1]\n , unshift = false\n , up = 0;\n\n while (i--) {\n if (path[i] === '.') {\n path.splice(i, 1);\n } else if (path[i] === '..') {\n path.splice(i, 1);\n up++;\n } else if (up) {\n if (i === 0) unshift = true;\n path.splice(i, 1);\n up--;\n }\n }\n\n if (unshift) path.unshift('');\n if (last === '.' || last === '..') path.push('');\n\n return path.join('/');\n}\n\n/**\n * The actual URL instance. Instead of returning an object we've opted-in to\n * create an actual constructor as it's much more memory efficient and\n * faster and it pleases my OCD.\n *\n * It is worth noting that we should not use `URL` as class name to prevent\n * clashes with the global URL instance that got introduced in browsers.\n *\n * @constructor\n * @param {String} address URL we want to parse.\n * @param {Object|String} [location] Location defaults for relative paths.\n * @param {Boolean|Function} [parser] Parser for the query string.\n * @private\n */\nfunction Url(address, location, parser) {\n address = trimLeft(address);\n address = address.replace(CRHTLF, '');\n\n if (!(this instanceof Url)) {\n return new Url(address, location, parser);\n }\n\n var relative, extracted, parse, instruction, index, key\n , instructions = rules.slice()\n , type = typeof location\n , url = this\n , i = 0;\n\n //\n // The following if statements allows this module two have compatibility with\n // 2 different API:\n //\n // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments\n // where the boolean indicates that the query string should also be parsed.\n //\n // 2. The `URL` interface of the browser which accepts a URL, object as\n // arguments. The supplied object will be used as default values / fall-back\n // for relative paths.\n //\n if ('object' !== type && 'string' !== type) {\n parser = location;\n location = null;\n }\n\n if (parser && 'function' !== typeof parser) parser = qs.parse;\n\n location = lolcation(location);\n\n //\n // Extract protocol information before running the instructions.\n //\n extracted = extractProtocol(address || '', location);\n relative = !extracted.protocol && !extracted.slashes;\n url.slashes = extracted.slashes || relative && location.slashes;\n url.protocol = extracted.protocol || location.protocol || '';\n address = extracted.rest;\n\n //\n // When the authority component is absent the URL starts with a path\n // component.\n //\n if (\n extracted.protocol === 'file:' && (\n extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) ||\n (!extracted.slashes &&\n (extracted.protocol ||\n extracted.slashesCount < 2 ||\n !isSpecial(url.protocol)))\n ) {\n instructions[3] = [/(.*)/, 'pathname'];\n }\n\n for (; i < instructions.length; i++) {\n instruction = instructions[i];\n\n if (typeof instruction === 'function') {\n address = instruction(address, url);\n continue;\n }\n\n parse = instruction[0];\n key = instruction[1];\n\n if (parse !== parse) {\n url[key] = address;\n } else if ('string' === typeof parse) {\n index = parse === '@'\n ? address.lastIndexOf(parse)\n : address.indexOf(parse);\n\n if (~index) {\n if ('number' === typeof instruction[2]) {\n url[key] = address.slice(0, index);\n address = address.slice(index + instruction[2]);\n } else {\n url[key] = address.slice(index);\n address = address.slice(0, index);\n }\n }\n } else if ((index = parse.exec(address))) {\n url[key] = index[1];\n address = address.slice(0, index.index);\n }\n\n url[key] = url[key] || (\n relative && instruction[3] ? location[key] || '' : ''\n );\n\n //\n // Hostname, host and protocol should be lowercased so they can be used to\n // create a proper `origin`.\n //\n if (instruction[4]) url[key] = url[key].toLowerCase();\n }\n\n //\n // Also parse the supplied query string in to an object. If we're supplied\n // with a custom parser as function use that instead of the default build-in\n // parser.\n //\n if (parser) url.query = parser(url.query);\n\n //\n // If the URL is relative, resolve the pathname against the base URL.\n //\n if (\n relative\n && location.slashes\n && url.pathname.charAt(0) !== '/'\n && (url.pathname !== '' || location.pathname !== '')\n ) {\n url.pathname = resolve(url.pathname, location.pathname);\n }\n\n //\n // Default to a / for pathname if none exists. This normalizes the URL\n // to always have a /\n //\n if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) {\n url.pathname = '/' + url.pathname;\n }\n\n //\n // We should not add port numbers if they are already the default port number\n // for a given protocol. As the host also contains the port number we're going\n // override it with the hostname which contains no port number.\n //\n if (!required(url.port, url.protocol)) {\n url.host = url.hostname;\n url.port = '';\n }\n\n //\n // Parse down the `auth` for the username and password.\n //\n url.username = url.password = '';\n\n if (url.auth) {\n index = url.auth.indexOf(':');\n\n if (~index) {\n url.username = url.auth.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = url.auth.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password))\n } else {\n url.username = encodeURIComponent(decodeURIComponent(url.auth));\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n }\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n //\n // The href is just the compiled result.\n //\n url.href = url.toString();\n}\n\n/**\n * This is convenience method for changing properties in the URL instance to\n * insure that they all propagate correctly.\n *\n * @param {String} part Property we need to adjust.\n * @param {Mixed} value The newly assigned value.\n * @param {Boolean|Function} fn When setting the query, it will be the function\n * used to parse the query.\n * When setting the protocol, double slash will be\n * removed from the final url if it is true.\n * @returns {URL} URL instance for chaining.\n * @public\n */\nfunction set(part, value, fn) {\n var url = this;\n\n switch (part) {\n case 'query':\n if ('string' === typeof value && value.length) {\n value = (fn || qs.parse)(value);\n }\n\n url[part] = value;\n break;\n\n case 'port':\n url[part] = value;\n\n if (!required(value, url.protocol)) {\n url.host = url.hostname;\n url[part] = '';\n } else if (value) {\n url.host = url.hostname +':'+ value;\n }\n\n break;\n\n case 'hostname':\n url[part] = value;\n\n if (url.port) value += ':'+ url.port;\n url.host = value;\n break;\n\n case 'host':\n url[part] = value;\n\n if (port.test(value)) {\n value = value.split(':');\n url.port = value.pop();\n url.hostname = value.join(':');\n } else {\n url.hostname = value;\n url.port = '';\n }\n\n break;\n\n case 'protocol':\n url.protocol = value.toLowerCase();\n url.slashes = !fn;\n break;\n\n case 'pathname':\n case 'hash':\n if (value) {\n var char = part === 'pathname' ? '/' : '#';\n url[part] = value.charAt(0) !== char ? char + value : value;\n } else {\n url[part] = value;\n }\n break;\n\n case 'username':\n case 'password':\n url[part] = encodeURIComponent(value);\n break;\n\n case 'auth':\n var index = value.indexOf(':');\n\n if (~index) {\n url.username = value.slice(0, index);\n url.username = encodeURIComponent(decodeURIComponent(url.username));\n\n url.password = value.slice(index + 1);\n url.password = encodeURIComponent(decodeURIComponent(url.password));\n } else {\n url.username = encodeURIComponent(decodeURIComponent(value));\n }\n }\n\n for (var i = 0; i < rules.length; i++) {\n var ins = rules[i];\n\n if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();\n }\n\n url.auth = url.password ? url.username +':'+ url.password : url.username;\n\n url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host\n ? url.protocol +'//'+ url.host\n : 'null';\n\n url.href = url.toString();\n\n return url;\n}\n\n/**\n * Transform the properties back in to a valid and full URL string.\n *\n * @param {Function} stringify Optional query stringify function.\n * @returns {String} Compiled version of the URL.\n * @public\n */\nfunction toString(stringify) {\n if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;\n\n var query\n , url = this\n , host = url.host\n , protocol = url.protocol;\n\n if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';\n\n var result =\n protocol +\n ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');\n\n if (url.username) {\n result += url.username;\n if (url.password) result += ':'+ url.password;\n result += '@';\n } else if (url.password) {\n result += ':'+ url.password;\n result += '@';\n } else if (\n url.protocol !== 'file:' &&\n isSpecial(url.protocol) &&\n !host &&\n url.pathname !== '/'\n ) {\n //\n // Add back the empty userinfo, otherwise the original invalid URL\n // might be transformed into a valid one with `url.pathname` as host.\n //\n result += '@';\n }\n\n //\n // Trailing colon is removed from `url.host` when it is parsed. If it still\n // ends with a colon, then add back the trailing colon that was removed. This\n // prevents an invalid URL from being transformed into a valid one.\n //\n if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) {\n host += ':';\n }\n\n result += host + url.pathname;\n\n query = 'object' === typeof url.query ? stringify(url.query) : url.query;\n if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;\n\n if (url.hash) result += url.hash;\n\n return result;\n}\n\nUrl.prototype = { set: set, toString: toString };\n\n//\n// Expose the URL parser and some additional properties that might be useful for\n// others or testing.\n//\nUrl.extractProtocol = extractProtocol;\nUrl.location = lolcation;\nUrl.trimLeft = trimLeft;\nUrl.qs = qs;\n\nmodule.exports = Url;\n\n}).call(this)}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n\n},{\"querystringify\":21,\"requires-port\":22}]},{},[4])(4)\n});\n//# sourceMappingURL=tus.js.map\n"],"names":["f","exports","module","define","amd","window","global","self","this","tus","r","e","n","t","o","i","c","require","u","a","Error","code","p","call","length","Object","defineProperty","value","_isReactNative","_interopRequireDefault","_uriToBlob","_FileSource","_StreamSource","obj","__esModule","_typeof","Symbol","iterator","constructor","prototype","_regeneratorRuntime","hasOwnProperty","asyncIterator","toStringTag","enumerable","configurable","writable","wrap","Generator","create","Context","makeInvokeMethod","tryCatch","type","arg","h","s","y","GeneratorFunction","GeneratorFunctionPrototype","d","getPrototypeOf","v","values","g","defineIteratorMethods","forEach","_invoke","AsyncIterator","invoke","resolve","__await","then","callInvokeWithMethodAndArg","done","method","delegate","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","TypeError","resultName","next","nextLoc","pushTryEntry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","push","resetTryEntry","completion","reset","isNaN","displayName","isGeneratorFunction","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","keys","reverse","pop","prev","charAt","slice","stop","rval","handle","complete","finish","delegateYield","asyncGeneratorStep","gen","reject","_next","_throw","key","info","error","_defineProperties","target","props","descriptor","input","hint","prim","toPrimitive","undefined","res","String","Number","_toPrimitive","FileReader","instance","Constructor","_classCallCheck","protoProps","staticProps","fn","_openFile","_callee","chunkSize","blob","_context","uri","t0","concat","size","read","isFinite","args","arguments","apply","err","_x","_x2","file","options","exifHash","exif","str","hash","charCodeAt","hashCode","JSON","stringify","endpoint","join","reactNativeFingerprint","lastModified","_createClass","XHRHttpStack","url","Request","_xhr","XMLHttpRequest","open","_method","_url","_headers","header","setRequestHeader","progressHandler","upload","onprogress","lengthComputable","loaded","_this","body","onload","Response","onerror","send","abort","xhr","status","getResponseHeader","responseText","get","_httpStack","_error","Upload","_urlStorage","canStoreURLs","defaultOptions","_logger","enableDebugLog","isSupported","_upload","_noopUrlStorage","_fileReader","_fileSignature","_toPropertyKey","_setPrototypeOf","bind","_createSuper","Derived","hasNativeReflectConstruct","Reflect","construct","sham","Proxy","Boolean","valueOf","_isNativeReflectConstruct","result","Super","_getPrototypeOf","NewTarget","_possibleConstructorReturn","ReferenceError","_assertThisInitialized","ownKeys","getOwnPropertySymbols","filter","getOwnPropertyDescriptor","_objectSpread","_defineProperty","getOwnPropertyDescriptors","defineProperties","httpStack","fileReader","urlStorage","WebStorageUrlStorage","fingerprint","_BaseUpload","subClass","superClass","_inherits","_super","terminate","Blob","navigator","product","toLowerCase","_isCordova","_readAsByteArray","FileSource","_file","start","end","len","blobOrArray","StreamSource","reader","_buffer","_bufferOffset","_reader","_done","_readUntilEnoughDataOrDone","hasEnoughData","_getDataFromBuffer","_ref","b","set","hasAllDataBeenRead","cancel","PhoneGap","Cordova","cordova","chunk","Uint8Array","readAsArrayBuffer","responseType","response","hasStorage","originalValue","localStorage","getItem","setItem","removeItem","SECURITY_ERR","QUOTA_EXCEEDED_ERR","results","_findEntries","urlStorageKey","id","Math","round","random","prefix","_key","indexOf","parse","_wrapNativeSuper","Class","_cache","Map","Function","toString","_isNativeFunction","has","Wrapper","_construct","Parent","DetailedError","_Error","message","causingErr","req","originalRequest","originalResponse","causingError","requestId","getHeader","getMethod","getURL","getStatus","getBody","isEnabled","log","msg","console","NoopUrlStorage","_jsBase","_urlParse","_uuid","_asyncToGenerator","_slicedToArray","arr","Array","isArray","_arrayWithHoles","l","_iterableToArrayLimit","minLen","_arrayLikeToArray","from","test","_unsupportedIterableToArray","_nonIterableRest","arr2","uploadUrl","metadata","uploadSize","onProgress","onChunkComplete","onSuccess","onError","onUploadUrlAvailable","overridePatchMethod","headers","addRequestId","onBeforeRequest","onAfterResponse","onShouldRetry","defaultOnShouldRetry","Infinity","retryDelays","parallelUploads","parallelUploadBoundaries","storeFingerprintForResuming","removeFingerprintOnSuccess","uploadLengthDeferred","uploadDataDuringCreation","BaseUpload","_req","_fingerprint","_urlStorageKey","_offset","_aborted","_size","_source","_retryAttempt","_retryTimeout","_offsetBeforeRetry","_parallelUploads","_parallelUploadUrls","findUploadsByFingerprint","previousUpload","parallelUploadUrls","_this2","_i","_arr","optionName","_emitError","openFile","source","_startParallelUpload","_startSingleUpload","_this$options$paralle","_this3","totalSize","totalProgress","partCount","parts","partSize","floor","splitSizeIntoParts","part","index","uploads","map","lastPartProgress","newPartProgress","_emitProgress","_saveUploadInUrlStorage","all","_openRequest","setHeader","encodeMetadata","_sendRequest","inStatusCategory","location","resolveUrl","_emitSuccess","_emitHttpError","_resumeUpload","_createUpload","shouldTerminate","_this4","clearTimeout","_removeFromUrlStorage","_this5","shouldRetry","delay","setTimeout","bytesSent","bytesTotal","bytesAccepted","_this6","promise","_addChunkToRequest","close","_handleUploadResponse","_performUpload","_this7","offset","parseInt","_this8","_this9","setProgressHandler","_ref2","valueSize","newSize","_emitChunkComplete","openRequest","_this10","removeUpload","_this11","storedUpload","creationTime","Date","addUpload","sendRequest","remainingDelays","newOptions","entries","_ref3","_ref4","Base64","encode","category","createRequest","_ref5","_ref6","_x3","_sendRequest2","retryAttempt","online","onLine","origin","link","replace","byteLength","b64","lens","getLens","validLen","placeHoldersLen","toByteArray","tmp","Arr","_byteLength","curByte","revLookup","fromByteArray","uint8","extraBytes","len2","encodeChunk","lookup","num","output","Buffer","base64","ieee754","SlowBuffer","alloc","INSPECT_MAX_BYTES","createBuffer","RangeError","buf","encodingOrOffset","allocUnsafe","string","encoding","isEncoding","actual","write","fromString","ArrayBuffer","isView","fromArrayLike","isInstance","buffer","array","byteOffset","fromArrayBuffer","isBuffer","checked","copy","numberIsNaN","data","fromObject","assertSize","mustMatch","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","m","bidirectionalIndexOf","val","dir","arrayIndexOf","lastIndexOf","indexSize","arrLength","valLength","readUInt16BE","foundIndex","found","j","hexWrite","remaining","strLen","parsed","substr","utf8Write","blitBuffer","asciiWrite","byteArray","asciiToBytes","latin1Write","base64Write","ucs2Write","units","hi","lo","utf16leToBytes","min","secondByte","thirdByte","fourthByte","tempCodePoint","firstByte","codePoint","bytesPerSequence","codePoints","fromCharCode","decodeCodePointsArray","kMaxLength","TYPED_ARRAY_SUPPORT","foo","typedArraySupport","species","poolSize","fill","allocUnsafeSlow","_isBuffer","compare","x","list","pos","swap16","swap32","swap64","toLocaleString","equals","inspect","max","trim","thisStart","thisEnd","thisCopy","targetCopy","includes","toJSON","ret","out","toHex","bytes","checkOffset","ext","checkInt","checkIEEE754","writeFloat","littleEndian","noAssert","writeDouble","newBuf","subarray","readUIntLE","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","pow","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","readFloatBE","readDoubleLE","readDoubleBE","writeUIntLE","writeUIntBE","writeUInt8","writeUInt16LE","writeUInt16BE","writeUInt32LE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","writeFloatLE","writeFloatBE","writeDoubleLE","writeDoubleBE","targetStart","copyWithin","INVALID_BASE64_RE","leadSurrogate","split","base64clean","src","dst","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","rt","abs","LN2","factory","_Base64","gBase64","noConflict","Meteor","tab","_hasatob","atob","_hasbtoa","btoa","_hasBuffer","_TD","TextDecoder","_TE","TextEncoder","b64chs","b64tab","b64re","_fromCC","_U8Afrom","it","_mkUriSafe","m0","_tidyB64","btoaPolyfill","bin","u32","c0","c1","c2","asc","pad","substring","_btoa","_fromUint8Array","u8a","strs","fromUint8Array","urlsafe","cb_utob","cc","re_utob","utob","_encode","encodeURI","re_btou","cb_btou","cccc","btou","atobPolyfill","u24","r1","r2","_atob","_toUint8Array","toUint8Array","_unURI","_decode","decode","_noEnum","extendString","_add","extendUint8Array","version","VERSION","fromBase64","toBase64","encodeURL","isValid","extendBuiltins","k","decodeURIComponent","encodeURIComponent","pairs","query","parser","exec","port","protocol","required","qs","controlOrWhitespace","CRHTLF","slashes","protocolre","windowsDriveLetter","trimLeft","rules","address","isSpecial","ignore","lolcation","loc","finaldestination","Url","unescape","pathname","href","scheme","extractProtocol","rest","match","forwardSlashes","otherSlashes","slashesCount","relative","extracted","instruction","instructions","base","path","last","unshift","up","splice","host","hostname","username","password","auth","char","ins"],"mappings":"CAAA,SAAUA,MAAuB,iBAAVC,SAAoC,oBAATC,OAAsBA,OAAOD,QAAQD,SAAS,GAAmB,mBAATG,QAAqBA,OAAOC,IAAKD,g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B,IAAIomB,UAErBtB,MAAQ,iBAAoB9kB,IAAI8kB,MAAQrlB,UAAUO,IAAI8kB,OAAS9kB,IAAI8kB,SACxDzhB,QAAU,MAAQyhB,MAAMnpB,OAAO,GAAK,IAAKmpB,MAAQA,OAExD9kB,IAAIX,OAAMgE,QAAUrD,IAAIX,MAErBgE,SAST6iB,IAAIK,gBAAkBA,gBACtBL,IAAIvW,SAAWoW,UACfG,IAAIR,SAAWA,SACfQ,IAAId,GAAKA,GAETrwB,OAAOD,QAAUoxB,MAEd9vB,KAAKf,QAAQe,KAAKf,KAAuB,oBAAXF,OAAyBA,OAAyB,oBAATC,KAAuBA,KAAyB,oBAAXF,OAAyBA,OAAS,KAE/I,gBAAkB,mBAAmB,MAAM,GAAG,CAAC,GA12J2T,CA02JvT"} \ No newline at end of file diff --git a/source/vimeo/amd/src/file_upload.js b/source/vimeo/amd/src/file_upload.js new file mode 100644 index 0000000..9eb2e55 --- /dev/null +++ b/source/vimeo/amd/src/file_upload.js @@ -0,0 +1,58 @@ +import Ajax from 'core/ajax'; +import Config from 'core/config'; +import Log from 'core/log'; +import Notification from 'core/notification'; + +const upload = async(resource) => { + const file = document.querySelector('input[name="videofile"]').files[0]; + const url = new URL(Config.wwwroot + '/admin/tool/mediatime/index.php'); + let offset = 0; + let response; + + url.searchParams.set('id', resource.id); + + do { + const request = new Request(resource.uploadurl, { + body: file, + headers: { + 'Tus-Resumable': '1.0.0', + 'Upload-Offset': String(offset), + 'Content-Type': 'application/offset+octet-stream' + }, + method: 'PATCH' + }); + response = await fetch(request); + document.querySelector('.progress').style.width = (response.headers.get('Upload-Offset') / file.size * 100) + '%'; + Log.debug(response.headers.get('Upload-Offset')); + } while (response.headers.get('Upload-Offset') < file.size); + window.location.href = url; +}; + +export default { + init: function() { + document.body.removeEventListener('click', this.handleClick); + document.body.addEventListener('click', this.handleClick); + }, + + handleClick: function(e) { + const button = e.target.closest('button[name="upload"]'); + if (button) { + const file = document.querySelector('input[name="videofile"]').files[0]; + e.preventDefault(); + Ajax.call([{ + args: { + filesize: Number(file.size), + description: document.querySelector('input[name="description"]').value, + name: document.querySelector('input[name="name"]').value, + tags: document.querySelector('input[name="tags"]').value, + title: document.querySelector('input[name="title"]').value + }, + contextid: 1, + done: upload, + fail: Notification.exception, + methodname: 'mediatimesrc_vimeo_create_token' + }]); + Log.debug(file.size); + } + } +}; diff --git a/source/vimeo/amd/src/tus.js b/source/vimeo/amd/src/tus.js new file mode 100644 index 0000000..c72ed62 --- /dev/null +++ b/source/vimeo/amd/src/tus.js @@ -0,0 +1,4973 @@ +(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.tus = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var FileReader = exports["default"] = /*#__PURE__*/function () { + function FileReader() { + _classCallCheck(this, FileReader); + } + _createClass(FileReader, [{ + key: "openFile", + value: function () { + var _openFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(input, chunkSize) { + var blob; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!((0, _isReactNative["default"])() && input && typeof input.uri !== 'undefined')) { + _context.next = 11; + break; + } + _context.prev = 1; + _context.next = 4; + return (0, _uriToBlob["default"])(input.uri); + case 4: + blob = _context.sent; + return _context.abrupt("return", new _FileSource["default"](blob)); + case 8: + _context.prev = 8; + _context.t0 = _context["catch"](1); + throw new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. ".concat(_context.t0)); + case 11: + if (!(typeof input.slice === 'function' && typeof input.size !== 'undefined')) { + _context.next = 13; + break; + } + return _context.abrupt("return", Promise.resolve(new _FileSource["default"](input))); + case 13: + if (!(typeof input.read === 'function')) { + _context.next = 18; + break; + } + chunkSize = Number(chunkSize); + if (Number.isFinite(chunkSize)) { + _context.next = 17; + break; + } + return _context.abrupt("return", Promise.reject(new Error('cannot create source for stream without a finite value for the `chunkSize` option'))); + case 17: + return _context.abrupt("return", Promise.resolve(new _StreamSource["default"](input, chunkSize))); + case 18: + return _context.abrupt("return", Promise.reject(new Error('source object may only be an instance of File, Blob, or Reader in this environment'))); + case 19: + case "end": + return _context.stop(); + } + }, _callee, null, [[1, 8]]); + })); + function openFile(_x, _x2) { + return _openFile.apply(this, arguments); + } + return openFile; + }() + }]); + return FileReader; +}(); + +},{"./isReactNative.js":5,"./sources/FileSource.js":6,"./sources/StreamSource.js":7,"./uriToBlob.js":10}],2:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = fingerprint; +var _isReactNative = _interopRequireDefault(require("./isReactNative.js")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +// TODO: Differenciate between input types + +/** + * Generate a fingerprint for a file which will be used the store the endpoint + * + * @param {File} file + * @param {Object} options + * @param {Function} callback + */ +function fingerprint(file, options) { + if ((0, _isReactNative["default"])()) { + return Promise.resolve(reactNativeFingerprint(file, options)); + } + return Promise.resolve(['tus-br', file.name, file.type, file.size, file.lastModified, options.endpoint].join('-')); +} +function reactNativeFingerprint(file, options) { + var exifHash = file.exif ? hashCode(JSON.stringify(file.exif)) : 'noexif'; + return ['tus-rn', file.name || 'noname', file.size || 'nosize', exifHash, options.endpoint].join('/'); +} +function hashCode(str) { + /* eslint-disable no-bitwise */ + // from https://stackoverflow.com/a/8831937/151666 + var hash = 0; + if (str.length === 0) { + return hash; + } + for (var i = 0; i < str.length; i++) { + var _char = str.charCodeAt(i); + hash = (hash << 5) - hash + _char; + hash &= hash; // Convert to 32bit integer + } + return hash; +} + +},{"./isReactNative.js":5}],3:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +/* eslint-disable max-classes-per-file */ +var XHRHttpStack = exports["default"] = /*#__PURE__*/function () { + function XHRHttpStack() { + _classCallCheck(this, XHRHttpStack); + } + _createClass(XHRHttpStack, [{ + key: "createRequest", + value: function createRequest(method, url) { + return new Request(method, url); + } + }, { + key: "getName", + value: function getName() { + return 'XHRHttpStack'; + } + }]); + return XHRHttpStack; +}(); +var Request = /*#__PURE__*/function () { + function Request(method, url) { + _classCallCheck(this, Request); + this._xhr = new XMLHttpRequest(); + this._xhr.open(method, url, true); + this._method = method; + this._url = url; + this._headers = {}; + } + _createClass(Request, [{ + key: "getMethod", + value: function getMethod() { + return this._method; + } + }, { + key: "getURL", + value: function getURL() { + return this._url; + } + }, { + key: "setHeader", + value: function setHeader(header, value) { + this._xhr.setRequestHeader(header, value); + this._headers[header] = value; + } + }, { + key: "getHeader", + value: function getHeader(header) { + return this._headers[header]; + } + }, { + key: "setProgressHandler", + value: function setProgressHandler(progressHandler) { + // Test support for progress events before attaching an event listener + if (!('upload' in this._xhr)) { + return; + } + this._xhr.upload.onprogress = function (e) { + if (!e.lengthComputable) { + return; + } + progressHandler(e.loaded); + }; + } + }, { + key: "send", + value: function send() { + var _this = this; + var body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + return new Promise(function (resolve, reject) { + _this._xhr.onload = function () { + resolve(new Response(_this._xhr)); + }; + _this._xhr.onerror = function (err) { + reject(err); + }; + _this._xhr.send(body); + }); + } + }, { + key: "abort", + value: function abort() { + this._xhr.abort(); + return Promise.resolve(); + } + }, { + key: "getUnderlyingObject", + value: function getUnderlyingObject() { + return this._xhr; + } + }]); + return Request; +}(); +var Response = /*#__PURE__*/function () { + function Response(xhr) { + _classCallCheck(this, Response); + this._xhr = xhr; + } + _createClass(Response, [{ + key: "getStatus", + value: function getStatus() { + return this._xhr.status; + } + }, { + key: "getHeader", + value: function getHeader(header) { + return this._xhr.getResponseHeader(header); + } + }, { + key: "getBody", + value: function getBody() { + return this._xhr.responseText; + } + }, { + key: "getUnderlyingObject", + value: function getUnderlyingObject() { + return this._xhr; + } + }]); + return Response; +}(); + +},{}],4:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "DefaultHttpStack", { + enumerable: true, + get: function get() { + return _httpStack["default"]; + } +}); +Object.defineProperty(exports, "DetailedError", { + enumerable: true, + get: function get() { + return _error["default"]; + } +}); +exports.Upload = void 0; +Object.defineProperty(exports, "canStoreURLs", { + enumerable: true, + get: function get() { + return _urlStorage.canStoreURLs; + } +}); +exports.defaultOptions = void 0; +Object.defineProperty(exports, "enableDebugLog", { + enumerable: true, + get: function get() { + return _logger.enableDebugLog; + } +}); +exports.isSupported = void 0; +var _upload = _interopRequireDefault(require("../upload.js")); +var _noopUrlStorage = _interopRequireDefault(require("../noopUrlStorage.js")); +var _logger = require("../logger.js"); +var _error = _interopRequireDefault(require("../error.js")); +var _urlStorage = require("./urlStorage.js"); +var _httpStack = _interopRequireDefault(require("./httpStack.js")); +var _fileReader = _interopRequireDefault(require("./fileReader.js")); +var _fileSignature = _interopRequireDefault(require("./fileSignature.js")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var defaultOptions = exports.defaultOptions = _objectSpread(_objectSpread({}, _upload["default"].defaultOptions), {}, { + httpStack: new _httpStack["default"](), + fileReader: new _fileReader["default"](), + urlStorage: _urlStorage.canStoreURLs ? new _urlStorage.WebStorageUrlStorage() : new _noopUrlStorage["default"](), + fingerprint: _fileSignature["default"] +}); +var Upload = exports.Upload = /*#__PURE__*/function (_BaseUpload) { + _inherits(Upload, _BaseUpload); + var _super = _createSuper(Upload); + function Upload() { + var file = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _classCallCheck(this, Upload); + options = _objectSpread(_objectSpread({}, defaultOptions), options); + return _super.call(this, file, options); + } + _createClass(Upload, null, [{ + key: "terminate", + value: function terminate(url) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + options = _objectSpread(_objectSpread({}, defaultOptions), options); + return _upload["default"].terminate(url, options); + } + }]); + return Upload; +}(_upload["default"]); // Note: We don't reference `window` here because these classes also exist in a Web Worker's context. +var isSupported = exports.isSupported = typeof XMLHttpRequest === 'function' && typeof Blob === 'function' && typeof Blob.prototype.slice === 'function'; + +},{"../error.js":12,"../logger.js":13,"../noopUrlStorage.js":14,"../upload.js":15,"./fileReader.js":1,"./fileSignature.js":2,"./httpStack.js":3,"./urlStorage.js":11}],5:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var isReactNative = function isReactNative() { + return typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative'; +}; +var _default = exports["default"] = isReactNative; + +},{}],6:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _isCordova = _interopRequireDefault(require("./isCordova.js")); +var _readAsByteArray = _interopRequireDefault(require("./readAsByteArray.js")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var FileSource = exports["default"] = /*#__PURE__*/function () { + // Make this.size a method + function FileSource(file) { + _classCallCheck(this, FileSource); + this._file = file; + this.size = file.size; + } + _createClass(FileSource, [{ + key: "slice", + value: function slice(start, end) { + // In Apache Cordova applications, a File must be resolved using + // FileReader instances, see + // https://cordova.apache.org/docs/en/8.x/reference/cordova-plugin-file/index.html#read-a-file + if ((0, _isCordova["default"])()) { + return (0, _readAsByteArray["default"])(this._file.slice(start, end)); + } + var value = this._file.slice(start, end); + var done = end >= this.size; + return Promise.resolve({ + value: value, + done: done + }); + } + }, { + key: "close", + value: function close() { + // Nothing to do here since we don't need to release any resources. + } + }]); + return FileSource; +}(); + +},{"./isCordova.js":8,"./readAsByteArray.js":9}],7:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function len(blobOrArray) { + if (blobOrArray === undefined) return 0; + if (blobOrArray.size !== undefined) return blobOrArray.size; + return blobOrArray.length; +} + +/* + Typed arrays and blobs don't have a concat method. + This function helps StreamSource accumulate data to reach chunkSize. +*/ +function concat(a, b) { + if (a.concat) { + // Is `a` an Array? + return a.concat(b); + } + if (a instanceof Blob) { + return new Blob([a, b], { + type: a.type + }); + } + if (a.set) { + // Is `a` a typed array? + var c = new a.constructor(a.length + b.length); + c.set(a); + c.set(b, a.length); + return c; + } + throw new Error('Unknown data type'); +} +var StreamSource = exports["default"] = /*#__PURE__*/function () { + function StreamSource(reader) { + _classCallCheck(this, StreamSource); + this._buffer = undefined; + this._bufferOffset = 0; + this._reader = reader; + this._done = false; + } + _createClass(StreamSource, [{ + key: "slice", + value: function slice(start, end) { + if (start < this._bufferOffset) { + return Promise.reject(new Error("Requested data is before the reader's current offset")); + } + return this._readUntilEnoughDataOrDone(start, end); + } + }, { + key: "_readUntilEnoughDataOrDone", + value: function _readUntilEnoughDataOrDone(start, end) { + var _this = this; + var hasEnoughData = end <= this._bufferOffset + len(this._buffer); + if (this._done || hasEnoughData) { + var value = this._getDataFromBuffer(start, end); + var done = value == null ? this._done : false; + return Promise.resolve({ + value: value, + done: done + }); + } + return this._reader.read().then(function (_ref) { + var value = _ref.value, + done = _ref.done; + if (done) { + _this._done = true; + } else if (_this._buffer === undefined) { + _this._buffer = value; + } else { + _this._buffer = concat(_this._buffer, value); + } + return _this._readUntilEnoughDataOrDone(start, end); + }); + } + }, { + key: "_getDataFromBuffer", + value: function _getDataFromBuffer(start, end) { + // Remove data from buffer before `start`. + // Data might be reread from the buffer if an upload fails, so we can only + // safely delete data when it comes *before* what is currently being read. + if (start > this._bufferOffset) { + this._buffer = this._buffer.slice(start - this._bufferOffset); + this._bufferOffset = start; + } + // If the buffer is empty after removing old data, all data has been read. + var hasAllDataBeenRead = len(this._buffer) === 0; + if (this._done && hasAllDataBeenRead) { + return null; + } + // We already removed data before `start`, so we just return the first + // chunk from the buffer. + return this._buffer.slice(0, end - start); + } + }, { + key: "close", + value: function close() { + if (this._reader.cancel) { + this._reader.cancel(); + } + } + }]); + return StreamSource; +}(); + +},{}],8:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var isCordova = function isCordova() { + return typeof window !== 'undefined' && (typeof window.PhoneGap !== 'undefined' || typeof window.Cordova !== 'undefined' || typeof window.cordova !== 'undefined'); +}; +var _default = exports["default"] = isCordova; + +},{}],9:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = readAsByteArray; +/** + * readAsByteArray converts a File object to a Uint8Array. + * This function is only used on the Apache Cordova platform. + * See https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html#read-a-file + */ +function readAsByteArray(chunk) { + return new Promise(function (resolve, reject) { + var reader = new FileReader(); + reader.onload = function () { + var value = new Uint8Array(reader.result); + resolve({ + value: value + }); + }; + reader.onerror = function (err) { + reject(err); + }; + reader.readAsArrayBuffer(chunk); + }); +} + +},{}],10:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = uriToBlob; +/** + * uriToBlob resolves a URI to a Blob object. This is used for + * React Native to retrieve a file (identified by a file:// + * URI) as a blob. + */ +function uriToBlob(uri) { + return new Promise(function (resolve, reject) { + var xhr = new XMLHttpRequest(); + xhr.responseType = 'blob'; + xhr.onload = function () { + var blob = xhr.response; + resolve(blob); + }; + xhr.onerror = function (err) { + reject(err); + }; + xhr.open('GET', uri); + xhr.send(); + }); +} + +},{}],11:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.canStoreURLs = exports.WebStorageUrlStorage = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var hasStorage = false; +try { + // Note: localStorage does not exist in the Web Worker's context, so we must use window here. + hasStorage = 'localStorage' in window; + + // Attempt to store and read entries from the local storage to detect Private + // Mode on Safari on iOS (see #49) + // If the key was not used before, we remove it from local storage again to + // not cause confusion where the entry came from. + var key = 'tusSupport'; + var originalValue = localStorage.getItem(key); + localStorage.setItem(key, originalValue); + if (originalValue === null) localStorage.removeItem(key); +} catch (e) { + // If we try to access localStorage inside a sandboxed iframe, a SecurityError + // is thrown. When in private mode on iOS Safari, a QuotaExceededError is + // thrown (see #49) + if (e.code === e.SECURITY_ERR || e.code === e.QUOTA_EXCEEDED_ERR) { + hasStorage = false; + } else { + throw e; + } +} +var canStoreURLs = exports.canStoreURLs = hasStorage; +var WebStorageUrlStorage = exports.WebStorageUrlStorage = /*#__PURE__*/function () { + function WebStorageUrlStorage() { + _classCallCheck(this, WebStorageUrlStorage); + } + _createClass(WebStorageUrlStorage, [{ + key: "findAllUploads", + value: function findAllUploads() { + var results = this._findEntries('tus::'); + return Promise.resolve(results); + } + }, { + key: "findUploadsByFingerprint", + value: function findUploadsByFingerprint(fingerprint) { + var results = this._findEntries("tus::".concat(fingerprint, "::")); + return Promise.resolve(results); + } + }, { + key: "removeUpload", + value: function removeUpload(urlStorageKey) { + localStorage.removeItem(urlStorageKey); + return Promise.resolve(); + } + }, { + key: "addUpload", + value: function addUpload(fingerprint, upload) { + var id = Math.round(Math.random() * 1e12); + var key = "tus::".concat(fingerprint, "::").concat(id); + localStorage.setItem(key, JSON.stringify(upload)); + return Promise.resolve(key); + } + }, { + key: "_findEntries", + value: function _findEntries(prefix) { + var results = []; + for (var i = 0; i < localStorage.length; i++) { + var _key = localStorage.key(i); + if (_key.indexOf(prefix) !== 0) continue; + try { + var upload = JSON.parse(localStorage.getItem(_key)); + upload.urlStorageKey = _key; + results.push(upload); + } catch (e) { + // The JSON parse error is intentionally ignored here, so a malformed + // entry in the storage cannot prevent an upload. + } + } + return results; + } + }]); + return WebStorageUrlStorage; +}(); + +},{}],12:[function(require,module,exports){ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +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, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); } +function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } +function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } +function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } +function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct.bind(); } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } +function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } +function _isNativeFunction(fn) { try { return Function.toString.call(fn).indexOf("[native code]") !== -1; } catch (e) { return typeof fn === "function"; } } +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } +var DetailedError = /*#__PURE__*/function (_Error) { + _inherits(DetailedError, _Error); + var _super = _createSuper(DetailedError); + function DetailedError(message) { + var _this; + var causingErr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + var req = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + var res = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + _classCallCheck(this, DetailedError); + _this = _super.call(this, message); + _this.originalRequest = req; + _this.originalResponse = res; + _this.causingError = causingErr; + if (causingErr != null) { + message += ", caused by ".concat(causingErr.toString()); + } + if (req != null) { + var requestId = req.getHeader('X-Request-ID') || 'n/a'; + var method = req.getMethod(); + var url = req.getURL(); + var status = res ? res.getStatus() : 'n/a'; + var body = res ? res.getBody() || '' : 'n/a'; + message += ", originated from request (method: ".concat(method, ", url: ").concat(url, ", response code: ").concat(status, ", response text: ").concat(body, ", request id: ").concat(requestId, ")"); + } + _this.message = message; + return _this; + } + return _createClass(DetailedError); +}( /*#__PURE__*/_wrapNativeSuper(Error)); +var _default = exports["default"] = DetailedError; + +},{}],13:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.enableDebugLog = enableDebugLog; +exports.log = log; +/* eslint no-console: "off" */ + +var isEnabled = false; +function enableDebugLog() { + isEnabled = true; +} +function log(msg) { + if (!isEnabled) return; + console.log(msg); +} + +},{}],14:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +/* eslint no-unused-vars: "off" */ +var NoopUrlStorage = exports["default"] = /*#__PURE__*/function () { + function NoopUrlStorage() { + _classCallCheck(this, NoopUrlStorage); + } + _createClass(NoopUrlStorage, [{ + key: "listAllUploads", + value: function listAllUploads() { + return Promise.resolve([]); + } + }, { + key: "findUploadsByFingerprint", + value: function findUploadsByFingerprint(fingerprint) { + return Promise.resolve([]); + } + }, { + key: "removeUpload", + value: function removeUpload(urlStorageKey) { + return Promise.resolve(); + } + }, { + key: "addUpload", + value: function addUpload(fingerprint, upload) { + return Promise.resolve(null); + } + }]); + return NoopUrlStorage; +}(); + +},{}],15:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _jsBase = require("js-base64"); +var _urlParse = _interopRequireDefault(require("url-parse")); +var _error = _interopRequireDefault(require("./error.js")); +var _logger = require("./logger.js"); +var _uuid = _interopRequireDefault(require("./uuid.js")); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } +function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } +function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } +function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } +function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } +function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var defaultOptions = { + endpoint: null, + uploadUrl: null, + metadata: {}, + fingerprint: null, + uploadSize: null, + onProgress: null, + onChunkComplete: null, + onSuccess: null, + onError: null, + onUploadUrlAvailable: null, + overridePatchMethod: false, + headers: {}, + addRequestId: false, + onBeforeRequest: null, + onAfterResponse: null, + onShouldRetry: defaultOnShouldRetry, + chunkSize: Infinity, + retryDelays: [0, 1000, 3000, 5000], + parallelUploads: 1, + parallelUploadBoundaries: null, + storeFingerprintForResuming: true, + removeFingerprintOnSuccess: false, + uploadLengthDeferred: false, + uploadDataDuringCreation: false, + urlStorage: null, + fileReader: null, + httpStack: null +}; +var BaseUpload = /*#__PURE__*/function () { + function BaseUpload(file, options) { + _classCallCheck(this, BaseUpload); + // Warn about removed options from previous versions + if ('resume' in options) { + // eslint-disable-next-line no-console + console.log('tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead.'); + } + + // The default options will already be added from the wrapper classes. + this.options = options; + + // Cast chunkSize to integer + this.options.chunkSize = Number(this.options.chunkSize); + + // The storage module used to store URLs + this._urlStorage = this.options.urlStorage; + + // The underlying File/Blob object + this.file = file; + + // The URL against which the file will be uploaded + this.url = null; + + // The underlying request object for the current PATCH request + this._req = null; + + // The fingerpinrt for the current file (set after start()) + this._fingerprint = null; + + // The key that the URL storage returned when saving an URL with a fingerprint, + this._urlStorageKey = null; + + // The offset used in the current PATCH request + this._offset = null; + + // True if the current PATCH request has been aborted + this._aborted = false; + + // The file's size in bytes + this._size = null; + + // The Source object which will wrap around the given file and provides us + // with a unified interface for getting its size and slice chunks from its + // content allowing us to easily handle Files, Blobs, Buffers and Streams. + this._source = null; + + // The current count of attempts which have been made. Zero indicates none. + this._retryAttempt = 0; + + // The timeout's ID which is used to delay the next retry + this._retryTimeout = null; + + // The offset of the remote upload before the latest attempt was started. + this._offsetBeforeRetry = 0; + + // An array of BaseUpload instances which are used for uploading the different + // parts, if the parallelUploads option is used. + this._parallelUploads = null; + + // An array of upload URLs which are used for uploading the different + // parts, if the parallelUploads option is used. + this._parallelUploadUrls = null; + } + + /** + * Use the Termination extension to delete an upload from the server by sending a DELETE + * request to the specified upload URL. This is only possible if the server supports the + * Termination extension. If the `options.retryDelays` property is set, the method will + * also retry if an error ocurrs. + * + * @param {String} url The upload's URL which will be terminated. + * @param {object} options Optional options for influencing HTTP requests. + * @return {Promise} The Promise will be resolved/rejected when the requests finish. + */ + _createClass(BaseUpload, [{ + key: "findPreviousUploads", + value: function findPreviousUploads() { + var _this = this; + return this.options.fingerprint(this.file, this.options).then(function (fingerprint) { + return _this._urlStorage.findUploadsByFingerprint(fingerprint); + }); + } + }, { + key: "resumeFromPreviousUpload", + value: function resumeFromPreviousUpload(previousUpload) { + this.url = previousUpload.uploadUrl || null; + this._parallelUploadUrls = previousUpload.parallelUploadUrls || null; + this._urlStorageKey = previousUpload.urlStorageKey; + } + }, { + key: "start", + value: function start() { + var _this2 = this; + var file = this.file; + if (!file) { + this._emitError(new Error('tus: no file or stream to upload provided')); + return; + } + if (!this.options.endpoint && !this.options.uploadUrl && !this.url) { + this._emitError(new Error('tus: neither an endpoint or an upload URL is provided')); + return; + } + var retryDelays = this.options.retryDelays; + if (retryDelays != null && Object.prototype.toString.call(retryDelays) !== '[object Array]') { + this._emitError(new Error('tus: the `retryDelays` option must either be an array or null')); + return; + } + if (this.options.parallelUploads > 1) { + // Test which options are incompatible with parallel uploads. + for (var _i = 0, _arr = ['uploadUrl', 'uploadSize', 'uploadLengthDeferred']; _i < _arr.length; _i++) { + var optionName = _arr[_i]; + if (this.options[optionName]) { + this._emitError(new Error("tus: cannot use the ".concat(optionName, " option when parallelUploads is enabled"))); + return; + } + } + } + if (this.options.parallelUploadBoundaries) { + if (this.options.parallelUploads <= 1) { + this._emitError(new Error('tus: cannot use the `parallelUploadBoundaries` option when `parallelUploads` is disabled')); + return; + } + if (this.options.parallelUploads !== this.options.parallelUploadBoundaries.length) { + this._emitError(new Error('tus: the `parallelUploadBoundaries` must have the same length as the value of `parallelUploads`')); + return; + } + } + this.options.fingerprint(file, this.options).then(function (fingerprint) { + if (fingerprint == null) { + (0, _logger.log)('No fingerprint was calculated meaning that the upload cannot be stored in the URL storage.'); + } else { + (0, _logger.log)("Calculated fingerprint: ".concat(fingerprint)); + } + _this2._fingerprint = fingerprint; + if (_this2._source) { + return _this2._source; + } + return _this2.options.fileReader.openFile(file, _this2.options.chunkSize); + }).then(function (source) { + _this2._source = source; + + // First, we look at the uploadLengthDeferred option. + // Next, we check if the caller has supplied a manual upload size. + // Finally, we try to use the calculated size from the source object. + if (_this2.options.uploadLengthDeferred) { + _this2._size = null; + } else if (_this2.options.uploadSize != null) { + _this2._size = Number(_this2.options.uploadSize); + if (Number.isNaN(_this2._size)) { + _this2._emitError(new Error('tus: cannot convert `uploadSize` option into a number')); + return; + } + } else { + _this2._size = _this2._source.size; + if (_this2._size == null) { + _this2._emitError(new Error("tus: cannot automatically derive upload's size from input. Specify it manually using the `uploadSize` option or use the `uploadLengthDeferred` option")); + return; + } + } + + // If the upload was configured to use multiple requests or if we resume from + // an upload which used multiple requests, we start a parallel upload. + if (_this2.options.parallelUploads > 1 || _this2._parallelUploadUrls != null) { + _this2._startParallelUpload(); + } else { + _this2._startSingleUpload(); + } + })["catch"](function (err) { + _this2._emitError(err); + }); + } + + /** + * Initiate the uploading procedure for a parallelized upload, where one file is split into + * multiple request which are run in parallel. + * + * @api private + */ + }, { + key: "_startParallelUpload", + value: function _startParallelUpload() { + var _this$options$paralle, + _this3 = this; + var totalSize = this._size; + var totalProgress = 0; + this._parallelUploads = []; + var partCount = this._parallelUploadUrls != null ? this._parallelUploadUrls.length : this.options.parallelUploads; + + // The input file will be split into multiple slices which are uploaded in separate + // requests. Here we get the start and end position for the slices. + var parts = (_this$options$paralle = this.options.parallelUploadBoundaries) !== null && _this$options$paralle !== void 0 ? _this$options$paralle : splitSizeIntoParts(this._source.size, partCount); + + // Attach URLs from previous uploads, if available. + if (this._parallelUploadUrls) { + parts.forEach(function (part, index) { + part.uploadUrl = _this3._parallelUploadUrls[index] || null; + }); + } + + // Create an empty list for storing the upload URLs + this._parallelUploadUrls = new Array(parts.length); + + // Generate a promise for each slice that will be resolve if the respective + // upload is completed. + var uploads = parts.map(function (part, index) { + var lastPartProgress = 0; + return _this3._source.slice(part.start, part.end).then(function (_ref) { + var value = _ref.value; + return new Promise(function (resolve, reject) { + // Merge with the user supplied options but overwrite some values. + var options = _objectSpread(_objectSpread({}, _this3.options), {}, { + // If available, the partial upload should be resumed from a previous URL. + uploadUrl: part.uploadUrl || null, + // We take manually care of resuming for partial uploads, so they should + // not be stored in the URL storage. + storeFingerprintForResuming: false, + removeFingerprintOnSuccess: false, + // Reset the parallelUploads option to not cause recursion. + parallelUploads: 1, + // Reset this option as we are not doing a parallel upload. + parallelUploadBoundaries: null, + metadata: {}, + // Add the header to indicate the this is a partial upload. + headers: _objectSpread(_objectSpread({}, _this3.options.headers), {}, { + 'Upload-Concat': 'partial' + }), + // Reject or resolve the promise if the upload errors or completes. + onSuccess: resolve, + onError: reject, + // Based in the progress for this partial upload, calculate the progress + // for the entire final upload. + onProgress: function onProgress(newPartProgress) { + totalProgress = totalProgress - lastPartProgress + newPartProgress; + lastPartProgress = newPartProgress; + _this3._emitProgress(totalProgress, totalSize); + }, + // Wait until every partial upload has an upload URL, so we can add + // them to the URL storage. + onUploadUrlAvailable: function onUploadUrlAvailable() { + _this3._parallelUploadUrls[index] = upload.url; + // Test if all uploads have received an URL + if (_this3._parallelUploadUrls.filter(function (u) { + return Boolean(u); + }).length === parts.length) { + _this3._saveUploadInUrlStorage(); + } + } + }); + var upload = new BaseUpload(value, options); + upload.start(); + + // Store the upload in an array, so we can later abort them if necessary. + _this3._parallelUploads.push(upload); + }); + }); + }); + var req; + // Wait until all partial uploads are finished and we can send the POST request for + // creating the final upload. + Promise.all(uploads).then(function () { + req = _this3._openRequest('POST', _this3.options.endpoint); + req.setHeader('Upload-Concat', "final;".concat(_this3._parallelUploadUrls.join(' '))); + + // Add metadata if values have been added + var metadata = encodeMetadata(_this3.options.metadata); + if (metadata !== '') { + req.setHeader('Upload-Metadata', metadata); + } + return _this3._sendRequest(req, null); + }).then(function (res) { + if (!inStatusCategory(res.getStatus(), 200)) { + _this3._emitHttpError(req, res, 'tus: unexpected response while creating upload'); + return; + } + var location = res.getHeader('Location'); + if (location == null) { + _this3._emitHttpError(req, res, 'tus: invalid or missing Location header'); + return; + } + _this3.url = resolveUrl(_this3.options.endpoint, location); + (0, _logger.log)("Created upload at ".concat(_this3.url)); + _this3._emitSuccess(); + })["catch"](function (err) { + _this3._emitError(err); + }); + } + + /** + * Initiate the uploading procedure for a non-parallel upload. Here the entire file is + * uploaded in a sequential matter. + * + * @api private + */ + }, { + key: "_startSingleUpload", + value: function _startSingleUpload() { + // Reset the aborted flag when the upload is started or else the + // _performUpload will stop before sending a request if the upload has been + // aborted previously. + this._aborted = false; + + // The upload had been started previously and we should reuse this URL. + if (this.url != null) { + (0, _logger.log)("Resuming upload from previous URL: ".concat(this.url)); + this._resumeUpload(); + return; + } + + // A URL has manually been specified, so we try to resume + if (this.options.uploadUrl != null) { + (0, _logger.log)("Resuming upload from provided URL: ".concat(this.options.uploadUrl)); + this.url = this.options.uploadUrl; + this._resumeUpload(); + return; + } + + // An upload has not started for the file yet, so we start a new one + (0, _logger.log)('Creating a new upload'); + this._createUpload(); + } + + /** + * Abort any running request and stop the current upload. After abort is called, no event + * handler will be invoked anymore. You can use the `start` method to resume the upload + * again. + * If `shouldTerminate` is true, the `terminate` function will be called to remove the + * current upload from the server. + * + * @param {boolean} shouldTerminate True if the upload should be deleted from the server. + * @return {Promise} The Promise will be resolved/rejected when the requests finish. + */ + }, { + key: "abort", + value: function abort(shouldTerminate) { + var _this4 = this; + // Stop any parallel partial uploads, that have been started in _startParallelUploads. + if (this._parallelUploads != null) { + this._parallelUploads.forEach(function (upload) { + upload.abort(shouldTerminate); + }); + } + + // Stop any current running request. + if (this._req !== null) { + this._req.abort(); + // Note: We do not close the file source here, so the user can resume in the future. + } + this._aborted = true; + + // Stop any timeout used for initiating a retry. + if (this._retryTimeout != null) { + clearTimeout(this._retryTimeout); + this._retryTimeout = null; + } + if (!shouldTerminate || this.url == null) { + return Promise.resolve(); + } + return BaseUpload.terminate(this.url, this.options) + // Remove entry from the URL storage since the upload URL is no longer valid. + .then(function () { + return _this4._removeFromUrlStorage(); + }); + } + }, { + key: "_emitHttpError", + value: function _emitHttpError(req, res, message, causingErr) { + this._emitError(new _error["default"](message, causingErr, req, res)); + } + }, { + key: "_emitError", + value: function _emitError(err) { + var _this5 = this; + // Do not emit errors, e.g. from aborted HTTP requests, if the upload has been stopped. + if (this._aborted) return; + + // Check if we should retry, when enabled, before sending the error to the user. + if (this.options.retryDelays != null) { + // We will reset the attempt counter if + // - we were already able to connect to the server (offset != null) and + // - we were able to upload a small chunk of data to the server + var shouldResetDelays = this._offset != null && this._offset > this._offsetBeforeRetry; + if (shouldResetDelays) { + this._retryAttempt = 0; + } + if (shouldRetry(err, this._retryAttempt, this.options)) { + var delay = this.options.retryDelays[this._retryAttempt++]; + this._offsetBeforeRetry = this._offset; + this._retryTimeout = setTimeout(function () { + _this5.start(); + }, delay); + return; + } + } + if (typeof this.options.onError === 'function') { + this.options.onError(err); + } else { + throw err; + } + } + + /** + * Publishes notification if the upload has been successfully completed. + * + * @api private + */ + }, { + key: "_emitSuccess", + value: function _emitSuccess() { + if (this.options.removeFingerprintOnSuccess) { + // Remove stored fingerprint and corresponding endpoint. This causes + // new uploads of the same file to be treated as a different file. + this._removeFromUrlStorage(); + } + if (typeof this.options.onSuccess === 'function') { + this.options.onSuccess(); + } + } + + /** + * Publishes notification when data has been sent to the server. This + * data may not have been accepted by the server yet. + * + * @param {number} bytesSent Number of bytes sent to the server. + * @param {number} bytesTotal Total number of bytes to be sent to the server. + * @api private + */ + }, { + key: "_emitProgress", + value: function _emitProgress(bytesSent, bytesTotal) { + if (typeof this.options.onProgress === 'function') { + this.options.onProgress(bytesSent, bytesTotal); + } + } + + /** + * Publishes notification when a chunk of data has been sent to the server + * and accepted by the server. + * @param {number} chunkSize Size of the chunk that was accepted by the server. + * @param {number} bytesAccepted Total number of bytes that have been + * accepted by the server. + * @param {number} bytesTotal Total number of bytes to be sent to the server. + * @api private + */ + }, { + key: "_emitChunkComplete", + value: function _emitChunkComplete(chunkSize, bytesAccepted, bytesTotal) { + if (typeof this.options.onChunkComplete === 'function') { + this.options.onChunkComplete(chunkSize, bytesAccepted, bytesTotal); + } + } + + /** + * Create a new upload using the creation extension by sending a POST + * request to the endpoint. After successful creation the file will be + * uploaded + * + * @api private + */ + }, { + key: "_createUpload", + value: function _createUpload() { + var _this6 = this; + if (!this.options.endpoint) { + this._emitError(new Error('tus: unable to create upload because no endpoint is provided')); + return; + } + var req = this._openRequest('POST', this.options.endpoint); + if (this.options.uploadLengthDeferred) { + req.setHeader('Upload-Defer-Length', 1); + } else { + req.setHeader('Upload-Length', this._size); + } + + // Add metadata if values have been added + var metadata = encodeMetadata(this.options.metadata); + if (metadata !== '') { + req.setHeader('Upload-Metadata', metadata); + } + var promise; + if (this.options.uploadDataDuringCreation && !this.options.uploadLengthDeferred) { + this._offset = 0; + promise = this._addChunkToRequest(req); + } else { + promise = this._sendRequest(req, null); + } + promise.then(function (res) { + if (!inStatusCategory(res.getStatus(), 200)) { + _this6._emitHttpError(req, res, 'tus: unexpected response while creating upload'); + return; + } + var location = res.getHeader('Location'); + if (location == null) { + _this6._emitHttpError(req, res, 'tus: invalid or missing Location header'); + return; + } + _this6.url = resolveUrl(_this6.options.endpoint, location); + (0, _logger.log)("Created upload at ".concat(_this6.url)); + if (typeof _this6.options.onUploadUrlAvailable === 'function') { + _this6.options.onUploadUrlAvailable(); + } + if (_this6._size === 0) { + // Nothing to upload and file was successfully created + _this6._emitSuccess(); + _this6._source.close(); + return; + } + _this6._saveUploadInUrlStorage().then(function () { + if (_this6.options.uploadDataDuringCreation) { + _this6._handleUploadResponse(req, res); + } else { + _this6._offset = 0; + _this6._performUpload(); + } + }); + })["catch"](function (err) { + _this6._emitHttpError(req, null, 'tus: failed to create upload', err); + }); + } + + /* + * Try to resume an existing upload. First a HEAD request will be sent + * to retrieve the offset. If the request fails a new upload will be + * created. In the case of a successful response the file will be uploaded. + * + * @api private + */ + }, { + key: "_resumeUpload", + value: function _resumeUpload() { + var _this7 = this; + var req = this._openRequest('HEAD', this.url); + var promise = this._sendRequest(req, null); + promise.then(function (res) { + var status = res.getStatus(); + if (!inStatusCategory(status, 200)) { + // If the upload is locked (indicated by the 423 Locked status code), we + // emit an error instead of directly starting a new upload. This way the + // retry logic can catch the error and will retry the upload. An upload + // is usually locked for a short period of time and will be available + // afterwards. + if (status === 423) { + _this7._emitHttpError(req, res, 'tus: upload is currently locked; retry later'); + return; + } + if (inStatusCategory(status, 400)) { + // Remove stored fingerprint and corresponding endpoint, + // on client errors since the file can not be found + _this7._removeFromUrlStorage(); + } + if (!_this7.options.endpoint) { + // Don't attempt to create a new upload if no endpoint is provided. + _this7._emitHttpError(req, res, 'tus: unable to resume upload (new upload cannot be created without an endpoint)'); + return; + } + + // Try to create a new upload + _this7.url = null; + _this7._createUpload(); + return; + } + var offset = parseInt(res.getHeader('Upload-Offset'), 10); + if (Number.isNaN(offset)) { + _this7._emitHttpError(req, res, 'tus: invalid or missing offset value'); + return; + } + var length = parseInt(res.getHeader('Upload-Length'), 10); + if (Number.isNaN(length) && !_this7.options.uploadLengthDeferred) { + _this7._emitHttpError(req, res, 'tus: invalid or missing length value'); + return; + } + if (typeof _this7.options.onUploadUrlAvailable === 'function') { + _this7.options.onUploadUrlAvailable(); + } + _this7._saveUploadInUrlStorage().then(function () { + // Upload has already been completed and we do not need to send additional + // data to the server + if (offset === length) { + _this7._emitProgress(length, length); + _this7._emitSuccess(); + return; + } + _this7._offset = offset; + _this7._performUpload(); + }); + })["catch"](function (err) { + _this7._emitHttpError(req, null, 'tus: failed to resume upload', err); + }); + } + + /** + * Start uploading the file using PATCH requests. The file will be divided + * into chunks as specified in the chunkSize option. During the upload + * the onProgress event handler may be invoked multiple times. + * + * @api private + */ + }, { + key: "_performUpload", + value: function _performUpload() { + var _this8 = this; + // If the upload has been aborted, we will not send the next PATCH request. + // This is important if the abort method was called during a callback, such + // as onChunkComplete or onProgress. + if (this._aborted) { + return; + } + var req; + + // Some browser and servers may not support the PATCH method. For those + // cases, you can tell tus-js-client to use a POST request with the + // X-HTTP-Method-Override header for simulating a PATCH request. + if (this.options.overridePatchMethod) { + req = this._openRequest('POST', this.url); + req.setHeader('X-HTTP-Method-Override', 'PATCH'); + } else { + req = this._openRequest('PATCH', this.url); + } + req.setHeader('Upload-Offset', this._offset); + var promise = this._addChunkToRequest(req); + promise.then(function (res) { + if (!inStatusCategory(res.getStatus(), 200)) { + _this8._emitHttpError(req, res, 'tus: unexpected response while uploading chunk'); + return; + } + _this8._handleUploadResponse(req, res); + })["catch"](function (err) { + // Don't emit an error if the upload was aborted manually + if (_this8._aborted) { + return; + } + _this8._emitHttpError(req, null, "tus: failed to upload chunk at offset ".concat(_this8._offset), err); + }); + } + + /** + * _addChunktoRequest reads a chunk from the source and sends it using the + * supplied request object. It will not handle the response. + * + * @api private + */ + }, { + key: "_addChunkToRequest", + value: function _addChunkToRequest(req) { + var _this9 = this; + var start = this._offset; + var end = this._offset + this.options.chunkSize; + req.setProgressHandler(function (bytesSent) { + _this9._emitProgress(start + bytesSent, _this9._size); + }); + req.setHeader('Content-Type', 'application/offset+octet-stream'); + + // The specified chunkSize may be Infinity or the calcluated end position + // may exceed the file's size. In both cases, we limit the end position to + // the input's total size for simpler calculations and correctness. + if ((end === Infinity || end > this._size) && !this.options.uploadLengthDeferred) { + end = this._size; + } + return this._source.slice(start, end).then(function (_ref2) { + var value = _ref2.value, + done = _ref2.done; + var valueSize = value && value.size ? value.size : 0; + + // If the upload length is deferred, the upload size was not specified during + // upload creation. So, if the file reader is done reading, we know the total + // upload size and can tell the tus server. + if (_this9.options.uploadLengthDeferred && done) { + _this9._size = _this9._offset + valueSize; + req.setHeader('Upload-Length', _this9._size); + } + + // The specified uploadSize might not match the actual amount of data that a source + // provides. In these cases, we cannot successfully complete the upload, so we + // rather error out and let the user know. If not, tus-js-client will be stuck + // in a loop of repeating empty PATCH requests. + // See https://community.transloadit.com/t/how-to-abort-hanging-companion-uploads/16488/13 + var newSize = _this9._offset + valueSize; + if (!_this9.options.uploadLengthDeferred && done && newSize !== _this9._size) { + return Promise.reject(new Error("upload was configured with a size of ".concat(_this9._size, " bytes, but the source is done after ").concat(newSize, " bytes"))); + } + if (value === null) { + return _this9._sendRequest(req); + } + _this9._emitProgress(_this9._offset, _this9._size); + return _this9._sendRequest(req, value); + }); + } + + /** + * _handleUploadResponse is used by requests that haven been sent using _addChunkToRequest + * and already have received a response. + * + * @api private + */ + }, { + key: "_handleUploadResponse", + value: function _handleUploadResponse(req, res) { + var offset = parseInt(res.getHeader('Upload-Offset'), 10); + if (Number.isNaN(offset)) { + this._emitHttpError(req, res, 'tus: invalid or missing offset value'); + return; + } + this._emitProgress(offset, this._size); + this._emitChunkComplete(offset - this._offset, offset, this._size); + this._offset = offset; + if (offset === this._size) { + // Yay, finally done :) + this._emitSuccess(); + this._source.close(); + return; + } + this._performUpload(); + } + + /** + * Create a new HTTP request object with the given method and URL. + * + * @api private + */ + }, { + key: "_openRequest", + value: function _openRequest(method, url) { + var req = openRequest(method, url, this.options); + this._req = req; + return req; + } + + /** + * Remove the entry in the URL storage, if it has been saved before. + * + * @api private + */ + }, { + key: "_removeFromUrlStorage", + value: function _removeFromUrlStorage() { + var _this10 = this; + if (!this._urlStorageKey) return; + this._urlStorage.removeUpload(this._urlStorageKey)["catch"](function (err) { + _this10._emitError(err); + }); + this._urlStorageKey = null; + } + + /** + * Add the upload URL to the URL storage, if possible. + * + * @api private + */ + }, { + key: "_saveUploadInUrlStorage", + value: function _saveUploadInUrlStorage() { + var _this11 = this; + // We do not store the upload URL + // - if it was disabled in the option, or + // - if no fingerprint was calculated for the input (i.e. a stream), or + // - if the URL is already stored (i.e. key is set alread). + if (!this.options.storeFingerprintForResuming || !this._fingerprint || this._urlStorageKey !== null) { + return Promise.resolve(); + } + var storedUpload = { + size: this._size, + metadata: this.options.metadata, + creationTime: new Date().toString() + }; + if (this._parallelUploads) { + // Save multiple URLs if the parallelUploads option is used ... + storedUpload.parallelUploadUrls = this._parallelUploadUrls; + } else { + // ... otherwise we just save the one available URL. + storedUpload.uploadUrl = this.url; + } + return this._urlStorage.addUpload(this._fingerprint, storedUpload).then(function (urlStorageKey) { + _this11._urlStorageKey = urlStorageKey; + }); + } + + /** + * Send a request with the provided body. + * + * @api private + */ + }, { + key: "_sendRequest", + value: function _sendRequest(req) { + var body = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + return sendRequest(req, body, this.options); + } + }], [{ + key: "terminate", + value: function terminate(url) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var req = openRequest('DELETE', url, options); + return sendRequest(req, null, options).then(function (res) { + // A 204 response indicates a successfull request + if (res.getStatus() === 204) { + return; + } + throw new _error["default"]('tus: unexpected response while terminating upload', null, req, res); + })["catch"](function (err) { + if (!(err instanceof _error["default"])) { + err = new _error["default"]('tus: failed to terminate upload', err, req, null); + } + if (!shouldRetry(err, 0, options)) { + throw err; + } + + // Instead of keeping track of the retry attempts, we remove the first element from the delays + // array. If the array is empty, all retry attempts are used up and we will bubble up the error. + // We recursively call the terminate function will removing elements from the retryDelays array. + var delay = options.retryDelays[0]; + var remainingDelays = options.retryDelays.slice(1); + var newOptions = _objectSpread(_objectSpread({}, options), {}, { + retryDelays: remainingDelays + }); + return new Promise(function (resolve) { + return setTimeout(resolve, delay); + }).then(function () { + return BaseUpload.terminate(url, newOptions); + }); + }); + } + }]); + return BaseUpload; +}(); +function encodeMetadata(metadata) { + return Object.entries(metadata).map(function (_ref3) { + var _ref4 = _slicedToArray(_ref3, 2), + key = _ref4[0], + value = _ref4[1]; + return "".concat(key, " ").concat(_jsBase.Base64.encode(String(value))); + }).join(','); +} + +/** + * Checks whether a given status is in the range of the expected category. + * For example, only a status between 200 and 299 will satisfy the category 200. + * + * @api private + */ +function inStatusCategory(status, category) { + return status >= category && status < category + 100; +} + +/** + * Create a new HTTP request with the specified method and URL. + * The necessary headers that are included in every request + * will be added, including the request ID. + * + * @api private + */ +function openRequest(method, url, options) { + var req = options.httpStack.createRequest(method, url); + req.setHeader('Tus-Resumable', '1.0.0'); + var headers = options.headers || {}; + Object.entries(headers).forEach(function (_ref5) { + var _ref6 = _slicedToArray(_ref5, 2), + name = _ref6[0], + value = _ref6[1]; + req.setHeader(name, value); + }); + if (options.addRequestId) { + var requestId = (0, _uuid["default"])(); + req.setHeader('X-Request-ID', requestId); + } + return req; +} + +/** + * Send a request with the provided body while invoking the onBeforeRequest + * and onAfterResponse callbacks. + * + * @api private + */ +function sendRequest(_x, _x2, _x3) { + return _sendRequest2.apply(this, arguments); +} +/** + * Checks whether the browser running this code has internet access. + * This function will always return true in the node.js environment + * + * @api private + */ +function _sendRequest2() { + _sendRequest2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(req, body, options) { + var res; + return _regeneratorRuntime().wrap(function _callee$(_context) { + while (1) switch (_context.prev = _context.next) { + case 0: + if (!(typeof options.onBeforeRequest === 'function')) { + _context.next = 3; + break; + } + _context.next = 3; + return options.onBeforeRequest(req); + case 3: + _context.next = 5; + return req.send(body); + case 5: + res = _context.sent; + if (!(typeof options.onAfterResponse === 'function')) { + _context.next = 9; + break; + } + _context.next = 9; + return options.onAfterResponse(req, res); + case 9: + return _context.abrupt("return", res); + case 10: + case "end": + return _context.stop(); + } + }, _callee); + })); + return _sendRequest2.apply(this, arguments); +} +function isOnline() { + var online = true; + // Note: We don't reference `window` here because the navigator object also exists + // in a Web Worker's context. + // eslint-disable-next-line no-undef + if (typeof navigator !== 'undefined' && navigator.onLine === false) { + online = false; + } + return online; +} + +/** + * Checks whether or not it is ok to retry a request. + * @param {Error|DetailedError} err the error returned from the last request + * @param {number} retryAttempt the number of times the request has already been retried + * @param {object} options tus Upload options + * + * @api private + */ +function shouldRetry(err, retryAttempt, options) { + // We only attempt a retry if + // - retryDelays option is set + // - we didn't exceed the maxium number of retries, yet, and + // - this error was caused by a request or it's response and + // - the error is server error (i.e. not a status 4xx except a 409 or 423) or + // a onShouldRetry is specified and returns true + // - the browser does not indicate that we are offline + if (options.retryDelays == null || retryAttempt >= options.retryDelays.length || err.originalRequest == null) { + return false; + } + if (options && typeof options.onShouldRetry === 'function') { + return options.onShouldRetry(err, retryAttempt, options); + } + return defaultOnShouldRetry(err); +} + +/** + * determines if the request should be retried. Will only retry if not a status 4xx except a 409 or 423 + * @param {DetailedError} err + * @returns {boolean} + */ +function defaultOnShouldRetry(err) { + var status = err.originalResponse ? err.originalResponse.getStatus() : 0; + return (!inStatusCategory(status, 400) || status === 409 || status === 423) && isOnline(); +} + +/** + * Resolve a relative link given the origin as source. For example, + * if a HTTP request to http://example.com/files/ returns a Location + * header with the value /upload/abc, the resolved URL will be: + * http://example.com/upload/abc + */ +function resolveUrl(origin, link) { + return new _urlParse["default"](link, origin).toString(); +} + +/** + * Calculate the start and end positions for the parts if an upload + * is split into multiple parallel requests. + * + * @param {number} totalSize The byte size of the upload, which will be split. + * @param {number} partCount The number in how many parts the upload will be split. + * @return {object[]} + * @api private + */ +function splitSizeIntoParts(totalSize, partCount) { + var partSize = Math.floor(totalSize / partCount); + var parts = []; + for (var i = 0; i < partCount; i++) { + parts.push({ + start: partSize * i, + end: partSize * (i + 1) + }); + } + parts[partCount - 1].end = totalSize; + return parts; +} +BaseUpload.defaultOptions = defaultOptions; +var _default = exports["default"] = BaseUpload; + +},{"./error.js":12,"./logger.js":13,"./uuid.js":16,"js-base64":20,"url-parse":23}],16:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = uuid; +/** + * Generate a UUID v4 based on random numbers. We intentioanlly use the less + * secure Math.random function here since the more secure crypto.getRandomNumbers + * is not available on all platforms. + * This is not a problem for us since we use the UUID only for generating a + * request ID, so we can correlate server logs to client errors. + * + * This function is taken from following site: + * https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript + * + * @return {string} The generate UUID + */ +function uuid() { + /* eslint-disable no-bitwise */ + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + var r = Math.random() * 16 | 0; + var v = c === 'x' ? r : r & 0x3 | 0x8; + return v.toString(16); + }); +} + +},{}],17:[function(require,module,exports){ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + +},{}],18:[function(require,module,exports){ +(function (Buffer){(function (){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species != null && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayLike(value) + } + + if (value == null) { + throw TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + buf = Buffer.from(buf) + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +}).call(this)}).call(this,require("buffer").Buffer) + +},{"base64-js":17,"buffer":18,"ieee754":19}],19:[function(require,module,exports){ +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = (nBytes * 8) - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],20:[function(require,module,exports){ +(function (global,Buffer){(function (){ +// +// THIS FILE IS AUTOMATICALLY GENERATED! DO NOT EDIT BY HAND! +// +; +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' + ? module.exports = factory() + : typeof define === 'function' && define.amd + ? define(factory) : + // cf. https://github.com/dankogai/js-base64/issues/119 + (function () { + // existing version for noConflict() + var _Base64 = global.Base64; + var gBase64 = factory(); + gBase64.noConflict = function () { + global.Base64 = _Base64; + return gBase64; + }; + if (global.Meteor) { // Meteor.js + Base64 = gBase64; + } + global.Base64 = gBase64; + })(); +}((typeof self !== 'undefined' ? self + : typeof window !== 'undefined' ? window + : typeof global !== 'undefined' ? global + : this), function () { + 'use strict'; + /** + * base64.ts + * + * Licensed under the BSD 3-Clause License. + * http://opensource.org/licenses/BSD-3-Clause + * + * References: + * http://en.wikipedia.org/wiki/Base64 + * + * @author Dan Kogai (https://github.com/dankogai) + */ + var version = '3.7.5'; + /** + * @deprecated use lowercase `version`. + */ + var VERSION = version; + var _hasatob = typeof atob === 'function'; + var _hasbtoa = typeof btoa === 'function'; + var _hasBuffer = typeof Buffer === 'function'; + var _TD = typeof TextDecoder === 'function' ? new TextDecoder() : undefined; + var _TE = typeof TextEncoder === 'function' ? new TextEncoder() : undefined; + var b64ch = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + var b64chs = Array.prototype.slice.call(b64ch); + var b64tab = (function (a) { + var tab = {}; + a.forEach(function (c, i) { return tab[c] = i; }); + return tab; + })(b64chs); + var b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/; + var _fromCC = String.fromCharCode.bind(String); + var _U8Afrom = typeof Uint8Array.from === 'function' + ? Uint8Array.from.bind(Uint8Array) + : function (it) { return new Uint8Array(Array.prototype.slice.call(it, 0)); }; + var _mkUriSafe = function (src) { return src + .replace(/=/g, '').replace(/[+\/]/g, function (m0) { return m0 == '+' ? '-' : '_'; }); }; + var _tidyB64 = function (s) { return s.replace(/[^A-Za-z0-9\+\/]/g, ''); }; + /** + * polyfill version of `btoa` + */ + var btoaPolyfill = function (bin) { + // console.log('polyfilled'); + var u32, c0, c1, c2, asc = ''; + var pad = bin.length % 3; + for (var i = 0; i < bin.length;) { + if ((c0 = bin.charCodeAt(i++)) > 255 || + (c1 = bin.charCodeAt(i++)) > 255 || + (c2 = bin.charCodeAt(i++)) > 255) + throw new TypeError('invalid character found'); + u32 = (c0 << 16) | (c1 << 8) | c2; + asc += b64chs[u32 >> 18 & 63] + + b64chs[u32 >> 12 & 63] + + b64chs[u32 >> 6 & 63] + + b64chs[u32 & 63]; + } + return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc; + }; + /** + * does what `window.btoa` of web browsers do. + * @param {String} bin binary string + * @returns {string} Base64-encoded string + */ + var _btoa = _hasbtoa ? function (bin) { return btoa(bin); } + : _hasBuffer ? function (bin) { return Buffer.from(bin, 'binary').toString('base64'); } + : btoaPolyfill; + var _fromUint8Array = _hasBuffer + ? function (u8a) { return Buffer.from(u8a).toString('base64'); } + : function (u8a) { + // cf. https://stackoverflow.com/questions/12710001/how-to-convert-uint8-array-to-base64-encoded-string/12713326#12713326 + var maxargs = 0x1000; + var strs = []; + for (var i = 0, l = u8a.length; i < l; i += maxargs) { + strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs))); + } + return _btoa(strs.join('')); + }; + /** + * converts a Uint8Array to a Base64 string. + * @param {boolean} [urlsafe] URL-and-filename-safe a la RFC4648 §5 + * @returns {string} Base64 string + */ + var fromUint8Array = function (u8a, urlsafe) { + if (urlsafe === void 0) { urlsafe = false; } + return urlsafe ? _mkUriSafe(_fromUint8Array(u8a)) : _fromUint8Array(u8a); + }; + // This trick is found broken https://github.com/dankogai/js-base64/issues/130 + // const utob = (src: string) => unescape(encodeURIComponent(src)); + // reverting good old fationed regexp + var cb_utob = function (c) { + if (c.length < 2) { + var cc = c.charCodeAt(0); + return cc < 0x80 ? c + : cc < 0x800 ? (_fromCC(0xc0 | (cc >>> 6)) + + _fromCC(0x80 | (cc & 0x3f))) + : (_fromCC(0xe0 | ((cc >>> 12) & 0x0f)) + + _fromCC(0x80 | ((cc >>> 6) & 0x3f)) + + _fromCC(0x80 | (cc & 0x3f))); + } + else { + var cc = 0x10000 + + (c.charCodeAt(0) - 0xD800) * 0x400 + + (c.charCodeAt(1) - 0xDC00); + return (_fromCC(0xf0 | ((cc >>> 18) & 0x07)) + + _fromCC(0x80 | ((cc >>> 12) & 0x3f)) + + _fromCC(0x80 | ((cc >>> 6) & 0x3f)) + + _fromCC(0x80 | (cc & 0x3f))); + } + }; + var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g; + /** + * @deprecated should have been internal use only. + * @param {string} src UTF-8 string + * @returns {string} UTF-16 string + */ + var utob = function (u) { return u.replace(re_utob, cb_utob); }; + // + var _encode = _hasBuffer + ? function (s) { return Buffer.from(s, 'utf8').toString('base64'); } + : _TE + ? function (s) { return _fromUint8Array(_TE.encode(s)); } + : function (s) { return _btoa(utob(s)); }; + /** + * converts a UTF-8-encoded string to a Base64 string. + * @param {boolean} [urlsafe] if `true` make the result URL-safe + * @returns {string} Base64 string + */ + var encode = function (src, urlsafe) { + if (urlsafe === void 0) { urlsafe = false; } + return urlsafe + ? _mkUriSafe(_encode(src)) + : _encode(src); + }; + /** + * converts a UTF-8-encoded string to URL-safe Base64 RFC4648 §5. + * @returns {string} Base64 string + */ + var encodeURI = function (src) { return encode(src, true); }; + // This trick is found broken https://github.com/dankogai/js-base64/issues/130 + // const btou = (src: string) => decodeURIComponent(escape(src)); + // reverting good old fationed regexp + var re_btou = /[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g; + var cb_btou = function (cccc) { + switch (cccc.length) { + case 4: + var cp = ((0x07 & cccc.charCodeAt(0)) << 18) + | ((0x3f & cccc.charCodeAt(1)) << 12) + | ((0x3f & cccc.charCodeAt(2)) << 6) + | (0x3f & cccc.charCodeAt(3)), offset = cp - 0x10000; + return (_fromCC((offset >>> 10) + 0xD800) + + _fromCC((offset & 0x3FF) + 0xDC00)); + case 3: + return _fromCC(((0x0f & cccc.charCodeAt(0)) << 12) + | ((0x3f & cccc.charCodeAt(1)) << 6) + | (0x3f & cccc.charCodeAt(2))); + default: + return _fromCC(((0x1f & cccc.charCodeAt(0)) << 6) + | (0x3f & cccc.charCodeAt(1))); + } + }; + /** + * @deprecated should have been internal use only. + * @param {string} src UTF-16 string + * @returns {string} UTF-8 string + */ + var btou = function (b) { return b.replace(re_btou, cb_btou); }; + /** + * polyfill version of `atob` + */ + var atobPolyfill = function (asc) { + // console.log('polyfilled'); + asc = asc.replace(/\s+/g, ''); + if (!b64re.test(asc)) + throw new TypeError('malformed base64.'); + asc += '=='.slice(2 - (asc.length & 3)); + var u24, bin = '', r1, r2; + for (var i = 0; i < asc.length;) { + u24 = b64tab[asc.charAt(i++)] << 18 + | b64tab[asc.charAt(i++)] << 12 + | (r1 = b64tab[asc.charAt(i++)]) << 6 + | (r2 = b64tab[asc.charAt(i++)]); + bin += r1 === 64 ? _fromCC(u24 >> 16 & 255) + : r2 === 64 ? _fromCC(u24 >> 16 & 255, u24 >> 8 & 255) + : _fromCC(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255); + } + return bin; + }; + /** + * does what `window.atob` of web browsers do. + * @param {String} asc Base64-encoded string + * @returns {string} binary string + */ + var _atob = _hasatob ? function (asc) { return atob(_tidyB64(asc)); } + : _hasBuffer ? function (asc) { return Buffer.from(asc, 'base64').toString('binary'); } + : atobPolyfill; + // + var _toUint8Array = _hasBuffer + ? function (a) { return _U8Afrom(Buffer.from(a, 'base64')); } + : function (a) { return _U8Afrom(_atob(a).split('').map(function (c) { return c.charCodeAt(0); })); }; + /** + * converts a Base64 string to a Uint8Array. + */ + var toUint8Array = function (a) { return _toUint8Array(_unURI(a)); }; + // + var _decode = _hasBuffer + ? function (a) { return Buffer.from(a, 'base64').toString('utf8'); } + : _TD + ? function (a) { return _TD.decode(_toUint8Array(a)); } + : function (a) { return btou(_atob(a)); }; + var _unURI = function (a) { return _tidyB64(a.replace(/[-_]/g, function (m0) { return m0 == '-' ? '+' : '/'; })); }; + /** + * converts a Base64 string to a UTF-8 string. + * @param {String} src Base64 string. Both normal and URL-safe are supported + * @returns {string} UTF-8 string + */ + var decode = function (src) { return _decode(_unURI(src)); }; + /** + * check if a value is a valid Base64 string + * @param {String} src a value to check + */ + var isValid = function (src) { + if (typeof src !== 'string') + return false; + var s = src.replace(/\s+/g, '').replace(/={0,2}$/, ''); + return !/[^\s0-9a-zA-Z\+/]/.test(s) || !/[^\s0-9a-zA-Z\-_]/.test(s); + }; + // + var _noEnum = function (v) { + return { + value: v, enumerable: false, writable: true, configurable: true + }; + }; + /** + * extend String.prototype with relevant methods + */ + var extendString = function () { + var _add = function (name, body) { return Object.defineProperty(String.prototype, name, _noEnum(body)); }; + _add('fromBase64', function () { return decode(this); }); + _add('toBase64', function (urlsafe) { return encode(this, urlsafe); }); + _add('toBase64URI', function () { return encode(this, true); }); + _add('toBase64URL', function () { return encode(this, true); }); + _add('toUint8Array', function () { return toUint8Array(this); }); + }; + /** + * extend Uint8Array.prototype with relevant methods + */ + var extendUint8Array = function () { + var _add = function (name, body) { return Object.defineProperty(Uint8Array.prototype, name, _noEnum(body)); }; + _add('toBase64', function (urlsafe) { return fromUint8Array(this, urlsafe); }); + _add('toBase64URI', function () { return fromUint8Array(this, true); }); + _add('toBase64URL', function () { return fromUint8Array(this, true); }); + }; + /** + * extend Builtin prototypes with relevant methods + */ + var extendBuiltins = function () { + extendString(); + extendUint8Array(); + }; + var gBase64 = { + version: version, + VERSION: VERSION, + atob: _atob, + atobPolyfill: atobPolyfill, + btoa: _btoa, + btoaPolyfill: btoaPolyfill, + fromBase64: decode, + toBase64: encode, + encode: encode, + encodeURI: encodeURI, + encodeURL: encodeURI, + utob: utob, + btou: btou, + decode: decode, + isValid: isValid, + fromUint8Array: fromUint8Array, + toUint8Array: toUint8Array, + extendString: extendString, + extendUint8Array: extendUint8Array, + extendBuiltins: extendBuiltins + }; + // + // export Base64 to the namespace + // + // ES5 is yet to have Object.assign() that may make transpilers unhappy. + // gBase64.Base64 = Object.assign({}, gBase64); + gBase64.Base64 = {}; + Object.keys(gBase64).forEach(function (k) { return gBase64.Base64[k] = gBase64[k]; }); + return gBase64; +})); + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) + +},{"buffer":18}],21:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , undef; + +/** + * Decode a URI encoded string. + * + * @param {String} input The URI encoded string. + * @returns {String|Null} The decoded string. + * @api private + */ +function decode(input) { + try { + return decodeURIComponent(input.replace(/\+/g, ' ')); + } catch (e) { + return null; + } +} + +/** + * Attempts to encode a given input. + * + * @param {String} input The string that needs to be encoded. + * @returns {String|Null} The encoded string. + * @api private + */ +function encode(input) { + try { + return encodeURIComponent(input); + } catch (e) { + return null; + } +} + +/** + * Simple query string parser. + * + * @param {String} query The query string that needs to be parsed. + * @returns {Object} + * @api public + */ +function querystring(query) { + var parser = /([^=?#&]+)=?([^&]*)/g + , result = {} + , part; + + while (part = parser.exec(query)) { + var key = decode(part[1]) + , value = decode(part[2]); + + // + // Prevent overriding of existing properties. This ensures that build-in + // methods like `toString` or __proto__ are not overriden by malicious + // querystrings. + // + // In the case if failed decoding, we want to omit the key/value pairs + // from the result. + // + if (key === null || value === null || key in result) continue; + result[key] = value; + } + + return result; +} + +/** + * Transform a query string to an object. + * + * @param {Object} obj Object that should be transformed. + * @param {String} prefix Optional prefix. + * @returns {String} + * @api public + */ +function querystringify(obj, prefix) { + prefix = prefix || ''; + + var pairs = [] + , value + , key; + + // + // Optionally prefix with a '?' if needed + // + if ('string' !== typeof prefix) prefix = '?'; + + for (key in obj) { + if (has.call(obj, key)) { + value = obj[key]; + + // + // Edge cases where we actually want to encode the value to an empty + // string instead of the stringified value. + // + if (!value && (value === null || value === undef || isNaN(value))) { + value = ''; + } + + key = encode(key); + value = encode(value); + + // + // If we failed to encode the strings, we should bail out as we don't + // want to add invalid strings to the query. + // + if (key === null || value === null) continue; + pairs.push(key +'='+ value); + } + } + + return pairs.length ? prefix + pairs.join('&') : ''; +} + +// +// Expose the module. +// +exports.stringify = querystringify; +exports.parse = querystring; + +},{}],22:[function(require,module,exports){ +'use strict'; + +/** + * Check if we're required to add a port number. + * + * @see https://url.spec.whatwg.org/#default-port + * @param {Number|String} port Port number we need to check + * @param {String} protocol Protocol we need to check against. + * @returns {Boolean} Is it a default port for the given protocol + * @api private + */ +module.exports = function required(port, protocol) { + protocol = protocol.split(':')[0]; + port = +port; + + if (!port) return false; + + switch (protocol) { + case 'http': + case 'ws': + return port !== 80; + + case 'https': + case 'wss': + return port !== 443; + + case 'ftp': + return port !== 21; + + case 'gopher': + return port !== 70; + + case 'file': + return false; + } + + return port !== 0; +}; + +},{}],23:[function(require,module,exports){ +(function (global){(function (){ +'use strict'; + +var required = require('requires-port') + , qs = require('querystringify') + , controlOrWhitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/ + , CRHTLF = /[\n\r\t]/g + , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\// + , port = /:\d+$/ + , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i + , windowsDriveLetter = /^[a-zA-Z]:/; + +/** + * Remove control characters and whitespace from the beginning of a string. + * + * @param {Object|String} str String to trim. + * @returns {String} A new string representing `str` stripped of control + * characters and whitespace from its beginning. + * @public + */ +function trimLeft(str) { + return (str ? str : '').toString().replace(controlOrWhitespace, ''); +} + +/** + * These are the parse rules for the URL parser, it informs the parser + * about: + * + * 0. The char it Needs to parse, if it's a string it should be done using + * indexOf, RegExp using exec and NaN means set as current value. + * 1. The property we should set when parsing this value. + * 2. Indication if it's backwards or forward parsing, when set as number it's + * the value of extra chars that should be split off. + * 3. Inherit from location if non existing in the parser. + * 4. `toLowerCase` the resulting value. + */ +var rules = [ + ['#', 'hash'], // Extract from the back. + ['?', 'query'], // Extract from the back. + function sanitize(address, url) { // Sanitize what is left of the address + return isSpecial(url.protocol) ? address.replace(/\\/g, '/') : address; + }, + ['/', 'pathname'], // Extract from the back. + ['@', 'auth', 1], // Extract from the front. + [NaN, 'host', undefined, 1, 1], // Set left over value. + [/:(\d*)$/, 'port', undefined, 1], // RegExp the back. + [NaN, 'hostname', undefined, 1, 1] // Set left over. +]; + +/** + * These properties should not be copied or inherited from. This is only needed + * for all non blob URL's as a blob URL does not include a hash, only the + * origin. + * + * @type {Object} + * @private + */ +var ignore = { hash: 1, query: 1 }; + +/** + * The location object differs when your code is loaded through a normal page, + * Worker or through a worker using a blob. And with the blobble begins the + * trouble as the location object will contain the URL of the blob, not the + * location of the page where our code is loaded in. The actual origin is + * encoded in the `pathname` so we can thankfully generate a good "default" + * location from it so we can generate proper relative URL's again. + * + * @param {Object|String} loc Optional default location object. + * @returns {Object} lolcation object. + * @public + */ +function lolcation(loc) { + var globalVar; + + if (typeof window !== 'undefined') globalVar = window; + else if (typeof global !== 'undefined') globalVar = global; + else if (typeof self !== 'undefined') globalVar = self; + else globalVar = {}; + + var location = globalVar.location || {}; + loc = loc || location; + + var finaldestination = {} + , type = typeof loc + , key; + + if ('blob:' === loc.protocol) { + finaldestination = new Url(unescape(loc.pathname), {}); + } else if ('string' === type) { + finaldestination = new Url(loc, {}); + for (key in ignore) delete finaldestination[key]; + } else if ('object' === type) { + for (key in loc) { + if (key in ignore) continue; + finaldestination[key] = loc[key]; + } + + if (finaldestination.slashes === undefined) { + finaldestination.slashes = slashes.test(loc.href); + } + } + + return finaldestination; +} + +/** + * Check whether a protocol scheme is special. + * + * @param {String} The protocol scheme of the URL + * @return {Boolean} `true` if the protocol scheme is special, else `false` + * @private + */ +function isSpecial(scheme) { + return ( + scheme === 'file:' || + scheme === 'ftp:' || + scheme === 'http:' || + scheme === 'https:' || + scheme === 'ws:' || + scheme === 'wss:' + ); +} + +/** + * @typedef ProtocolExtract + * @type Object + * @property {String} protocol Protocol matched in the URL, in lowercase. + * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`. + * @property {String} rest Rest of the URL that is not part of the protocol. + */ + +/** + * Extract protocol information from a URL with/without double slash ("//"). + * + * @param {String} address URL we want to extract from. + * @param {Object} location + * @return {ProtocolExtract} Extracted information. + * @private + */ +function extractProtocol(address, location) { + address = trimLeft(address); + address = address.replace(CRHTLF, ''); + location = location || {}; + + var match = protocolre.exec(address); + var protocol = match[1] ? match[1].toLowerCase() : ''; + var forwardSlashes = !!match[2]; + var otherSlashes = !!match[3]; + var slashesCount = 0; + var rest; + + if (forwardSlashes) { + if (otherSlashes) { + rest = match[2] + match[3] + match[4]; + slashesCount = match[2].length + match[3].length; + } else { + rest = match[2] + match[4]; + slashesCount = match[2].length; + } + } else { + if (otherSlashes) { + rest = match[3] + match[4]; + slashesCount = match[3].length; + } else { + rest = match[4] + } + } + + if (protocol === 'file:') { + if (slashesCount >= 2) { + rest = rest.slice(2); + } + } else if (isSpecial(protocol)) { + rest = match[4]; + } else if (protocol) { + if (forwardSlashes) { + rest = rest.slice(2); + } + } else if (slashesCount >= 2 && isSpecial(location.protocol)) { + rest = match[4]; + } + + return { + protocol: protocol, + slashes: forwardSlashes || isSpecial(protocol), + slashesCount: slashesCount, + rest: rest + }; +} + +/** + * Resolve a relative URL pathname against a base URL pathname. + * + * @param {String} relative Pathname of the relative URL. + * @param {String} base Pathname of the base URL. + * @return {String} Resolved pathname. + * @private + */ +function resolve(relative, base) { + if (relative === '') return base; + + var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) + , i = path.length + , last = path[i - 1] + , unshift = false + , up = 0; + + while (i--) { + if (path[i] === '.') { + path.splice(i, 1); + } else if (path[i] === '..') { + path.splice(i, 1); + up++; + } else if (up) { + if (i === 0) unshift = true; + path.splice(i, 1); + up--; + } + } + + if (unshift) path.unshift(''); + if (last === '.' || last === '..') path.push(''); + + return path.join('/'); +} + +/** + * The actual URL instance. Instead of returning an object we've opted-in to + * create an actual constructor as it's much more memory efficient and + * faster and it pleases my OCD. + * + * It is worth noting that we should not use `URL` as class name to prevent + * clashes with the global URL instance that got introduced in browsers. + * + * @constructor + * @param {String} address URL we want to parse. + * @param {Object|String} [location] Location defaults for relative paths. + * @param {Boolean|Function} [parser] Parser for the query string. + * @private + */ +function Url(address, location, parser) { + address = trimLeft(address); + address = address.replace(CRHTLF, ''); + + if (!(this instanceof Url)) { + return new Url(address, location, parser); + } + + var relative, extracted, parse, instruction, index, key + , instructions = rules.slice() + , type = typeof location + , url = this + , i = 0; + + // + // The following if statements allows this module two have compatibility with + // 2 different API: + // + // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments + // where the boolean indicates that the query string should also be parsed. + // + // 2. The `URL` interface of the browser which accepts a URL, object as + // arguments. The supplied object will be used as default values / fall-back + // for relative paths. + // + if ('object' !== type && 'string' !== type) { + parser = location; + location = null; + } + + if (parser && 'function' !== typeof parser) parser = qs.parse; + + location = lolcation(location); + + // + // Extract protocol information before running the instructions. + // + extracted = extractProtocol(address || '', location); + relative = !extracted.protocol && !extracted.slashes; + url.slashes = extracted.slashes || relative && location.slashes; + url.protocol = extracted.protocol || location.protocol || ''; + address = extracted.rest; + + // + // When the authority component is absent the URL starts with a path + // component. + // + if ( + extracted.protocol === 'file:' && ( + extracted.slashesCount !== 2 || windowsDriveLetter.test(address)) || + (!extracted.slashes && + (extracted.protocol || + extracted.slashesCount < 2 || + !isSpecial(url.protocol))) + ) { + instructions[3] = [/(.*)/, 'pathname']; + } + + for (; i < instructions.length; i++) { + instruction = instructions[i]; + + if (typeof instruction === 'function') { + address = instruction(address, url); + continue; + } + + parse = instruction[0]; + key = instruction[1]; + + if (parse !== parse) { + url[key] = address; + } else if ('string' === typeof parse) { + index = parse === '@' + ? address.lastIndexOf(parse) + : address.indexOf(parse); + + if (~index) { + if ('number' === typeof instruction[2]) { + url[key] = address.slice(0, index); + address = address.slice(index + instruction[2]); + } else { + url[key] = address.slice(index); + address = address.slice(0, index); + } + } + } else if ((index = parse.exec(address))) { + url[key] = index[1]; + address = address.slice(0, index.index); + } + + url[key] = url[key] || ( + relative && instruction[3] ? location[key] || '' : '' + ); + + // + // Hostname, host and protocol should be lowercased so they can be used to + // create a proper `origin`. + // + if (instruction[4]) url[key] = url[key].toLowerCase(); + } + + // + // Also parse the supplied query string in to an object. If we're supplied + // with a custom parser as function use that instead of the default build-in + // parser. + // + if (parser) url.query = parser(url.query); + + // + // If the URL is relative, resolve the pathname against the base URL. + // + if ( + relative + && location.slashes + && url.pathname.charAt(0) !== '/' + && (url.pathname !== '' || location.pathname !== '') + ) { + url.pathname = resolve(url.pathname, location.pathname); + } + + // + // Default to a / for pathname if none exists. This normalizes the URL + // to always have a / + // + if (url.pathname.charAt(0) !== '/' && isSpecial(url.protocol)) { + url.pathname = '/' + url.pathname; + } + + // + // We should not add port numbers if they are already the default port number + // for a given protocol. As the host also contains the port number we're going + // override it with the hostname which contains no port number. + // + if (!required(url.port, url.protocol)) { + url.host = url.hostname; + url.port = ''; + } + + // + // Parse down the `auth` for the username and password. + // + url.username = url.password = ''; + + if (url.auth) { + index = url.auth.indexOf(':'); + + if (~index) { + url.username = url.auth.slice(0, index); + url.username = encodeURIComponent(decodeURIComponent(url.username)); + + url.password = url.auth.slice(index + 1); + url.password = encodeURIComponent(decodeURIComponent(url.password)) + } else { + url.username = encodeURIComponent(decodeURIComponent(url.auth)); + } + + url.auth = url.password ? url.username +':'+ url.password : url.username; + } + + url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host + ? url.protocol +'//'+ url.host + : 'null'; + + // + // The href is just the compiled result. + // + url.href = url.toString(); +} + +/** + * This is convenience method for changing properties in the URL instance to + * insure that they all propagate correctly. + * + * @param {String} part Property we need to adjust. + * @param {Mixed} value The newly assigned value. + * @param {Boolean|Function} fn When setting the query, it will be the function + * used to parse the query. + * When setting the protocol, double slash will be + * removed from the final url if it is true. + * @returns {URL} URL instance for chaining. + * @public + */ +function set(part, value, fn) { + var url = this; + + switch (part) { + case 'query': + if ('string' === typeof value && value.length) { + value = (fn || qs.parse)(value); + } + + url[part] = value; + break; + + case 'port': + url[part] = value; + + if (!required(value, url.protocol)) { + url.host = url.hostname; + url[part] = ''; + } else if (value) { + url.host = url.hostname +':'+ value; + } + + break; + + case 'hostname': + url[part] = value; + + if (url.port) value += ':'+ url.port; + url.host = value; + break; + + case 'host': + url[part] = value; + + if (port.test(value)) { + value = value.split(':'); + url.port = value.pop(); + url.hostname = value.join(':'); + } else { + url.hostname = value; + url.port = ''; + } + + break; + + case 'protocol': + url.protocol = value.toLowerCase(); + url.slashes = !fn; + break; + + case 'pathname': + case 'hash': + if (value) { + var char = part === 'pathname' ? '/' : '#'; + url[part] = value.charAt(0) !== char ? char + value : value; + } else { + url[part] = value; + } + break; + + case 'username': + case 'password': + url[part] = encodeURIComponent(value); + break; + + case 'auth': + var index = value.indexOf(':'); + + if (~index) { + url.username = value.slice(0, index); + url.username = encodeURIComponent(decodeURIComponent(url.username)); + + url.password = value.slice(index + 1); + url.password = encodeURIComponent(decodeURIComponent(url.password)); + } else { + url.username = encodeURIComponent(decodeURIComponent(value)); + } + } + + for (var i = 0; i < rules.length; i++) { + var ins = rules[i]; + + if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); + } + + url.auth = url.password ? url.username +':'+ url.password : url.username; + + url.origin = url.protocol !== 'file:' && isSpecial(url.protocol) && url.host + ? url.protocol +'//'+ url.host + : 'null'; + + url.href = url.toString(); + + return url; +} + +/** + * Transform the properties back in to a valid and full URL string. + * + * @param {Function} stringify Optional query stringify function. + * @returns {String} Compiled version of the URL. + * @public + */ +function toString(stringify) { + if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify; + + var query + , url = this + , host = url.host + , protocol = url.protocol; + + if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; + + var result = + protocol + + ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : ''); + + if (url.username) { + result += url.username; + if (url.password) result += ':'+ url.password; + result += '@'; + } else if (url.password) { + result += ':'+ url.password; + result += '@'; + } else if ( + url.protocol !== 'file:' && + isSpecial(url.protocol) && + !host && + url.pathname !== '/' + ) { + // + // Add back the empty userinfo, otherwise the original invalid URL + // might be transformed into a valid one with `url.pathname` as host. + // + result += '@'; + } + + // + // Trailing colon is removed from `url.host` when it is parsed. If it still + // ends with a colon, then add back the trailing colon that was removed. This + // prevents an invalid URL from being transformed into a valid one. + // + if (host[host.length - 1] === ':' || (port.test(url.hostname) && !url.port)) { + host += ':'; + } + + result += host + url.pathname; + + query = 'object' === typeof url.query ? stringify(url.query) : url.query; + if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; + + if (url.hash) result += url.hash; + + return result; +} + +Url.prototype = { set: set, toString: toString }; + +// +// Expose the URL parser and some additional properties that might be useful for +// others or testing. +// +Url.extractProtocol = extractProtocol; +Url.location = lolcation; +Url.trimLeft = trimLeft; +Url.qs = qs; + +module.exports = Url; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"querystringify":21,"requires-port":22}]},{},[4])(4) +}); +//# sourceMappingURL=tus.js.map diff --git a/source/vimeo/classes/api.php b/source/vimeo/classes/api.php new file mode 100644 index 0000000..c231fe9 --- /dev/null +++ b/source/vimeo/classes/api.php @@ -0,0 +1,46 @@ +. + +/** + * Manage Vimeo source files + * + * @package mediatimesrc_vimeo + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mediatimesrc_vimeo; + +use moodle_exception; +use stdClass; + +/** + * Manage Vimeo source files + * + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class api extends \videotimeplugin_repository\api { + /** + * Create place holder for upload + * + * @param array $params Upload params + * @return array + */ + public function create_token($params = []) { + return $this->request('/me/videos', $params, 'POST')['body']; + } +} diff --git a/source/vimeo/classes/event/resource_created.php b/source/vimeo/classes/event/resource_created.php new file mode 100644 index 0000000..690b0b3 --- /dev/null +++ b/source/vimeo/classes/event/resource_created.php @@ -0,0 +1,36 @@ +. + +namespace mediatimesrc_vimeo\event; + +/** + * The resource_created event class. + * + * @package mediatimesrc_vimeo + * @category event + * @copyright 2024 bdecent gmbh + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class resource_created extends \tool_mediatime\event\resource_created { + /** + * Returns event name. + * + * @return string + */ + public static function get_name() { + return get_string('event_resource_created', 'mediatimesrc_vimeo'); + } +} diff --git a/source/vimeo/classes/event/resource_deleted.php b/source/vimeo/classes/event/resource_deleted.php new file mode 100644 index 0000000..a3866da --- /dev/null +++ b/source/vimeo/classes/event/resource_deleted.php @@ -0,0 +1,38 @@ +. + +namespace mediatimesrc_vimeo\event; + +use core\event\base; + +/** + * The resource_deleted event class. + * + * @package mediatimesrc_vimeo + * @category event + * @copyright 2024 bdecent gmbh + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class resource_deleted extends \tool_mediatime\event\resource_deleted { + /** + * Returns event name. + * + * @return string + */ + public static function get_name() { + return get_string('event_resource_deleted', 'mediatimesrc_vimeo'); + } +} diff --git a/source/vimeo/classes/event/resource_updated.php b/source/vimeo/classes/event/resource_updated.php new file mode 100644 index 0000000..792c428 --- /dev/null +++ b/source/vimeo/classes/event/resource_updated.php @@ -0,0 +1,38 @@ +. + +namespace mediatimesrc_vimeo\event; + +use core\event\base; + +/** + * The resource_updated event class. + * + * @package mediatimesrc_vimeo + * @category event + * @copyright 2024 bdecent gmbh + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class resource_updated extends \tool_mediatime\event\resource_updated { + /** + * Returns event name. + * + * @return string + */ + public static function get_name() { + return get_string('event_resource_updated', 'mediatimesrc_vimeo'); + } +} diff --git a/source/vimeo/classes/external/create_token.php b/source/vimeo/classes/external/create_token.php new file mode 100644 index 0000000..1cce5d4 --- /dev/null +++ b/source/vimeo/classes/external/create_token.php @@ -0,0 +1,140 @@ +. + +namespace mediatimesrc_vimeo\external; + +use mediatimesrc_vimeo\api; +use cache; +use context; +use context_system; +use core_external\external_api; +use core_external\external_function_parameters; +use core_external\external_multiple_structure; +use core_external\external_single_structure; +use core_external\external_value; +use core_tag_tag; +use stdClass; + +/** + * External function for creating resource place holder for Vimeo upload + * + * @package mediatimesrc_vimeo + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class create_token extends external_api { + /** + * Get parameter definition for execute. + * + * @return external_function_parameters + */ + public static function execute_parameters(): external_function_parameters { + return new external_function_parameters( + [ + 'description' => new external_value(PARAM_TEXT, 'Resource description'), + 'filesize' => new external_value(PARAM_INT, 'Video file size'), + 'name' => new external_value(PARAM_TEXT, 'Resource name'), + 'tags' => new external_value(PARAM_RAW, 'Resource tags'), + 'title' => new external_value(PARAM_TEXT, 'Resource title'), + ] + ); + } + + /** + * Create place holder + * + * @param int $filesize Video file size + * @param string $description Name of resource + * @param string $filesize Video file size + * @param string $name Name of resource + * @param string $tags Name of resource + * @param string $title Name of resource + * @return array Upload information + */ + public static function execute($description, $filesize, $name, $tags, $title): array { + global $DB, $USER; + + $params = self::validate_parameters(self::execute_parameters(), [ + 'filesize' => $filesize, + 'description' => $description, + 'name' => $name, + 'tags' => $tags, + 'title' => $title, + ]); + + $context = context_system::instance(); + self::validate_context($context); + + require_login(); + require_capability('mediatimesrc/vimeo:upload', $context); + + $api = new api(); + + $video = $api->create_token([ + 'upload' => [ + 'approach' => 'tus', + 'size' => $params['filesize'], + ], + ]); + $video = $api->request($video['uri'], [ + 'name' => $params['title'], + 'description' => $params['description'], + ], 'PATCH')['body']; + $id = $DB->insert_record('tool_mediatime', [ + 'name' => $params['name'], + 'source' => 'vimeo', + 'content' => json_encode($video), + 'timecreated' => time(), + 'timemodified' => time(), + 'usermodified' => $USER->id, + ]); + + if (!empty($params['tags'])) { + core_tag_tag::set_item_tags( + 'tool_mediatime', + 'tool_mediatime', + $id, + $context, + json_decode(htmlspecialchars_decode($params['tags'])) + ); + } + + $event = \mediatimesrc_vimeo\event\resource_created::create([ + 'contextid' => SYSCONTEXTID, + 'objectid' => $id, + ]); + $event->trigger(); + + return [ + 'id' => $id, + 'uploadurl' => $video['upload']['upload_link'], + 'uri' => $video->uri, + ]; + } + + /** + * Get return definition for execute + * + * @return external_single_structure + */ + public static function execute_returns(): external_single_structure { + return new external_single_structure([ + 'id' => new external_value(PARAM_INT, 'Resource id'), + 'uploadurl' => new external_value(PARAM_TEXT, 'Upload url'), + 'uri' => new external_value(PARAM_TEXT, 'Vimeo uri'), + ]); + } +} diff --git a/source/vimeo/classes/form/delete_resource.php b/source/vimeo/classes/form/delete_resource.php new file mode 100644 index 0000000..02b7f50 --- /dev/null +++ b/source/vimeo/classes/form/delete_resource.php @@ -0,0 +1,66 @@ +. + +/** + * Media Time media edit form + * + * @package mediatimesrc_vimeo + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mediatimesrc_vimeo\form; + +use context_system; +use moodleform; +use mediatimesrc_vimeo\api; +use mediatimesrc_vimeo\output\media_resource; + +/** + * Media Time media edit form + * + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class delete_resource extends \tool_mediatime\form\delete_resource { + /** + * Definition + */ + public function definition() { + $mform = $this->_form; + + $mform->addElement('hidden', 'source'); + $mform->setType('source', PARAM_TEXT); + $mform->setDefault('source', 'vimeo'); + + $mform->addElement('static', 'name', get_string('resourcename', 'tool_mediatime'), $this->_customdata['name']); + $mform->setType('name', PARAM_TEXT); + + $mform->addElement('hidden', 'delete'); + $mform->setType('delete', PARAM_INT); + + $action = [ + $mform->createElement('radio', 'action', '', get_string('keepvimeofiles', 'mediatimesrc_vimeo'), 1, []), + $mform->createElement('radio', 'action', '', get_string('removevimeofiles', 'mediatimesrc_vimeo'), 2, []), + ]; + $mform->addGroup($action, 'vimeofileaction', get_string('vimeofileaction', 'mediatimesrc_vimeo'), [' '], false); + $mform->setType('action', PARAM_INT); + $mform->setDefault('action', 2); + $mform->addHelpButton('vimeofileaction', 'vimeofileaction', 'mediatimesrc_vimeo'); + + $this->add_action_buttons(true, get_string('delete')); + } +} diff --git a/source/vimeo/classes/form/edit_resource.php b/source/vimeo/classes/form/edit_resource.php new file mode 100644 index 0000000..61f4296 --- /dev/null +++ b/source/vimeo/classes/form/edit_resource.php @@ -0,0 +1,161 @@ +. + +/** + * Media Time media edit form + * + * @package mediatimesrc_vimeo + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mediatimesrc_vimeo\form; + +use context_system; +use moodleform; +use videotimeplugin_repository\api; +use mediatimesrc_vimeo\output\media_resource; +use mediatimesrc_vimeo\output\video; + +/** + * Media Time media edit form + * + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class edit_resource extends \tool_mediatime\form\edit_resource { + /** + * Definition + */ + public function definition() { + $mform = $this->_form; + + $mform->addElement('hidden', 'create'); + $mform->setType('create', PARAM_TEXT); + + $mform->addElement('hidden', 'source'); + $mform->setType('source', PARAM_TEXT); + $mform->setDefault('source', 'vimeo'); + + $mform->addElement('text', 'name', get_string('resourcename', 'tool_mediatime')); + $mform->setType('name', PARAM_TEXT); + $mform->addHelpButton('name', 'resourcename', 'tool_mediatime'); + + $mform->addElement('text', 'title', get_string('title', 'tool_mediatime')); + $mform->setType('title', PARAM_TEXT); + $mform->addHelpButton('title', 'title', 'tool_mediatime'); + + $mform->addElement('hidden', 'edit'); + $mform->setType('edit', PARAM_INT); + + $filesource = [ + $mform->createElement('radio', 'newfile', '', get_string('uploadnewfile', 'mediatimesrc_vimeo'), 1, []), + $mform->createElement('radio', 'newfile', '', get_string('selectexistingfile', 'mediatimesrc_vimeo'), 0, []), + $mform->createElement('radio', 'newfile', '', get_string('selecturl', 'mediatimesrc_vimeo'), 2, []), + ]; + $mform->addGroup($filesource, 'filesource', get_string('videofile', 'mediatimesrc_vimeo'), [' '], false); + $mform->setType('newfile', PARAM_INT); + $mform->addHelpButton('filesource', 'videofile', 'mediatimesrc_vimeo'); + $mform->disabledIf('title', 'newfile', 'neq', 1); + $mform->disabledIf('description', 'newfile', 'neq', 1); + + $mform->addElement('url', 'vimeo_url', get_string('vimeo_url', 'mod_videotime')); + $mform->hideIf('vimeo_url', 'newfile', 'neq', 2); + $mform->setType('vimeo_url', PARAM_URL); + + $mform->addElement('textarea', 'description', get_string('description')); + $mform->setType('description', PARAM_TEXT); + + $this->tag_elements(); + + $this->add_action_buttons(); + } + + /** + * Display resource or add file fields + */ + public function definition_after_data() { + global $DB, $OUTPUT; + + $mform =& $this->_form; + + $id = $mform->getElementValue('edit'); + $record = $DB->get_record('tool_mediatime', ['id' => $id]); + $context = context_system::instance(); + if ($record) { + $resource = new media_resource($record); + $content = json_decode($record->content); + $video = new video($content); + $mform->insertElementBefore( + $mform->createElement('html', $OUTPUT->render($video)), + 'name' + ); + $mform->removeElement('vimeo_url'); + $mform->insertElementBefore( + $mform->createElement('static', 'vimeo_url', get_string('vimeolink', 'mediatimesrc_vimeo'), $content->link), + 'filesource' + ); + $mform->removeElement('filesource'); + } else { + if (has_capability('mediatimesrc/vimeo:viewall', $context)) { + $options = [null => '']; + $api = new api(); + $videos = $api->request('/me/videos')['body']['data']; + foreach ($videos as $video) { + $options[$video['uri']] = $video['name']; + } + + $mform->insertElementBefore( + $mform->createElement('autocomplete', 'file', '', $options, [ + ]), + 'description' + ); + $mform->hideIf('file', 'newfile', 'neq', 0); + $mform->setDefault('newfile', 1); + $mform->setDefault('file', []); + + if (has_capability('mediatimesrc/vimeo:upload', context_system::instance())) { + $maxbytes = 200000000; + $mform->insertElementBefore( + $mform->createElement( + 'filemanager', + 'videofile', + get_string('videofile', 'mediatimesrc_videotime'), + null, + [ + 'subdirs' => 0, + 'maxbytes' => $maxbytes, + 'areamaxbytes' => $maxbytes, + 'maxfiles' => 1, + 'accepted_types' => ['video'], + 'return_types' => FILE_INTERNAL, + ] + ), + 'description' + ); + $mform->addHelpButton('videofile', 'videofile', 'mediatimesrc_videotime'); + $mform->hideIf('videofile', 'newfile', 'neq', 1); + } + } else { + $mform->removeElement('filesource'); + $mform->insertElementBefore( + $mform->createElement('hidden', 'newfile', 1), + 'description' + ); + } + } + } +} diff --git a/source/vimeo/classes/manager.php b/source/vimeo/classes/manager.php new file mode 100644 index 0000000..a82add3 --- /dev/null +++ b/source/vimeo/classes/manager.php @@ -0,0 +1,288 @@ +. + +/** + * Manage Vimeo source files + * + * @package mediatimesrc_vimeo + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mediatimesrc_vimeo; + +use context_system; +use context_user; +use core_tag_tag; +use moodle_exception; +use moodle_url; +use moodleform; +use renderable; +use renderer_base; +use stdClass; +use templatable; + +/** + * Manage Vimeo source files + * + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class manager implements renderable, templatable { + /** @var $api Vimeo API instance */ + protected ?api $api = null; + + /** @var $content Cached Vimeo video record */ + protected ?stdClass $content = null; + + /** @var $record Media time record for resource */ + protected ?stdClass $record = null; + + /** @var $form Editing form */ + protected ?moodleform $form = null; + + /** + * Constructor + * + * @param ?stdClass $record Media time record for resource + */ + public function __construct($record = null) { + global $DB, $USER; + + $this->api = new api(); + + $this->record = $record; + + if ($record) { + $this->content = json_decode($record->content); + } + + if ($delete = optional_param('delete', null, PARAM_INT)) { + $this->form = new form\delete_resource(null, (array)$this->record); + $this->form->set_data(['delete' => $delete]); + } else { + $this->form = new form\edit_resource(); + } + + $data = [ + 'create' => optional_param('create', '', PARAM_TEXT), + 'edit' => optional_param('edit', null, PARAM_INT), + ]; + $maxbytes = get_config('mediatimesrc_videotime', 'maxbytes'); + if ($edit = optional_param('edit', null, PARAM_INT)) { + $draftitemid = file_get_submitted_draft_itemid('videofile'); + file_prepare_draft_area( + $draftitemid, + SYSCONTEXTID, + 'mediatimesrc_vimeo', + 'videofile', + $edit, + [ + 'subdirs' => 0, + 'maxbytes' => $maxbytes, + 'maxfiles' => 1, + ] + ); + + $this->content->tags = core_tag_tag::get_item_tags_array('tool_mediatime', 'tool_mediatime', $edit); + + $data += ['name' => $this->record->name, 'title' => $this->content->name] + (array)$this->content; + } + $this->form->set_data($data); + if ($this->form->is_cancelled()) { + $redirect = new moodle_url('/admin/tool/mediatime/index.php'); + redirect($redirect); + } else if ( + optional_param('delete', null, PARAM_INT) + && ($data = $this->form->get_data()) + ) { + $this->delete_resource($data->action == 2); + + $redirect = new moodle_url('/admin/tool/mediatime/index.php'); + redirect($redirect); + } else if (($data = $this->form->get_data()) && (!empty($data->newfile) && $data->newfile == 1)) { + require_sesskey(); + $data->timemodified = time(); + $data->usermodified = $USER->id; + $data->timecreated = $data->timemodified; + + $fs = get_file_storage(); + foreach ($fs->get_area_files(context_user::instance($USER->id)->id, 'user', 'draft', $data->videofile) as $file) { + if (!$file->is_directory()) { + $data->edit = $DB->insert_record('tool_mediatime', $data); + + file_save_draft_area_files( + $data->videofile, + SYSCONTEXTID, + 'mediatimesrc_vimeo', + 'videofile', + $data->edit, + [ + 'subdirs' => 0, + 'maxbytes' => $maxbytes, + 'maxfiles' => 1, + ] + ); + $url = moodle_url::make_pluginfile_url( + SYSCONTEXTID, + 'mediatimesrc_vimeo', + 'videofile', + $data->edit, + '/' . $file->get_contenthash() . $file->get_filepath(), + $file->get_filename() + ); + + $video = $this->api->create_token([ + 'upload' => [ + 'approach' => 'pull', + 'size' => $file->get_filesize(), + 'link' => $url->out(), + ], + ]); + + $event = \mediatimesrc_vimeo\event\resource_created::create([ + 'contextid' => SYSCONTEXTID, + 'objectid' => $data->edit, + ]); + $event->trigger(); + + if (!empty($data->tags)) { + core_tag_tag::set_item_tags( + 'tool_mediatime', + 'tool_mediatime', + $data->edit, + context_system::instance(), + $data->tags + ); + } + + $video = $this->api->request($video['uri'], [ + 'name' => $data->title, + 'description' => $data->description, + ], 'PATCH')['body']; + $data->id = $data->edit; + $data->content = json_encode($video); + $DB->update_record('tool_mediatime', $data); + $redirect = new moodle_url('/admin/tool/mediatime/index.php', ['id' => $data->edit]); + redirect($redirect); + } + } + } else if (($data = $this->form->get_data()) && (empty($data->newfile) || $data->newfile != 1)) { + require_sesskey(); + $data->timemodified = time(); + $data->usermodified = $USER->id; + + if (empty($data->edit)) { + if (empty($data->newfile)) { + $video = $this->api->request("$data->file")['body']; + } else { + $vimeoid = mod_videotime_get_vimeo_id_from_link($data->vimeo_url); + $video = $this->api->request("/videos/$vimeoid")['body']; + } + $data->content = json_encode($video); + $data->timecreated = $data->timemodified; + $data->edit = $DB->insert_record('tool_mediatime', $data); + } else { + $data->id = $data->edit; + $this->api->request($this->content->uri, array_intersect_key(['name' => $data->title] + (array)$data, [ + 'description' => true, + 'name' => true, + ]), 'PATCH'); + $video = $this->api->request($this->content->uri)['body']; + $data->content = json_encode($video + [ + 'description' => $data->description, + 'title' => $data->title, + 'name' => $data->title, + ]); + $DB->update_record('tool_mediatime', $data); + + $event = \mediatimesrc_vimeo\event\resource_updated::create([ + 'contextid' => SYSCONTEXTID, + 'objectid' => $this->record->id, + ]); + $event->trigger(); + } + + $context = context_system::instance(); + core_tag_tag::set_item_tags( + 'tool_mediatime', + 'tool_mediatime', + $data->edit, + $context, + $data->tags + ); + + $redirect = new moodle_url('/admin/tool/mediatime/index.php', ['id' => $data->edit]); + redirect($redirect); + } + } + + /** + * Export this data so it can be used as the context for a mustache template. + * + * @param \renderer_base $output + * @return array + */ + public function export_for_template(renderer_base $output) { + global $DB; + + if (optional_param('id', null, PARAM_INT)) { + $resource = new output\media_resource($this->record); + return [ + 'resource' => $output->render($resource), + ]; + } else if (($data = $this->form->get_data()) && $this->form->is_submitted() && $data->newfile == 1) { + require_sesskey(); + require_capability('mediatimesrc/vimeo:upload', context_system::instance()); + + return [ + 'form' => $output->render_from_template('mediatimesrc_vimeo/file_upload', [ + 'name' => json_encode($data->name), + 'description' => json_encode($data->description), + 'title' => json_encode($data->title), + 'tags' => htmlspecialchars(json_encode($data->tags)), + ]), + ]; + } + return [ + 'form' => $this->form->render(), + ]; + } + + /** + * Delete resource + * + * @param bool $removevimeofile Whether to delete server resource at Vimeo + */ + public function delete_resource(bool $removevimeofile = false) { + global $DB; + + if ($removevimeofile) { + $uri = $this->content->uri; + $this->api->request($uri, [], 'DELETE'); + } + + $DB->delete_records('tool_mediatime', [ + 'id' => $this->record->id, + ]); + + $event = \mediatimesrc_vimeo\event\resource_deleted::create([ + 'contextid' => SYSCONTEXTID, + 'objectid' => $this->record->id, + ]); + $event->trigger(); + } +} diff --git a/source/vimeo/classes/output/media_resource.php b/source/vimeo/classes/output/media_resource.php new file mode 100644 index 0000000..72cf918 --- /dev/null +++ b/source/vimeo/classes/output/media_resource.php @@ -0,0 +1,119 @@ +. + +/** + * Display a resource in the media library + * + * @package mediatimesrc_vimeo + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mediatimesrc_vimeo\output; + +use moodle_url; +use stdClass; +use renderable; +use renderer_base; +use templatable; + +/** + * Display a resource in the media library + * + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class media_resource implements renderable, templatable { + /** @var $context System context */ + protected $context = null; + + /** @var ?stdClass $record Media Time resource record */ + protected $record; + + /** + * Constructor + * + * @param stdClass $record Media Time resource record + */ + public function __construct(stdClass $record) { + $this->record = $record; + } + + /** + * Export this data so it can be used as the context for a mustache template. + * + * @param \renderer_base $output + * @return array + */ + public function export_for_template(renderer_base $output) { + global $DB, $USER; + $content = json_decode($this->record->content); + $api = new \mediatimesrc_vimeo\api(); + $context = \context_system::instance(); + + $video = new video($content); + return [ + 'canedit' => has_capability('tool/mediatime:manage', $context) || ($USER->id == $this->record->usermodified), + 'id' => $this->record->id, + 'libraryhome' => new moodle_url('/admin/tool/mediatime/index.php'), + 'name' => $this->record->name, + 'resource' => $content, + 'video' => $output->render($video), + ]; + } + + /** + * Return url for poster image + * + * @param \renderer_base $output + * @return string url + */ + public function image_url(renderer_base $output) { + if (empty(json_decode($this->record->content)->pictures)) { + return ''; + } + return json_decode($this->record->content)->pictures->sizes[2]->link; + } + + /** + * Return resource title + * + * @return string + */ + public function get_title() { + return json_decode($this->record->content)->name ?? ''; + } + + /** + * Return url for video content + * + * @param \renderer_base $output + * @return string url + */ + public function video_url($output) { + return json_decode($this->record->content)->link; + } + + /** + * Return video file content + * + * @param \renderer_base $output + * @return string url + */ + public function video_file_content($output) { + return file_get_contents($this->video_url($output)); + } +} diff --git a/source/vimeo/classes/output/video.php b/source/vimeo/classes/output/video.php new file mode 100644 index 0000000..cf089ed --- /dev/null +++ b/source/vimeo/classes/output/video.php @@ -0,0 +1,93 @@ +. + +/** + * Display a resource in the media library + * + * @package mediatimesrc_vimeo + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mediatimesrc_vimeo\output; + +use moodle_url; +use stdClass; +use renderable; +use renderer_base; +use templatable; + +/** + * Display a resource in the media library + * + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class video implements renderable, templatable { + /** @var ?stdClass $content Media Time content */ + protected $content; + + /** + * Constructor + * + * @param stdClass $content Vimeo data object + */ + public function __construct(stdClass $content) { + $this->content = $content; + } + + /** + * Export this data so it can be used as the context for a mustache template. + * + * @param \renderer_base $output + * @return array + */ + public function export_for_template(renderer_base $output) { + global $DB, $USER; + $api = new \mediatimesrc_vimeo\api(); + $context = \context_system::instance(); + + return [ + 'resource' => $this->content, + 'instance' => json_encode([ + 'vimeo_url' => $this->content->link, + 'autopause' => 1, + 'autoplay' => 1, + 'background' => 0, + 'byline' => 1, + 'color' => 1, + 'controls' => 1, + 'dnt' => 1, + 'height' => 1, + 'loop' => 1, + 'maxheight' => 0, + 'maxwidth' => 0, + 'muted' => 1, + 'portrait' => 1, + 'pip' => 1, + 'playsinline' => 1, + 'responsive' => 1, + 'speed' => 1, + 'title' => 1, + 'transparent' => 1, + 'url' => 1, + 'width' => 1, + ]), + 'interval' => 5, + 'uniqueid' => uniqid(), + ]; + } +} diff --git a/source/vimeo/classes/privacy/provider.php b/source/vimeo/classes/privacy/provider.php new file mode 100644 index 0000000..93730c3 --- /dev/null +++ b/source/vimeo/classes/privacy/provider.php @@ -0,0 +1,43 @@ +. + +/** + * Privacy Subsystem implementation for mediatimesrc_vimeo. + * + * @package mediatimesrc_vimeo + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +namespace mediatimesrc_vimeo\privacy; + +/** + * Privacy Subsystem for mediatimesrc_vimeo implementing null_provider. + * + * @copyright 2024 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class provider implements \core_privacy\local\metadata\null_provider { + /** + * Get the language string identifier with the component's language + * file to explain why this plugin stores no data. + * + * @return string + */ + public static function get_reason(): string { + return 'privacy:metadata'; + } +} diff --git a/source/vimeo/db/access.php b/source/vimeo/db/access.php new file mode 100644 index 0000000..0928690 --- /dev/null +++ b/source/vimeo/db/access.php @@ -0,0 +1,49 @@ +. + +/** + * Plugin capabilities are defined here. + * + * @package mediatimesrc_vimeo + * @category access + * @copyright 2024 bdecent gmbh + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$capabilities = [ + + 'mediatimesrc/vimeo:upload' => [ + 'riskbitmask' => RISK_SPAM | RISK_XSS, + 'captype' => 'write', + 'contextlevel' => CONTEXT_SYSTEM, + 'archetypes' => [ + 'coursecreator' => CAP_ALLOW, + ], + 'clonepermissionsfrom' => 'moodle/blog:manageentries', + ], + + 'mediatimesrc/vimeo:viewall' => [ + 'riskbitmask' => RISK_SPAM | RISK_XSS, + 'captype' => 'view', + 'contextlevel' => CONTEXT_SYSTEM, + 'archetypes' => [ + 'coursecreator' => CAP_ALLOW, + ], + 'clonepermissionsfrom' => 'moodle/blog:manageentries', + ], +]; diff --git a/source/vimeo/db/install.php b/source/vimeo/db/install.php new file mode 100644 index 0000000..bbafb18 --- /dev/null +++ b/source/vimeo/db/install.php @@ -0,0 +1,32 @@ +. + +/** + * Code to be executed after the plugin's database scheme has been installed is defined here. + * + * @package mediatimesrc_vimeo + * @category upgrade + * @copyright 2024 bdecent gmbh + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * Custom code to be run on installing the plugin. + */ +function xmldb_mediatimesrc_vimeo_install() { + + return true; +} diff --git a/source/vimeo/db/services.php b/source/vimeo/db/services.php new file mode 100644 index 0000000..816d1eb --- /dev/null +++ b/source/vimeo/db/services.php @@ -0,0 +1,35 @@ +. +/** + * External functions and service definitions. + * + * @package mediatimesrc_vimeo + * @category external + * @copyright 2024 bdecent gmbh + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die; + +$functions = [ + 'mediatimesrc_vimeo_create_token' => [ + 'classname' => '\\mediatimesrc_vimeo\\external\\create_token', + 'methodname' => 'execute', + 'description' => 'Create place holder to upload video', + 'type' => 'write', + 'ajax' => true, + ], +]; diff --git a/source/vimeo/db/upgrade.php b/source/vimeo/db/upgrade.php new file mode 100644 index 0000000..c11abda --- /dev/null +++ b/source/vimeo/db/upgrade.php @@ -0,0 +1,43 @@ +. + +/** + * Plugin upgrade steps are defined here. + * + * @package mediatimesrc_vimeo + * @category upgrade + * @copyright 2024 bdecent gmbh + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * Execute mediatimesrc_vimeo upgrade from the given old version. + * + * @param int $oldversion + * @return bool + */ +function xmldb_mediatimesrc_vimeo_upgrade($oldversion) { + global $DB; + + $dbman = $DB->get_manager(); + + // For further information please read {@link https://docs.moodle.org/dev/Upgrade_API}. + // + // You will also have to create the db/install.xml file by using the XMLDB Editor. + // Documentation for the XMLDB Editor can be found at {@link https://docs.moodle.org/dev/XMLDB_editor}. + + return true; +} diff --git a/source/vimeo/lang/en/mediatimesrc_vimeo.php b/source/vimeo/lang/en/mediatimesrc_vimeo.php new file mode 100644 index 0000000..26eb625 --- /dev/null +++ b/source/vimeo/lang/en/mediatimesrc_vimeo.php @@ -0,0 +1,43 @@ +. + +/** + * Plugin strings are defined here. + * + * @package mediatimesrc_vimeo + * @category string + * @copyright 2024 bdecent gmbh + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$string['event_resource_deleted'] = 'Vimeo resource deleted'; +$string['event_resource_updated'] = 'Vimeo resource updated'; +$string['keepvimeofiles'] = 'Keep Vimeo files'; +$string['pluginname'] = 'Vimeo'; +$string['privacy:metadata'] = 'The Vimeo plugin for Media Time does not store personal data. It does transmit files associated with educational video content that normally does not contain user data. If it is used for personal data, a separate agreement with the provider may be required.'; +$string['removevimeofiles'] = 'Remove Vimeo files'; +$string['selectexistingfile'] = 'Select existing file'; +$string['selecturl'] = 'Use existing Vimeo URL'; +$string['uploadnewfile'] = 'Upload new file'; +$string['videofile'] = 'Video file'; +$string['videofile_help'] = 'Choose to upload a new video, or choose to use an existing one that you select'; +$string['vimeo:upload'] = 'Upload files to Vimeo'; +$string['vimeo:viewall'] = 'View all files available'; +$string['vimeofileaction'] = 'Vimeo file action'; +$string['vimeofileaction_help'] = 'Select whether the file should be deleted on Vimeo when the local content is deleted. If the file is used in other local resources, it will no longer be available to users.'; +$string['vimeolink'] = 'Vimeo link'; diff --git a/source/vimeo/lib.php b/source/vimeo/lib.php new file mode 100644 index 0000000..aa13ac6 --- /dev/null +++ b/source/vimeo/lib.php @@ -0,0 +1,81 @@ +. + +/** + * Library of interface functions and constants. + * + * @package mediatimesrc_vimeo + * @copyright 2022 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +require_once("$CFG->libdir/resourcelib.php"); + +/** + * File serving callback + * + * @param stdClass $course course object + * @param stdClass $cm course module object + * @param stdClass $context context object + * @param string $filearea file area + * @param array $args extra arguments + * @param bool $forcedownload whether or not force download + * @param array $options additional options affecting the file serving + * @return bool false if the file was not found, just send the file otherwise and do not return anything + */ +function mediatimesrc_vimeo_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = []) { + if ($context->contextlevel != CONTEXT_SYSTEM) { + return false; + } + + if ( + in_array($filearea, [ + 'posterimage', + 'videofile', + ]) + ) { + $itemid = array_shift($args); + $contenthash = array_shift($args); + + $relativepath = implode('/', $args); + + $fullpath = "/$context->id/mediatimesrc_vimeo/$filearea/$itemid/$relativepath"; + + $fs = get_file_storage(); + if ( + (!$file = $fs->get_file_by_hash(sha1($fullpath))) + || $file->is_directory() + || ($contenthash != $file->get_contenthash()) + ) { + return false; + } + + send_stored_file($file, null, 0, $forcedownload, $options); + } +} + +/** + * Return file areas for backup + * + * @return array List of file areas + */ +function mediatimesrc_vimeo_config_file_areas() { + return [ + 'videofile', + ]; +} diff --git a/source/vimeo/templates/file_upload.mustache b/source/vimeo/templates/file_upload.mustache new file mode 100644 index 0000000..51487ec --- /dev/null +++ b/source/vimeo/templates/file_upload.mustache @@ -0,0 +1,56 @@ +{{! + This file is part of Moodle - http://moodle.org/ + + Moodle is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Moodle is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Moodle. If not, see . +}} +{{! + @template mediatimesrc_vimeo/file_upload + + This template will render the file upload form for add files to Vimeo + + Variables required for this template: + + Variables optional for this template: + + Example context (json): + { + } + +}} +
+
+ + + + + + + +
+ +
+
+
+
+
+ + +
+
+
+{{# js }} + require(['mediatimesrc_vimeo/file_upload'], function(FileUpload) { + FileUpload.init('{{ filesize }}'); + }); +{{/ js }} diff --git a/source/vimeo/templates/manager.mustache b/source/vimeo/templates/manager.mustache new file mode 100644 index 0000000..71b3b48 --- /dev/null +++ b/source/vimeo/templates/manager.mustache @@ -0,0 +1,34 @@ +{{! + This file is part of Moodle - http://moodle.org/ + + Moodle is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Moodle is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Moodle. If not, see . +}} +{{! + @template mediatimesrc_vimeo/manager + + This template will render the Media manager for media time + + Variables required for this template: + + Variables optional for this template: + + Example context (json): + { + } + +}} +
+{{{ form }}} +{{{ resource }}} +
diff --git a/source/vimeo/templates/media_resource.mustache b/source/vimeo/templates/media_resource.mustache new file mode 100644 index 0000000..778cb4c --- /dev/null +++ b/source/vimeo/templates/media_resource.mustache @@ -0,0 +1,62 @@ +{{! + This file is part of Moodle - http://moodle.org/ + + Moodle is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Moodle is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Moodle. If not, see . +}} +{{! + @template mediatimesrc_vimeo/media_resource + + This template will render a resource to embed in library + + Variables required for this template: + + Variables optional for this template: + + Example context (json): + { + "canedit": true, + "id": 2, + "resource": { + "title": "title", + "name": "name", + "description": "big and blue" + } + } + +}} +
+
+ {{# canedit }} + + + + {{/ canedit }} + {{# libraryhome }} + {{# str }}library, tool_mediatime {{/ str }} + {{/ libraryhome }} +
+
+

{{ name }}

+

{{ resource.name }}

+ {{{ video }}} +

{{ resource.description }}

+
+
{{# str }} filelinks, tool_mediatime {{/ str }}
+
Playlist
+
+
+
diff --git a/source/vimeo/templates/video.mustache b/source/vimeo/templates/video.mustache new file mode 100644 index 0000000..cd6d091 --- /dev/null +++ b/source/vimeo/templates/video.mustache @@ -0,0 +1,49 @@ +{{! + This file is part of Moodle - http://moodle.org/ + + Moodle is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Moodle is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Moodle. If not, see . +}} +{{! + @template mediatimesrc_vimeo/video + + This template will render a resource to embed in library + + Variables required for this template: + + Variables optional for this template: + + Example context (json): + { + "id": "324lk32sK", + "screenshot": { + "normal": "example.com/image.jpg" + } + } + +}} +
+
+ {{{intro}}} +
+
+
+ {{{video_description}}} +
+
+{{#js}} + require(['mod_videotime/videotime'], function(VideoTime) { + var v = new VideoTime('vimeo-embed-{{uniqueid}}', 0, false, {{interval}}, {{{instance}}}); + v.initialize(); + }); +{{/js}} diff --git a/source/vimeo/thirdpartylibs.xml b/source/vimeo/thirdpartylibs.xml new file mode 100644 index 0000000..91cbffa --- /dev/null +++ b/source/vimeo/thirdpartylibs.xml @@ -0,0 +1,10 @@ + + + + amd/src/tus.js + TUS js client + MIT + 4.0.1 + + + diff --git a/source/vimeo/version.php b/source/vimeo/version.php new file mode 100644 index 0000000..814190a --- /dev/null +++ b/source/vimeo/version.php @@ -0,0 +1,31 @@ +. + +/** + * Plugin version and other meta-data are defined here. + * + * @package mediatimesrc_vimeo + * @copyright 2024 bdecent gmbh + * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); + +$plugin->component = 'mediatimesrc_vimeo'; +$plugin->release = '1.0'; +$plugin->version = 2024010802; +$plugin->requires = 2022112800; +$plugin->maturity = MATURITY_ALPHA; diff --git a/templates/media_manager.mustache b/templates/media_manager.mustache index 8ac3ad5..2062871 100644 --- a/templates/media_manager.mustache +++ b/templates/media_manager.mustache @@ -44,20 +44,20 @@
- {{# content.name }} - {{ content.name }} - {{/ content.name }} - {{^ content.name }} - {{ content.title }} - {{/ content.name }} + {{# name }} + {{ name }} + {{/ name }} + {{^ name }} + {{ title }} + {{/ name }}
- -

{{ content.description }}

+ +

{{ description }}

{{{ tags }}}