From 770d201652a614641cc4ee5be498ba66fac6fc52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Halil=20=C4=B0brahim=20Kalkan?= Date: Fri, 19 Mar 2021 13:39:12 +0300 Subject: [PATCH] Added uppy. --- .../package.json | 1 + .../wwwroot/libs/uppy/uppy.css | 4298 ++ .../wwwroot/libs/uppy/uppy.js | 41259 ++++++++++++++++ .../wwwroot/libs/uppy/uppy.js.map | 509 + .../wwwroot/libs/uppy/uppy.min.css | 11 + .../wwwroot/libs/uppy/uppy.min.js | 2 + .../wwwroot/libs/uppy/uppy.min.js.map | 5126 ++ .../MyCompanyName.MyProjectName.Web/yarn.lock | 732 +- 8 files changed, 51935 insertions(+), 3 deletions(-) create mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.css create mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.js create mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.js.map create mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.min.css create mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.min.js create mode 100644 templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.min.js.map diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/package.json b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/package.json index 44d7a881aa..4b1f769870 100644 --- a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/package.json +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/package.json @@ -7,6 +7,7 @@ "@abp/cms-kit": "^4.2.2", "@abp/tui-editor": "^4.2.2", "@abp/slugify": "^4.2.2", + "@abp/uppy": "^4.2.2", // "@abp/aspnetcore.mvc.ui.theme.basic": "^4.2.2" } diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.css b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.css new file mode 100644 index 0000000000..4df7599351 --- /dev/null +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.css @@ -0,0 +1,4298 @@ +@charset "UTF-8"; +/** +* General Uppy styles that apply to everything inside the .uppy-Root container +*/ +.uppy-Root { + box-sizing: border-box; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; + line-height: 1; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + text-align: left; + position: relative; + color: #333; +} + +[dir=rtl] .uppy-Root, .uppy-Root[dir=rtl] { + text-align: right; +} + +.uppy-Root *, .uppy-Root *:before, .uppy-Root *:after { + box-sizing: inherit; +} + +.uppy-Root [hidden] { + display: none; +} + +.uppy-u-reset { + -webkit-appearance: none; + line-height: 1; + padding: 0; + margin: 0; + border: 0; + color: inherit; + -webkit-backface-visibility: visible; + backface-visibility: visible; + background: none; + border: medium none currentColor; + border-collapse: separate; + border-image: none; + border-radius: 0; + border-spacing: 0; + box-shadow: none; + clear: none; + cursor: auto; + display: inline; + empty-cells: show; + float: none; + font-family: inherit; + font-size: inherit; + font-style: normal; + font-variant: normal; + font-weight: normal; + font-stretch: normal; + -webkit-hyphens: none; + -ms-hyphens: none; + hyphens: none; + left: auto; + letter-spacing: normal; + list-style: none; + margin: 0; + max-height: none; + max-width: none; + min-height: 0; + min-width: 0; + opacity: 1; + outline: medium none invert; + overflow: visible; + overflow-x: visible; + overflow-y: visible; + text-align: left; + text-decoration: none; + text-indent: 0; + text-shadow: none; + text-transform: none; + top: auto; + transform: none; + transform-origin: 50% 50% 0; + transform-style: flat; + transition: none 0s ease 0s; + unicode-bidi: normal; + vertical-align: baseline; + visibility: visible; + white-space: normal; + z-index: auto; +} + +[dir=rtl] .uppy-u-reset { + text-align: right; +} + +.uppy-c-textInput { + border: 1px solid #ddd; + border-radius: 4px; + font-size: 14px; + line-height: 1.5; + padding: 6px 8px; + background-color: #fff; +} +.uppy-size--md .uppy-c-textInput { + padding: 8px 10px; +} +.uppy-c-textInput:focus { + border-color: rgba(34, 117, 215, 0.6); + outline: none; + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.15); +} +[data-uppy-theme=dark] .uppy-c-textInput { + background-color: #333; + border-color: #333; + color: #eaeaea; +} +[data-uppy-theme=dark] .uppy-c-textInput:focus { + border-color: #525252; + box-shadow: none; +} + +.uppy-c-icon { + max-width: 100%; + max-height: 100%; + fill: currentColor; + display: inline-block; + overflow: hidden; +} + +.uppy-c-btn { + display: inline-block; + text-align: center; + white-space: nowrap; + vertical-align: middle; + font-family: inherit; + font-size: 16px; + line-height: 1; + font-weight: 500; + transition-property: background-color, color; + transition-duration: 0.3s; + -webkit-user-select: none; + -ms-user-select: none; + user-select: none; +} +[dir=rtl] .uppy-c-btn { + text-align: center; +} + +.uppy-c-btn:not(:disabled):not(.disabled) { + cursor: pointer; +} + +.uppy-c-btn::-moz-focus-inner { + border: 0; +} + +.uppy-c-btn-primary { + font-size: 14px; + padding: 10px 18px; + border-radius: 4px; + background-color: #2275d7; + color: #fff; +} +.uppy-c-btn-primary:hover { + background-color: #1b5dab; +} +.uppy-c-btn-primary:focus { + outline: none; + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.4); +} +.uppy-size--md .uppy-c-btn-primary { + padding: 13px 22px; +} +[data-uppy-theme=dark] .uppy-c-btn-primary { + color: #eaeaea; +} +[data-uppy-theme=dark] .uppy-c-btn-primary:focus { + outline: none; +} +[data-uppy-theme=dark] .uppy-c-btn-primary::-moz-focus-inner { + border: 0; +} +[data-uppy-theme=dark] .uppy-c-btn-primary:focus { + box-shadow: 0 0 0 2px rgba(170, 225, 255, 0.85); +} + +.uppy-c-btn-link { + font-size: 14px; + line-height: 1; + padding: 10px 15px; + border-radius: 4px; + background-color: transparent; + color: #525252; +} +.uppy-c-btn-link:hover { + color: #333; +} +.uppy-c-btn-link:focus { + outline: none; + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.25); +} +.uppy-size--md .uppy-c-btn-link { + padding: 13px 18px; +} +[data-uppy-theme=dark] .uppy-c-btn-link { + color: #eaeaea; +} +[data-uppy-theme=dark] .uppy-c-btn-link:focus { + outline: none; +} +[data-uppy-theme=dark] .uppy-c-btn-link::-moz-focus-inner { + border: 0; +} +[data-uppy-theme=dark] .uppy-c-btn-link:focus { + box-shadow: 0 0 0 2px rgba(170, 225, 255, 0.85); +} +[data-uppy-theme=dark] .uppy-c-btn-link:hover { + color: #939393; +} + +.uppy-c-btn--small { + font-size: 0.9em; + padding: 7px 16px; + border-radius: 2px; +} +.uppy-size--md .uppy-c-btn--small { + padding: 8px 10px; + border-radius: 2px; +} + +.uppy-Informer { + position: absolute; + bottom: 60px; + left: 0; + right: 0; + text-align: center; + opacity: 1; + transform: none; + transition: all 250ms ease-in; + z-index: 1005; +} + +.uppy-Informer[aria-hidden=true] { + opacity: 0; + transform: translateY(350%); + transition: all 300ms ease-in; + z-index: -1000; +} + +.uppy-Informer p { + display: inline-block; + margin: 0; + padding: 0; + font-size: 12px; + line-height: 1.4; + font-weight: 400; + padding: 6px 15px; + background-color: #757575; + color: #fff; + border-radius: 18px; + max-width: 90%; +} +.uppy-size--md .uppy-Informer p { + font-size: 14px; + line-height: 1.3; + max-width: 500px; + padding: 10px 20px; +} +[data-uppy-theme=dark] .uppy-Informer p { + background-color: #333; +} + +[dir="ltr"] .uppy-Informer span{ + left: 3px; +} + +[dir="rtl"] .uppy-Informer span{ + right: 3px; +} + +[dir="ltr"] .uppy-Informer span{ + margin-left: -1px; +} + +[dir="rtl"] .uppy-Informer span{ + margin-right: -1px; +} + +.uppy-Informer span { + line-height: 12px; + width: 13px; + height: 13px; + display: inline-block; + vertical-align: middle; + color: #525252; + background-color: #fff; + border-radius: 50%; + position: relative; + top: -1px; + font-size: 10px; + -webkit-margin-start: -1px; +} + +.uppy-Informer span:hover { + cursor: help; +} + +.uppy-Informer span:after { + line-height: 1.3; + word-wrap: break-word; +} + +/* ------------------------------------------------------------------- + Microtip + + Modern, lightweight css-only tooltips + Just 1kb minified and gzipped + + @author Ghosh + @package Microtip + +---------------------------------------------------------------------- + 1. Base Styles + 2. Direction Modifiers + 3. Position Modifiers +--------------------------------------------------------------------*/ +/* ------------------------------------------------ + [1] Base Styles +-------------------------------------------------*/ +.uppy-Root [aria-label][role~=tooltip] { + /* no important */ + position: relative; +} + +.uppy-Root [aria-label][role~=tooltip]::before, +.uppy-Root [aria-label][role~=tooltip]::after { + /* no important */ + transform: translate3d(0, 0, 0); + -webkit-backface-visibility: hidden; + backface-visibility: hidden; + will-change: transform; + opacity: 0; + pointer-events: none; + transition: all var(--microtip-transition-duration, 0.18s) var(--microtip-transition-easing, ease-in-out) var(--microtip-transition-delay, 0s); + position: absolute; + box-sizing: border-box; + z-index: 10; + transform-origin: top; +} + +.uppy-Root [aria-label][role~=tooltip]::before { + /* no important */ + background-size: 100% auto !important; + content: ""; +} + +.uppy-Root [aria-label][role~=tooltip]::after { + /* no important */ + background: rgba(17, 17, 17, 0.9); + border-radius: 4px; + color: #ffffff; + content: attr(aria-label); + font-size: var(--microtip-font-size, 13px); + font-weight: var(--microtip-font-weight, normal); + text-transform: var(--microtip-text-transform, none); + padding: 0.5em 1em; + white-space: nowrap; + box-sizing: content-box; +} + +.uppy-Root [aria-label][role~=tooltip]:hover::before, +.uppy-Root [aria-label][role~=tooltip]:hover::after, +.uppy-Root [aria-label][role~=tooltip]:focus::before, +.uppy-Root [aria-label][role~=tooltip]:focus::after { + /* no important */ + opacity: 1; + pointer-events: auto; +} + +/* ------------------------------------------------ + [2] Position Modifiers +-------------------------------------------------*/ +.uppy-Root [role~=tooltip][data-microtip-position|=top]::before { + /* no important */ + background: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2236px%22%20height%3D%2212px%22%3E%3Cpath%20fill%3D%22rgba%2817,%2017,%2017,%200.9%29%22%20transform%3D%22rotate%280%29%22%20d%3D%22M2.658,0.000%20C-13.615,0.000%2050.938,0.000%2034.662,0.000%20C28.662,0.000%2023.035,12.002%2018.660,12.002%20C14.285,12.002%208.594,0.000%202.658,0.000%20Z%22/%3E%3C/svg%3E") no-repeat; + height: 6px; + width: 18px; + margin-bottom: 5px; +} + +.uppy-Root [role~=tooltip][data-microtip-position|=top]::after { + /* no important */ + margin-bottom: 11px; +} + +.uppy-Root [role~=tooltip][data-microtip-position|=top]::before { + /* no important */ + transform: translate3d(-50%, 0, 0); + bottom: 100%; + left: 50%; +} + +.uppy-Root [role~=tooltip][data-microtip-position|=top]:hover::before { + /* no important */ + transform: translate3d(-50%, -5px, 0); +} + +.uppy-Root [role~=tooltip][data-microtip-position|=top]::after { + /* no important */ + transform: translate3d(-50%, 0, 0); + bottom: 100%; + left: 50%; +} + +.uppy-Root [role~=tooltip][data-microtip-position=top]:hover::after { + /* no important */ + transform: translate3d(-50%, -5px, 0); +} + +/* ------------------------------------------------ + [2.1] Top Left +-------------------------------------------------*/ +.uppy-Root [role~=tooltip][data-microtip-position=top-left]::after { + /* no important */ + transform: translate3d(calc(-100% + 16px), 0, 0); + bottom: 100%; +} + +.uppy-Root [role~=tooltip][data-microtip-position=top-left]:hover::after { + /* no important */ + transform: translate3d(calc(-100% + 16px), -5px, 0); +} + +/* ------------------------------------------------ + [2.2] Top Right +-------------------------------------------------*/ +.uppy-Root [role~=tooltip][data-microtip-position=top-right]::after { + /* no important */ + transform: translate3d(calc(0% + -16px), 0, 0); + bottom: 100%; +} + +.uppy-Root [role~=tooltip][data-microtip-position=top-right]:hover::after { + /* no important */ + transform: translate3d(calc(0% + -16px), -5px, 0); +} + +/* ------------------------------------------------ + [2.3] Bottom +-------------------------------------------------*/ +.uppy-Root [role~=tooltip][data-microtip-position|=bottom]::before { + /* no important */ + background: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2236px%22%20height%3D%2212px%22%3E%3Cpath%20fill%3D%22rgba%2817,%2017,%2017,%200.9%29%22%20transform%3D%22rotate%28180%2018%206%29%22%20d%3D%22M2.658,0.000%20C-13.615,0.000%2050.938,0.000%2034.662,0.000%20C28.662,0.000%2023.035,12.002%2018.660,12.002%20C14.285,12.002%208.594,0.000%202.658,0.000%20Z%22/%3E%3C/svg%3E") no-repeat; + height: 6px; + width: 18px; + margin-top: 5px; + margin-bottom: 0; +} + +.uppy-Root [role~=tooltip][data-microtip-position|=bottom]::after { + /* no important */ + margin-top: 11px; +} + +.uppy-Root [role~=tooltip][data-microtip-position|=bottom]::before { + /* no important */ + transform: translate3d(-50%, -10px, 0); + bottom: auto; + left: 50%; + top: 100%; +} + +.uppy-Root [role~=tooltip][data-microtip-position|=bottom]:hover::before { + /* no important */ + transform: translate3d(-50%, 0, 0); +} + +.uppy-Root [role~=tooltip][data-microtip-position|=bottom]::after { + /* no important */ + transform: translate3d(-50%, -10px, 0); + top: 100%; + left: 50%; +} + +.uppy-Root [role~=tooltip][data-microtip-position=bottom]:hover::after { + /* no important */ + transform: translate3d(-50%, 0, 0); +} + +/* ------------------------------------------------ + [2.4] Bottom Left +-------------------------------------------------*/ +.uppy-Root [role~=tooltip][data-microtip-position=bottom-left]::after { + /* no important */ + transform: translate3d(calc(-100% + 16px), -10px, 0); + top: 100%; +} + +.uppy-Root [role~=tooltip][data-microtip-position=bottom-left]:hover::after { + /* no important */ + transform: translate3d(calc(-100% + 16px), 0, 0); +} + +/* ------------------------------------------------ + [2.5] Bottom Right +-------------------------------------------------*/ +.uppy-Root [role~=tooltip][data-microtip-position=bottom-right]::after { + /* no important */ + transform: translate3d(calc(0% + -16px), -10px, 0); + top: 100%; +} + +.uppy-Root [role~=tooltip][data-microtip-position=bottom-right]:hover::after { + /* no important */ + transform: translate3d(calc(0% + -16px), 0, 0); +} + +/* ------------------------------------------------ + [2.6] Left +-------------------------------------------------*/ +.uppy-Root [role~=tooltip][data-microtip-position=left]::before, +.uppy-Root [role~=tooltip][data-microtip-position=left]::after { + /* no important */ + bottom: auto; + left: auto; + right: 100%; + top: 50%; + transform: translate3d(10px, -50%, 0); +} + +.uppy-Root [role~=tooltip][data-microtip-position=left]::before { + /* no important */ + background: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2212px%22%20height%3D%2236px%22%3E%3Cpath%20fill%3D%22rgba%2817,%2017,%2017,%200.9%29%22%20transform%3D%22rotate%28-90%2018%2018%29%22%20d%3D%22M2.658,0.000%20C-13.615,0.000%2050.938,0.000%2034.662,0.000%20C28.662,0.000%2023.035,12.002%2018.660,12.002%20C14.285,12.002%208.594,0.000%202.658,0.000%20Z%22/%3E%3C/svg%3E") no-repeat; + height: 18px; + width: 6px; + margin-right: 5px; + margin-bottom: 0; +} + +.uppy-Root [role~=tooltip][data-microtip-position=left]::after { + /* no important */ + margin-right: 11px; +} + +.uppy-Root [role~=tooltip][data-microtip-position=left]:hover::before, +.uppy-Root [role~=tooltip][data-microtip-position=left]:hover::after { + /* no important */ + transform: translate3d(0, -50%, 0); +} + +/* ------------------------------------------------ + [2.7] Right +-------------------------------------------------*/ +.uppy-Root [role~=tooltip][data-microtip-position=right]::before, +.uppy-Root [role~=tooltip][data-microtip-position=right]::after { + /* no important */ + bottom: auto; + left: 100%; + top: 50%; + transform: translate3d(-10px, -50%, 0); +} + +.uppy-Root [role~=tooltip][data-microtip-position=right]::before { + /* no important */ + background: url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2212px%22%20height%3D%2236px%22%3E%3Cpath%20fill%3D%22rgba%2817,%2017,%2017,%200.9%29%22%20transform%3D%22rotate%2890%206%206%29%22%20d%3D%22M2.658,0.000%20C-13.615,0.000%2050.938,0.000%2034.662,0.000%20C28.662,0.000%2023.035,12.002%2018.660,12.002%20C14.285,12.002%208.594,0.000%202.658,0.000%20Z%22/%3E%3C/svg%3E") no-repeat; + height: 18px; + width: 6px; + margin-bottom: 0; + margin-left: 5px; +} + +.uppy-Root [role~=tooltip][data-microtip-position=right]::after { + /* no important */ + margin-left: 11px; +} + +.uppy-Root [role~=tooltip][data-microtip-position=right]:hover::before, +.uppy-Root [role~=tooltip][data-microtip-position=right]:hover::after { + /* no important */ + transform: translate3d(0, -50%, 0); +} + +/* ------------------------------------------------ + [3] Size +-------------------------------------------------*/ +.uppy-Root [role~=tooltip][data-microtip-size=small]::after { + /* no important */ + white-space: initial; + width: 80px; +} + +.uppy-Root [role~=tooltip][data-microtip-size=medium]::after { + /* no important */ + white-space: initial; + width: 150px; +} + +.uppy-Root [role~=tooltip][data-microtip-size=large]::after { + /* no important */ + white-space: initial; + width: 260px; +} + +.uppy-StatusBar { + display: -ms-flexbox; + display: flex; + position: relative; + height: 40px; + line-height: 40px; + font-size: 12px; + font-weight: 400; + color: #fff; + background-color: #fff; + z-index: 1001; + transition: height 0.2s; +} +[data-uppy-theme=dark] .uppy-StatusBar { + background-color: #1f1f1f; +} + +.uppy-size--md .uppy-StatusBar { + height: 46px; +} + +.uppy-StatusBar:before { + content: ""; + position: absolute; + left: 0; + right: 0; + top: 0; + bottom: 0; + width: 100%; + height: 2px; + background-color: #eaeaea; +} +[data-uppy-theme=dark] .uppy-StatusBar:before { + background-color: #757575; +} + +.uppy-StatusBar[aria-hidden=true] { + overflow-y: hidden; + height: 0; +} + +.uppy-StatusBar.is-complete .uppy-StatusBar-progress { + background-color: #1bb240; +} + +.uppy-StatusBar.is-error .uppy-StatusBar-progress { + background-color: #e32437; +} + +.uppy-StatusBar.is-complete .uppy-StatusBar-statusIndicator { + color: #1bb240; +} + +.uppy-StatusBar.is-error .uppy-StatusBar-statusIndicator { + color: #e32437; +} + +.uppy-StatusBar:not([aria-hidden=true]).is-waiting { + background-color: #fff; + height: 65px; + border-top: 1px solid #eaeaea; +} +[data-uppy-theme=dark] .uppy-StatusBar:not([aria-hidden=true]).is-waiting { + background-color: #1f1f1f; + border-top: 1px solid #333; +} + +.uppy-StatusBar-progress { + background-color: #2275d7; + height: 2px; + position: absolute; + z-index: 1001; + transition: background-color, width 0.3s ease-out; +} +.uppy-StatusBar-progress.is-indeterminate { + background-size: 64px 64px; + background-image: linear-gradient(45deg, rgba(0, 0, 0, 0.3) 25%, transparent 25%, transparent 50%, rgba(0, 0, 0, 0.3) 50%, rgba(0, 0, 0, 0.3) 75%, transparent 75%, transparent); + animation: uppy-StatusBar-ProgressStripes 1s linear infinite; +} + +@keyframes uppy-StatusBar-ProgressStripes { + from { + background-position: 0 0; + } + to { + background-position: 64px 0; + } +} +.uppy-StatusBar.is-preprocessing .uppy-StatusBar-progress, +.uppy-StatusBar.is-postprocessing .uppy-StatusBar-progress { + background-color: #f6a623; +} + +.uppy-StatusBar.is-waiting .uppy-StatusBar-progress { + display: none; +} + +[dir="ltr"] .uppy-StatusBar-content{ + padding-left: 10px; +} + +[dir="rtl"] .uppy-StatusBar-content{ + padding-right: 10px; +} + +.uppy-StatusBar-content { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + position: relative; + z-index: 1002; + -webkit-padding-start: 10px; + white-space: nowrap; + text-overflow: ellipsis; + color: #333; + height: 100%; +} +[dir="ltr"] .uppy-size--md .uppy-StatusBar-content{ + padding-left: 15px; +} +[dir="rtl"] .uppy-size--md .uppy-StatusBar-content{ + padding-right: 15px; +} +.uppy-size--md .uppy-StatusBar-content { + -webkit-padding-start: 15px; +} +[data-uppy-theme=dark] .uppy-StatusBar-content { + color: #eaeaea; +} + +[dir="ltr"] .uppy-StatusBar-status{ + padding-right: 0.3em; +} + +[dir="rtl"] .uppy-StatusBar-status{ + padding-left: 0.3em; +} + +.uppy-StatusBar-status { + line-height: 1.4; + font-weight: normal; + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; + -ms-flex-pack: center; + justify-content: center; + -webkit-padding-end: 0.3em; +} + +.uppy-StatusBar-statusPrimary { + font-weight: 500; + line-height: 1; +} +[data-uppy-theme=dark] .uppy-StatusBar-statusPrimary { + color: #eaeaea; +} + +.uppy-StatusBar-statusSecondary { + margin-top: 1px; + font-size: 11px; + line-height: 1.2; + display: inline-block; + color: #757575; + white-space: nowrap; +} +[data-uppy-theme=dark] .uppy-StatusBar-statusSecondary { + color: #bbb; +} + +[dir="ltr"] .uppy-StatusBar-statusSecondaryHint{ + margin-right: 5px; +} + +[dir="rtl"] .uppy-StatusBar-statusSecondaryHint{ + margin-left: 5px; +} + +.uppy-StatusBar-statusSecondaryHint { + display: inline-block; + vertical-align: middle; + -webkit-margin-end: 5px; + line-height: 1; +} +[dir="ltr"] .uppy-size--md .uppy-StatusBar-statusSecondaryHint{ + margin-right: 8px; +} +[dir="rtl"] .uppy-size--md .uppy-StatusBar-statusSecondaryHint{ + margin-left: 8px; +} +.uppy-size--md .uppy-StatusBar-statusSecondaryHint { + -webkit-margin-end: 8px; +} + +[dir="ltr"] .uppy-StatusBar-statusIndicator{ + margin-right: 7px; +} + +[dir="rtl"] .uppy-StatusBar-statusIndicator{ + margin-left: 7px; +} + +.uppy-StatusBar-statusIndicator { + position: relative; + top: 1px; + color: #525252; + -webkit-margin-end: 7px; +} +.uppy-StatusBar-statusIndicator svg { + vertical-align: text-bottom; +} + +[dir="ltr"] .uppy-StatusBar-actions{ + right: 10px; +} + +[dir="rtl"] .uppy-StatusBar-actions{ + left: 10px; +} + +.uppy-StatusBar-actions { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + position: absolute; + top: 0; + bottom: 0; + z-index: 1004; +} + +.uppy-StatusBar.is-waiting .uppy-StatusBar-actions { + width: 100%; + position: static; + padding: 0 15px; + background-color: #fafafa; +} +[data-uppy-theme=dark] .uppy-StatusBar.is-waiting .uppy-StatusBar-actions { + background-color: #1f1f1f; +} + +.uppy-StatusBar-actionCircleBtn { + line-height: 1; + cursor: pointer; + margin: 3px; + opacity: 0.9; +} +.uppy-StatusBar-actionCircleBtn:focus { + outline: none; +} +.uppy-StatusBar-actionCircleBtn::-moz-focus-inner { + border: 0; +} +.uppy-StatusBar-actionCircleBtn:focus { + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.5); +} +[data-uppy-theme=dark] .uppy-StatusBar-actionCircleBtn:focus { + outline: none; +} +[data-uppy-theme=dark] .uppy-StatusBar-actionCircleBtn::-moz-focus-inner { + border: 0; +} +[data-uppy-theme=dark] .uppy-StatusBar-actionCircleBtn:focus { + box-shadow: 0 0 0 2px rgba(170, 225, 255, 0.85); +} +.uppy-StatusBar-actionCircleBtn:hover { + opacity: 1; +} +.uppy-StatusBar-actionCircleBtn:focus { + border-radius: 50%; +} + +.uppy-StatusBar-actionCircleBtn svg { + vertical-align: bottom; +} + +.uppy-StatusBar-actionBtn { + display: inline-block; + vertical-align: middle; + font-size: 10px; + line-height: inherit; + color: #2275d7; +} +.uppy-size--md .uppy-StatusBar-actionBtn { + font-size: 11px; +} + +[dir="ltr"] .uppy-StatusBar-actionBtn--retry{ + margin-right: 6px; +} + +[dir="rtl"] .uppy-StatusBar-actionBtn--retry{ + margin-left: 6px; +} + +.uppy-StatusBar-actionBtn--retry { + height: 16px; + border-radius: 8px; + -webkit-margin-end: 6px; + background-color: #ff4b23; + line-height: 1; + color: #fff; + padding: 1px 6px 3px 18px; + position: relative; +} +.uppy-StatusBar-actionBtn--retry:focus { + outline: none; +} +.uppy-StatusBar-actionBtn--retry::-moz-focus-inner { + border: 0; +} +.uppy-StatusBar-actionBtn--retry:focus { + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.5); +} +[data-uppy-theme=dark] .uppy-StatusBar-actionBtn--retry:focus { + outline: none; +} +[data-uppy-theme=dark] .uppy-StatusBar-actionBtn--retry::-moz-focus-inner { + border: 0; +} +[data-uppy-theme=dark] .uppy-StatusBar-actionBtn--retry:focus { + box-shadow: 0 0 0 2px rgba(170, 225, 255, 0.85); +} +.uppy-StatusBar-actionBtn--retry:hover { + background-color: #f92d00; +} +[dir="ltr"] .uppy-StatusBar-actionBtn--retry svg{ + left: 6px; +} +[dir="rtl"] .uppy-StatusBar-actionBtn--retry svg{ + right: 6px; +} +.uppy-StatusBar-actionBtn--retry svg { + position: absolute; + top: 3px; +} + +.uppy-StatusBar.is-waiting .uppy-StatusBar-actionBtn--upload { + font-size: 14px; + width: 100%; + padding: 15px 10px; + color: #fff; + background-color: #1bb240; + line-height: 1; +} +.uppy-StatusBar.is-waiting .uppy-StatusBar-actionBtn--upload:hover { + background-color: #189c38; +} +[data-uppy-theme=dark] .uppy-StatusBar.is-waiting .uppy-StatusBar-actionBtn--upload { + background-color: #1c8b37; +} +[data-uppy-theme=dark] .uppy-StatusBar.is-waiting .uppy-StatusBar-actionBtn--upload:hover { + background-color: #18762f; +} + +.uppy-size--md .uppy-StatusBar.is-waiting .uppy-StatusBar-actionBtn--upload { + padding: 13px 22px; + width: auto; +} + +.uppy-StatusBar:not(.is-waiting) .uppy-StatusBar-actionBtn--upload { + background-color: transparent; + color: #2275d7; +} + +[dir="ltr"] .uppy-StatusBar-actionBtn--uploadNewlyAdded{ + padding-right: 3px; +} + +[dir="rtl"] .uppy-StatusBar-actionBtn--uploadNewlyAdded{ + padding-left: 3px; +} + +[dir="ltr"] .uppy-StatusBar-actionBtn--uploadNewlyAdded{ + padding-left: 3px; +} + +[dir="rtl"] .uppy-StatusBar-actionBtn--uploadNewlyAdded{ + padding-right: 3px; +} + +.uppy-StatusBar-actionBtn--uploadNewlyAdded { + -webkit-padding-end: 3px; + -webkit-padding-start: 3px; + padding-bottom: 1px; + border-radius: 3px; +} +.uppy-StatusBar-actionBtn--uploadNewlyAdded:focus { + outline: none; +} +.uppy-StatusBar-actionBtn--uploadNewlyAdded::-moz-focus-inner { + border: 0; +} +.uppy-StatusBar-actionBtn--uploadNewlyAdded:focus { + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.5); +} +[data-uppy-theme=dark] .uppy-StatusBar-actionBtn--uploadNewlyAdded:focus { + outline: none; +} +[data-uppy-theme=dark] .uppy-StatusBar-actionBtn--uploadNewlyAdded::-moz-focus-inner { + border: 0; +} +[data-uppy-theme=dark] .uppy-StatusBar-actionBtn--uploadNewlyAdded:focus { + box-shadow: 0 0 0 2px rgba(170, 225, 255, 0.85); +} + +.uppy-StatusBar-actionBtn--done { + line-height: 1; + border-radius: 3px; + padding: 7px 8px; +} +.uppy-StatusBar-actionBtn--done:focus { + outline: none; +} +.uppy-StatusBar-actionBtn--done::-moz-focus-inner { + border: 0; +} +.uppy-StatusBar-actionBtn--done:hover { + color: #1b5dab; +} +.uppy-StatusBar-actionBtn--done:focus { + background-color: #eceef2; +} +[data-uppy-theme=dark] .uppy-StatusBar-actionBtn--done:focus { + background-color: #333; +} +[data-uppy-theme=dark] .uppy-StatusBar-actionBtn--done { + color: #02baf2; +} + +.uppy-size--md .uppy-StatusBar-actionBtn--done { + font-size: 14px; +} + +[dir="ltr"] .uppy-StatusBar-details{ + left: 2px; +} + +[dir="rtl"] .uppy-StatusBar-details{ + right: 2px; +} + +.uppy-StatusBar-details { + line-height: 12px; + width: 13px; + height: 13px; + display: inline-block; + vertical-align: middle; + color: #fff; + background-color: #939393; + border-radius: 50%; + position: relative; + top: 0; + font-size: 10px; + font-weight: 600; + text-align: center; + cursor: help; +} + +.uppy-StatusBar-details:after { + line-height: 1.3; + word-wrap: break-word; +} + +[dir="ltr"] .uppy-StatusBar-spinner{ + margin-right: 10px; +} + +[dir="rtl"] .uppy-StatusBar-spinner{ + margin-left: 10px; +} + +.uppy-StatusBar-spinner { + animation-name: uppy-StatusBar-spinnerAnimation; + animation-duration: 1s; + animation-iteration-count: infinite; + animation-timing-function: linear; + -webkit-margin-end: 10px; + fill: #2275d7; +} + +.uppy-StatusBar.is-preprocessing .uppy-StatusBar-spinner, +.uppy-StatusBar.is-postprocessing .uppy-StatusBar-spinner { + fill: #f6a623; +} + +@keyframes uppy-StatusBar-spinnerAnimation { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} +.uppy-ProviderBrowser-viewType--grid ul.uppy-ProviderBrowser-list { + display: -ms-flexbox; + display: flex; + -ms-flex-direction: row; + flex-direction: row; + -ms-flex-wrap: wrap; + flex-wrap: wrap; + -ms-flex-pack: justify; + justify-content: space-between; + -ms-flex-align: start; + align-items: flex-start; + padding: 6px; +} +.uppy-ProviderBrowser-viewType--grid ul.uppy-ProviderBrowser-list::after { + content: ""; + -ms-flex: auto; + flex: auto; +} +.uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem { + width: 50%; + position: relative; + margin: 0; +} +.uppy-size--md .uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem { + width: 33.3333%; +} +.uppy-size--lg .uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem { + width: 25%; +} +.uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem::before { + content: ""; + padding-top: 100%; + display: block; +} +.uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem--selected img, .uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem--selected svg { + opacity: 0.85; +} +.uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem--disabled { + opacity: 0.5; +} +.uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem--noPreview .uppy-ProviderBrowserItem-inner { + background-color: rgba(147, 147, 147, 0.2); +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem--noPreview .uppy-ProviderBrowserItem-inner { + background-color: rgba(234, 234, 234, 0.2); +} +.uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem--noPreview svg { + fill: rgba(0, 0, 0, 0.7); + width: 30%; + height: 30%; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-viewType--grid li.uppy-ProviderBrowserItem--noPreview svg { + fill: rgba(255, 255, 255, 0.8); +} +.uppy-ProviderBrowser-viewType--grid button.uppy-ProviderBrowserItem-inner { + border-radius: 4px; + overflow: hidden; + position: absolute; + top: 7px; + left: 7px; + right: 7px; + bottom: 7px; + text-align: center; + width: calc(100% - 14px); + height: calc(100% - 14px); +} +.uppy-ProviderBrowser-viewType--grid button.uppy-ProviderBrowserItem-inner:focus { + outline: none; + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.9); +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-viewType--grid button.uppy-ProviderBrowserItem-inner { + box-shadow: 0 0 0 3px rgba(170, 225, 255, 0.7); +} +.uppy-ProviderBrowser-viewType--grid button.uppy-ProviderBrowserItem-inner img { + width: 100%; + height: 100%; + object-fit: cover; + border-radius: 4px; +} +.uppy-ProviderBrowser-viewType--grid .uppy-ProviderBrowserItem-fakeCheckbox { + position: absolute; + top: 16px; + right: 16px; + width: 26px; + height: 26px; + background-color: #2275d7; + border-radius: 50%; + z-index: 1002; + opacity: 0; +} +[dir="ltr"] .uppy-ProviderBrowser-viewType--grid .uppy-ProviderBrowserItem-fakeCheckbox:after{ + left: 7px; +} +[dir="rtl"] .uppy-ProviderBrowser-viewType--grid .uppy-ProviderBrowserItem-fakeCheckbox:after{ + right: 7px; +} +.uppy-ProviderBrowser-viewType--grid .uppy-ProviderBrowserItem-fakeCheckbox:after { + width: 12px; + height: 7px; + top: 8px; +} +.uppy-ProviderBrowser-viewType--grid .uppy-ProviderBrowserItem-fakeCheckbox--is-checked { + opacity: 1; +} + +.uppy-ProviderBrowser-viewType--list { + background-color: #fff; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-viewType--list { + background-color: #1f1f1f; +} +.uppy-ProviderBrowser-viewType--list li.uppy-ProviderBrowserItem { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + padding: 7px 15px; + margin: 0; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-viewType--list li.uppy-ProviderBrowserItem { + color: #eaeaea; +} +.uppy-ProviderBrowser-viewType--list li.uppy-ProviderBrowserItem--disabled { + opacity: 0.6; +} +[dir="ltr"] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-fakeCheckbox{ + margin-right: 15px; +} +[dir="rtl"] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-fakeCheckbox{ + margin-left: 15px; +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-fakeCheckbox { + -webkit-margin-end: 15px; + height: 17px; + width: 17px; + border-radius: 3px; + background-color: #fff; + border: 1px solid #cfcfcf; +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-fakeCheckbox:focus { + border: 1px solid #2275d7; + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.25); + outline: none; +} +[dir="ltr"] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-fakeCheckbox::after{ + left: 3px; +} +[dir="rtl"] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-fakeCheckbox::after{ + right: 3px; +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-fakeCheckbox::after { + opacity: 0; + height: 5px; + width: 9px; + top: 4px; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-fakeCheckbox:focus { + border-color: rgba(2, 186, 242, 0.7); + box-shadow: 0 0 0 3px rgba(2, 186, 242, 0.2); +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-fakeCheckbox--is-checked { + background-color: #2275d7; + border-color: #2275d7; +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-fakeCheckbox--is-checked::after { + opacity: 1; +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-inner { + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + padding: 2px; +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-inner:focus { + outline: none; + text-decoration: underline; +} +[dir="ltr"] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-inner img,[dir="ltr"] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-inner svg{ + margin-right: 8px; +} +[dir="rtl"] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-inner img,[dir="rtl"] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-inner svg{ + margin-left: 8px; +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-inner img, .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-inner svg { + -webkit-margin-end: 8px; + max-width: 20px; + max-height: 20px; +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-inner span { + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem--disabled .uppy-ProviderBrowserItem-inner { + cursor: default; +} +[dir="ltr"] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-iconWrap{ + margin-right: 7px; +} +[dir="rtl"] .uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-iconWrap{ + margin-left: 7px; +} +.uppy-ProviderBrowser-viewType--list .uppy-ProviderBrowserItem-iconWrap { + width: 20px; + -webkit-margin-end: 7px; +} + +.uppy-ProviderBrowserItem-fakeCheckbox { + position: relative; + cursor: pointer; + -ms-flex-negative: 0; + flex-shrink: 0; +} +.uppy-ProviderBrowserItem-fakeCheckbox:disabled { + cursor: default; +} +.uppy-ProviderBrowserItem-fakeCheckbox::after { + content: ""; + position: absolute; + cursor: pointer; + border-left: 2px solid #eaeaea; + border-bottom: 2px solid #eaeaea; + transform: rotate(-45deg); +} +.uppy-ProviderBrowserItem-fakeCheckbox:disabled::after { + cursor: default; +} +[data-uppy-theme=dark] .uppy-ProviderBrowserItem-fakeCheckbox { + background-color: #1f1f1f; + border-color: #939393; +} + +[data-uppy-theme=dark] .uppy-ProviderBrowserItem-fakeCheckbox--is-checked { + background-color: #333; +} + +.uppy-SearchProvider { + width: 100%; + height: 100%; + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; + -ms-flex-pack: center; + justify-content: center; + -ms-flex-align: center; + align-items: center; + -ms-flex: 1; + flex: 1; +} +[data-uppy-theme=dark] .uppy-SearchProvider { + background-color: #1f1f1f; +} + +.uppy-SearchProvider-input { + width: 90%; + max-width: 650px; + margin-bottom: 15px; +} +.uppy-size--md .uppy-SearchProvider-input { + margin-bottom: 20px; +} + +.uppy-SearchProvider-searchButton { + padding: 13px 25px; +} +.uppy-size--md .uppy-SearchProvider-searchButton { + padding: 13px 30px; +} + +.uppy-DashboardContent-panelBody { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: center; + justify-content: center; + -ms-flex: 1; + flex: 1; +} +[data-uppy-theme=dark] .uppy-DashboardContent-panelBody { + background-color: #1f1f1f; +} + +.uppy-Provider-auth, +.uppy-Provider-error, +.uppy-Provider-loading, +.uppy-Provider-empty { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: center; + justify-content: center; + -ms-flex-flow: column wrap; + flex-flow: column wrap; + -ms-flex: 1; + flex: 1; + color: #939393; +} + +.uppy-Provider-empty { + color: #939393; +} + +.uppy-Provider-authIcon svg { + width: 100px; + height: 75px; + margin-bottom: 15px; +} + +.uppy-Provider-authTitle { + font-size: 17px; + line-height: 1.4; + font-weight: 400; + margin-bottom: 30px; + padding: 0 15px; + max-width: 500px; + text-align: center; + color: #757575; +} +.uppy-size--md .uppy-Provider-authTitle { + font-size: 20px; +} +[data-uppy-theme=dark] .uppy-Provider-authTitle { + color: #cfcfcf; +} + +[dir="ltr"] .uppy-Provider-breadcrumbs{ + text-align: left; +} + +[dir="rtl"] .uppy-Provider-breadcrumbs{ + text-align: right; +} + +.uppy-Provider-breadcrumbs { + -ms-flex: 1; + flex: 1; + color: #525252; + font-size: 12px; + margin-bottom: 10px; +} +.uppy-size--md .uppy-Provider-breadcrumbs { + margin-bottom: 0; +} +[data-uppy-theme=dark] .uppy-Provider-breadcrumbs { + color: #eaeaea; +} + +[dir="ltr"] .uppy-Provider-breadcrumbsIcon{ + margin-right: 4px; +} + +[dir="rtl"] .uppy-Provider-breadcrumbsIcon{ + margin-left: 4px; +} + +.uppy-Provider-breadcrumbsIcon { + display: inline-block; + color: #525252; + vertical-align: middle; + -webkit-margin-end: 4px; + line-height: 1; +} + +.uppy-Provider-breadcrumbsIcon svg { + width: 13px; + height: 13px; + fill: #525252; +} + +.uppy-Provider-breadcrumbs button { + display: inline-block; + line-height: inherit; + padding: 4px; + border-radius: 3px; +} +.uppy-Provider-breadcrumbs button:focus { + outline: none; +} +.uppy-Provider-breadcrumbs button::-moz-focus-inner { + border: 0; +} +.uppy-Provider-breadcrumbs button:hover { + color: #1b5dab; +} +.uppy-Provider-breadcrumbs button:focus { + background-color: #eceef2; +} +[data-uppy-theme=dark] .uppy-Provider-breadcrumbs button:focus { + background-color: #333; +} +.uppy-Provider-breadcrumbs button:hover { + text-decoration: underline; + cursor: pointer; +} +[data-uppy-theme=dark] .uppy-Provider-breadcrumbs button { + color: #eaeaea; +} + +.uppy-ProviderBrowser { + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; + -ms-flex: 1; + flex: 1; + font-size: 14px; + font-weight: 400; + height: 100%; +} + +.uppy-ProviderBrowser-user { + margin: 0 8px 0 0; + font-weight: 500; + color: #333; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-user { + color: #eaeaea; +} + +[dir="ltr"] .uppy-ProviderBrowser-user:after{ + left: 4px; +} + +[dir="rtl"] .uppy-ProviderBrowser-user:after{ + right: 4px; +} + +.uppy-ProviderBrowser-user:after { + content: "·"; + position: relative; + color: #939393; + font-weight: normal; +} + +.uppy-ProviderBrowser-header { + z-index: 1001; + border-bottom: 1px solid #eaeaea; + position: relative; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-header { + border-bottom: 1px solid #333; +} + +.uppy-ProviderBrowser-headerBar { + padding: 7px 15px; + background-color: #fafafa; + z-index: 1001; + color: #757575; + line-height: 1.4; + font-size: 12px; +} +.uppy-size--md .uppy-ProviderBrowser-headerBar { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-headerBar { + background-color: #1f1f1f; +} + +.uppy-ProviderBrowser-headerBar--simple { + text-align: center; + display: block; + -ms-flex-pack: center; + justify-content: center; +} + +.uppy-ProviderBrowser-headerBar--simple .uppy-Provider-breadcrumbsWrap { + -ms-flex: none; + flex: none; + display: inline-block; + vertical-align: middle; +} + +.uppy-ProviderBrowser-search { + width: 100%; + background-color: #fff; + position: relative; + height: 30px; + margin-top: 10px; + margin-bottom: 5px; + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-search { + background-color: #1f1f1f; +} + +[dir="ltr"] .uppy-ProviderBrowser-searchIcon{ + left: 16px; +} + +[dir="rtl"] .uppy-ProviderBrowser-searchIcon{ + right: 16px; +} + +.uppy-ProviderBrowser-searchIcon { + position: absolute; + width: 12px; + height: 12px; + z-index: 1002; + color: #bbb; +} + +[dir="ltr"] .uppy-ProviderBrowser-searchInput{ + padding-left: 27px; +} + +[dir="rtl"] .uppy-ProviderBrowser-searchInput{ + padding-right: 27px; +} + +.uppy-ProviderBrowser-searchInput { + width: 100%; + height: 30px; + background-color: transparent; + outline: 0; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; + font-size: 12px; + line-height: 1.4; + border: 0; + margin: 0 8px; + -webkit-padding-start: 27px; + z-index: 1001; + border-radius: 4px; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-searchInput { + background-color: #1f1f1f; + color: #eaeaea; +} + +.uppy-ProviderBrowser-searchInput:focus { + outline: 0; + background-color: #f4f4f4; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-searchInput:focus { + background-color: #333; +} + +[dir="ltr"] .uppy-ProviderBrowser-searchClose{ + right: 12px; +} + +[dir="rtl"] .uppy-ProviderBrowser-searchClose{ + left: 12px; +} + +.uppy-ProviderBrowser-searchClose { + position: absolute; + width: 22px; + height: 22px; + padding: 6px; + top: 4px; + z-index: 1002; + color: #939393; + cursor: pointer; +} +.uppy-ProviderBrowser-searchClose:hover { + color: #757575; +} + +.uppy-ProviderBrowser-searchClose svg { + vertical-align: text-top; +} + +.uppy-ProviderBrowser-searchInput:-ms-input-placeholder { + color: #939393; + opacity: 1; +} + +.uppy-ProviderBrowser-searchInput::placeholder { + color: #939393; + opacity: 1; +} + +.uppy-ProviderBrowser-userLogout { + cursor: pointer; + line-height: inherit; + color: #2275d7; + padding: 4px; + border-radius: 3px; +} +.uppy-ProviderBrowser-userLogout:focus { + outline: none; +} +.uppy-ProviderBrowser-userLogout::-moz-focus-inner { + border: 0; +} +.uppy-ProviderBrowser-userLogout:hover { + color: #1b5dab; +} +.uppy-ProviderBrowser-userLogout:focus { + background-color: #eceef2; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-userLogout:focus { + background-color: #333; +} +.uppy-ProviderBrowser-userLogout:hover { + text-decoration: underline; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-userLogout { + color: #eaeaea; +} + +.uppy-ProviderBrowser-body { + -ms-flex: 1; + flex: 1; + position: relative; +} + +.uppy-ProviderBrowser-list { + -ms-flex: 1; + flex: 1; + position: relative; + display: block; + width: 100%; + height: 100%; + background-color: #fff; + border-spacing: 0; + overflow-x: hidden; + overflow-y: auto; + -webkit-overflow-scrolling: touch; + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + list-style: none; + margin: 0; + padding: 0; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-list { + background-color: #1f1f1f; +} +.uppy-ProviderBrowser-list:focus { + outline: none; +} + +.uppy-ProviderBrowserItem-inner { + cursor: pointer; + font-weight: 500; + font-size: 13px; +} + +.uppy-ProviderBrowser-footer { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + background-color: #fff; + height: 65px; + border-top: 1px solid #eaeaea; + padding: 0 15px; +} +[dir="ltr"] .uppy-ProviderBrowser-footer button{ + margin-right: 8px; +} +[dir="rtl"] .uppy-ProviderBrowser-footer button{ + margin-left: 8px; +} +.uppy-ProviderBrowser-footer button { + -webkit-margin-end: 8px; +} +[data-uppy-theme=dark] .uppy-ProviderBrowser-footer { + background-color: #1f1f1f; + border-top: 1px solid #333; +} + +.uppy-Dashboard-Item-previewInnerWrap { + width: 100%; + height: 100%; + overflow: hidden; + position: relative; + display: -ms-flexbox; + display: flex; + -ms-flex-pack: center; + justify-content: center; + -ms-flex-align: center; + align-items: center; + -ms-flex-direction: column; + flex-direction: column; + box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.4); + border-radius: 3px; +} +.uppy-size--md .uppy-Dashboard-Item-previewInnerWrap { + box-shadow: 0 1px 2px rgba(0, 0, 0, 0.15); +} + +.uppy-Dashboard-Item-previewInnerWrap:after { + content: ""; + position: absolute; + left: 0; + right: 0; + top: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.65); + display: none; + z-index: 1001; +} + +.uppy-Dashboard-Item-previewLink { + position: absolute; + left: 0; + right: 0; + top: 0; + bottom: 0; + z-index: 1002; +} +.uppy-Dashboard-Item-previewLink:focus { + box-shadow: inset 0 0 0 3px #76abe9; +} +[data-uppy-theme=dark] .uppy-Dashboard-Item-previewLink:focus { + box-shadow: inset 0 0 0 3px #016c8d; +} + +.uppy-Dashboard-Item-preview img.uppy-Dashboard-Item-previewImg { + width: 100%; + height: 100%; + object-fit: cover; + transform: translateZ(0); + border-radius: 3px; +} + +.uppy-Dashboard-Item-progress { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + z-index: 1002; + color: #fff; + text-align: center; + width: 120px; + transition: all 0.35 ease; +} + +.uppy-Dashboard-Item-progressIndicator { + display: inline-block; + width: 38px; + height: 38px; + opacity: 0.9; +} +.uppy-size--md .uppy-Dashboard-Item-progressIndicator { + width: 55px; + height: 55px; +} + +button.uppy-Dashboard-Item-progressIndicator { + cursor: pointer; +} +button.uppy-Dashboard-Item-progressIndicator:focus { + outline: none; +} +button.uppy-Dashboard-Item-progressIndicator::-moz-focus-inner { + border: 0; +} +button.uppy-Dashboard-Item-progressIndicator:focus .uppy-Dashboard-Item-progressIcon--bg, +button.uppy-Dashboard-Item-progressIndicator:focus .uppy-Dashboard-Item-progressIcon--retry { + fill: #76abe9; +} + +.uppy-Dashboard-Item-progressIcon--circle { + width: 100%; + height: 100%; +} + +.uppy-Dashboard-Item-progressIcon--bg { + stroke: rgba(255, 255, 255, 0.4); +} + +.uppy-Dashboard-Item-progressIcon--progress { + stroke: #fff; + transition: stroke-dashoffset 0.5s ease-out; +} + +.uppy-Dashboard-Item-progressIcon--play { + stroke: #fff; + fill: #fff; + transition: all 0.2s; +} + +.uppy-Dashboard-Item-progressIcon--cancel { + fill: #fff; + transition: all 0.2s; +} + +.uppy-Dashboard-Item-progressIcon--pause { + stroke: #fff; + fill: #fff; + transition: all 0.2s; +} + +.uppy-Dashboard-Item-progressIcon--check { + fill: #fff; + transition: all 0.2s; +} + +.uppy-Dashboard-Item-progressIcon--retry { + fill: #fff; +} + +[dir="ltr"] .uppy-Dashboard-Item.is-complete .uppy-Dashboard-Item-progress{ + right: -8px; +} + +[dir="rtl"] .uppy-Dashboard-Item.is-complete .uppy-Dashboard-Item-progress{ + left: -8px; +} + +[dir="ltr"] .uppy-Dashboard-Item.is-complete .uppy-Dashboard-Item-progress{ + left: initial; +} + +[dir="rtl"] .uppy-Dashboard-Item.is-complete .uppy-Dashboard-Item-progress{ + right: initial; +} + +.uppy-Dashboard-Item.is-complete .uppy-Dashboard-Item-progress { + transform: initial; + top: -9px; + width: auto; +} + +.uppy-Dashboard-Item.is-error .uppy-Dashboard-Item-progressIndicator { + width: 18px; + height: 18px; +} +.uppy-size--md .uppy-Dashboard-Item.is-error .uppy-Dashboard-Item-progressIndicator { + width: 28px; + height: 28px; +} + +.uppy-Dashboard-Item.is-complete .uppy-Dashboard-Item-progressIndicator { + width: 18px; + height: 18px; + opacity: 1; +} +.uppy-size--md .uppy-Dashboard-Item.is-complete .uppy-Dashboard-Item-progressIndicator { + width: 22px; + height: 22px; +} + +.uppy-Dashboard-Item.is-processing .uppy-Dashboard-Item-progress { + opacity: 0; +} + +[dir="ltr"] .uppy-Dashboard-Item-fileInfo{ + padding-right: 5px; +} + +[dir="rtl"] .uppy-Dashboard-Item-fileInfo{ + padding-left: 5px; +} + +.uppy-Dashboard-Item-fileInfo { + -webkit-padding-end: 5px; +} + +.uppy-Dashboard-Item-name { + font-size: 12px; + line-height: 1.3; + font-weight: 500; + margin-bottom: 4px; + word-break: break-all; + word-wrap: anywhere; +} +[data-uppy-theme=dark] .uppy-Dashboard-Item-name { + color: #eaeaea; +} + +.uppy-Dashboard-Item-status { + font-size: 11px; + line-height: 1.3; + font-weight: normal; + color: #757575; +} +[data-uppy-theme=dark] .uppy-Dashboard-Item-status { + color: #bbb; +} + +.uppy-Dashboard-Item-statusSize { + display: inline-block; + vertical-align: bottom; + text-transform: uppercase; +} + +.uppy-Dashboard-Item-sourceIcon { + display: none; + vertical-align: bottom; + color: #bbb; +} +[dir="ltr"] .uppy-Dashboard-Item-sourceIcon:not(:first-child){ + margin-left: 14px; +} +[dir="rtl"] .uppy-Dashboard-Item-sourceIcon:not(:first-child){ + margin-right: 14px; +} +.uppy-Dashboard-Item-sourceIcon:not(:first-child) { + position: relative; + -webkit-margin-start: 14px; +} +.uppy-Dashboard-Item-sourceIcon svg, +.uppy-Dashboard-Item-sourceIcon svg * { + max-width: 100%; + max-height: 100%; + display: inline-block; + vertical-align: text-bottom; + overflow: hidden; + fill: currentColor; + width: 11px; + height: 12px; +} + +.uppy-Dashboard-Item-action { + cursor: pointer; + color: #939393; +} +.uppy-Dashboard-Item-action:focus { + outline: none; +} +.uppy-Dashboard-Item-action::-moz-focus-inner { + border: 0; +} +.uppy-Dashboard-Item-action:focus { + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.5); +} +.uppy-Dashboard-Item-action:hover { + opacity: 1; + color: #1f1f1f; +} +[data-uppy-theme=dark] .uppy-Dashboard-Item-action { + color: #cfcfcf; +} +[data-uppy-theme=dark] .uppy-Dashboard-Item-action:focus { + outline: none; +} +[data-uppy-theme=dark] .uppy-Dashboard-Item-action::-moz-focus-inner { + border: 0; +} +[data-uppy-theme=dark] .uppy-Dashboard-Item-action:focus { + box-shadow: 0 0 0 2px rgba(170, 225, 255, 0.85); +} +[data-uppy-theme=dark] .uppy-Dashboard-Item-action:hover { + color: #eaeaea; +} + +.uppy-Dashboard-Item-action--remove { + color: #1f1f1f; + opacity: 0.95; +} +.uppy-Dashboard-Item-action--remove:hover { + opacity: 1; + color: #000; +} +[data-uppy-theme=dark] .uppy-Dashboard-Item-action--remove { + color: #525252; +} +[data-uppy-theme=dark] .uppy-Dashboard-Item-action--remove:hover { + color: #333; +} + +.uppy-Dashboard:not(.uppy-size--md) .uppy-Dashboard-Item-actionWrapper { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; +} +.uppy-Dashboard:not(.uppy-size--md) .uppy-Dashboard-Item-action { + width: 22px; + height: 22px; + padding: 3px; + margin-left: 3px; +} +.uppy-Dashboard:not(.uppy-size--md) .uppy-Dashboard-Item-action:focus { + border-radius: 3px; +} + +.uppy-size--md .uppy-Dashboard-Item-action--copyLink, +.uppy-size--md .uppy-Dashboard-Item-action--edit { + width: 16px; + height: 16px; + padding: 0; +} +.uppy-size--md .uppy-Dashboard-Item-action--copyLink:focus, +.uppy-size--md .uppy-Dashboard-Item-action--edit:focus { + border-radius: 3px; +} +[dir="ltr"] .uppy-size--md .uppy-Dashboard-Item-action--remove{ + right: -8px; +} +[dir="rtl"] .uppy-size--md .uppy-Dashboard-Item-action--remove{ + left: -8px; +} +.uppy-size--md .uppy-Dashboard-Item-action--remove { + z-index: 1002; + position: absolute; + top: -8px; + width: 18px; + height: 18px; + padding: 0; +} +.uppy-size--md .uppy-Dashboard-Item-action--remove:focus { + border-radius: 50%; +} + +[dir="ltr"] .uppy-Dashboard-Item{ + padding-right: 0; +} + +[dir="rtl"] .uppy-Dashboard-Item{ + padding-left: 0; +} + +.uppy-Dashboard-Item { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + border-bottom: 1px solid #eaeaea; + padding: 10px; + -webkit-padding-end: 0; +} +[data-uppy-theme=dark] .uppy-Dashboard-Item { + border-bottom: 1px solid #333; +} +[dir="ltr"] .uppy-size--md .uppy-Dashboard-Item{ + float: left; +} +[dir="rtl"] .uppy-size--md .uppy-Dashboard-Item{ + float: right; +} +.uppy-size--md .uppy-Dashboard-Item { + position: relative; + display: block; + margin: 5px 15px; + padding: 0; + /* When changing width: also update `itemsPerRow` values in `src/components/Dashboard.js`. */ + width: calc(33.333% - 15px - 15px); + height: 215px; + border-bottom: 0; +} +.uppy-size--lg .uppy-Dashboard-Item { + margin: 5px 15px; + /* When changing width: also update `itemsPerRow` values in `src/components/Dashboard.js`. */ + width: calc(25% - 15px - 15px); + height: 190px; +} +.uppy-size--xl .uppy-Dashboard-Item { + /* When changing width: also update `itemsPerRow` values in `src/components/Dashboard.js`. */ + width: calc(20% - 15px - 15px); + height: 210px; +} + +.uppy-Dashboard-Item-preview { + position: relative; +} +.uppy-Dashboard:not(.uppy-size--md) .uppy-Dashboard-Item-preview { + -ms-flex-negative: 0; + flex-shrink: 0; + -ms-flex-positive: 0; + flex-grow: 0; + width: 50px; + height: 50px; +} +.uppy-size--md .uppy-Dashboard-Item-preview { + width: 100%; + height: 140px; +} +.uppy-size--lg .uppy-Dashboard-Item-preview { + height: 120px; +} +.uppy-size--xl .uppy-Dashboard-Item-preview { + height: 140px; +} + +[dir="ltr"] .uppy-Dashboard-Item-fileInfoAndButtons{ + padding-right: 8px; +} + +[dir="rtl"] .uppy-Dashboard-Item-fileInfoAndButtons{ + padding-left: 8px; +} + +[dir="ltr"] .uppy-Dashboard-Item-fileInfoAndButtons{ + padding-left: 12px; +} + +[dir="rtl"] .uppy-Dashboard-Item-fileInfoAndButtons{ + padding-right: 12px; +} + +.uppy-Dashboard-Item-fileInfoAndButtons { + -ms-flex-positive: 1; + flex-grow: 1; + -webkit-padding-end: 8px; + -webkit-padding-start: 12px; + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: justify; + justify-content: space-between; +} +.uppy-size--md .uppy-Dashboard-Item-fileInfoAndButtons { + -ms-flex-align: start; + align-items: flex-start; + width: 100%; + padding: 0; + padding-top: 9px; +} + +.uppy-Dashboard-Item-fileInfo { + -ms-flex-positive: 1; + flex-grow: 1; + -ms-flex-negative: 1; + flex-shrink: 1; +} + +.uppy-Dashboard-Item-actionWrapper { + -ms-flex-positive: 0; + flex-grow: 0; + -ms-flex-negative: 0; + flex-shrink: 0; +} + +.uppy-Dashboard-Item.is-inprogress .uppy-Dashboard-Item-previewInnerWrap:after, +.uppy-Dashboard-Item.is-error .uppy-Dashboard-Item-previewInnerWrap:after { + display: block; +} + +.uppy-Dashboard-Item.is-inprogress:not(.is-resumable) .uppy-Dashboard-Item-action--remove { + display: none; +} + +[dir="ltr"] .uppy-Dashboard-Item-errorDetails{ + left: 6px; +} + +[dir="rtl"] .uppy-Dashboard-Item-errorDetails{ + right: 6px; +} + +.uppy-Dashboard-Item-errorDetails { + line-height: 12px; + width: 12px; + height: 12px; + display: inline-block; + vertical-align: middle; + color: #fff; + background-color: #939393; + border-radius: 50%; + position: relative; + top: -1px; + font-size: 8px; + font-weight: 600; + text-align: center; + cursor: help; +} + +.uppy-Dashboard-Item-errorDetails:after { + line-height: 1.3; + word-wrap: break-word; +} + +.uppy-Dashboard-FileCard { + width: 100%; + height: 100%; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + z-index: 1005; + box-shadow: 0px 0px 10px 4px rgba(0, 0, 0, 0.1); + background-color: #fff; + border-radius: 5px; + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; +} +.uppy-Dashboard-FileCard .uppy-DashboardContent-bar { + border-top-left-radius: 5px; + border-top-right-radius: 5px; +} +.uppy-Dashboard-FileCard .uppy-Dashboard-FileCard-actions { + border-bottom-left-radius: 5px; + border-bottom-right-radius: 5px; +} + +.uppy-Dashboard-FileCard-inner { + height: 100%; + -ms-flex-positive: 1; + flex-grow: 1; + -ms-flex-negative: 1; + flex-shrink: 1; + min-height: 0; + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; +} + +.uppy-Dashboard-FileCard-preview { + height: 60%; + -ms-flex-positive: 0; + flex-grow: 0; + -ms-flex-negative: 1; + flex-shrink: 1; + min-height: 0; + border-bottom: 1px solid #eaeaea; + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: center; + justify-content: center; + position: relative; +} +[data-uppy-theme=dark] .uppy-Dashboard-FileCard-preview { + background-color: #333; + border-bottom: 0; +} + +.uppy-Dashboard-FileCard-preview img.uppy-Dashboard-Item-previewImg { + max-width: 90%; + max-height: 90%; + object-fit: cover; + -ms-flex: 0 0 auto; + flex: 0 0 auto; + border-radius: 3px; + box-shadow: 0px 3px 20px rgba(0, 0, 0, 0.15); +} + +[dir="ltr"] .uppy-Dashboard-FileCard-edit{ + right: 10px; +} + +[dir="rtl"] .uppy-Dashboard-FileCard-edit{ + left: 10px; +} + +.uppy-Dashboard-FileCard-edit { + position: absolute; + top: 10px; + font-size: 13px; + background-color: rgba(0, 0, 0, 0.5); + color: #fff; + padding: 7px 15px; + border-radius: 50px; +} +.uppy-Dashboard-FileCard-edit:focus { + outline: none; +} +.uppy-Dashboard-FileCard-edit::-moz-focus-inner { + border: 0; +} +.uppy-Dashboard-FileCard-edit:focus { + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.5); +} +.uppy-Dashboard-FileCard-edit:hover { + background-color: rgba(0, 0, 0, 0.8); +} + +.uppy-Dashboard-FileCard-info { + height: 40%; + -ms-flex-positive: 0; + flex-grow: 0; + -ms-flex-negative: 0; + flex-shrink: 0; + padding: 30px 20px 20px 20px; + overflow-y: auto; + -webkit-overflow-scrolling: touch; +} +[data-uppy-theme=dark] .uppy-Dashboard-FileCard-info { + background-color: #1f1f1f; +} + +.uppy-Dashboard-FileCard-fieldset { + font-size: 0; + border: 0; + padding: 0; + max-width: 640px; + margin: auto; + margin-bottom: 12px; +} + +.uppy-Dashboard-FileCard-label { + display: inline-block; + vertical-align: middle; + width: 22%; + font-size: 12px; + color: #525252; +} +.uppy-size--md .uppy-Dashboard-FileCard-label { + font-size: 14px; +} +[data-uppy-theme=dark] .uppy-Dashboard-FileCard-label { + color: #eaeaea; +} + +.uppy-Dashboard-FileCard-input { + display: inline-block; + vertical-align: middle; + width: 78%; +} + +.uppy-Dashboard-FileCard-actions { + height: 55px; + -ms-flex-negative: 0; + flex-shrink: 0; + -ms-flex-positive: 0; + flex-grow: 0; + border-top: 1px solid #eaeaea; + padding: 0 15px; + background-color: #fafafa; + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; +} +.uppy-size--md .uppy-Dashboard-FileCard-actions { + height: 65px; +} +[data-uppy-theme=dark] .uppy-Dashboard-FileCard-actions { + border-top: 1px solid #333; + background-color: #1f1f1f; +} + +[dir="ltr"] .uppy-Dashboard-FileCard-actionsBtn{ + margin-right: 10px; +} + +[dir="rtl"] .uppy-Dashboard-FileCard-actionsBtn{ + margin-left: 10px; +} + +.uppy-Dashboard-FileCard-actionsBtn { + -webkit-margin-end: 10px; +} + +.uppy-transition-slideDownUp-enter { + opacity: 0.01; + transform: translate3d(0, -105%, 0); + transition: transform 0.25s ease-in-out, opacity 0.25s ease-in-out; +} + +.uppy-transition-slideDownUp-enter.uppy-transition-slideDownUp-enter-active { + opacity: 1; + transform: translate3d(0, 0, 0); +} + +.uppy-transition-slideDownUp-leave { + opacity: 1; + transform: translate3d(0, 0, 0); + transition: transform 0.25s ease-in-out, opacity 0.25s ease-in-out; +} + +.uppy-transition-slideDownUp-leave.uppy-transition-slideDownUp-leave-active { + opacity: 0.01; + transform: translate3d(0, -105%, 0); +} + +@keyframes uppy-Dashboard-fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} +@keyframes uppy-Dashboard-fadeOut { + from { + opacity: 1; + } + to { + opacity: 0; + } +} +@keyframes uppy-Dashboard-slideDownAndFadeIn { + from { + transform: translate3d(-50%, -70%, 0); + opacity: 0; + } + to { + transform: translate3d(-50%, -50%, 0); + opacity: 1; + } +} +@keyframes uppy-Dashboard-slideDownAndFadeIn--small { + from { + transform: translate3d(0, -20%, 0); + opacity: 0; + } + to { + transform: translate3d(0, 0, 0); + opacity: 1; + } +} +@keyframes uppy-Dashboard-slideUpFadeOut { + from { + transform: translate3d(-50%, -50%, 0); + opacity: 1; + } + to { + transform: translate3d(-50%, -70%, 0); + opacity: 0; + } +} +@keyframes uppy-Dashboard-slideUpFadeOut--small { + from { + transform: translate3d(0, 0, 0); + opacity: 1; + } + to { + transform: translate3d(0, -20%, 0); + opacity: 0; + } +} +.uppy-Dashboard--modal { + z-index: 1001; +} + +.uppy-Dashboard--modal[aria-hidden=true] { + display: none; +} + +.uppy-Dashboard--modal.uppy-Dashboard--animateOpenClose > .uppy-Dashboard-inner { + animation: uppy-Dashboard-slideDownAndFadeIn--small 0.3s cubic-bezier(0, 0, 0.2, 1); +} +@media only screen and (min-width: 820px) { + .uppy-Dashboard--modal.uppy-Dashboard--animateOpenClose > .uppy-Dashboard-inner { + animation: uppy-Dashboard-slideDownAndFadeIn 0.3s cubic-bezier(0, 0, 0.2, 1); + } +} + +.uppy-Dashboard--modal.uppy-Dashboard--animateOpenClose > .uppy-Dashboard-overlay { + animation: uppy-Dashboard-fadeIn 0.3s cubic-bezier(0, 0, 0.2, 1); +} + +.uppy-Dashboard--modal.uppy-Dashboard--animateOpenClose.uppy-Dashboard--isClosing > .uppy-Dashboard-inner { + animation: uppy-Dashboard-slideUpFadeOut--small 0.3s cubic-bezier(0, 0, 0.2, 1); +} +@media only screen and (min-width: 820px) { + .uppy-Dashboard--modal.uppy-Dashboard--animateOpenClose.uppy-Dashboard--isClosing > .uppy-Dashboard-inner { + animation: uppy-Dashboard-slideUpFadeOut 0.3s cubic-bezier(0, 0, 0.2, 1); + } +} + +.uppy-Dashboard--modal.uppy-Dashboard--animateOpenClose.uppy-Dashboard--isClosing > .uppy-Dashboard-overlay { + animation: uppy-Dashboard-fadeOut 0.3s cubic-bezier(0, 0, 0.2, 1); +} + +.uppy-Dashboard-isFixed { + overflow: hidden; + height: 100vh; +} + +.uppy-Dashboard--modal .uppy-Dashboard-overlay { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(0, 0, 0, 0.5); + z-index: 1001; +} + +.uppy-Dashboard-inner { + position: relative; + background-color: #fafafa; + max-width: 100%; + max-height: 100%; + outline: none; + border: 1px solid #eaeaea; + border-radius: 5px; +} +.uppy-size--md .uppy-Dashboard-inner { + min-height: auto; +} +@media only screen and (min-width: 820px) { + .uppy-Dashboard-inner { + width: 750px; + height: 550px; + } +} +.uppy-Dashboard--modal .uppy-Dashboard-inner { + z-index: 1002; +} +[data-uppy-theme=dark] .uppy-Dashboard-inner { + background-color: #1f1f1f; +} +.uppy-Dashboard--isDisabled .uppy-Dashboard-inner { + cursor: not-allowed; +} + +.uppy-Dashboard-innerWrap { + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; + height: 100%; + overflow: hidden; + position: relative; + border-radius: 5px; + opacity: 0; +} +.uppy-Dashboard--isInnerWrapVisible .uppy-Dashboard-innerWrap { + opacity: 1; +} +.uppy-Dashboard--isDisabled .uppy-Dashboard-innerWrap { + pointer-events: none; + opacity: 0.6; + filter: grayscale(100%); + -webkit-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.uppy-Dashboard--isDisabled .uppy-ProviderIconBg { + fill: #9f9f9f; +} + +.uppy-Dashboard--modal .uppy-Dashboard-inner { + position: fixed; + top: 35px; + left: 15px; + right: 15px; + bottom: 15px; + border: none; +} +@media only screen and (min-width: 820px) { + .uppy-Dashboard--modal .uppy-Dashboard-inner { + top: 50%; + left: 50%; + right: auto; + transform: translate(-50%, -50%); + box-shadow: 0 5px 15px 4px rgba(0, 0, 0, 0.15); + } +} + +[dir="ltr"] .uppy-Dashboard-close{ + right: -2px; +} + +[dir="rtl"] .uppy-Dashboard-close{ + left: -2px; +} + +.uppy-Dashboard-close { + display: block; + position: absolute; + top: -33px; + cursor: pointer; + color: rgba(255, 255, 255, 0.9); + font-size: 27px; + z-index: 1005; +} +.uppy-Dashboard-close:focus { + outline: none; +} +.uppy-Dashboard-close::-moz-focus-inner { + border: 0; +} +.uppy-Dashboard-close:focus { + color: #8cb8ed; +} +@media only screen and (min-width: 820px) { + [dir="ltr"] .uppy-Dashboard-close{ + right: -35px; + } + [dir="rtl"] .uppy-Dashboard-close{ + left: -35px; + } + .uppy-Dashboard-close { + font-size: 35px; + top: -10px; + } +} + +.uppy-Dashboard-AddFiles { + display: -ms-flexbox; + display: flex; + -ms-flex-pack: center; + justify-content: center; + -ms-flex-align: center; + align-items: center; + -ms-flex-direction: column; + flex-direction: column; + height: 100%; + position: relative; + text-align: center; +} +[data-uppy-drag-drop-supported=true] .uppy-Dashboard-AddFiles { + margin: 7px; + height: calc(100% - 14px); + border-radius: 3px; + border: 1px dashed #dfdfdf; +} +.uppy-Dashboard-AddFilesPanel .uppy-Dashboard-AddFiles { + border: none; + height: calc(100% - 14px - 40px); +} +.uppy-Dashboard--modal .uppy-Dashboard-AddFiles { + border-color: #cfcfcf; +} +[data-uppy-theme=dark] .uppy-Dashboard-AddFiles { + border-color: #757575; +} + +.uppy-Dashboard-AddFiles-info { + padding-top: 15px; + padding-bottom: 15px; + margin-top: auto; + display: none; +} +.uppy-size--height-md .uppy-Dashboard-AddFiles-info { + display: block; +} +.uppy-size--md .uppy-Dashboard-AddFiles-info { + position: absolute; + bottom: 25px; + left: 0; + right: 0; + padding-top: 30px; + padding-bottom: 0; +} +[data-uppy-num-acquirers="0"] .uppy-Dashboard-AddFiles-info { + margin-top: 0; +} + +.uppy-Dashboard-browse { + cursor: pointer; + color: rgba(34, 117, 215, 0.9); +} +.uppy-Dashboard-browse:focus { + outline: none; +} +.uppy-Dashboard-browse::-moz-focus-inner { + border: 0; +} +.uppy-Dashboard-browse:hover, .uppy-Dashboard-browse:focus { + border-bottom: 1px solid #2275d7; +} +[data-uppy-theme=dark] .uppy-Dashboard-browse { + color: rgba(2, 186, 242, 0.9); +} +[data-uppy-theme=dark] .uppy-Dashboard-browse:hover, [data-uppy-theme=dark] .uppy-Dashboard-browse:focus { + border-bottom: 1px solid #02baf2; +} + +.uppy-Dashboard-browseBtn { + display: block; + font-size: 14px; + font-weight: 500; + margin-top: 8px; + margin-bottom: 5px; + width: 100%; +} +.uppy-size--md .uppy-Dashboard-browseBtn { + font-size: 15px; + width: auto; + margin: auto; + margin-top: 15px; + margin-bottom: 15px; + padding: 13px 44px; +} + +.uppy-Dashboard-AddFiles-list { + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; + -ms-flex: 1; + flex: 1; + overflow-y: auto; + -webkit-overflow-scrolling: touch; + margin-top: 2px; + padding: 2px 0; + width: 100%; +} +.uppy-size--md .uppy-Dashboard-AddFiles-list { + -ms-flex-direction: row; + flex-direction: row; + -ms-flex-wrap: wrap; + flex-wrap: wrap; + -ms-flex-pack: center; + justify-content: center; + max-width: 600px; + overflow-y: visible; + margin-top: 15px; + padding-top: 0; + -ms-flex: none; + flex: none; +} + +.uppy-DashboardTab { + width: 100%; + text-align: center; + border-bottom: 1px solid #eaeaea; +} +[data-uppy-theme=dark] .uppy-DashboardTab { + border-bottom: 1px solid #333; +} +.uppy-size--md .uppy-DashboardTab { + display: inline-block; + width: initial; + margin-bottom: 10px; + border-bottom: none; +} + +.uppy-DashboardTab-btn { + width: 100%; + height: 100%; + cursor: pointer; + border: 0; + background-color: transparent; + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; + color: #525252; + display: -ms-flexbox; + display: flex; + -ms-flex-direction: row; + flex-direction: row; + -ms-flex-align: center; + align-items: center; + padding: 12px 15px; + line-height: 1; + text-align: center; +} +.uppy-DashboardTab-btn:focus { + outline: none; +} +.uppy-DashboardTab-btn::-moz-focus-inner { + border: 0; +} +[dir="ltr"] .uppy-size--md .uppy-DashboardTab-btn{ + margin-right: 1px; +} +[dir="rtl"] .uppy-size--md .uppy-DashboardTab-btn{ + margin-left: 1px; +} +.uppy-size--md .uppy-DashboardTab-btn { + width: 86px; + -webkit-margin-end: 1px; + -ms-flex-direction: column; + flex-direction: column; + padding: 10px 3px; + border-radius: 5px; +} +[data-uppy-theme=dark] .uppy-DashboardTab-btn { + color: #eaeaea; +} + +.uppy-DashboardTab-btn::-moz-focus-inner { + border: 0; +} + +.uppy-DashboardTab-btn:hover { + background-color: #f1f3f6; +} +[data-uppy-theme=dark] .uppy-DashboardTab-btn:hover { + background-color: #333; +} + +.uppy-DashboardTab-btn:active, +.uppy-DashboardTab-btn:focus { + background-color: #eceef2; +} +[data-uppy-theme=dark] .uppy-DashboardTab-btn:active, +[data-uppy-theme=dark] .uppy-DashboardTab-btn:focus { + background-color: #525252; +} + +[dir="ltr"] .uppy-DashboardTab-btn svg{ + margin-right: 10px; +} + +[dir="rtl"] .uppy-DashboardTab-btn svg{ + margin-left: 10px; +} + +.uppy-DashboardTab-btn svg { + max-width: 100%; + max-height: 100%; + display: inline-block; + vertical-align: text-top; + overflow: hidden; + transition: transform ease-in-out 0.15s; + -webkit-margin-end: 10px; +} +[dir="ltr"] .uppy-size--md .uppy-DashboardTab-btn svg{ + margin-right: 0; +} +[dir="rtl"] .uppy-size--md .uppy-DashboardTab-btn svg{ + margin-left: 0; +} +.uppy-size--md .uppy-DashboardTab-btn svg { + -webkit-margin-end: 0; +} + +.uppy-DashboardTab-name { + font-size: 14px; + font-weight: 500; +} +.uppy-size--md .uppy-DashboardTab-name { + font-size: 11px; + line-height: 15px; + margin-top: 8px; + margin-bottom: 0; +} + +.uppy-DashboardTab svg { + width: 23px; + height: 23px; + vertical-align: middle; +} +.uppy-size--md .uppy-DashboardTab svg { + width: 30px; + height: 30px; +} + +.uppy-Dashboard-input { + width: 0.1px; + height: 0.1px; + opacity: 0; + overflow: hidden; + position: absolute; + z-index: -1; +} + +.uppy-DashboardContent-bar { + -ms-flex-negative: 0; + flex-shrink: 0; + height: 40px; + width: 100%; + padding: 0 10px; + z-index: 1004; + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: justify; + justify-content: space-between; + position: relative; + border-bottom: 1px solid #eaeaea; + background-color: #fafafa; +} +.uppy-size--md .uppy-DashboardContent-bar { + height: 50px; + padding: 0 15px; +} +[data-uppy-theme=dark] .uppy-DashboardContent-bar { + background-color: #1f1f1f; + border-bottom: 1px solid #333; +} + +.uppy-DashboardContent-title { + position: absolute; + top: 0; + left: 0; + right: 0; + text-align: center; + font-size: 12px; + line-height: 40px; + font-weight: 500; + width: 100%; + max-width: 170px; + text-overflow: ellipsis; + white-space: nowrap; + overflow-x: hidden; + margin: auto; +} +.uppy-size--md .uppy-DashboardContent-title { + font-size: 14px; + line-height: 50px; + max-width: 300px; +} +[data-uppy-theme=dark] .uppy-DashboardContent-title { + color: #eaeaea; +} + +[dir="ltr"] .uppy-DashboardContent-back{ + margin-left: -6px; +} + +[dir="rtl"] .uppy-DashboardContent-back{ + margin-right: -6px; +} + +.uppy-DashboardContent-back { + background: none; + -webkit-appearance: none; + font-family: inherit; + font-size: inherit; + line-height: 1; + padding: 0; + margin: 0; + border: 0; + color: inherit; + border-radius: 3px; + font-size: 12px; + font-weight: 400; + cursor: pointer; + color: #2275d7; + padding: 7px 6px; + -webkit-margin-start: -6px; +} +.uppy-DashboardContent-back:focus { + outline: none; +} +.uppy-DashboardContent-back::-moz-focus-inner { + border: 0; +} +.uppy-DashboardContent-back:hover { + color: #1b5dab; +} +.uppy-DashboardContent-back:focus { + background-color: #eceef2; +} +[data-uppy-theme=dark] .uppy-DashboardContent-back:focus { + background-color: #333; +} +.uppy-size--md .uppy-DashboardContent-back { + font-size: 14px; +} +[data-uppy-theme=dark] .uppy-DashboardContent-back { + color: #02baf2; +} + +[dir="ltr"] .uppy-DashboardContent-addMore{ + margin-right: -5px; +} + +[dir="rtl"] .uppy-DashboardContent-addMore{ + margin-left: -5px; +} + +.uppy-DashboardContent-addMore { + background: none; + -webkit-appearance: none; + font-family: inherit; + font-size: inherit; + line-height: 1; + padding: 0; + margin: 0; + border: 0; + color: inherit; + border-radius: 3px; + font-weight: 500; + cursor: pointer; + color: #2275d7; + width: 29px; + height: 29px; + padding: 7px 8px; + -webkit-margin-end: -5px; +} +.uppy-DashboardContent-addMore:focus { + outline: none; +} +.uppy-DashboardContent-addMore::-moz-focus-inner { + border: 0; +} +.uppy-DashboardContent-addMore:hover { + color: #1b5dab; +} +.uppy-DashboardContent-addMore:focus { + background-color: #eceef2; +} +[data-uppy-theme=dark] .uppy-DashboardContent-addMore:focus { + background-color: #333; +} +[dir="ltr"] .uppy-size--md .uppy-DashboardContent-addMore{ + margin-right: -8px; +} +[dir="rtl"] .uppy-size--md .uppy-DashboardContent-addMore{ + margin-left: -8px; +} +.uppy-size--md .uppy-DashboardContent-addMore { + font-size: 14px; + width: auto; + height: auto; + -webkit-margin-end: -8px; +} +[data-uppy-theme=dark] .uppy-DashboardContent-addMore { + color: #02baf2; +} + +[dir="ltr"] .uppy-DashboardContent-addMore svg{ + margin-right: 4px; +} + +[dir="rtl"] .uppy-DashboardContent-addMore svg{ + margin-left: 4px; +} + +.uppy-DashboardContent-addMore svg { + vertical-align: baseline; + -webkit-margin-end: 4px; +} +.uppy-size--md .uppy-DashboardContent-addMore svg { + width: 11px; + height: 11px; +} + +.uppy-DashboardContent-addMoreCaption { + display: none; +} +.uppy-size--md .uppy-DashboardContent-addMoreCaption { + display: inline; +} + +.uppy-DashboardContent-panel { + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + background-color: whitesmoke; + overflow: hidden; + z-index: 1005; + border-radius: 5px; + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; + -ms-flex: 1; + flex: 1; +} + +.uppy-Dashboard-AddFilesPanel { + position: absolute; + top: 0; + bottom: 0; + left: 0; + right: 0; + background: #fafafa; + background: linear-gradient(0deg, #fafafa 35%, rgba(250, 250, 250, 0.85) 100%); + box-shadow: 0 0 10px 5px rgba(0, 0, 0, 0.15); + overflow: hidden; + z-index: 1005; + border-radius: 5px; + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; +} +[data-uppy-theme=dark] .uppy-Dashboard-AddFilesPanel { + background-color: #333; + background: linear-gradient(0deg, #1f1f1f 35%, rgba(31, 31, 31, 0.85) 100%); +} + +.uppy-Dashboard--isAddFilesPanelVisible .uppy-Dashboard-files { + filter: blur(2px); +} + +.uppy-Dashboard-progress { + position: absolute; + bottom: 0; + left: 0; + width: 100%; + height: 12%; +} + +.uppy-Dashboard-progressBarContainer.is-active { + z-index: 1004; + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; +} + +.uppy-Dashboard:not(.uppy-size--md) .uppy-StatusBar-additionalInfo { + display: none; +} + +.uppy-Dashboard-filesContainer { + position: relative; + overflow-y: hidden; + margin: 0; + -ms-flex: 1; + flex: 1; +} +.uppy-Dashboard-filesContainer:after { + content: ""; + display: table; + clear: both; +} + +.uppy-Dashboard-files { + margin: 0; + padding: 0 0 10px 0; + overflow-y: auto; + -webkit-overflow-scrolling: touch; + -ms-flex: 1; + flex: 1; +} +.uppy-size--md .uppy-Dashboard-files { + padding-top: 10px; +} + +.uppy-Dashboard-dropFilesHereHint { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: center; + justify-content: center; + visibility: hidden; + position: absolute; + top: 7px; + right: 7px; + bottom: 7px; + left: 7px; + padding-top: 90px; + border: 1px dashed #2275d7; + border-radius: 3px; + z-index: 2000; + text-align: center; + background-image: url("data:image/svg+xml,%3Csvg width='48' height='48' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M24 1v1C11.85 2 2 11.85 2 24s9.85 22 22 22 22-9.85 22-22S36.15 2 24 2V1zm0 0V0c13.254 0 24 10.746 24 24S37.254 48 24 48 0 37.254 0 24 10.746 0 24 0v1zm7.707 19.293a.999.999 0 1 1-1.414 1.414L25 16.414V34a1 1 0 1 1-2 0V16.414l-5.293 5.293a.999.999 0 1 1-1.414-1.414l7-7a.999.999 0 0 1 1.414 0l7 7z' fill='%232275D7' fill-rule='nonzero'/%3E%3C/svg%3E"); + background-position: 50% 50%; + background-repeat: no-repeat; + color: #757575; + font-size: 16px; +} +[data-uppy-theme=dark] .uppy-Dashboard-dropFilesHereHint { + color: #bbb; + border-color: #02baf2; + background-image: url("data:image/svg+xml,%3Csvg width='48' height='48' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M24 1v1C11.85 2 2 11.85 2 24s9.85 22 22 22 22-9.85 22-22S36.15 2 24 2V1zm0 0V0c13.254 0 24 10.746 24 24S37.254 48 24 48 0 37.254 0 24 10.746 0 24 0v1zm7.707 19.293a.999.999 0 1 1-1.414 1.414L25 16.414V34a1 1 0 1 1-2 0V16.414l-5.293 5.293a.999.999 0 1 1-1.414-1.414l7-7a.999.999 0 0 1 1.414 0l7 7z' fill='%2302BAF2' fill-rule='nonzero'/%3E%3C/svg%3E"); +} + +.uppy-Dashboard.uppy-Dashboard--isDraggingOver .uppy-Dashboard-dropFilesHereHint { + visibility: visible; +} +.uppy-Dashboard.uppy-Dashboard--isDraggingOver .uppy-DashboardContent-bar, +.uppy-Dashboard.uppy-Dashboard--isDraggingOver .uppy-Dashboard-files, +.uppy-Dashboard.uppy-Dashboard--isDraggingOver .uppy-Dashboard-progressindicators { + opacity: 0.15; +} +.uppy-Dashboard.uppy-Dashboard--isDraggingOver .uppy-Dashboard-AddFiles { + opacity: 0.03; +} + +.uppy-Dashboard-dropFilesIcon { + display: none; + margin-bottom: 15px; +} +.uppy-size--md.uppy-size--height-md .uppy-Dashboard-dropFilesIcon { + display: block; +} + +.uppy-Dashboard-AddFiles-title { + font-size: 17px; + line-height: 1.35; + font-weight: 500; + color: #000; + margin-top: 15px; + margin-bottom: 5px; + text-align: inline-start; + padding: 0 15px; + width: 100%; +} +.uppy-size--md .uppy-Dashboard-AddFiles-title { + font-size: 25px; + margin-top: 5px; + font-weight: 400; + text-align: center; + max-width: 480px; +} +[data-uppy-num-acquirers="0"] .uppy-Dashboard-AddFiles-title { + text-align: center; +} +[data-uppy-theme=dark] .uppy-Dashboard-AddFiles-title { + color: #eaeaea; +} +.uppy-Dashboard-AddFiles-title button { + font-weight: 500; +} +.uppy-size--md .uppy-Dashboard-AddFiles-title button { + font-weight: 400; +} + +.uppy-Dashboard-note { + font-size: 14px; + line-height: 1.25; + text-align: center; + color: #757575; + max-width: 350px; + margin: auto; + padding: 0 15px; +} +.uppy-size--md .uppy-Dashboard-note { + font-size: 15px; + line-height: 1.35; + max-width: 600px; +} +[data-uppy-theme=dark] .uppy-Dashboard-note { + color: #cfcfcf; +} + +a.uppy-Dashboard-poweredBy { + display: inline-block; + text-align: center; + font-size: 11px; + color: #939393; + text-decoration: none; + margin-top: 8px; +} + +.uppy-Dashboard-poweredByIcon { + stroke: #939393; + fill: none; + margin-left: 1px; + margin-right: 1px; + position: relative; + top: 1px; + opacity: 0.9; + vertical-align: text-top; +} + +.uppy-Dashboard-Item-previewIcon { + width: 25px; + height: 25px; + z-index: 100; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); +} +.uppy-size--md .uppy-Dashboard-Item-previewIcon { + width: 38px; + height: 38px; +} +.uppy-Dashboard-Item-previewIcon svg { + width: 100%; + height: 100%; +} + +.uppy-Dashboard-Item-previewIconWrap { + height: 76px; + max-height: 75%; + position: relative; +} + +.uppy-Dashboard-Item-previewIconBg { + width: 100%; + height: 100%; + filter: drop-shadow(rgba(0, 0, 0, 0.1) 0px 1px 1px); +} + +.uppy-Dashboard-upload { + position: relative; + width: 50px; + height: 50px; +} +.uppy-size--md .uppy-Dashboard-upload { + width: 60px; + height: 60px; +} + +.uppy-Dashboard-upload .uppy-c-icon { + position: relative; + top: 1px; + width: 50%; +} + +[dir="ltr"] .uppy-Dashboard-uploadCount{ + right: -12px; +} + +[dir="rtl"] .uppy-Dashboard-uploadCount{ + left: -12px; +} + +.uppy-Dashboard-uploadCount { + position: absolute; + top: -12px; + background-color: #1bb240; + color: #fff; + border-radius: 50%; + width: 16px; + height: 16px; + line-height: 16px; + font-size: 8px; +} +.uppy-size--md .uppy-Dashboard-uploadCount { + width: 18px; + height: 18px; + line-height: 18px; + font-size: 9px; +} + +.uppy-DragDrop-container { + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: center; + justify-content: center; + border-radius: 7px; + background-color: #fff; + cursor: pointer; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; + max-width: 100%; +} +.uppy-DragDrop-container:focus { + outline: none; + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.4); +} +.uppy-DragDrop-container::-moz-focus-inner { + border: 0; +} + +.uppy-DragDrop-inner { + margin: 0; + text-align: center; + padding: 80px 20px; + line-height: 1.4; +} + +.uppy-DragDrop-arrow { + width: 60px; + height: 60px; + fill: #e0e0e0; + margin-bottom: 17px; +} + +.uppy-DragDrop--isDragDropSupported { + border: 2px dashed #adadad; +} + +.uppy-DragDrop--isDraggingOver { + border: 2px dashed #2275d7; + background: #eaeaea; +} +.uppy-DragDrop--isDraggingOver .uppy-DragDrop-arrow { + fill: #939393; +} + +.uppy-DragDrop-label { + display: block; + font-size: 1.15em; + margin-bottom: 5px; +} + +.uppy-DragDrop-browse { + color: #2275d7; + cursor: pointer; +} + +.uppy-DragDrop-note { + font-size: 1em; + color: #adadad; +} + +.uppy-FileInput-container { + margin-bottom: 15px; +} + +.uppy-FileInput-btn { + background: none; + -webkit-appearance: none; + font-family: inherit; + font-size: inherit; + line-height: 1; + padding: 0; + margin: 0; + border: 0; + color: inherit; + font-family: sans-serif; + font-size: 0.85em; + padding: 10px 15px; + color: #14457f; + border: 1px solid #14457f; + border-radius: 8px; + cursor: pointer; +} +.uppy-FileInput-btn:hover { + background-color: #14457f; + color: #fff; +} + +.uppy-ProgressBar { + /* no important */ + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 3px; + z-index: 10000; + transition: height 0.2s; +} + +.uppy-ProgressBar[aria-hidden=true] { + /* no important */ + height: 0; +} + +.uppy-ProgressBar-inner { + /* no important */ + background-color: #2275d7; + box-shadow: 0 0 10px rgba(34, 117, 215, 0.7); + height: 100%; + width: 0; + transition: width 0.4s ease; +} + +.uppy-ProgressBar-percentage { + /* no important */ + display: none; + text-align: center; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + color: #fff; +} + +.uppy-Url { + width: 100%; + height: 100%; + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; + -ms-flex-pack: center; + justify-content: center; + -ms-flex-align: center; + align-items: center; + -ms-flex: 1; + flex: 1; +} +[data-uppy-theme=dark] .uppy-Url { + background-color: #1f1f1f; +} + +.uppy-Url-input { + width: 90%; + max-width: 650px; + margin-bottom: 15px; +} +.uppy-size--md .uppy-Url-input { + margin-bottom: 20px; +} + +.uppy-Url-importButton { + padding: 13px 25px; +} +.uppy-size--md .uppy-Url-importButton { + padding: 13px 30px; +} + +.uppy-Webcam-container { + width: 100%; + height: 100%; + display: -ms-flexbox; + display: flex; + -ms-flex-pack: center; + justify-content: center; + -ms-flex-align: center; + align-items: center; + -ms-flex-direction: column; + flex-direction: column; +} + +.uppy-Webcam-videoContainer { + width: 100%; + -ms-flex: 1; + flex: 1; + -ms-flex-positive: 1; + flex-grow: 1; + overflow: hidden; + background-color: #333; + text-align: center; + position: relative; +} + +.uppy-Webcam-video { + max-width: 100%; + max-height: 100%; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + margin: auto; +} + +.uppy-Webcam-video--mirrored { + transform: scaleX(-1); +} + +.uppy-Webcam-footer { + width: 100%; + min-height: 75px; + display: -ms-flexbox; + display: flex; + -ms-flex-wrap: wrap; + flex-wrap: wrap; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: justify; + justify-content: space-between; + padding: 20px 20px; +} + +.uppy-Webcam-videoSourceContainer { + width: 100%; + -ms-flex-positive: 0; + flex-grow: 0; +} + +.uppy-size--lg .uppy-Webcam-videoSourceContainer { + width: 33%; + margin: 0; +} + +.uppy-Webcam-videoSource-select { + display: block; + font-size: 16px; + line-height: 1.2; + padding: 0.4em 1em 0.3em 0.4em; + width: 100%; + max-width: 90%; + border: 1px solid #757575; + background-image: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23757575%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E"); + background-repeat: no-repeat; + background-position: right 0.4em top 50%, 0 0; + background-size: 0.65em auto, 100%; + margin: auto; + margin-bottom: 10px; + white-space: nowrap; + text-overflow: ellipsis; +} +.uppy-size--lg .uppy-Webcam-videoSource-select { + font-size: 14px; + margin-bottom: 0; +} + +.uppy-Webcam-videoSource-select::-ms-expand { + display: none; +} + +.uppy-Webcam-buttonContainer { + width: 50%; + margin-left: 25%; + text-align: center; +} + +.uppy-size--lg .uppy-Webcam-buttonContainer { + width: 34%; + margin-left: 0; +} + +.uppy-Webcam-recordingLength { + width: 25%; + -ms-flex-positive: 0; + flex-grow: 0; + color: #757575; + font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + text-align: right; +} + +.uppy-size--lg .uppy-Webcam-recordingLength { + width: 33%; +} + +.uppy-Webcam-button { + width: 45px; + height: 45px; + border-radius: 50%; + background-color: #e32437; + color: #fff; + cursor: pointer; + transition: all 0.3s; +} +.uppy-Webcam-button:focus { + outline: none; +} +.uppy-Webcam-button::-moz-focus-inner { + border: 0; +} +.uppy-Webcam-button:focus { + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.5); +} +[data-uppy-theme=dark] .uppy-Webcam-button:focus { + outline: none; +} +[data-uppy-theme=dark] .uppy-Webcam-button::-moz-focus-inner { + border: 0; +} +[data-uppy-theme=dark] .uppy-Webcam-button:focus { + box-shadow: 0 0 0 2px rgba(170, 225, 255, 0.85); +} + +.uppy-Webcam-button svg { + width: 30px; + height: 30px; + max-width: 100%; + max-height: 100%; + display: inline-block; + vertical-align: text-top; + overflow: hidden; + fill: currentColor; +} + +.uppy-size--md .uppy-Webcam-button { + width: 60px; + height: 60px; +} + +.uppy-Webcam-button:hover { + background-color: #d31b2d; +} + +.uppy-Webcam-button--picture { + margin-right: 12px; +} + +.uppy-Webcam-permissons { + padding: 15px; + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: center; + justify-content: center; + -ms-flex-flow: column wrap; + flex-flow: column wrap; + height: 100%; + -ms-flex: 1; + flex: 1; +} + +.uppy-Webcam-permissons p { + max-width: 450px; + line-height: 1.3; + text-align: center; + line-height: 1.45; + color: #939393; + margin: 0; +} + +.uppy-Webcam-permissonsIcon svg { + width: 100px; + height: 75px; + color: #bbb; + margin-bottom: 30px; +} + +.uppy-Webcam-title { + font-size: 22px; + line-height: 1.35; + font-weight: 400; + margin: 0; + margin-bottom: 5px; + padding: 0 15px; + max-width: 500px; + text-align: center; + color: #333; +} +[data-uppy-theme=dark] .uppy-Webcam-title { + color: #eaeaea; +} + +.uppy-ScreenCapture-container { + width: 100%; + height: 100%; + display: -ms-flexbox; + display: flex; + -ms-flex-pack: center; + justify-content: center; + -ms-flex-align: center; + align-items: center; + -ms-flex-direction: column; + flex-direction: column; +} + +.uppy-ScreenCapture-videoContainer { + width: 100%; + -ms-flex: 1; + flex: 1; + -ms-flex-positive: 1; + flex-grow: 1; + overflow: hidden; + background-color: #333; + text-align: center; + position: relative; +} +.uppy-size--md .uppy-ScreenCapture-videoContainer { + max-width: 100%; +} + +.uppy-ScreenCapture-video { + max-width: 100%; + max-height: 100%; + position: absolute; + top: 0; + right: 0; + bottom: 0; + left: 0; + margin: auto; + outline: 0; +} + +.uppy-ScreenCapture-buttonContainer { + width: 100%; + height: 75px; + border-top: 1px solid #eaeaea; + display: -ms-flexbox; + display: flex; + -ms-flex-align: center; + align-items: center; + -ms-flex-pack: center; + justify-content: center; + padding: 0 20px; + background-color: #fff; +} +[data-uppy-theme=dark] .uppy-ScreenCapture-buttonContainer { + background-color: #1f1f1f; + border-top: 1px solid #333; +} + +.uppy-ScreenCapture-button { + width: 45px; + height: 45px; + border-radius: 50%; + color: #fff; + cursor: pointer; + transition: all 0.3s; +} +.uppy-ScreenCapture-button:focus { + outline: none; +} +.uppy-ScreenCapture-button::-moz-focus-inner { + border: 0; +} +.uppy-ScreenCapture-button:focus { + box-shadow: 0 0 0 3px rgba(34, 117, 215, 0.5); +} +[data-uppy-theme=dark] .uppy-ScreenCapture-button:focus { + outline: none; +} +[data-uppy-theme=dark] .uppy-ScreenCapture-button::-moz-focus-inner { + border: 0; +} +[data-uppy-theme=dark] .uppy-ScreenCapture-button:focus { + box-shadow: 0 0 0 2px rgba(170, 225, 255, 0.85); +} +.uppy-size--md .uppy-ScreenCapture-button { + width: 60px; + height: 60px; +} +.uppy-ScreenCapture-button:hover { + background-color: #d31b2d; +} + +.uppy-ScreenCapture-button svg { + width: 30px; + height: 30px; + max-width: 100%; + max-height: 100%; + display: inline-block; + vertical-align: text-top; + overflow: hidden; + fill: currentColor; +} + +.uppy-ScreenCapture-button--submit { + background-color: #2275d7; + margin-left: 12px; +} +.uppy-ScreenCapture-button--submit:hover { + background-color: #1f69c1; +} +.uppy-ScreenCapture-button--submit:disabled { + background-color: #939393; + cursor: default; +} +.uppy-ScreenCapture-button--submit:disabled:hover { + background-color: #eaeaea; +} + +.uppy-ScreenCapture-title { + font-size: 22px; + line-height: 1.35; + font-weight: 400; + margin: 0; + margin-bottom: 5px; + padding: 0 15px; + max-width: 500px; + text-align: center; + color: #333; +} + +.uppy-ScreenCapture-icon--stream { + position: absolute; + right: 0; + top: 0; + margin: 1rem; + z-index: 1; +} +.uppy-ScreenCapture-icon--stream svg { + fill: #939393; +} + +.uppy-ScreenCapture-icon--streamActive svg { + animation: uppy-ScreenCapture-icon--blink 1s cubic-bezier(0.47, 0, 0.75, 0.72) infinite; +} + +@keyframes uppy-ScreenCapture-icon--blink { + 0% { + fill: #2275d7; + } + 50% { + fill: #939393; + } + 100% { + fill: #2275d7; + } +} +.uppy-ScreenCapture-button--video { + color: #fff; + background: #e32437; +} +.uppy-ScreenCapture-button--video:hover { + background-color: #bc1828; +} + +/*! + * Cropper.js v1.5.6 + * https://fengyuanchen.github.io/cropperjs + * + * Copyright 2015-present Chen Fengyuan + * Released under the MIT license + * + * Date: 2019-10-04T04:33:44.164Z + */ +.cropper-container { + direction: ltr; + font-size: 0; + line-height: 0; + position: relative; + -ms-touch-action: none; + touch-action: none; + -webkit-user-select: none; + -ms-user-select: none; + user-select: none; +} + +.cropper-container img { + display: block; + height: 100%; + image-orientation: 0deg; + max-height: none !important; + max-width: none !important; + min-height: 0 !important; + min-width: 0 !important; + width: 100%; +} + +.cropper-wrap-box, +.cropper-canvas, +.cropper-drag-box, +.cropper-crop-box, +.cropper-modal { + bottom: 0; + left: 0; + position: absolute; + right: 0; + top: 0; +} + +.cropper-wrap-box, +.cropper-canvas { + overflow: hidden; +} + +.cropper-drag-box { + background-color: #fff; + opacity: 0; +} + +.cropper-modal { + background-color: #000; + opacity: 0.5; +} + +.cropper-view-box { + display: block; + height: 100%; + outline: 1px solid #39f; + outline-color: rgba(51, 153, 255, 0.75); + overflow: hidden; + width: 100%; +} + +.cropper-dashed { + border: 0 dashed #eee; + display: block; + opacity: 0.5; + position: absolute; +} + +.cropper-dashed.dashed-h { + border-bottom-width: 1px; + border-top-width: 1px; + height: calc(100% / 3); + left: 0; + top: calc(100% / 3); + width: 100%; +} + +.cropper-dashed.dashed-v { + border-left-width: 1px; + border-right-width: 1px; + height: 100%; + left: calc(100% / 3); + top: 0; + width: calc(100% / 3); +} + +.cropper-center { + display: block; + height: 0; + left: 50%; + opacity: 0.75; + position: absolute; + top: 50%; + width: 0; +} + +.cropper-center::before, +.cropper-center::after { + background-color: #eee; + content: " "; + display: block; + position: absolute; +} + +.cropper-center::before { + height: 1px; + left: -3px; + top: 0; + width: 7px; +} + +.cropper-center::after { + height: 7px; + left: 0; + top: -3px; + width: 1px; +} + +.cropper-face, +.cropper-line, +.cropper-point { + display: block; + height: 100%; + opacity: 0.1; + position: absolute; + width: 100%; +} + +.cropper-face { + background-color: #fff; + left: 0; + top: 0; +} + +.cropper-line { + background-color: #39f; +} + +.cropper-line.line-e { + cursor: ew-resize; + right: -3px; + top: 0; + width: 5px; +} + +.cropper-line.line-n { + cursor: ns-resize; + height: 5px; + left: 0; + top: -3px; +} + +.cropper-line.line-w { + cursor: ew-resize; + left: -3px; + top: 0; + width: 5px; +} + +.cropper-line.line-s { + bottom: -3px; + cursor: ns-resize; + height: 5px; + left: 0; +} + +.cropper-point { + background-color: #39f; + height: 5px; + opacity: 0.75; + width: 5px; +} + +.cropper-point.point-e { + cursor: ew-resize; + margin-top: -3px; + right: -3px; + top: 50%; +} + +.cropper-point.point-n { + cursor: ns-resize; + left: 50%; + margin-left: -3px; + top: -3px; +} + +.cropper-point.point-w { + cursor: ew-resize; + left: -3px; + margin-top: -3px; + top: 50%; +} + +.cropper-point.point-s { + bottom: -3px; + cursor: s-resize; + left: 50%; + margin-left: -3px; +} + +.cropper-point.point-ne { + cursor: nesw-resize; + right: -3px; + top: -3px; +} + +.cropper-point.point-nw { + cursor: nwse-resize; + left: -3px; + top: -3px; +} + +.cropper-point.point-sw { + bottom: -3px; + cursor: nesw-resize; + left: -3px; +} + +.cropper-point.point-se { + bottom: -3px; + cursor: nwse-resize; + height: 20px; + opacity: 1; + right: -3px; + width: 20px; +} + +@media (min-width: 768px) { + .cropper-point.point-se { + height: 15px; + width: 15px; + } +} +@media (min-width: 992px) { + .cropper-point.point-se { + height: 10px; + width: 10px; + } +} +@media (min-width: 1200px) { + .cropper-point.point-se { + height: 5px; + opacity: 0.75; + width: 5px; + } +} +.cropper-point.point-se::before { + background-color: #39f; + bottom: -50%; + content: " "; + display: block; + height: 200%; + opacity: 0; + position: absolute; + right: -50%; + width: 200%; +} + +.cropper-invisible { + opacity: 0; +} + +.cropper-bg { + background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC"); +} + +.cropper-hide { + display: block; + height: 0; + position: absolute; + width: 0; +} + +.cropper-hidden { + display: none !important; +} + +.cropper-move { + cursor: move; +} + +.cropper-crop { + cursor: crosshair; +} + +.cropper-disabled .cropper-drag-box, +.cropper-disabled .cropper-face, +.cropper-disabled .cropper-line, +.cropper-disabled .cropper-point { + cursor: not-allowed; +} + +.uppy-ImageCropper { + display: -ms-flexbox; + display: flex; + -ms-flex-direction: column; + flex-direction: column; + width: 100%; + height: 100%; +} + +.uppy-ImageCropper-container { + -ms-flex-positive: 1; + flex-grow: 1; +} + +.uppy-ImageCropper-image { + display: block; + max-height: 400px; +} + +.uppy-ImageCropper-controls { + position: absolute; + bottom: 15px; + left: 50%; + transform: translateX(-50%); + background-color: rgba(0, 0, 0, 0.6); + color: #fff; + display: -ms-flexbox; + display: flex; + -ms-flex-pack: center; + justify-content: center; + -ms-flex-align: center; + align-items: center; +} + +.uppy-ImageCropper-controls button { + width: 35px; + height: 35px; +} +.uppy-ImageCropper-controls button svg { + padding: 3px; +} +.uppy-size--md .uppy-ImageCropper-controls button { + width: 40px; + height: 40px; +} +.uppy-size--md .uppy-ImageCropper-controls button svg { + padding: 1px; +} +.uppy-ImageCropper-controls button:hover { + background-color: rgba(34, 117, 215, 0.8); +} +.uppy-ImageCropper-controls button:focus { + outline: none; + background-color: rgba(34, 117, 215, 0.8); +} + +.uppy-ImageCropper .cropper-point { + width: 8px; + height: 8px; +} + +.uppy-ImageCropper .cropper-view-box { + outline: 2px solid #39f; +} \ No newline at end of file diff --git a/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.js b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.js new file mode 100644 index 0000000000..e2c635b6ac --- /dev/null +++ b/templates/app/aspnet-core/src/MyCompanyName.MyProjectName.Web/wwwroot/libs/uppy/uppy.js @@ -0,0 +1,41259 @@ +(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.Uppy = 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= 10 || num % 1 === 0) { + // Do not show decimals when the number is two-digit, or if the number has no + // decimal component. + return (neg ? '-' : '') + num.toFixed(0) + ' ' + unit + } else { + return (neg ? '-' : '') + num.toFixed(1) + ' ' + unit + } +} + +},{}],2:[function(require,module,exports){ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +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, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + 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 + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); +} + +function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); +} + +function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); +} + +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); + return true; + } catch (e) { + return false; + } +} + +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} + +function _possibleConstructorReturn(self, call) { + if (call && (typeof call === "object" || typeof call === "function")) { + return call; + } + + return _assertThisInitialized(self); +} + +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 _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = _getPrototypeOf(object); + if (object === null) break; + } + + return object; +} + +function _get(target, property, receiver) { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get; + } else { + _get = function _get(target, property, receiver) { + var base = _superPropBase(target, property); + + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.get) { + return desc.get.call(receiver); + } + + return desc.value; + }; + } + + return _get(target, property, receiver || target); +} + +var Emitter = /*#__PURE__*/function () { + function Emitter() { + _classCallCheck(this, Emitter); + + Object.defineProperty(this, 'listeners', { + value: {}, + writable: true, + configurable: true + }); + } + + _createClass(Emitter, [{ + key: "addEventListener", + value: function addEventListener(type, callback) { + if (!(type in this.listeners)) { + this.listeners[type] = []; + } + + this.listeners[type].push(callback); + } + }, { + key: "removeEventListener", + value: function removeEventListener(type, callback) { + if (!(type in this.listeners)) { + return; + } + + var stack = this.listeners[type]; + + for (var i = 0, l = stack.length; i < l; i++) { + if (stack[i] === callback) { + stack.splice(i, 1); + return; + } + } + } + }, { + key: "dispatchEvent", + value: function dispatchEvent(event) { + var _this = this; + + if (!(event.type in this.listeners)) { + return; + } + + var debounce = function debounce(callback) { + setTimeout(function () { + return callback.call(_this, event); + }); + }; + + var stack = this.listeners[event.type]; + + for (var i = 0, l = stack.length; i < l; i++) { + debounce(stack[i]); + } + + return !event.defaultPrevented; + } + }]); + + return Emitter; +}(); + +var AbortSignal = /*#__PURE__*/function (_Emitter) { + _inherits(AbortSignal, _Emitter); + + var _super = _createSuper(AbortSignal); + + function AbortSignal() { + var _this2; + + _classCallCheck(this, AbortSignal); + + _this2 = _super.call(this); // Some versions of babel does not transpile super() correctly for IE <= 10, if the parent + // constructor has failed to run, then "this.listeners" will still be undefined and then we call + // the parent constructor directly instead as a workaround. For general details, see babel bug: + // https://github.com/babel/babel/issues/3041 + // This hack was added as a fix for the issue described here: + // https://github.com/Financial-Times/polyfill-library/pull/59#issuecomment-477558042 + + if (!_this2.listeners) { + Emitter.call(_assertThisInitialized(_this2)); + } // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and + // we want Object.keys(new AbortController().signal) to be [] for compat with the native impl + + + Object.defineProperty(_assertThisInitialized(_this2), 'aborted', { + value: false, + writable: true, + configurable: true + }); + Object.defineProperty(_assertThisInitialized(_this2), 'onabort', { + value: null, + writable: true, + configurable: true + }); + return _this2; + } + + _createClass(AbortSignal, [{ + key: "toString", + value: function toString() { + return '[object AbortSignal]'; + } + }, { + key: "dispatchEvent", + value: function dispatchEvent(event) { + if (event.type === 'abort') { + this.aborted = true; + + if (typeof this.onabort === 'function') { + this.onabort.call(this, event); + } + } + + _get(_getPrototypeOf(AbortSignal.prototype), "dispatchEvent", this).call(this, event); + } + }]); + + return AbortSignal; +}(Emitter); +var AbortController = /*#__PURE__*/function () { + function AbortController() { + _classCallCheck(this, AbortController); + + // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and + // we want Object.keys(new AbortController()) to be [] for compat with the native impl + Object.defineProperty(this, 'signal', { + value: new AbortSignal(), + writable: true, + configurable: true + }); + } + + _createClass(AbortController, [{ + key: "abort", + value: function abort() { + var event; + + try { + event = new Event('abort'); + } catch (e) { + if (typeof document !== 'undefined') { + if (!document.createEvent) { + // For Internet Explorer 8: + event = document.createEventObject(); + event.type = 'abort'; + } else { + // For Internet Explorer 11: + event = document.createEvent('Event'); + event.initEvent('abort', false, false); + } + } else { + // Fallback where document isn't available: + event = { + type: 'abort', + bubbles: false, + cancelable: false + }; + } + } + + this.signal.dispatchEvent(event); + } + }, { + key: "toString", + value: function toString() { + return '[object AbortController]'; + } + }]); + + return AbortController; +}(); + +if (typeof Symbol !== 'undefined' && Symbol.toStringTag) { + // These are necessary to make sure that we get correct output for: + // Object.prototype.toString.call(new AbortController()) + AbortController.prototype[Symbol.toStringTag] = 'AbortController'; + AbortSignal.prototype[Symbol.toStringTag] = 'AbortSignal'; +} + +exports.AbortController = AbortController; +exports.AbortSignal = AbortSignal; +exports.default = AbortController; + +},{}],3:[function(require,module,exports){ +module.exports = after + +function after(count, callback, err_cb) { + var bail = false + err_cb = err_cb || noop + proxy.count = count + + return (count === 0) ? callback() : proxy + + function proxy(err, result) { + if (proxy.count <= 0) { + throw new Error('after called too many times') + } + --proxy.count + + // after first error, rest are passed to err_cb + if (err) { + bail = true + callback(err) + // future error callbacks will go to error handler + callback = err_cb + } else if (proxy.count === 0 && !bail) { + callback(null, result) + } + } +} + +function noop() {} + +},{}],4:[function(require,module,exports){ +/** + * An abstraction for slicing an arraybuffer even when + * ArrayBuffer.prototype.slice is not supported + * + * @api public + */ + +module.exports = function(arraybuffer, start, end) { + var bytes = arraybuffer.byteLength; + start = start || 0; + end = end || bytes; + + if (arraybuffer.slice) { return arraybuffer.slice(start, end); } + + if (start < 0) { start += bytes; } + if (end < 0) { end += bytes; } + if (end > bytes) { end = bytes; } + + if (start >= bytes || start >= end || bytes === 0) { + return new ArrayBuffer(0); + } + + var abv = new Uint8Array(arraybuffer); + var result = new Uint8Array(end - start); + for (var i = start, ii = 0; i < end; i++, ii++) { + result[ii] = abv[i]; + } + return result.buffer; +}; + +},{}],5:[function(require,module,exports){ + +/** + * Expose `Backoff`. + */ + +module.exports = Backoff; + +/** + * Initialize backoff timer with `opts`. + * + * - `min` initial timeout in milliseconds [100] + * - `max` max timeout [10000] + * - `jitter` [0] + * - `factor` [2] + * + * @param {Object} opts + * @api public + */ + +function Backoff(opts) { + opts = opts || {}; + this.ms = opts.min || 100; + this.max = opts.max || 10000; + this.factor = opts.factor || 2; + this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0; + this.attempts = 0; +} + +/** + * Return the backoff duration. + * + * @return {Number} + * @api public + */ + +Backoff.prototype.duration = function(){ + var ms = this.ms * Math.pow(this.factor, this.attempts++); + if (this.jitter) { + var rand = Math.random(); + var deviation = Math.floor(rand * this.jitter * ms); + ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation; + } + return Math.min(ms, this.max) | 0; +}; + +/** + * Reset the number of attempts. + * + * @api public + */ + +Backoff.prototype.reset = function(){ + this.attempts = 0; +}; + +/** + * Set the minimum duration + * + * @api public + */ + +Backoff.prototype.setMin = function(min){ + this.ms = min; +}; + +/** + * Set the maximum duration + * + * @api public + */ + +Backoff.prototype.setMax = function(max){ + this.max = max; +}; + +/** + * Set the jitter + * + * @api public + */ + +Backoff.prototype.setJitter = function(jitter){ + this.jitter = jitter; +}; + + +},{}],6:[function(require,module,exports){ +/* + * base64-arraybuffer + * https://github.com/niklasvh/base64-arraybuffer + * + * Copyright (c) 2012 Niklas von Hertzen + * Licensed under the MIT license. + */ +(function(){ + "use strict"; + + var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + // Use a lookup table to find the index. + var lookup = new Uint8Array(256); + for (var i = 0; i < chars.length; i++) { + lookup[chars.charCodeAt(i)] = i; + } + + exports.encode = function(arraybuffer) { + var bytes = new Uint8Array(arraybuffer), + i, len = bytes.length, base64 = ""; + + for (i = 0; i < len; i+=3) { + base64 += chars[bytes[i] >> 2]; + base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; + base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; + base64 += chars[bytes[i + 2] & 63]; + } + + if ((len % 3) === 2) { + base64 = base64.substring(0, base64.length - 1) + "="; + } else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + "=="; + } + + return base64; + }; + + exports.decode = function(base64) { + var bufferLength = base64.length * 0.75, + len = base64.length, i, p = 0, + encoded1, encoded2, encoded3, encoded4; + + if (base64[base64.length - 1] === "=") { + bufferLength--; + if (base64[base64.length - 2] === "=") { + bufferLength--; + } + } + + var arraybuffer = new ArrayBuffer(bufferLength), + bytes = new Uint8Array(arraybuffer); + + for (i = 0; i < len; i+=4) { + encoded1 = lookup[base64.charCodeAt(i)]; + encoded2 = lookup[base64.charCodeAt(i+1)]; + encoded3 = lookup[base64.charCodeAt(i+2)]; + encoded4 = lookup[base64.charCodeAt(i+3)]; + + bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); + bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); + bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); + } + + return arraybuffer; + }; +})(); + +},{}],7:[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('') +} + +},{}],8:[function(require,module,exports){ +/** + * Create a blob builder even when vendor prefixes exist + */ + +var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : + typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder : + typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : + typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : + false; + +/** + * Check if Blob constructor is supported + */ + +var blobSupported = (function() { + try { + var a = new Blob(['hi']); + return a.size === 2; + } catch(e) { + return false; + } +})(); + +/** + * Check if Blob constructor supports ArrayBufferViews + * Fails in Safari 6, so we need to map to ArrayBuffers there. + */ + +var blobSupportsArrayBufferView = blobSupported && (function() { + try { + var b = new Blob([new Uint8Array([1,2])]); + return b.size === 2; + } catch(e) { + return false; + } +})(); + +/** + * Check if BlobBuilder is supported + */ + +var blobBuilderSupported = BlobBuilder + && BlobBuilder.prototype.append + && BlobBuilder.prototype.getBlob; + +/** + * Helper function that maps ArrayBufferViews to ArrayBuffers + * Used by BlobBuilder constructor and old browsers that didn't + * support it in the Blob constructor. + */ + +function mapArrayBufferViews(ary) { + return ary.map(function(chunk) { + if (chunk.buffer instanceof ArrayBuffer) { + var buf = chunk.buffer; + + // if this is a subarray, make a copy so we only + // include the subarray region from the underlying buffer + if (chunk.byteLength !== buf.byteLength) { + var copy = new Uint8Array(chunk.byteLength); + copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength)); + buf = copy.buffer; + } + + return buf; + } + + return chunk; + }); +} + +function BlobBuilderConstructor(ary, options) { + options = options || {}; + + var bb = new BlobBuilder(); + mapArrayBufferViews(ary).forEach(function(part) { + bb.append(part); + }); + + return (options.type) ? bb.getBlob(options.type) : bb.getBlob(); +}; + +function BlobConstructor(ary, options) { + return new Blob(mapArrayBufferViews(ary), options || {}); +}; + +if (typeof Blob !== 'undefined') { + BlobBuilderConstructor.prototype = Blob.prototype; + BlobConstructor.prototype = Blob.prototype; +} + +module.exports = (function() { + if (blobSupported) { + return blobSupportsArrayBufferView ? Blob : BlobConstructor; + } else if (blobBuilderSupported) { + return BlobBuilderConstructor; + } else { + return undefined; + } +})(); + +},{}],9:[function(require,module,exports){ + +},{}],10:[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":7,"buffer":10,"ieee754":26}],11:[function(require,module,exports){ +/*! + Copyright (c) 2017 Jed Watson. + Licensed under the MIT License (MIT), see + http://jedwatson.github.io/classnames +*/ +/* global define */ + +(function () { + 'use strict'; + + var hasOwn = {}.hasOwnProperty; + + function classNames () { + var classes = []; + + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + if (!arg) continue; + + var argType = typeof arg; + + if (argType === 'string' || argType === 'number') { + classes.push(arg); + } else if (Array.isArray(arg) && arg.length) { + var inner = classNames.apply(null, arg); + if (inner) { + classes.push(inner); + } + } else if (argType === 'object') { + for (var key in arg) { + if (hasOwn.call(arg, key) && arg[key]) { + classes.push(key); + } + } + } + } + + return classes.join(' '); + } + + if (typeof module !== 'undefined' && module.exports) { + classNames.default = classNames; + module.exports = classNames; + } else if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { + // register as 'classnames', consistent with npm package name + define('classnames', [], function () { + return classNames; + }); + } else { + window.classNames = classNames; + } +}()); + +},{}],12:[function(require,module,exports){ +/** + * Slice reference. + */ + +var slice = [].slice; + +/** + * Bind `obj` to `fn`. + * + * @param {Object} obj + * @param {Function|String} fn or string + * @return {Function} + * @api public + */ + +module.exports = function(obj, fn){ + if ('string' == typeof fn) fn = obj[fn]; + if ('function' != typeof fn) throw new Error('bind() requires a function'); + var args = slice.call(arguments, 2); + return function(){ + return fn.apply(obj, args.concat(slice.call(arguments))); + } +}; + +},{}],13:[function(require,module,exports){ + +/** + * Expose `Emitter`. + */ + +if (typeof module !== 'undefined') { + module.exports = Emitter; +} + +/** + * Initialize a new `Emitter`. + * + * @api public + */ + +function Emitter(obj) { + if (obj) return mixin(obj); +}; + +/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */ + +function mixin(obj) { + for (var key in Emitter.prototype) { + obj[key] = Emitter.prototype[key]; + } + return obj; +} + +/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.on = +Emitter.prototype.addEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + (this._callbacks['$' + event] = this._callbacks['$' + event] || []) + .push(fn); + return this; +}; + +/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.once = function(event, fn){ + function on() { + this.off(event, on); + fn.apply(this, arguments); + } + + on.fn = fn; + this.on(event, on); + return this; +}; + +/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */ + +Emitter.prototype.off = +Emitter.prototype.removeListener = +Emitter.prototype.removeAllListeners = +Emitter.prototype.removeEventListener = function(event, fn){ + this._callbacks = this._callbacks || {}; + + // all + if (0 == arguments.length) { + this._callbacks = {}; + return this; + } + + // specific event + var callbacks = this._callbacks['$' + event]; + if (!callbacks) return this; + + // remove all handlers + if (1 == arguments.length) { + delete this._callbacks['$' + event]; + return this; + } + + // remove specific handler + var cb; + for (var i = 0; i < callbacks.length; i++) { + cb = callbacks[i]; + if (cb === fn || cb.fn === fn) { + callbacks.splice(i, 1); + break; + } + } + + // Remove event specific arrays for event types that no + // one is subscribed for to avoid memory leak. + if (callbacks.length === 0) { + delete this._callbacks['$' + event]; + } + + return this; +}; + +/** + * Emit `event` with the given args. + * + * @param {String} event + * @param {Mixed} ... + * @return {Emitter} + */ + +Emitter.prototype.emit = function(event){ + this._callbacks = this._callbacks || {}; + + var args = new Array(arguments.length - 1) + , callbacks = this._callbacks['$' + event]; + + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + + if (callbacks) { + callbacks = callbacks.slice(0); + for (var i = 0, len = callbacks.length; i < len; ++i) { + callbacks[i].apply(this, args); + } + } + + return this; +}; + +/** + * Return array of callbacks for `event`. + * + * @param {String} event + * @return {Array} + * @api public + */ + +Emitter.prototype.listeners = function(event){ + this._callbacks = this._callbacks || {}; + return this._callbacks['$' + event] || []; +}; + +/** + * Check if this emitter has `event` handlers. + * + * @param {String} event + * @return {Boolean} + * @api public + */ + +Emitter.prototype.hasListeners = function(event){ + return !! this.listeners(event).length; +}; + +},{}],14:[function(require,module,exports){ + +module.exports = function(a, b){ + var fn = function(){}; + fn.prototype = b.prototype; + a.prototype = new fn; + a.prototype.constructor = a; +}; +},{}],15:[function(require,module,exports){ +/*! + * Cropper.js v1.5.7 + * https://fengyuanchen.github.io/cropperjs + * + * Copyright 2015-present Chen Fengyuan + * Released under the MIT license + * + * Date: 2020-05-23T05:23:00.081Z + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.Cropper = factory()); +}(this, (function () { 'use strict'; + + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(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, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; + } + + function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; + } + + function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); + } + + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); + } + + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); + } + + 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 _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + var IS_BROWSER = typeof window !== 'undefined' && typeof window.document !== 'undefined'; + var WINDOW = IS_BROWSER ? window : {}; + var IS_TOUCH_DEVICE = IS_BROWSER && WINDOW.document.documentElement ? 'ontouchstart' in WINDOW.document.documentElement : false; + var HAS_POINTER_EVENT = IS_BROWSER ? 'PointerEvent' in WINDOW : false; + var NAMESPACE = 'cropper'; // Actions + + var ACTION_ALL = 'all'; + var ACTION_CROP = 'crop'; + var ACTION_MOVE = 'move'; + var ACTION_ZOOM = 'zoom'; + var ACTION_EAST = 'e'; + var ACTION_WEST = 'w'; + var ACTION_SOUTH = 's'; + var ACTION_NORTH = 'n'; + var ACTION_NORTH_EAST = 'ne'; + var ACTION_NORTH_WEST = 'nw'; + var ACTION_SOUTH_EAST = 'se'; + var ACTION_SOUTH_WEST = 'sw'; // Classes + + var CLASS_CROP = "".concat(NAMESPACE, "-crop"); + var CLASS_DISABLED = "".concat(NAMESPACE, "-disabled"); + var CLASS_HIDDEN = "".concat(NAMESPACE, "-hidden"); + var CLASS_HIDE = "".concat(NAMESPACE, "-hide"); + var CLASS_INVISIBLE = "".concat(NAMESPACE, "-invisible"); + var CLASS_MODAL = "".concat(NAMESPACE, "-modal"); + var CLASS_MOVE = "".concat(NAMESPACE, "-move"); // Data keys + + var DATA_ACTION = "".concat(NAMESPACE, "Action"); + var DATA_PREVIEW = "".concat(NAMESPACE, "Preview"); // Drag modes + + var DRAG_MODE_CROP = 'crop'; + var DRAG_MODE_MOVE = 'move'; + var DRAG_MODE_NONE = 'none'; // Events + + var EVENT_CROP = 'crop'; + var EVENT_CROP_END = 'cropend'; + var EVENT_CROP_MOVE = 'cropmove'; + var EVENT_CROP_START = 'cropstart'; + var EVENT_DBLCLICK = 'dblclick'; + var EVENT_TOUCH_START = IS_TOUCH_DEVICE ? 'touchstart' : 'mousedown'; + var EVENT_TOUCH_MOVE = IS_TOUCH_DEVICE ? 'touchmove' : 'mousemove'; + var EVENT_TOUCH_END = IS_TOUCH_DEVICE ? 'touchend touchcancel' : 'mouseup'; + var EVENT_POINTER_DOWN = HAS_POINTER_EVENT ? 'pointerdown' : EVENT_TOUCH_START; + var EVENT_POINTER_MOVE = HAS_POINTER_EVENT ? 'pointermove' : EVENT_TOUCH_MOVE; + var EVENT_POINTER_UP = HAS_POINTER_EVENT ? 'pointerup pointercancel' : EVENT_TOUCH_END; + var EVENT_READY = 'ready'; + var EVENT_RESIZE = 'resize'; + var EVENT_WHEEL = 'wheel'; + var EVENT_ZOOM = 'zoom'; // Mime types + + var MIME_TYPE_JPEG = 'image/jpeg'; // RegExps + + var REGEXP_ACTIONS = /^e|w|s|n|se|sw|ne|nw|all|crop|move|zoom$/; + var REGEXP_DATA_URL = /^data:/; + var REGEXP_DATA_URL_JPEG = /^data:image\/jpeg;base64,/; + var REGEXP_TAG_NAME = /^img|canvas$/i; // Misc + + var DEFAULTS = { + // Define the view mode of the cropper + viewMode: 0, + // 0, 1, 2, 3 + // Define the dragging mode of the cropper + dragMode: DRAG_MODE_CROP, + // 'crop', 'move' or 'none' + // Define the initial aspect ratio of the crop box + initialAspectRatio: NaN, + // Define the aspect ratio of the crop box + aspectRatio: NaN, + // An object with the previous cropping result data + data: null, + // A selector for adding extra containers to preview + preview: '', + // Re-render the cropper when resize the window + responsive: true, + // Restore the cropped area after resize the window + restore: true, + // Check if the current image is a cross-origin image + checkCrossOrigin: true, + // Check the current image's Exif Orientation information + checkOrientation: true, + // Show the black modal + modal: true, + // Show the dashed lines for guiding + guides: true, + // Show the center indicator for guiding + center: true, + // Show the white modal to highlight the crop box + highlight: true, + // Show the grid background + background: true, + // Enable to crop the image automatically when initialize + autoCrop: true, + // Define the percentage of automatic cropping area when initializes + autoCropArea: 0.8, + // Enable to move the image + movable: true, + // Enable to rotate the image + rotatable: true, + // Enable to scale the image + scalable: true, + // Enable to zoom the image + zoomable: true, + // Enable to zoom the image by dragging touch + zoomOnTouch: true, + // Enable to zoom the image by wheeling mouse + zoomOnWheel: true, + // Define zoom ratio when zoom the image by wheeling mouse + wheelZoomRatio: 0.1, + // Enable to move the crop box + cropBoxMovable: true, + // Enable to resize the crop box + cropBoxResizable: true, + // Toggle drag mode between "crop" and "move" when click twice on the cropper + toggleDragModeOnDblclick: true, + // Size limitation + minCanvasWidth: 0, + minCanvasHeight: 0, + minCropBoxWidth: 0, + minCropBoxHeight: 0, + minContainerWidth: 200, + minContainerHeight: 100, + // Shortcuts of events + ready: null, + cropstart: null, + cropmove: null, + cropend: null, + crop: null, + zoom: null + }; + + var TEMPLATE = '
' + '
' + '
' + '
' + '
' + '
' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '
' + '
'; + + /** + * Check if the given value is not a number. + */ + + var isNaN = Number.isNaN || WINDOW.isNaN; + /** + * Check if the given value is a number. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is a number, else `false`. + */ + + function isNumber(value) { + return typeof value === 'number' && !isNaN(value); + } + /** + * Check if the given value is a positive number. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is a positive number, else `false`. + */ + + var isPositiveNumber = function isPositiveNumber(value) { + return value > 0 && value < Infinity; + }; + /** + * Check if the given value is undefined. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is undefined, else `false`. + */ + + function isUndefined(value) { + return typeof value === 'undefined'; + } + /** + * Check if the given value is an object. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is an object, else `false`. + */ + + function isObject(value) { + return _typeof(value) === 'object' && value !== null; + } + var hasOwnProperty = Object.prototype.hasOwnProperty; + /** + * Check if the given value is a plain object. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is a plain object, else `false`. + */ + + function isPlainObject(value) { + if (!isObject(value)) { + return false; + } + + try { + var _constructor = value.constructor; + var prototype = _constructor.prototype; + return _constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf'); + } catch (error) { + return false; + } + } + /** + * Check if the given value is a function. + * @param {*} value - The value to check. + * @returns {boolean} Returns `true` if the given value is a function, else `false`. + */ + + function isFunction(value) { + return typeof value === 'function'; + } + var slice = Array.prototype.slice; + /** + * Convert array-like or iterable object to an array. + * @param {*} value - The value to convert. + * @returns {Array} Returns a new array. + */ + + function toArray(value) { + return Array.from ? Array.from(value) : slice.call(value); + } + /** + * Iterate the given data. + * @param {*} data - The data to iterate. + * @param {Function} callback - The process function for each element. + * @returns {*} The original data. + */ + + function forEach(data, callback) { + if (data && isFunction(callback)) { + if (Array.isArray(data) || isNumber(data.length) + /* array-like */ + ) { + toArray(data).forEach(function (value, key) { + callback.call(data, value, key, data); + }); + } else if (isObject(data)) { + Object.keys(data).forEach(function (key) { + callback.call(data, data[key], key, data); + }); + } + } + + return data; + } + /** + * Extend the given object. + * @param {*} target - The target object to extend. + * @param {*} args - The rest objects for merging to the target object. + * @returns {Object} The extended object. + */ + + var assign = Object.assign || function assign(target) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + if (isObject(target) && args.length > 0) { + args.forEach(function (arg) { + if (isObject(arg)) { + Object.keys(arg).forEach(function (key) { + target[key] = arg[key]; + }); + } + }); + } + + return target; + }; + var REGEXP_DECIMALS = /\.\d*(?:0|9){12}\d*$/; + /** + * Normalize decimal number. + * Check out {@link https://0.30000000000000004.com/} + * @param {number} value - The value to normalize. + * @param {number} [times=100000000000] - The times for normalizing. + * @returns {number} Returns the normalized number. + */ + + function normalizeDecimalNumber(value) { + var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000000; + return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value; + } + var REGEXP_SUFFIX = /^width|height|left|top|marginLeft|marginTop$/; + /** + * Apply styles to the given element. + * @param {Element} element - The target element. + * @param {Object} styles - The styles for applying. + */ + + function setStyle(element, styles) { + var style = element.style; + forEach(styles, function (value, property) { + if (REGEXP_SUFFIX.test(property) && isNumber(value)) { + value = "".concat(value, "px"); + } + + style[property] = value; + }); + } + /** + * Check if the given element has a special class. + * @param {Element} element - The element to check. + * @param {string} value - The class to search. + * @returns {boolean} Returns `true` if the special class was found. + */ + + function hasClass(element, value) { + return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1; + } + /** + * Add classes to the given element. + * @param {Element} element - The target element. + * @param {string} value - The classes to be added. + */ + + function addClass(element, value) { + if (!value) { + return; + } + + if (isNumber(element.length)) { + forEach(element, function (elem) { + addClass(elem, value); + }); + return; + } + + if (element.classList) { + element.classList.add(value); + return; + } + + var className = element.className.trim(); + + if (!className) { + element.className = value; + } else if (className.indexOf(value) < 0) { + element.className = "".concat(className, " ").concat(value); + } + } + /** + * Remove classes from the given element. + * @param {Element} element - The target element. + * @param {string} value - The classes to be removed. + */ + + function removeClass(element, value) { + if (!value) { + return; + } + + if (isNumber(element.length)) { + forEach(element, function (elem) { + removeClass(elem, value); + }); + return; + } + + if (element.classList) { + element.classList.remove(value); + return; + } + + if (element.className.indexOf(value) >= 0) { + element.className = element.className.replace(value, ''); + } + } + /** + * Add or remove classes from the given element. + * @param {Element} element - The target element. + * @param {string} value - The classes to be toggled. + * @param {boolean} added - Add only. + */ + + function toggleClass(element, value, added) { + if (!value) { + return; + } + + if (isNumber(element.length)) { + forEach(element, function (elem) { + toggleClass(elem, value, added); + }); + return; + } // IE10-11 doesn't support the second parameter of `classList.toggle` + + + if (added) { + addClass(element, value); + } else { + removeClass(element, value); + } + } + var REGEXP_CAMEL_CASE = /([a-z\d])([A-Z])/g; + /** + * Transform the given string from camelCase to kebab-case + * @param {string} value - The value to transform. + * @returns {string} The transformed value. + */ + + function toParamCase(value) { + return value.replace(REGEXP_CAMEL_CASE, '$1-$2').toLowerCase(); + } + /** + * Get data from the given element. + * @param {Element} element - The target element. + * @param {string} name - The data key to get. + * @returns {string} The data value. + */ + + function getData(element, name) { + if (isObject(element[name])) { + return element[name]; + } + + if (element.dataset) { + return element.dataset[name]; + } + + return element.getAttribute("data-".concat(toParamCase(name))); + } + /** + * Set data to the given element. + * @param {Element} element - The target element. + * @param {string} name - The data key to set. + * @param {string} data - The data value. + */ + + function setData(element, name, data) { + if (isObject(data)) { + element[name] = data; + } else if (element.dataset) { + element.dataset[name] = data; + } else { + element.setAttribute("data-".concat(toParamCase(name)), data); + } + } + /** + * Remove data from the given element. + * @param {Element} element - The target element. + * @param {string} name - The data key to remove. + */ + + function removeData(element, name) { + if (isObject(element[name])) { + try { + delete element[name]; + } catch (error) { + element[name] = undefined; + } + } else if (element.dataset) { + // #128 Safari not allows to delete dataset property + try { + delete element.dataset[name]; + } catch (error) { + element.dataset[name] = undefined; + } + } else { + element.removeAttribute("data-".concat(toParamCase(name))); + } + } + var REGEXP_SPACES = /\s\s*/; + + var onceSupported = function () { + var supported = false; + + if (IS_BROWSER) { + var once = false; + + var listener = function listener() {}; + + var options = Object.defineProperty({}, 'once', { + get: function get() { + supported = true; + return once; + }, + + /** + * This setter can fix a `TypeError` in strict mode + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only} + * @param {boolean} value - The value to set + */ + set: function set(value) { + once = value; + } + }); + WINDOW.addEventListener('test', listener, options); + WINDOW.removeEventListener('test', listener, options); + } + + return supported; + }(); + /** + * Remove event listener from the target element. + * @param {Element} element - The event target. + * @param {string} type - The event type(s). + * @param {Function} listener - The event listener. + * @param {Object} options - The event options. + */ + + + function removeListener(element, type, listener) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var handler = listener; + type.trim().split(REGEXP_SPACES).forEach(function (event) { + if (!onceSupported) { + var listeners = element.listeners; + + if (listeners && listeners[event] && listeners[event][listener]) { + handler = listeners[event][listener]; + delete listeners[event][listener]; + + if (Object.keys(listeners[event]).length === 0) { + delete listeners[event]; + } + + if (Object.keys(listeners).length === 0) { + delete element.listeners; + } + } + } + + element.removeEventListener(event, handler, options); + }); + } + /** + * Add event listener to the target element. + * @param {Element} element - The event target. + * @param {string} type - The event type(s). + * @param {Function} listener - The event listener. + * @param {Object} options - The event options. + */ + + function addListener(element, type, listener) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var _handler = listener; + type.trim().split(REGEXP_SPACES).forEach(function (event) { + if (options.once && !onceSupported) { + var _element$listeners = element.listeners, + listeners = _element$listeners === void 0 ? {} : _element$listeners; + + _handler = function handler() { + delete listeners[event][listener]; + element.removeEventListener(event, _handler, options); + + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + + listener.apply(element, args); + }; + + if (!listeners[event]) { + listeners[event] = {}; + } + + if (listeners[event][listener]) { + element.removeEventListener(event, listeners[event][listener], options); + } + + listeners[event][listener] = _handler; + element.listeners = listeners; + } + + element.addEventListener(event, _handler, options); + }); + } + /** + * Dispatch event on the target element. + * @param {Element} element - The event target. + * @param {string} type - The event type(s). + * @param {Object} data - The additional event data. + * @returns {boolean} Indicate if the event is default prevented or not. + */ + + function dispatchEvent(element, type, data) { + var event; // Event and CustomEvent on IE9-11 are global objects, not constructors + + if (isFunction(Event) && isFunction(CustomEvent)) { + event = new CustomEvent(type, { + detail: data, + bubbles: true, + cancelable: true + }); + } else { + event = document.createEvent('CustomEvent'); + event.initCustomEvent(type, true, true, data); + } + + return element.dispatchEvent(event); + } + /** + * Get the offset base on the document. + * @param {Element} element - The target element. + * @returns {Object} The offset data. + */ + + function getOffset(element) { + var box = element.getBoundingClientRect(); + return { + left: box.left + (window.pageXOffset - document.documentElement.clientLeft), + top: box.top + (window.pageYOffset - document.documentElement.clientTop) + }; + } + var location = WINDOW.location; + var REGEXP_ORIGINS = /^(\w+:)\/\/([^:/?#]*):?(\d*)/i; + /** + * Check if the given URL is a cross origin URL. + * @param {string} url - The target URL. + * @returns {boolean} Returns `true` if the given URL is a cross origin URL, else `false`. + */ + + function isCrossOriginURL(url) { + var parts = url.match(REGEXP_ORIGINS); + return parts !== null && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port); + } + /** + * Add timestamp to the given URL. + * @param {string} url - The target URL. + * @returns {string} The result URL. + */ + + function addTimestamp(url) { + var timestamp = "timestamp=".concat(new Date().getTime()); + return url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp; + } + /** + * Get transforms base on the given object. + * @param {Object} obj - The target object. + * @returns {string} A string contains transform values. + */ + + function getTransforms(_ref) { + var rotate = _ref.rotate, + scaleX = _ref.scaleX, + scaleY = _ref.scaleY, + translateX = _ref.translateX, + translateY = _ref.translateY; + var values = []; + + if (isNumber(translateX) && translateX !== 0) { + values.push("translateX(".concat(translateX, "px)")); + } + + if (isNumber(translateY) && translateY !== 0) { + values.push("translateY(".concat(translateY, "px)")); + } // Rotate should come first before scale to match orientation transform + + + if (isNumber(rotate) && rotate !== 0) { + values.push("rotate(".concat(rotate, "deg)")); + } + + if (isNumber(scaleX) && scaleX !== 1) { + values.push("scaleX(".concat(scaleX, ")")); + } + + if (isNumber(scaleY) && scaleY !== 1) { + values.push("scaleY(".concat(scaleY, ")")); + } + + var transform = values.length ? values.join(' ') : 'none'; + return { + WebkitTransform: transform, + msTransform: transform, + transform: transform + }; + } + /** + * Get the max ratio of a group of pointers. + * @param {string} pointers - The target pointers. + * @returns {number} The result ratio. + */ + + function getMaxZoomRatio(pointers) { + var pointers2 = _objectSpread2({}, pointers); + + var ratios = []; + forEach(pointers, function (pointer, pointerId) { + delete pointers2[pointerId]; + forEach(pointers2, function (pointer2) { + var x1 = Math.abs(pointer.startX - pointer2.startX); + var y1 = Math.abs(pointer.startY - pointer2.startY); + var x2 = Math.abs(pointer.endX - pointer2.endX); + var y2 = Math.abs(pointer.endY - pointer2.endY); + var z1 = Math.sqrt(x1 * x1 + y1 * y1); + var z2 = Math.sqrt(x2 * x2 + y2 * y2); + var ratio = (z2 - z1) / z1; + ratios.push(ratio); + }); + }); + ratios.sort(function (a, b) { + return Math.abs(a) < Math.abs(b); + }); + return ratios[0]; + } + /** + * Get a pointer from an event object. + * @param {Object} event - The target event object. + * @param {boolean} endOnly - Indicates if only returns the end point coordinate or not. + * @returns {Object} The result pointer contains start and/or end point coordinates. + */ + + function getPointer(_ref2, endOnly) { + var pageX = _ref2.pageX, + pageY = _ref2.pageY; + var end = { + endX: pageX, + endY: pageY + }; + return endOnly ? end : _objectSpread2({ + startX: pageX, + startY: pageY + }, end); + } + /** + * Get the center point coordinate of a group of pointers. + * @param {Object} pointers - The target pointers. + * @returns {Object} The center point coordinate. + */ + + function getPointersCenter(pointers) { + var pageX = 0; + var pageY = 0; + var count = 0; + forEach(pointers, function (_ref3) { + var startX = _ref3.startX, + startY = _ref3.startY; + pageX += startX; + pageY += startY; + count += 1; + }); + pageX /= count; + pageY /= count; + return { + pageX: pageX, + pageY: pageY + }; + } + /** + * Get the max sizes in a rectangle under the given aspect ratio. + * @param {Object} data - The original sizes. + * @param {string} [type='contain'] - The adjust type. + * @returns {Object} The result sizes. + */ + + function getAdjustedSizes(_ref4) // or 'cover' + { + var aspectRatio = _ref4.aspectRatio, + height = _ref4.height, + width = _ref4.width; + var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contain'; + var isValidWidth = isPositiveNumber(width); + var isValidHeight = isPositiveNumber(height); + + if (isValidWidth && isValidHeight) { + var adjustedWidth = height * aspectRatio; + + if (type === 'contain' && adjustedWidth > width || type === 'cover' && adjustedWidth < width) { + height = width / aspectRatio; + } else { + width = height * aspectRatio; + } + } else if (isValidWidth) { + height = width / aspectRatio; + } else if (isValidHeight) { + width = height * aspectRatio; + } + + return { + width: width, + height: height + }; + } + /** + * Get the new sizes of a rectangle after rotated. + * @param {Object} data - The original sizes. + * @returns {Object} The result sizes. + */ + + function getRotatedSizes(_ref5) { + var width = _ref5.width, + height = _ref5.height, + degree = _ref5.degree; + degree = Math.abs(degree) % 180; + + if (degree === 90) { + return { + width: height, + height: width + }; + } + + var arc = degree % 90 * Math.PI / 180; + var sinArc = Math.sin(arc); + var cosArc = Math.cos(arc); + var newWidth = width * cosArc + height * sinArc; + var newHeight = width * sinArc + height * cosArc; + return degree > 90 ? { + width: newHeight, + height: newWidth + } : { + width: newWidth, + height: newHeight + }; + } + /** + * Get a canvas which drew the given image. + * @param {HTMLImageElement} image - The image for drawing. + * @param {Object} imageData - The image data. + * @param {Object} canvasData - The canvas data. + * @param {Object} options - The options. + * @returns {HTMLCanvasElement} The result canvas. + */ + + function getSourceCanvas(image, _ref6, _ref7, _ref8) { + var imageAspectRatio = _ref6.aspectRatio, + imageNaturalWidth = _ref6.naturalWidth, + imageNaturalHeight = _ref6.naturalHeight, + _ref6$rotate = _ref6.rotate, + rotate = _ref6$rotate === void 0 ? 0 : _ref6$rotate, + _ref6$scaleX = _ref6.scaleX, + scaleX = _ref6$scaleX === void 0 ? 1 : _ref6$scaleX, + _ref6$scaleY = _ref6.scaleY, + scaleY = _ref6$scaleY === void 0 ? 1 : _ref6$scaleY; + var aspectRatio = _ref7.aspectRatio, + naturalWidth = _ref7.naturalWidth, + naturalHeight = _ref7.naturalHeight; + var _ref8$fillColor = _ref8.fillColor, + fillColor = _ref8$fillColor === void 0 ? 'transparent' : _ref8$fillColor, + _ref8$imageSmoothingE = _ref8.imageSmoothingEnabled, + imageSmoothingEnabled = _ref8$imageSmoothingE === void 0 ? true : _ref8$imageSmoothingE, + _ref8$imageSmoothingQ = _ref8.imageSmoothingQuality, + imageSmoothingQuality = _ref8$imageSmoothingQ === void 0 ? 'low' : _ref8$imageSmoothingQ, + _ref8$maxWidth = _ref8.maxWidth, + maxWidth = _ref8$maxWidth === void 0 ? Infinity : _ref8$maxWidth, + _ref8$maxHeight = _ref8.maxHeight, + maxHeight = _ref8$maxHeight === void 0 ? Infinity : _ref8$maxHeight, + _ref8$minWidth = _ref8.minWidth, + minWidth = _ref8$minWidth === void 0 ? 0 : _ref8$minWidth, + _ref8$minHeight = _ref8.minHeight, + minHeight = _ref8$minHeight === void 0 ? 0 : _ref8$minHeight; + var canvas = document.createElement('canvas'); + var context = canvas.getContext('2d'); + var maxSizes = getAdjustedSizes({ + aspectRatio: aspectRatio, + width: maxWidth, + height: maxHeight + }); + var minSizes = getAdjustedSizes({ + aspectRatio: aspectRatio, + width: minWidth, + height: minHeight + }, 'cover'); + var width = Math.min(maxSizes.width, Math.max(minSizes.width, naturalWidth)); + var height = Math.min(maxSizes.height, Math.max(minSizes.height, naturalHeight)); // Note: should always use image's natural sizes for drawing as + // imageData.naturalWidth === canvasData.naturalHeight when rotate % 180 === 90 + + var destMaxSizes = getAdjustedSizes({ + aspectRatio: imageAspectRatio, + width: maxWidth, + height: maxHeight + }); + var destMinSizes = getAdjustedSizes({ + aspectRatio: imageAspectRatio, + width: minWidth, + height: minHeight + }, 'cover'); + var destWidth = Math.min(destMaxSizes.width, Math.max(destMinSizes.width, imageNaturalWidth)); + var destHeight = Math.min(destMaxSizes.height, Math.max(destMinSizes.height, imageNaturalHeight)); + var params = [-destWidth / 2, -destHeight / 2, destWidth, destHeight]; + canvas.width = normalizeDecimalNumber(width); + canvas.height = normalizeDecimalNumber(height); + context.fillStyle = fillColor; + context.fillRect(0, 0, width, height); + context.save(); + context.translate(width / 2, height / 2); + context.rotate(rotate * Math.PI / 180); + context.scale(scaleX, scaleY); + context.imageSmoothingEnabled = imageSmoothingEnabled; + context.imageSmoothingQuality = imageSmoothingQuality; + context.drawImage.apply(context, [image].concat(_toConsumableArray(params.map(function (param) { + return Math.floor(normalizeDecimalNumber(param)); + })))); + context.restore(); + return canvas; + } + var fromCharCode = String.fromCharCode; + /** + * Get string from char code in data view. + * @param {DataView} dataView - The data view for read. + * @param {number} start - The start index. + * @param {number} length - The read length. + * @returns {string} The read result. + */ + + function getStringFromCharCode(dataView, start, length) { + var str = ''; + length += start; + + for (var i = start; i < length; i += 1) { + str += fromCharCode(dataView.getUint8(i)); + } + + return str; + } + var REGEXP_DATA_URL_HEAD = /^data:.*,/; + /** + * Transform Data URL to array buffer. + * @param {string} dataURL - The Data URL to transform. + * @returns {ArrayBuffer} The result array buffer. + */ + + function dataURLToArrayBuffer(dataURL) { + var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, ''); + var binary = atob(base64); + var arrayBuffer = new ArrayBuffer(binary.length); + var uint8 = new Uint8Array(arrayBuffer); + forEach(uint8, function (value, i) { + uint8[i] = binary.charCodeAt(i); + }); + return arrayBuffer; + } + /** + * Transform array buffer to Data URL. + * @param {ArrayBuffer} arrayBuffer - The array buffer to transform. + * @param {string} mimeType - The mime type of the Data URL. + * @returns {string} The result Data URL. + */ + + function arrayBufferToDataURL(arrayBuffer, mimeType) { + var chunks = []; // Chunk Typed Array for better performance (#435) + + var chunkSize = 8192; + var uint8 = new Uint8Array(arrayBuffer); + + while (uint8.length > 0) { + // XXX: Babel's `toConsumableArray` helper will throw error in IE or Safari 9 + // eslint-disable-next-line prefer-spread + chunks.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize)))); + uint8 = uint8.subarray(chunkSize); + } + + return "data:".concat(mimeType, ";base64,").concat(btoa(chunks.join(''))); + } + /** + * Get orientation value from given array buffer. + * @param {ArrayBuffer} arrayBuffer - The array buffer to read. + * @returns {number} The read orientation value. + */ + + function resetAndGetOrientation(arrayBuffer) { + var dataView = new DataView(arrayBuffer); + var orientation; // Ignores range error when the image does not have correct Exif information + + try { + var littleEndian; + var app1Start; + var ifdStart; // Only handle JPEG image (start by 0xFFD8) + + if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) { + var length = dataView.byteLength; + var offset = 2; + + while (offset + 1 < length) { + if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) { + app1Start = offset; + break; + } + + offset += 1; + } + } + + if (app1Start) { + var exifIDCode = app1Start + 4; + var tiffOffset = app1Start + 10; + + if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') { + var endianness = dataView.getUint16(tiffOffset); + littleEndian = endianness === 0x4949; + + if (littleEndian || endianness === 0x4D4D + /* bigEndian */ + ) { + if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) { + var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian); + + if (firstIFDOffset >= 0x00000008) { + ifdStart = tiffOffset + firstIFDOffset; + } + } + } + } + } + + if (ifdStart) { + var _length = dataView.getUint16(ifdStart, littleEndian); + + var _offset; + + var i; + + for (i = 0; i < _length; i += 1) { + _offset = ifdStart + i * 12 + 2; + + if (dataView.getUint16(_offset, littleEndian) === 0x0112 + /* Orientation */ + ) { + // 8 is the offset of the current tag's value + _offset += 8; // Get the original orientation value + + orientation = dataView.getUint16(_offset, littleEndian); // Override the orientation with its default value + + dataView.setUint16(_offset, 1, littleEndian); + break; + } + } + } + } catch (error) { + orientation = 1; + } + + return orientation; + } + /** + * Parse Exif Orientation value. + * @param {number} orientation - The orientation to parse. + * @returns {Object} The parsed result. + */ + + function parseOrientation(orientation) { + var rotate = 0; + var scaleX = 1; + var scaleY = 1; + + switch (orientation) { + // Flip horizontal + case 2: + scaleX = -1; + break; + // Rotate left 180° + + case 3: + rotate = -180; + break; + // Flip vertical + + case 4: + scaleY = -1; + break; + // Flip vertical and rotate right 90° + + case 5: + rotate = 90; + scaleY = -1; + break; + // Rotate right 90° + + case 6: + rotate = 90; + break; + // Flip horizontal and rotate right 90° + + case 7: + rotate = 90; + scaleX = -1; + break; + // Rotate left 90° + + case 8: + rotate = -90; + break; + } + + return { + rotate: rotate, + scaleX: scaleX, + scaleY: scaleY + }; + } + + var render = { + render: function render() { + this.initContainer(); + this.initCanvas(); + this.initCropBox(); + this.renderCanvas(); + + if (this.cropped) { + this.renderCropBox(); + } + }, + initContainer: function initContainer() { + var element = this.element, + options = this.options, + container = this.container, + cropper = this.cropper; + addClass(cropper, CLASS_HIDDEN); + removeClass(element, CLASS_HIDDEN); + var containerData = { + width: Math.max(container.offsetWidth, Number(options.minContainerWidth) || 200), + height: Math.max(container.offsetHeight, Number(options.minContainerHeight) || 100) + }; + this.containerData = containerData; + setStyle(cropper, { + width: containerData.width, + height: containerData.height + }); + addClass(element, CLASS_HIDDEN); + removeClass(cropper, CLASS_HIDDEN); + }, + // Canvas (image wrapper) + initCanvas: function initCanvas() { + var containerData = this.containerData, + imageData = this.imageData; + var viewMode = this.options.viewMode; + var rotated = Math.abs(imageData.rotate) % 180 === 90; + var naturalWidth = rotated ? imageData.naturalHeight : imageData.naturalWidth; + var naturalHeight = rotated ? imageData.naturalWidth : imageData.naturalHeight; + var aspectRatio = naturalWidth / naturalHeight; + var canvasWidth = containerData.width; + var canvasHeight = containerData.height; + + if (containerData.height * aspectRatio > containerData.width) { + if (viewMode === 3) { + canvasWidth = containerData.height * aspectRatio; + } else { + canvasHeight = containerData.width / aspectRatio; + } + } else if (viewMode === 3) { + canvasHeight = containerData.width / aspectRatio; + } else { + canvasWidth = containerData.height * aspectRatio; + } + + var canvasData = { + aspectRatio: aspectRatio, + naturalWidth: naturalWidth, + naturalHeight: naturalHeight, + width: canvasWidth, + height: canvasHeight + }; + canvasData.left = (containerData.width - canvasWidth) / 2; + canvasData.top = (containerData.height - canvasHeight) / 2; + canvasData.oldLeft = canvasData.left; + canvasData.oldTop = canvasData.top; + this.canvasData = canvasData; + this.limited = viewMode === 1 || viewMode === 2; + this.limitCanvas(true, true); + this.initialImageData = assign({}, imageData); + this.initialCanvasData = assign({}, canvasData); + }, + limitCanvas: function limitCanvas(sizeLimited, positionLimited) { + var options = this.options, + containerData = this.containerData, + canvasData = this.canvasData, + cropBoxData = this.cropBoxData; + var viewMode = options.viewMode; + var aspectRatio = canvasData.aspectRatio; + var cropped = this.cropped && cropBoxData; + + if (sizeLimited) { + var minCanvasWidth = Number(options.minCanvasWidth) || 0; + var minCanvasHeight = Number(options.minCanvasHeight) || 0; + + if (viewMode > 1) { + minCanvasWidth = Math.max(minCanvasWidth, containerData.width); + minCanvasHeight = Math.max(minCanvasHeight, containerData.height); + + if (viewMode === 3) { + if (minCanvasHeight * aspectRatio > minCanvasWidth) { + minCanvasWidth = minCanvasHeight * aspectRatio; + } else { + minCanvasHeight = minCanvasWidth / aspectRatio; + } + } + } else if (viewMode > 0) { + if (minCanvasWidth) { + minCanvasWidth = Math.max(minCanvasWidth, cropped ? cropBoxData.width : 0); + } else if (minCanvasHeight) { + minCanvasHeight = Math.max(minCanvasHeight, cropped ? cropBoxData.height : 0); + } else if (cropped) { + minCanvasWidth = cropBoxData.width; + minCanvasHeight = cropBoxData.height; + + if (minCanvasHeight * aspectRatio > minCanvasWidth) { + minCanvasWidth = minCanvasHeight * aspectRatio; + } else { + minCanvasHeight = minCanvasWidth / aspectRatio; + } + } + } + + var _getAdjustedSizes = getAdjustedSizes({ + aspectRatio: aspectRatio, + width: minCanvasWidth, + height: minCanvasHeight + }); + + minCanvasWidth = _getAdjustedSizes.width; + minCanvasHeight = _getAdjustedSizes.height; + canvasData.minWidth = minCanvasWidth; + canvasData.minHeight = minCanvasHeight; + canvasData.maxWidth = Infinity; + canvasData.maxHeight = Infinity; + } + + if (positionLimited) { + if (viewMode > (cropped ? 0 : 1)) { + var newCanvasLeft = containerData.width - canvasData.width; + var newCanvasTop = containerData.height - canvasData.height; + canvasData.minLeft = Math.min(0, newCanvasLeft); + canvasData.minTop = Math.min(0, newCanvasTop); + canvasData.maxLeft = Math.max(0, newCanvasLeft); + canvasData.maxTop = Math.max(0, newCanvasTop); + + if (cropped && this.limited) { + canvasData.minLeft = Math.min(cropBoxData.left, cropBoxData.left + (cropBoxData.width - canvasData.width)); + canvasData.minTop = Math.min(cropBoxData.top, cropBoxData.top + (cropBoxData.height - canvasData.height)); + canvasData.maxLeft = cropBoxData.left; + canvasData.maxTop = cropBoxData.top; + + if (viewMode === 2) { + if (canvasData.width >= containerData.width) { + canvasData.minLeft = Math.min(0, newCanvasLeft); + canvasData.maxLeft = Math.max(0, newCanvasLeft); + } + + if (canvasData.height >= containerData.height) { + canvasData.minTop = Math.min(0, newCanvasTop); + canvasData.maxTop = Math.max(0, newCanvasTop); + } + } + } + } else { + canvasData.minLeft = -canvasData.width; + canvasData.minTop = -canvasData.height; + canvasData.maxLeft = containerData.width; + canvasData.maxTop = containerData.height; + } + } + }, + renderCanvas: function renderCanvas(changed, transformed) { + var canvasData = this.canvasData, + imageData = this.imageData; + + if (transformed) { + var _getRotatedSizes = getRotatedSizes({ + width: imageData.naturalWidth * Math.abs(imageData.scaleX || 1), + height: imageData.naturalHeight * Math.abs(imageData.scaleY || 1), + degree: imageData.rotate || 0 + }), + naturalWidth = _getRotatedSizes.width, + naturalHeight = _getRotatedSizes.height; + + var width = canvasData.width * (naturalWidth / canvasData.naturalWidth); + var height = canvasData.height * (naturalHeight / canvasData.naturalHeight); + canvasData.left -= (width - canvasData.width) / 2; + canvasData.top -= (height - canvasData.height) / 2; + canvasData.width = width; + canvasData.height = height; + canvasData.aspectRatio = naturalWidth / naturalHeight; + canvasData.naturalWidth = naturalWidth; + canvasData.naturalHeight = naturalHeight; + this.limitCanvas(true, false); + } + + if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) { + canvasData.left = canvasData.oldLeft; + } + + if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) { + canvasData.top = canvasData.oldTop; + } + + canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth); + canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight); + this.limitCanvas(false, true); + canvasData.left = Math.min(Math.max(canvasData.left, canvasData.minLeft), canvasData.maxLeft); + canvasData.top = Math.min(Math.max(canvasData.top, canvasData.minTop), canvasData.maxTop); + canvasData.oldLeft = canvasData.left; + canvasData.oldTop = canvasData.top; + setStyle(this.canvas, assign({ + width: canvasData.width, + height: canvasData.height + }, getTransforms({ + translateX: canvasData.left, + translateY: canvasData.top + }))); + this.renderImage(changed); + + if (this.cropped && this.limited) { + this.limitCropBox(true, true); + } + }, + renderImage: function renderImage(changed) { + var canvasData = this.canvasData, + imageData = this.imageData; + var width = imageData.naturalWidth * (canvasData.width / canvasData.naturalWidth); + var height = imageData.naturalHeight * (canvasData.height / canvasData.naturalHeight); + assign(imageData, { + width: width, + height: height, + left: (canvasData.width - width) / 2, + top: (canvasData.height - height) / 2 + }); + setStyle(this.image, assign({ + width: imageData.width, + height: imageData.height + }, getTransforms(assign({ + translateX: imageData.left, + translateY: imageData.top + }, imageData)))); + + if (changed) { + this.output(); + } + }, + initCropBox: function initCropBox() { + var options = this.options, + canvasData = this.canvasData; + var aspectRatio = options.aspectRatio || options.initialAspectRatio; + var autoCropArea = Number(options.autoCropArea) || 0.8; + var cropBoxData = { + width: canvasData.width, + height: canvasData.height + }; + + if (aspectRatio) { + if (canvasData.height * aspectRatio > canvasData.width) { + cropBoxData.height = cropBoxData.width / aspectRatio; + } else { + cropBoxData.width = cropBoxData.height * aspectRatio; + } + } + + this.cropBoxData = cropBoxData; + this.limitCropBox(true, true); // Initialize auto crop area + + cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth); + cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight); // The width/height of auto crop area must large than "minWidth/Height" + + cropBoxData.width = Math.max(cropBoxData.minWidth, cropBoxData.width * autoCropArea); + cropBoxData.height = Math.max(cropBoxData.minHeight, cropBoxData.height * autoCropArea); + cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2; + cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2; + cropBoxData.oldLeft = cropBoxData.left; + cropBoxData.oldTop = cropBoxData.top; + this.initialCropBoxData = assign({}, cropBoxData); + }, + limitCropBox: function limitCropBox(sizeLimited, positionLimited) { + var options = this.options, + containerData = this.containerData, + canvasData = this.canvasData, + cropBoxData = this.cropBoxData, + limited = this.limited; + var aspectRatio = options.aspectRatio; + + if (sizeLimited) { + var minCropBoxWidth = Number(options.minCropBoxWidth) || 0; + var minCropBoxHeight = Number(options.minCropBoxHeight) || 0; + var maxCropBoxWidth = limited ? Math.min(containerData.width, canvasData.width, canvasData.width + canvasData.left, containerData.width - canvasData.left) : containerData.width; + var maxCropBoxHeight = limited ? Math.min(containerData.height, canvasData.height, canvasData.height + canvasData.top, containerData.height - canvasData.top) : containerData.height; // The min/maxCropBoxWidth/Height must be less than container's width/height + + minCropBoxWidth = Math.min(minCropBoxWidth, containerData.width); + minCropBoxHeight = Math.min(minCropBoxHeight, containerData.height); + + if (aspectRatio) { + if (minCropBoxWidth && minCropBoxHeight) { + if (minCropBoxHeight * aspectRatio > minCropBoxWidth) { + minCropBoxHeight = minCropBoxWidth / aspectRatio; + } else { + minCropBoxWidth = minCropBoxHeight * aspectRatio; + } + } else if (minCropBoxWidth) { + minCropBoxHeight = minCropBoxWidth / aspectRatio; + } else if (minCropBoxHeight) { + minCropBoxWidth = minCropBoxHeight * aspectRatio; + } + + if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) { + maxCropBoxHeight = maxCropBoxWidth / aspectRatio; + } else { + maxCropBoxWidth = maxCropBoxHeight * aspectRatio; + } + } // The minWidth/Height must be less than maxWidth/Height + + + cropBoxData.minWidth = Math.min(minCropBoxWidth, maxCropBoxWidth); + cropBoxData.minHeight = Math.min(minCropBoxHeight, maxCropBoxHeight); + cropBoxData.maxWidth = maxCropBoxWidth; + cropBoxData.maxHeight = maxCropBoxHeight; + } + + if (positionLimited) { + if (limited) { + cropBoxData.minLeft = Math.max(0, canvasData.left); + cropBoxData.minTop = Math.max(0, canvasData.top); + cropBoxData.maxLeft = Math.min(containerData.width, canvasData.left + canvasData.width) - cropBoxData.width; + cropBoxData.maxTop = Math.min(containerData.height, canvasData.top + canvasData.height) - cropBoxData.height; + } else { + cropBoxData.minLeft = 0; + cropBoxData.minTop = 0; + cropBoxData.maxLeft = containerData.width - cropBoxData.width; + cropBoxData.maxTop = containerData.height - cropBoxData.height; + } + } + }, + renderCropBox: function renderCropBox() { + var options = this.options, + containerData = this.containerData, + cropBoxData = this.cropBoxData; + + if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) { + cropBoxData.left = cropBoxData.oldLeft; + } + + if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) { + cropBoxData.top = cropBoxData.oldTop; + } + + cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth); + cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight); + this.limitCropBox(false, true); + cropBoxData.left = Math.min(Math.max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft); + cropBoxData.top = Math.min(Math.max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop); + cropBoxData.oldLeft = cropBoxData.left; + cropBoxData.oldTop = cropBoxData.top; + + if (options.movable && options.cropBoxMovable) { + // Turn to move the canvas when the crop box is equal to the container + setData(this.face, DATA_ACTION, cropBoxData.width >= containerData.width && cropBoxData.height >= containerData.height ? ACTION_MOVE : ACTION_ALL); + } + + setStyle(this.cropBox, assign({ + width: cropBoxData.width, + height: cropBoxData.height + }, getTransforms({ + translateX: cropBoxData.left, + translateY: cropBoxData.top + }))); + + if (this.cropped && this.limited) { + this.limitCanvas(true, true); + } + + if (!this.disabled) { + this.output(); + } + }, + output: function output() { + this.preview(); + dispatchEvent(this.element, EVENT_CROP, this.getData()); + } + }; + + var preview = { + initPreview: function initPreview() { + var element = this.element, + crossOrigin = this.crossOrigin; + var preview = this.options.preview; + var url = crossOrigin ? this.crossOriginUrl : this.url; + var alt = element.alt || 'The image to preview'; + var image = document.createElement('img'); + + if (crossOrigin) { + image.crossOrigin = crossOrigin; + } + + image.src = url; + image.alt = alt; + this.viewBox.appendChild(image); + this.viewBoxImage = image; + + if (!preview) { + return; + } + + var previews = preview; + + if (typeof preview === 'string') { + previews = element.ownerDocument.querySelectorAll(preview); + } else if (preview.querySelector) { + previews = [preview]; + } + + this.previews = previews; + forEach(previews, function (el) { + var img = document.createElement('img'); // Save the original size for recover + + setData(el, DATA_PREVIEW, { + width: el.offsetWidth, + height: el.offsetHeight, + html: el.innerHTML + }); + + if (crossOrigin) { + img.crossOrigin = crossOrigin; + } + + img.src = url; + img.alt = alt; + /** + * Override img element styles + * Add `display:block` to avoid margin top issue + * Add `height:auto` to override `height` attribute on IE8 + * (Occur only when margin-top <= -height) + */ + + img.style.cssText = 'display:block;' + 'width:100%;' + 'height:auto;' + 'min-width:0!important;' + 'min-height:0!important;' + 'max-width:none!important;' + 'max-height:none!important;' + 'image-orientation:0deg!important;"'; + el.innerHTML = ''; + el.appendChild(img); + }); + }, + resetPreview: function resetPreview() { + forEach(this.previews, function (element) { + var data = getData(element, DATA_PREVIEW); + setStyle(element, { + width: data.width, + height: data.height + }); + element.innerHTML = data.html; + removeData(element, DATA_PREVIEW); + }); + }, + preview: function preview() { + var imageData = this.imageData, + canvasData = this.canvasData, + cropBoxData = this.cropBoxData; + var cropBoxWidth = cropBoxData.width, + cropBoxHeight = cropBoxData.height; + var width = imageData.width, + height = imageData.height; + var left = cropBoxData.left - canvasData.left - imageData.left; + var top = cropBoxData.top - canvasData.top - imageData.top; + + if (!this.cropped || this.disabled) { + return; + } + + setStyle(this.viewBoxImage, assign({ + width: width, + height: height + }, getTransforms(assign({ + translateX: -left, + translateY: -top + }, imageData)))); + forEach(this.previews, function (element) { + var data = getData(element, DATA_PREVIEW); + var originalWidth = data.width; + var originalHeight = data.height; + var newWidth = originalWidth; + var newHeight = originalHeight; + var ratio = 1; + + if (cropBoxWidth) { + ratio = originalWidth / cropBoxWidth; + newHeight = cropBoxHeight * ratio; + } + + if (cropBoxHeight && newHeight > originalHeight) { + ratio = originalHeight / cropBoxHeight; + newWidth = cropBoxWidth * ratio; + newHeight = originalHeight; + } + + setStyle(element, { + width: newWidth, + height: newHeight + }); + setStyle(element.getElementsByTagName('img')[0], assign({ + width: width * ratio, + height: height * ratio + }, getTransforms(assign({ + translateX: -left * ratio, + translateY: -top * ratio + }, imageData)))); + }); + } + }; + + var events = { + bind: function bind() { + var element = this.element, + options = this.options, + cropper = this.cropper; + + if (isFunction(options.cropstart)) { + addListener(element, EVENT_CROP_START, options.cropstart); + } + + if (isFunction(options.cropmove)) { + addListener(element, EVENT_CROP_MOVE, options.cropmove); + } + + if (isFunction(options.cropend)) { + addListener(element, EVENT_CROP_END, options.cropend); + } + + if (isFunction(options.crop)) { + addListener(element, EVENT_CROP, options.crop); + } + + if (isFunction(options.zoom)) { + addListener(element, EVENT_ZOOM, options.zoom); + } + + addListener(cropper, EVENT_POINTER_DOWN, this.onCropStart = this.cropStart.bind(this)); + + if (options.zoomable && options.zoomOnWheel) { + addListener(cropper, EVENT_WHEEL, this.onWheel = this.wheel.bind(this), { + passive: false, + capture: true + }); + } + + if (options.toggleDragModeOnDblclick) { + addListener(cropper, EVENT_DBLCLICK, this.onDblclick = this.dblclick.bind(this)); + } + + addListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove = this.cropMove.bind(this)); + addListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd = this.cropEnd.bind(this)); + + if (options.responsive) { + addListener(window, EVENT_RESIZE, this.onResize = this.resize.bind(this)); + } + }, + unbind: function unbind() { + var element = this.element, + options = this.options, + cropper = this.cropper; + + if (isFunction(options.cropstart)) { + removeListener(element, EVENT_CROP_START, options.cropstart); + } + + if (isFunction(options.cropmove)) { + removeListener(element, EVENT_CROP_MOVE, options.cropmove); + } + + if (isFunction(options.cropend)) { + removeListener(element, EVENT_CROP_END, options.cropend); + } + + if (isFunction(options.crop)) { + removeListener(element, EVENT_CROP, options.crop); + } + + if (isFunction(options.zoom)) { + removeListener(element, EVENT_ZOOM, options.zoom); + } + + removeListener(cropper, EVENT_POINTER_DOWN, this.onCropStart); + + if (options.zoomable && options.zoomOnWheel) { + removeListener(cropper, EVENT_WHEEL, this.onWheel, { + passive: false, + capture: true + }); + } + + if (options.toggleDragModeOnDblclick) { + removeListener(cropper, EVENT_DBLCLICK, this.onDblclick); + } + + removeListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove); + removeListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd); + + if (options.responsive) { + removeListener(window, EVENT_RESIZE, this.onResize); + } + } + }; + + var handlers = { + resize: function resize() { + if (this.disabled) { + return; + } + + var options = this.options, + container = this.container, + containerData = this.containerData; + var ratio = container.offsetWidth / containerData.width; // Resize when width changed or height changed + + if (ratio !== 1 || container.offsetHeight !== containerData.height) { + var canvasData; + var cropBoxData; + + if (options.restore) { + canvasData = this.getCanvasData(); + cropBoxData = this.getCropBoxData(); + } + + this.render(); + + if (options.restore) { + this.setCanvasData(forEach(canvasData, function (n, i) { + canvasData[i] = n * ratio; + })); + this.setCropBoxData(forEach(cropBoxData, function (n, i) { + cropBoxData[i] = n * ratio; + })); + } + } + }, + dblclick: function dblclick() { + if (this.disabled || this.options.dragMode === DRAG_MODE_NONE) { + return; + } + + this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? DRAG_MODE_MOVE : DRAG_MODE_CROP); + }, + wheel: function wheel(event) { + var _this = this; + + var ratio = Number(this.options.wheelZoomRatio) || 0.1; + var delta = 1; + + if (this.disabled) { + return; + } + + event.preventDefault(); // Limit wheel speed to prevent zoom too fast (#21) + + if (this.wheeling) { + return; + } + + this.wheeling = true; + setTimeout(function () { + _this.wheeling = false; + }, 50); + + if (event.deltaY) { + delta = event.deltaY > 0 ? 1 : -1; + } else if (event.wheelDelta) { + delta = -event.wheelDelta / 120; + } else if (event.detail) { + delta = event.detail > 0 ? 1 : -1; + } + + this.zoom(-delta * ratio, event); + }, + cropStart: function cropStart(event) { + var buttons = event.buttons, + button = event.button; + + if (this.disabled // Handle mouse event and pointer event and ignore touch event + || (event.type === 'mousedown' || event.type === 'pointerdown' && event.pointerType === 'mouse') && ( // No primary button (Usually the left button) + isNumber(buttons) && buttons !== 1 || isNumber(button) && button !== 0 // Open context menu + || event.ctrlKey)) { + return; + } + + var options = this.options, + pointers = this.pointers; + var action; + + if (event.changedTouches) { + // Handle touch event + forEach(event.changedTouches, function (touch) { + pointers[touch.identifier] = getPointer(touch); + }); + } else { + // Handle mouse event and pointer event + pointers[event.pointerId || 0] = getPointer(event); + } + + if (Object.keys(pointers).length > 1 && options.zoomable && options.zoomOnTouch) { + action = ACTION_ZOOM; + } else { + action = getData(event.target, DATA_ACTION); + } + + if (!REGEXP_ACTIONS.test(action)) { + return; + } + + if (dispatchEvent(this.element, EVENT_CROP_START, { + originalEvent: event, + action: action + }) === false) { + return; + } // This line is required for preventing page zooming in iOS browsers + + + event.preventDefault(); + this.action = action; + this.cropping = false; + + if (action === ACTION_CROP) { + this.cropping = true; + addClass(this.dragBox, CLASS_MODAL); + } + }, + cropMove: function cropMove(event) { + var action = this.action; + + if (this.disabled || !action) { + return; + } + + var pointers = this.pointers; + event.preventDefault(); + + if (dispatchEvent(this.element, EVENT_CROP_MOVE, { + originalEvent: event, + action: action + }) === false) { + return; + } + + if (event.changedTouches) { + forEach(event.changedTouches, function (touch) { + // The first parameter should not be undefined (#432) + assign(pointers[touch.identifier] || {}, getPointer(touch, true)); + }); + } else { + assign(pointers[event.pointerId || 0] || {}, getPointer(event, true)); + } + + this.change(event); + }, + cropEnd: function cropEnd(event) { + if (this.disabled) { + return; + } + + var action = this.action, + pointers = this.pointers; + + if (event.changedTouches) { + forEach(event.changedTouches, function (touch) { + delete pointers[touch.identifier]; + }); + } else { + delete pointers[event.pointerId || 0]; + } + + if (!action) { + return; + } + + event.preventDefault(); + + if (!Object.keys(pointers).length) { + this.action = ''; + } + + if (this.cropping) { + this.cropping = false; + toggleClass(this.dragBox, CLASS_MODAL, this.cropped && this.options.modal); + } + + dispatchEvent(this.element, EVENT_CROP_END, { + originalEvent: event, + action: action + }); + } + }; + + var change = { + change: function change(event) { + var options = this.options, + canvasData = this.canvasData, + containerData = this.containerData, + cropBoxData = this.cropBoxData, + pointers = this.pointers; + var action = this.action; + var aspectRatio = options.aspectRatio; + var left = cropBoxData.left, + top = cropBoxData.top, + width = cropBoxData.width, + height = cropBoxData.height; + var right = left + width; + var bottom = top + height; + var minLeft = 0; + var minTop = 0; + var maxWidth = containerData.width; + var maxHeight = containerData.height; + var renderable = true; + var offset; // Locking aspect ratio in "free mode" by holding shift key + + if (!aspectRatio && event.shiftKey) { + aspectRatio = width && height ? width / height : 1; + } + + if (this.limited) { + minLeft = cropBoxData.minLeft; + minTop = cropBoxData.minTop; + maxWidth = minLeft + Math.min(containerData.width, canvasData.width, canvasData.left + canvasData.width); + maxHeight = minTop + Math.min(containerData.height, canvasData.height, canvasData.top + canvasData.height); + } + + var pointer = pointers[Object.keys(pointers)[0]]; + var range = { + x: pointer.endX - pointer.startX, + y: pointer.endY - pointer.startY + }; + + var check = function check(side) { + switch (side) { + case ACTION_EAST: + if (right + range.x > maxWidth) { + range.x = maxWidth - right; + } + + break; + + case ACTION_WEST: + if (left + range.x < minLeft) { + range.x = minLeft - left; + } + + break; + + case ACTION_NORTH: + if (top + range.y < minTop) { + range.y = minTop - top; + } + + break; + + case ACTION_SOUTH: + if (bottom + range.y > maxHeight) { + range.y = maxHeight - bottom; + } + + break; + } + }; + + switch (action) { + // Move crop box + case ACTION_ALL: + left += range.x; + top += range.y; + break; + // Resize crop box + + case ACTION_EAST: + if (range.x >= 0 && (right >= maxWidth || aspectRatio && (top <= minTop || bottom >= maxHeight))) { + renderable = false; + break; + } + + check(ACTION_EAST); + width += range.x; + + if (width < 0) { + action = ACTION_WEST; + width = -width; + left -= width; + } + + if (aspectRatio) { + height = width / aspectRatio; + top += (cropBoxData.height - height) / 2; + } + + break; + + case ACTION_NORTH: + if (range.y <= 0 && (top <= minTop || aspectRatio && (left <= minLeft || right >= maxWidth))) { + renderable = false; + break; + } + + check(ACTION_NORTH); + height -= range.y; + top += range.y; + + if (height < 0) { + action = ACTION_SOUTH; + height = -height; + top -= height; + } + + if (aspectRatio) { + width = height * aspectRatio; + left += (cropBoxData.width - width) / 2; + } + + break; + + case ACTION_WEST: + if (range.x <= 0 && (left <= minLeft || aspectRatio && (top <= minTop || bottom >= maxHeight))) { + renderable = false; + break; + } + + check(ACTION_WEST); + width -= range.x; + left += range.x; + + if (width < 0) { + action = ACTION_EAST; + width = -width; + left -= width; + } + + if (aspectRatio) { + height = width / aspectRatio; + top += (cropBoxData.height - height) / 2; + } + + break; + + case ACTION_SOUTH: + if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && (left <= minLeft || right >= maxWidth))) { + renderable = false; + break; + } + + check(ACTION_SOUTH); + height += range.y; + + if (height < 0) { + action = ACTION_NORTH; + height = -height; + top -= height; + } + + if (aspectRatio) { + width = height * aspectRatio; + left += (cropBoxData.width - width) / 2; + } + + break; + + case ACTION_NORTH_EAST: + if (aspectRatio) { + if (range.y <= 0 && (top <= minTop || right >= maxWidth)) { + renderable = false; + break; + } + + check(ACTION_NORTH); + height -= range.y; + top += range.y; + width = height * aspectRatio; + } else { + check(ACTION_NORTH); + check(ACTION_EAST); + + if (range.x >= 0) { + if (right < maxWidth) { + width += range.x; + } else if (range.y <= 0 && top <= minTop) { + renderable = false; + } + } else { + width += range.x; + } + + if (range.y <= 0) { + if (top > minTop) { + height -= range.y; + top += range.y; + } + } else { + height -= range.y; + top += range.y; + } + } + + if (width < 0 && height < 0) { + action = ACTION_SOUTH_WEST; + height = -height; + width = -width; + top -= height; + left -= width; + } else if (width < 0) { + action = ACTION_NORTH_WEST; + width = -width; + left -= width; + } else if (height < 0) { + action = ACTION_SOUTH_EAST; + height = -height; + top -= height; + } + + break; + + case ACTION_NORTH_WEST: + if (aspectRatio) { + if (range.y <= 0 && (top <= minTop || left <= minLeft)) { + renderable = false; + break; + } + + check(ACTION_NORTH); + height -= range.y; + top += range.y; + width = height * aspectRatio; + left += cropBoxData.width - width; + } else { + check(ACTION_NORTH); + check(ACTION_WEST); + + if (range.x <= 0) { + if (left > minLeft) { + width -= range.x; + left += range.x; + } else if (range.y <= 0 && top <= minTop) { + renderable = false; + } + } else { + width -= range.x; + left += range.x; + } + + if (range.y <= 0) { + if (top > minTop) { + height -= range.y; + top += range.y; + } + } else { + height -= range.y; + top += range.y; + } + } + + if (width < 0 && height < 0) { + action = ACTION_SOUTH_EAST; + height = -height; + width = -width; + top -= height; + left -= width; + } else if (width < 0) { + action = ACTION_NORTH_EAST; + width = -width; + left -= width; + } else if (height < 0) { + action = ACTION_SOUTH_WEST; + height = -height; + top -= height; + } + + break; + + case ACTION_SOUTH_WEST: + if (aspectRatio) { + if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) { + renderable = false; + break; + } + + check(ACTION_WEST); + width -= range.x; + left += range.x; + height = width / aspectRatio; + } else { + check(ACTION_SOUTH); + check(ACTION_WEST); + + if (range.x <= 0) { + if (left > minLeft) { + width -= range.x; + left += range.x; + } else if (range.y >= 0 && bottom >= maxHeight) { + renderable = false; + } + } else { + width -= range.x; + left += range.x; + } + + if (range.y >= 0) { + if (bottom < maxHeight) { + height += range.y; + } + } else { + height += range.y; + } + } + + if (width < 0 && height < 0) { + action = ACTION_NORTH_EAST; + height = -height; + width = -width; + top -= height; + left -= width; + } else if (width < 0) { + action = ACTION_SOUTH_EAST; + width = -width; + left -= width; + } else if (height < 0) { + action = ACTION_NORTH_WEST; + height = -height; + top -= height; + } + + break; + + case ACTION_SOUTH_EAST: + if (aspectRatio) { + if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) { + renderable = false; + break; + } + + check(ACTION_EAST); + width += range.x; + height = width / aspectRatio; + } else { + check(ACTION_SOUTH); + check(ACTION_EAST); + + if (range.x >= 0) { + if (right < maxWidth) { + width += range.x; + } else if (range.y >= 0 && bottom >= maxHeight) { + renderable = false; + } + } else { + width += range.x; + } + + if (range.y >= 0) { + if (bottom < maxHeight) { + height += range.y; + } + } else { + height += range.y; + } + } + + if (width < 0 && height < 0) { + action = ACTION_NORTH_WEST; + height = -height; + width = -width; + top -= height; + left -= width; + } else if (width < 0) { + action = ACTION_SOUTH_WEST; + width = -width; + left -= width; + } else if (height < 0) { + action = ACTION_NORTH_EAST; + height = -height; + top -= height; + } + + break; + // Move canvas + + case ACTION_MOVE: + this.move(range.x, range.y); + renderable = false; + break; + // Zoom canvas + + case ACTION_ZOOM: + this.zoom(getMaxZoomRatio(pointers), event); + renderable = false; + break; + // Create crop box + + case ACTION_CROP: + if (!range.x || !range.y) { + renderable = false; + break; + } + + offset = getOffset(this.cropper); + left = pointer.startX - offset.left; + top = pointer.startY - offset.top; + width = cropBoxData.minWidth; + height = cropBoxData.minHeight; + + if (range.x > 0) { + action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST; + } else if (range.x < 0) { + left -= width; + action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST; + } + + if (range.y < 0) { + top -= height; + } // Show the crop box if is hidden + + + if (!this.cropped) { + removeClass(this.cropBox, CLASS_HIDDEN); + this.cropped = true; + + if (this.limited) { + this.limitCropBox(true, true); + } + } + + break; + } + + if (renderable) { + cropBoxData.width = width; + cropBoxData.height = height; + cropBoxData.left = left; + cropBoxData.top = top; + this.action = action; + this.renderCropBox(); + } // Override + + + forEach(pointers, function (p) { + p.startX = p.endX; + p.startY = p.endY; + }); + } + }; + + var methods = { + // Show the crop box manually + crop: function crop() { + if (this.ready && !this.cropped && !this.disabled) { + this.cropped = true; + this.limitCropBox(true, true); + + if (this.options.modal) { + addClass(this.dragBox, CLASS_MODAL); + } + + removeClass(this.cropBox, CLASS_HIDDEN); + this.setCropBoxData(this.initialCropBoxData); + } + + return this; + }, + // Reset the image and crop box to their initial states + reset: function reset() { + if (this.ready && !this.disabled) { + this.imageData = assign({}, this.initialImageData); + this.canvasData = assign({}, this.initialCanvasData); + this.cropBoxData = assign({}, this.initialCropBoxData); + this.renderCanvas(); + + if (this.cropped) { + this.renderCropBox(); + } + } + + return this; + }, + // Clear the crop box + clear: function clear() { + if (this.cropped && !this.disabled) { + assign(this.cropBoxData, { + left: 0, + top: 0, + width: 0, + height: 0 + }); + this.cropped = false; + this.renderCropBox(); + this.limitCanvas(true, true); // Render canvas after crop box rendered + + this.renderCanvas(); + removeClass(this.dragBox, CLASS_MODAL); + addClass(this.cropBox, CLASS_HIDDEN); + } + + return this; + }, + + /** + * Replace the image's src and rebuild the cropper + * @param {string} url - The new URL. + * @param {boolean} [hasSameSize] - Indicate if the new image has the same size as the old one. + * @returns {Cropper} this + */ + replace: function replace(url) { + var hasSameSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (!this.disabled && url) { + if (this.isImg) { + this.element.src = url; + } + + if (hasSameSize) { + this.url = url; + this.image.src = url; + + if (this.ready) { + this.viewBoxImage.src = url; + forEach(this.previews, function (element) { + element.getElementsByTagName('img')[0].src = url; + }); + } + } else { + if (this.isImg) { + this.replaced = true; + } + + this.options.data = null; + this.uncreate(); + this.load(url); + } + } + + return this; + }, + // Enable (unfreeze) the cropper + enable: function enable() { + if (this.ready && this.disabled) { + this.disabled = false; + removeClass(this.cropper, CLASS_DISABLED); + } + + return this; + }, + // Disable (freeze) the cropper + disable: function disable() { + if (this.ready && !this.disabled) { + this.disabled = true; + addClass(this.cropper, CLASS_DISABLED); + } + + return this; + }, + + /** + * Destroy the cropper and remove the instance from the image + * @returns {Cropper} this + */ + destroy: function destroy() { + var element = this.element; + + if (!element[NAMESPACE]) { + return this; + } + + element[NAMESPACE] = undefined; + + if (this.isImg && this.replaced) { + element.src = this.originalUrl; + } + + this.uncreate(); + return this; + }, + + /** + * Move the canvas with relative offsets + * @param {number} offsetX - The relative offset distance on the x-axis. + * @param {number} [offsetY=offsetX] - The relative offset distance on the y-axis. + * @returns {Cropper} this + */ + move: function move(offsetX) { + var offsetY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : offsetX; + var _this$canvasData = this.canvasData, + left = _this$canvasData.left, + top = _this$canvasData.top; + return this.moveTo(isUndefined(offsetX) ? offsetX : left + Number(offsetX), isUndefined(offsetY) ? offsetY : top + Number(offsetY)); + }, + + /** + * Move the canvas to an absolute point + * @param {number} x - The x-axis coordinate. + * @param {number} [y=x] - The y-axis coordinate. + * @returns {Cropper} this + */ + moveTo: function moveTo(x) { + var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x; + var canvasData = this.canvasData; + var changed = false; + x = Number(x); + y = Number(y); + + if (this.ready && !this.disabled && this.options.movable) { + if (isNumber(x)) { + canvasData.left = x; + changed = true; + } + + if (isNumber(y)) { + canvasData.top = y; + changed = true; + } + + if (changed) { + this.renderCanvas(true); + } + } + + return this; + }, + + /** + * Zoom the canvas with a relative ratio + * @param {number} ratio - The target ratio. + * @param {Event} _originalEvent - The original event if any. + * @returns {Cropper} this + */ + zoom: function zoom(ratio, _originalEvent) { + var canvasData = this.canvasData; + ratio = Number(ratio); + + if (ratio < 0) { + ratio = 1 / (1 - ratio); + } else { + ratio = 1 + ratio; + } + + return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, null, _originalEvent); + }, + + /** + * Zoom the canvas to an absolute ratio + * @param {number} ratio - The target ratio. + * @param {Object} pivot - The zoom pivot point coordinate. + * @param {Event} _originalEvent - The original event if any. + * @returns {Cropper} this + */ + zoomTo: function zoomTo(ratio, pivot, _originalEvent) { + var options = this.options, + canvasData = this.canvasData; + var width = canvasData.width, + height = canvasData.height, + naturalWidth = canvasData.naturalWidth, + naturalHeight = canvasData.naturalHeight; + ratio = Number(ratio); + + if (ratio >= 0 && this.ready && !this.disabled && options.zoomable) { + var newWidth = naturalWidth * ratio; + var newHeight = naturalHeight * ratio; + + if (dispatchEvent(this.element, EVENT_ZOOM, { + ratio: ratio, + oldRatio: width / naturalWidth, + originalEvent: _originalEvent + }) === false) { + return this; + } + + if (_originalEvent) { + var pointers = this.pointers; + var offset = getOffset(this.cropper); + var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : { + pageX: _originalEvent.pageX, + pageY: _originalEvent.pageY + }; // Zoom from the triggering point of the event + + canvasData.left -= (newWidth - width) * ((center.pageX - offset.left - canvasData.left) / width); + canvasData.top -= (newHeight - height) * ((center.pageY - offset.top - canvasData.top) / height); + } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) { + canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width); + canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height); + } else { + // Zoom from the center of the canvas + canvasData.left -= (newWidth - width) / 2; + canvasData.top -= (newHeight - height) / 2; + } + + canvasData.width = newWidth; + canvasData.height = newHeight; + this.renderCanvas(true); + } + + return this; + }, + + /** + * Rotate the canvas with a relative degree + * @param {number} degree - The rotate degree. + * @returns {Cropper} this + */ + rotate: function rotate(degree) { + return this.rotateTo((this.imageData.rotate || 0) + Number(degree)); + }, + + /** + * Rotate the canvas to an absolute degree + * @param {number} degree - The rotate degree. + * @returns {Cropper} this + */ + rotateTo: function rotateTo(degree) { + degree = Number(degree); + + if (isNumber(degree) && this.ready && !this.disabled && this.options.rotatable) { + this.imageData.rotate = degree % 360; + this.renderCanvas(true, true); + } + + return this; + }, + + /** + * Scale the image on the x-axis. + * @param {number} scaleX - The scale ratio on the x-axis. + * @returns {Cropper} this + */ + scaleX: function scaleX(_scaleX) { + var scaleY = this.imageData.scaleY; + return this.scale(_scaleX, isNumber(scaleY) ? scaleY : 1); + }, + + /** + * Scale the image on the y-axis. + * @param {number} scaleY - The scale ratio on the y-axis. + * @returns {Cropper} this + */ + scaleY: function scaleY(_scaleY) { + var scaleX = this.imageData.scaleX; + return this.scale(isNumber(scaleX) ? scaleX : 1, _scaleY); + }, + + /** + * Scale the image + * @param {number} scaleX - The scale ratio on the x-axis. + * @param {number} [scaleY=scaleX] - The scale ratio on the y-axis. + * @returns {Cropper} this + */ + scale: function scale(scaleX) { + var scaleY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : scaleX; + var imageData = this.imageData; + var transformed = false; + scaleX = Number(scaleX); + scaleY = Number(scaleY); + + if (this.ready && !this.disabled && this.options.scalable) { + if (isNumber(scaleX)) { + imageData.scaleX = scaleX; + transformed = true; + } + + if (isNumber(scaleY)) { + imageData.scaleY = scaleY; + transformed = true; + } + + if (transformed) { + this.renderCanvas(true, true); + } + } + + return this; + }, + + /** + * Get the cropped area position and size data (base on the original image) + * @param {boolean} [rounded=false] - Indicate if round the data values or not. + * @returns {Object} The result cropped data. + */ + getData: function getData() { + var rounded = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var options = this.options, + imageData = this.imageData, + canvasData = this.canvasData, + cropBoxData = this.cropBoxData; + var data; + + if (this.ready && this.cropped) { + data = { + x: cropBoxData.left - canvasData.left, + y: cropBoxData.top - canvasData.top, + width: cropBoxData.width, + height: cropBoxData.height + }; + var ratio = imageData.width / imageData.naturalWidth; + forEach(data, function (n, i) { + data[i] = n / ratio; + }); + + if (rounded) { + // In case rounding off leads to extra 1px in right or bottom border + // we should round the top-left corner and the dimension (#343). + var bottom = Math.round(data.y + data.height); + var right = Math.round(data.x + data.width); + data.x = Math.round(data.x); + data.y = Math.round(data.y); + data.width = right - data.x; + data.height = bottom - data.y; + } + } else { + data = { + x: 0, + y: 0, + width: 0, + height: 0 + }; + } + + if (options.rotatable) { + data.rotate = imageData.rotate || 0; + } + + if (options.scalable) { + data.scaleX = imageData.scaleX || 1; + data.scaleY = imageData.scaleY || 1; + } + + return data; + }, + + /** + * Set the cropped area position and size with new data + * @param {Object} data - The new data. + * @returns {Cropper} this + */ + setData: function setData(data) { + var options = this.options, + imageData = this.imageData, + canvasData = this.canvasData; + var cropBoxData = {}; + + if (this.ready && !this.disabled && isPlainObject(data)) { + var transformed = false; + + if (options.rotatable) { + if (isNumber(data.rotate) && data.rotate !== imageData.rotate) { + imageData.rotate = data.rotate; + transformed = true; + } + } + + if (options.scalable) { + if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) { + imageData.scaleX = data.scaleX; + transformed = true; + } + + if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) { + imageData.scaleY = data.scaleY; + transformed = true; + } + } + + if (transformed) { + this.renderCanvas(true, true); + } + + var ratio = imageData.width / imageData.naturalWidth; + + if (isNumber(data.x)) { + cropBoxData.left = data.x * ratio + canvasData.left; + } + + if (isNumber(data.y)) { + cropBoxData.top = data.y * ratio + canvasData.top; + } + + if (isNumber(data.width)) { + cropBoxData.width = data.width * ratio; + } + + if (isNumber(data.height)) { + cropBoxData.height = data.height * ratio; + } + + this.setCropBoxData(cropBoxData); + } + + return this; + }, + + /** + * Get the container size data. + * @returns {Object} The result container data. + */ + getContainerData: function getContainerData() { + return this.ready ? assign({}, this.containerData) : {}; + }, + + /** + * Get the image position and size data. + * @returns {Object} The result image data. + */ + getImageData: function getImageData() { + return this.sized ? assign({}, this.imageData) : {}; + }, + + /** + * Get the canvas position and size data. + * @returns {Object} The result canvas data. + */ + getCanvasData: function getCanvasData() { + var canvasData = this.canvasData; + var data = {}; + + if (this.ready) { + forEach(['left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight'], function (n) { + data[n] = canvasData[n]; + }); + } + + return data; + }, + + /** + * Set the canvas position and size with new data. + * @param {Object} data - The new canvas data. + * @returns {Cropper} this + */ + setCanvasData: function setCanvasData(data) { + var canvasData = this.canvasData; + var aspectRatio = canvasData.aspectRatio; + + if (this.ready && !this.disabled && isPlainObject(data)) { + if (isNumber(data.left)) { + canvasData.left = data.left; + } + + if (isNumber(data.top)) { + canvasData.top = data.top; + } + + if (isNumber(data.width)) { + canvasData.width = data.width; + canvasData.height = data.width / aspectRatio; + } else if (isNumber(data.height)) { + canvasData.height = data.height; + canvasData.width = data.height * aspectRatio; + } + + this.renderCanvas(true); + } + + return this; + }, + + /** + * Get the crop box position and size data. + * @returns {Object} The result crop box data. + */ + getCropBoxData: function getCropBoxData() { + var cropBoxData = this.cropBoxData; + var data; + + if (this.ready && this.cropped) { + data = { + left: cropBoxData.left, + top: cropBoxData.top, + width: cropBoxData.width, + height: cropBoxData.height + }; + } + + return data || {}; + }, + + /** + * Set the crop box position and size with new data. + * @param {Object} data - The new crop box data. + * @returns {Cropper} this + */ + setCropBoxData: function setCropBoxData(data) { + var cropBoxData = this.cropBoxData; + var aspectRatio = this.options.aspectRatio; + var widthChanged; + var heightChanged; + + if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) { + if (isNumber(data.left)) { + cropBoxData.left = data.left; + } + + if (isNumber(data.top)) { + cropBoxData.top = data.top; + } + + if (isNumber(data.width) && data.width !== cropBoxData.width) { + widthChanged = true; + cropBoxData.width = data.width; + } + + if (isNumber(data.height) && data.height !== cropBoxData.height) { + heightChanged = true; + cropBoxData.height = data.height; + } + + if (aspectRatio) { + if (widthChanged) { + cropBoxData.height = cropBoxData.width / aspectRatio; + } else if (heightChanged) { + cropBoxData.width = cropBoxData.height * aspectRatio; + } + } + + this.renderCropBox(); + } + + return this; + }, + + /** + * Get a canvas drawn the cropped image. + * @param {Object} [options={}] - The config options. + * @returns {HTMLCanvasElement} - The result canvas. + */ + getCroppedCanvas: function getCroppedCanvas() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + if (!this.ready || !window.HTMLCanvasElement) { + return null; + } + + var canvasData = this.canvasData; + var source = getSourceCanvas(this.image, this.imageData, canvasData, options); // Returns the source canvas if it is not cropped. + + if (!this.cropped) { + return source; + } + + var _this$getData = this.getData(), + initialX = _this$getData.x, + initialY = _this$getData.y, + initialWidth = _this$getData.width, + initialHeight = _this$getData.height; + + var ratio = source.width / Math.floor(canvasData.naturalWidth); + + if (ratio !== 1) { + initialX *= ratio; + initialY *= ratio; + initialWidth *= ratio; + initialHeight *= ratio; + } + + var aspectRatio = initialWidth / initialHeight; + var maxSizes = getAdjustedSizes({ + aspectRatio: aspectRatio, + width: options.maxWidth || Infinity, + height: options.maxHeight || Infinity + }); + var minSizes = getAdjustedSizes({ + aspectRatio: aspectRatio, + width: options.minWidth || 0, + height: options.minHeight || 0 + }, 'cover'); + + var _getAdjustedSizes = getAdjustedSizes({ + aspectRatio: aspectRatio, + width: options.width || (ratio !== 1 ? source.width : initialWidth), + height: options.height || (ratio !== 1 ? source.height : initialHeight) + }), + width = _getAdjustedSizes.width, + height = _getAdjustedSizes.height; + + width = Math.min(maxSizes.width, Math.max(minSizes.width, width)); + height = Math.min(maxSizes.height, Math.max(minSizes.height, height)); + var canvas = document.createElement('canvas'); + var context = canvas.getContext('2d'); + canvas.width = normalizeDecimalNumber(width); + canvas.height = normalizeDecimalNumber(height); + context.fillStyle = options.fillColor || 'transparent'; + context.fillRect(0, 0, width, height); + var _options$imageSmoothi = options.imageSmoothingEnabled, + imageSmoothingEnabled = _options$imageSmoothi === void 0 ? true : _options$imageSmoothi, + imageSmoothingQuality = options.imageSmoothingQuality; + context.imageSmoothingEnabled = imageSmoothingEnabled; + + if (imageSmoothingQuality) { + context.imageSmoothingQuality = imageSmoothingQuality; + } // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage + + + var sourceWidth = source.width; + var sourceHeight = source.height; // Source canvas parameters + + var srcX = initialX; + var srcY = initialY; + var srcWidth; + var srcHeight; // Destination canvas parameters + + var dstX; + var dstY; + var dstWidth; + var dstHeight; + + if (srcX <= -initialWidth || srcX > sourceWidth) { + srcX = 0; + srcWidth = 0; + dstX = 0; + dstWidth = 0; + } else if (srcX <= 0) { + dstX = -srcX; + srcX = 0; + srcWidth = Math.min(sourceWidth, initialWidth + srcX); + dstWidth = srcWidth; + } else if (srcX <= sourceWidth) { + dstX = 0; + srcWidth = Math.min(initialWidth, sourceWidth - srcX); + dstWidth = srcWidth; + } + + if (srcWidth <= 0 || srcY <= -initialHeight || srcY > sourceHeight) { + srcY = 0; + srcHeight = 0; + dstY = 0; + dstHeight = 0; + } else if (srcY <= 0) { + dstY = -srcY; + srcY = 0; + srcHeight = Math.min(sourceHeight, initialHeight + srcY); + dstHeight = srcHeight; + } else if (srcY <= sourceHeight) { + dstY = 0; + srcHeight = Math.min(initialHeight, sourceHeight - srcY); + dstHeight = srcHeight; + } + + var params = [srcX, srcY, srcWidth, srcHeight]; // Avoid "IndexSizeError" + + if (dstWidth > 0 && dstHeight > 0) { + var scale = width / initialWidth; + params.push(dstX * scale, dstY * scale, dstWidth * scale, dstHeight * scale); + } // All the numerical parameters should be integer for `drawImage` + // https://github.com/fengyuanchen/cropper/issues/476 + + + context.drawImage.apply(context, [source].concat(_toConsumableArray(params.map(function (param) { + return Math.floor(normalizeDecimalNumber(param)); + })))); + return canvas; + }, + + /** + * Change the aspect ratio of the crop box. + * @param {number} aspectRatio - The new aspect ratio. + * @returns {Cropper} this + */ + setAspectRatio: function setAspectRatio(aspectRatio) { + var options = this.options; + + if (!this.disabled && !isUndefined(aspectRatio)) { + // 0 -> NaN + options.aspectRatio = Math.max(0, aspectRatio) || NaN; + + if (this.ready) { + this.initCropBox(); + + if (this.cropped) { + this.renderCropBox(); + } + } + } + + return this; + }, + + /** + * Change the drag mode. + * @param {string} mode - The new drag mode. + * @returns {Cropper} this + */ + setDragMode: function setDragMode(mode) { + var options = this.options, + dragBox = this.dragBox, + face = this.face; + + if (this.ready && !this.disabled) { + var croppable = mode === DRAG_MODE_CROP; + var movable = options.movable && mode === DRAG_MODE_MOVE; + mode = croppable || movable ? mode : DRAG_MODE_NONE; + options.dragMode = mode; + setData(dragBox, DATA_ACTION, mode); + toggleClass(dragBox, CLASS_CROP, croppable); + toggleClass(dragBox, CLASS_MOVE, movable); + + if (!options.cropBoxMovable) { + // Sync drag mode to crop box when it is not movable + setData(face, DATA_ACTION, mode); + toggleClass(face, CLASS_CROP, croppable); + toggleClass(face, CLASS_MOVE, movable); + } + } + + return this; + } + }; + + var AnotherCropper = WINDOW.Cropper; + + var Cropper = /*#__PURE__*/function () { + /** + * Create a new Cropper. + * @param {Element} element - The target element for cropping. + * @param {Object} [options={}] - The configuration options. + */ + function Cropper(element) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + _classCallCheck(this, Cropper); + + if (!element || !REGEXP_TAG_NAME.test(element.tagName)) { + throw new Error('The first argument is required and must be an or element.'); + } + + this.element = element; + this.options = assign({}, DEFAULTS, isPlainObject(options) && options); + this.cropped = false; + this.disabled = false; + this.pointers = {}; + this.ready = false; + this.reloading = false; + this.replaced = false; + this.sized = false; + this.sizing = false; + this.init(); + } + + _createClass(Cropper, [{ + key: "init", + value: function init() { + var element = this.element; + var tagName = element.tagName.toLowerCase(); + var url; + + if (element[NAMESPACE]) { + return; + } + + element[NAMESPACE] = this; + + if (tagName === 'img') { + this.isImg = true; // e.g.: "img/picture.jpg" + + url = element.getAttribute('src') || ''; + this.originalUrl = url; // Stop when it's a blank image + + if (!url) { + return; + } // e.g.: "https://example.com/img/picture.jpg" + + + url = element.src; + } else if (tagName === 'canvas' && window.HTMLCanvasElement) { + url = element.toDataURL(); + } + + this.load(url); + } + }, { + key: "load", + value: function load(url) { + var _this = this; + + if (!url) { + return; + } + + this.url = url; + this.imageData = {}; + var element = this.element, + options = this.options; + + if (!options.rotatable && !options.scalable) { + options.checkOrientation = false; + } // Only IE10+ supports Typed Arrays + + + if (!options.checkOrientation || !window.ArrayBuffer) { + this.clone(); + return; + } // Detect the mime type of the image directly if it is a Data URL + + + if (REGEXP_DATA_URL.test(url)) { + // Read ArrayBuffer from Data URL of JPEG images directly for better performance + if (REGEXP_DATA_URL_JPEG.test(url)) { + this.read(dataURLToArrayBuffer(url)); + } else { + // Only a JPEG image may contains Exif Orientation information, + // the rest types of Data URLs are not necessary to check orientation at all. + this.clone(); + } + + return; + } // 1. Detect the mime type of the image by a XMLHttpRequest. + // 2. Load the image as ArrayBuffer for reading orientation if its a JPEG image. + + + var xhr = new XMLHttpRequest(); + var clone = this.clone.bind(this); + this.reloading = true; + this.xhr = xhr; // 1. Cross origin requests are only supported for protocol schemes: + // http, https, data, chrome, chrome-extension. + // 2. Access to XMLHttpRequest from a Data URL will be blocked by CORS policy + // in some browsers as IE11 and Safari. + + xhr.onabort = clone; + xhr.onerror = clone; + xhr.ontimeout = clone; + + xhr.onprogress = function () { + // Abort the request directly if it not a JPEG image for better performance + if (xhr.getResponseHeader('content-type') !== MIME_TYPE_JPEG) { + xhr.abort(); + } + }; + + xhr.onload = function () { + _this.read(xhr.response); + }; + + xhr.onloadend = function () { + _this.reloading = false; + _this.xhr = null; + }; // Bust cache when there is a "crossOrigin" property to avoid browser cache error + + + if (options.checkCrossOrigin && isCrossOriginURL(url) && element.crossOrigin) { + url = addTimestamp(url); + } + + xhr.open('GET', url); + xhr.responseType = 'arraybuffer'; + xhr.withCredentials = element.crossOrigin === 'use-credentials'; + xhr.send(); + } + }, { + key: "read", + value: function read(arrayBuffer) { + var options = this.options, + imageData = this.imageData; // Reset the orientation value to its default value 1 + // as some iOS browsers will render image with its orientation + + var orientation = resetAndGetOrientation(arrayBuffer); + var rotate = 0; + var scaleX = 1; + var scaleY = 1; + + if (orientation > 1) { + // Generate a new URL which has the default orientation value + this.url = arrayBufferToDataURL(arrayBuffer, MIME_TYPE_JPEG); + + var _parseOrientation = parseOrientation(orientation); + + rotate = _parseOrientation.rotate; + scaleX = _parseOrientation.scaleX; + scaleY = _parseOrientation.scaleY; + } + + if (options.rotatable) { + imageData.rotate = rotate; + } + + if (options.scalable) { + imageData.scaleX = scaleX; + imageData.scaleY = scaleY; + } + + this.clone(); + } + }, { + key: "clone", + value: function clone() { + var element = this.element, + url = this.url; + var crossOrigin = element.crossOrigin; + var crossOriginUrl = url; + + if (this.options.checkCrossOrigin && isCrossOriginURL(url)) { + if (!crossOrigin) { + crossOrigin = 'anonymous'; + } // Bust cache when there is not a "crossOrigin" property (#519) + + + crossOriginUrl = addTimestamp(url); + } + + this.crossOrigin = crossOrigin; + this.crossOriginUrl = crossOriginUrl; + var image = document.createElement('img'); + + if (crossOrigin) { + image.crossOrigin = crossOrigin; + } + + image.src = crossOriginUrl || url; + image.alt = element.alt || 'The image to crop'; + this.image = image; + image.onload = this.start.bind(this); + image.onerror = this.stop.bind(this); + addClass(image, CLASS_HIDE); + element.parentNode.insertBefore(image, element.nextSibling); + } + }, { + key: "start", + value: function start() { + var _this2 = this; + + var image = this.image; + image.onload = null; + image.onerror = null; + this.sizing = true; // Match all browsers that use WebKit as the layout engine in iOS devices, + // such as Safari for iOS, Chrome for iOS, and in-app browsers. + + var isIOSWebKit = WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent); + + var done = function done(naturalWidth, naturalHeight) { + assign(_this2.imageData, { + naturalWidth: naturalWidth, + naturalHeight: naturalHeight, + aspectRatio: naturalWidth / naturalHeight + }); + _this2.sizing = false; + _this2.sized = true; + + _this2.build(); + }; // Most modern browsers (excepts iOS WebKit) + + + if (image.naturalWidth && !isIOSWebKit) { + done(image.naturalWidth, image.naturalHeight); + return; + } + + var sizingImage = document.createElement('img'); + var body = document.body || document.documentElement; + this.sizingImage = sizingImage; + + sizingImage.onload = function () { + done(sizingImage.width, sizingImage.height); + + if (!isIOSWebKit) { + body.removeChild(sizingImage); + } + }; + + sizingImage.src = image.src; // iOS WebKit will convert the image automatically + // with its orientation once append it into DOM (#279) + + if (!isIOSWebKit) { + sizingImage.style.cssText = 'left:0;' + 'max-height:none!important;' + 'max-width:none!important;' + 'min-height:0!important;' + 'min-width:0!important;' + 'opacity:0;' + 'position:absolute;' + 'top:0;' + 'z-index:-1;'; + body.appendChild(sizingImage); + } + } + }, { + key: "stop", + value: function stop() { + var image = this.image; + image.onload = null; + image.onerror = null; + image.parentNode.removeChild(image); + this.image = null; + } + }, { + key: "build", + value: function build() { + if (!this.sized || this.ready) { + return; + } + + var element = this.element, + options = this.options, + image = this.image; // Create cropper elements + + var container = element.parentNode; + var template = document.createElement('div'); + template.innerHTML = TEMPLATE; + var cropper = template.querySelector(".".concat(NAMESPACE, "-container")); + var canvas = cropper.querySelector(".".concat(NAMESPACE, "-canvas")); + var dragBox = cropper.querySelector(".".concat(NAMESPACE, "-drag-box")); + var cropBox = cropper.querySelector(".".concat(NAMESPACE, "-crop-box")); + var face = cropBox.querySelector(".".concat(NAMESPACE, "-face")); + this.container = container; + this.cropper = cropper; + this.canvas = canvas; + this.dragBox = dragBox; + this.cropBox = cropBox; + this.viewBox = cropper.querySelector(".".concat(NAMESPACE, "-view-box")); + this.face = face; + canvas.appendChild(image); // Hide the original image + + addClass(element, CLASS_HIDDEN); // Inserts the cropper after to the current image + + container.insertBefore(cropper, element.nextSibling); // Show the image if is hidden + + if (!this.isImg) { + removeClass(image, CLASS_HIDE); + } + + this.initPreview(); + this.bind(); + options.initialAspectRatio = Math.max(0, options.initialAspectRatio) || NaN; + options.aspectRatio = Math.max(0, options.aspectRatio) || NaN; + options.viewMode = Math.max(0, Math.min(3, Math.round(options.viewMode))) || 0; + addClass(cropBox, CLASS_HIDDEN); + + if (!options.guides) { + addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-dashed")), CLASS_HIDDEN); + } + + if (!options.center) { + addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-center")), CLASS_HIDDEN); + } + + if (options.background) { + addClass(cropper, "".concat(NAMESPACE, "-bg")); + } + + if (!options.highlight) { + addClass(face, CLASS_INVISIBLE); + } + + if (options.cropBoxMovable) { + addClass(face, CLASS_MOVE); + setData(face, DATA_ACTION, ACTION_ALL); + } + + if (!options.cropBoxResizable) { + addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-line")), CLASS_HIDDEN); + addClass(cropBox.getElementsByClassName("".concat(NAMESPACE, "-point")), CLASS_HIDDEN); + } + + this.render(); + this.ready = true; + this.setDragMode(options.dragMode); + + if (options.autoCrop) { + this.crop(); + } + + this.setData(options.data); + + if (isFunction(options.ready)) { + addListener(element, EVENT_READY, options.ready, { + once: true + }); + } + + dispatchEvent(element, EVENT_READY); + } + }, { + key: "unbuild", + value: function unbuild() { + if (!this.ready) { + return; + } + + this.ready = false; + this.unbind(); + this.resetPreview(); + this.cropper.parentNode.removeChild(this.cropper); + removeClass(this.element, CLASS_HIDDEN); + } + }, { + key: "uncreate", + value: function uncreate() { + if (this.ready) { + this.unbuild(); + this.ready = false; + this.cropped = false; + } else if (this.sizing) { + this.sizingImage.onload = null; + this.sizing = false; + this.sized = false; + } else if (this.reloading) { + this.xhr.onabort = null; + this.xhr.abort(); + } else if (this.image) { + this.stop(); + } + } + /** + * Get the no conflict cropper class. + * @returns {Cropper} The cropper class. + */ + + }], [{ + key: "noConflict", + value: function noConflict() { + window.Cropper = AnotherCropper; + return Cropper; + } + /** + * Change the default options. + * @param {Object} options - The new default options. + */ + + }, { + key: "setDefaults", + value: function setDefaults(options) { + assign(DEFAULTS, isPlainObject(options) && options); + } + }]); + + return Cropper; + }(); + + assign(Cropper.prototype, render, preview, events, handlers, change, methods); + + return Cropper; + +}))); + +},{}],16:[function(require,module,exports){ +/** + * cuid.js + * Collision-resistant UID generator for browsers and node. + * Sequential for fast db lookups and recency sorting. + * Safe for element IDs and server-side lookups. + * + * Extracted from CLCTR + * + * Copyright (c) Eric Elliott 2012 + * MIT License + */ + +var fingerprint = require('./lib/fingerprint.js'); +var pad = require('./lib/pad.js'); +var getRandomValue = require('./lib/getRandomValue.js'); + +var c = 0, + blockSize = 4, + base = 36, + discreteValues = Math.pow(base, blockSize); + +function randomBlock () { + return pad((getRandomValue() * + discreteValues << 0) + .toString(base), blockSize); +} + +function safeCounter () { + c = c < discreteValues ? c : 0; + c++; // this is not subliminal + return c - 1; +} + +function cuid () { + // Starting with a lowercase letter makes + // it HTML element ID friendly. + var letter = 'c', // hard-coded allows for sequential access + + // timestamp + // warning: this exposes the exact date and time + // that the uid was created. + timestamp = (new Date().getTime()).toString(base), + + // Prevent same-machine collisions. + counter = pad(safeCounter().toString(base), blockSize), + + // A few chars to generate distinct ids for different + // clients (so different computers are far less + // likely to generate the same id) + print = fingerprint(), + + // Grab some more chars from Math.random() + random = randomBlock() + randomBlock(); + + return letter + timestamp + counter + print + random; +} + +cuid.slug = function slug () { + var date = new Date().getTime().toString(36), + counter = safeCounter().toString(36).slice(-4), + print = fingerprint().slice(0, 1) + + fingerprint().slice(-1), + random = randomBlock().slice(-2); + + return date.slice(-2) + + counter + print + random; +}; + +cuid.isCuid = function isCuid (stringToCheck) { + if (typeof stringToCheck !== 'string') return false; + if (stringToCheck.startsWith('c')) return true; + return false; +}; + +cuid.isSlug = function isSlug (stringToCheck) { + if (typeof stringToCheck !== 'string') return false; + var stringLength = stringToCheck.length; + if (stringLength >= 7 && stringLength <= 10) return true; + return false; +}; + +cuid.fingerprint = fingerprint; + +module.exports = cuid; + +},{"./lib/fingerprint.js":17,"./lib/getRandomValue.js":18,"./lib/pad.js":19}],17:[function(require,module,exports){ +var pad = require('./pad.js'); + +var env = typeof window === 'object' ? window : self; +var globalCount = Object.keys(env).length; +var mimeTypesLength = navigator.mimeTypes ? navigator.mimeTypes.length : 0; +var clientId = pad((mimeTypesLength + + navigator.userAgent.length).toString(36) + + globalCount.toString(36), 4); + +module.exports = function fingerprint () { + return clientId; +}; + +},{"./pad.js":19}],18:[function(require,module,exports){ + +var getRandomValue; + +var crypto = typeof window !== 'undefined' && + (window.crypto || window.msCrypto) || + typeof self !== 'undefined' && + self.crypto; + +if (crypto) { + var lim = Math.pow(2, 32) - 1; + getRandomValue = function () { + return Math.abs(crypto.getRandomValues(new Uint32Array(1))[0] / lim); + }; +} else { + getRandomValue = Math.random; +} + +module.exports = getRandomValue; + +},{}],19:[function(require,module,exports){ +module.exports = function pad (num, size) { + var s = '000000000' + num; + return s.substr(s.length - size); +}; + +},{}],20:[function(require,module,exports){ +// This file can be required in Browserify and Node.js for automatic polyfill +// To use it: require('es6-promise/auto'); +'use strict'; +module.exports = require('./').polyfill(); + +},{"./":21}],21:[function(require,module,exports){ +(function (process,global){(function (){ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE + * @version v4.2.8+1e68dce6 + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ES6Promise = factory()); +}(this, (function () { 'use strict'; + +function objectOrFunction(x) { + var type = typeof x; + return x !== null && (type === 'object' || type === 'function'); +} + +function isFunction(x) { + return typeof x === 'function'; +} + + + +var _isArray = void 0; +if (Array.isArray) { + _isArray = Array.isArray; +} else { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} + +var isArray = _isArray; + +var len = 0; +var vertxNext = void 0; +var customSchedulerFn = void 0; + +var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } +}; + +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} + +function setAsap(asapFn) { + asap = asapFn; +} + +var browserWindow = typeof window !== 'undefined' ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function () { + return process.nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function () { + vertxNext(flush); + }; + } + + return useSetTimeout(); +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function () { + node.data = iterations = ++iterations % 2; + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + // Store setTimeout reference so es6-promise will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var globalSetTimeout = setTimeout; + return function () { + return globalSetTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; + + callback(arg); + + queue[i] = undefined; + queue[i + 1] = undefined; + } + + len = 0; +} + +function attemptVertx() { + try { + var vertx = Function('return this')().require('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} + +var scheduleFlush = void 0; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && typeof require === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} + +function then(onFulfillment, onRejection) { + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } + + var _state = parent._state; + + + if (_state) { + var callback = arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; +} + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +function resolve$1(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + resolve(promise, object); + return promise; +} + +var PROMISE_ID = Math.random().toString(36).substring(2); + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} + +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { + try { + then$$1.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then$$1) { + asap(function (promise) { + var sealed = false; + var error = tryThen(then$$1, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; + + reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function (value) { + return resolve(promise, value); + }, function (reason) { + return reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable, then$$1) { + if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$1 === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$1)) { + handleForeignThenable(promise, maybeThenable, then$$1); + } else { + fulfill(promise, maybeThenable); + } + } +} + +function resolve(promise, value) { + if (promise === value) { + reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + var then$$1 = void 0; + try { + then$$1 = value.then; + } catch (error) { + reject(promise, error); + return; + } + handleMaybeThenable(promise, value, then$$1); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} + +function reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; + + + parent._onerror = null; + + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { + return; + } + + var child = void 0, + callback = void 0, + detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = void 0, + error = void 0, + succeeded = true; + + if (hasCallback) { + try { + value = callback(detail); + } catch (e) { + succeeded = false; + error = e; + } + + if (promise === value) { + reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (succeeded === false) { + reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + resolve(promise, value); + }, function rejectPromise(reason) { + reject(promise, reason); + }); + } catch (e) { + reject(promise, e); + } +} + +var id = 0; +function nextId() { + return id++; +} + +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} + +function validationError() { + return new Error('Array Methods must be provided an Array'); +} + +var Enumerator = function () { + function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + + if (isArray(input)) { + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(input); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + reject(this.promise, validationError()); + } + } + + Enumerator.prototype._enumerate = function _enumerate(input) { + for (var i = 0; this._state === PENDING && i < input.length; i++) { + this._eachEntry(input[i], i); + } + }; + + Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { + var c = this._instanceConstructor; + var resolve$$1 = c.resolve; + + + if (resolve$$1 === resolve$1) { + var _then = void 0; + var error = void 0; + var didError = false; + try { + _then = entry.then; + } catch (e) { + didError = true; + error = e; + } + + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise$1) { + var promise = new c(noop); + if (didError) { + reject(promise, error); + } else { + handleMaybeThenable(promise, entry, _then); + } + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$1) { + return resolve$$1(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$1(entry), i); + } + }; + + Enumerator.prototype._settledAt = function _settledAt(state, i, value) { + var promise = this.promise; + + + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + fulfill(promise, this._result); + } + }; + + Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); + }; + + return Enumerator; +}(); + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +function all(entries) { + return new Enumerator(this, entries).promise; +} + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function (_, reject) { + return reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function (resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } +} + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +function reject$1(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + reject(promise, reason); + return promise; +} + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {Function} resolver + Useful for tooling. + @constructor +*/ + +var Promise$1 = function () { + function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } + } + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + Chaining + -------- + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + Assimilation + ------------ + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + If the assimliated promise rejects, then the downstream promise will also reject. + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + Simple Example + -------------- + Synchronous Example + ```javascript + let result; + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + Errback Example + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + Promise Example; + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + Advanced Example + -------------- + Synchronous Example + ```javascript + let author, books; + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + Errback Example + ```js + function foundBooks(books) { + } + function failure(reason) { + } + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + Promise Example; + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + + + Promise.prototype.catch = function _catch(onRejection) { + return this.then(null, onRejection); + }; + + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + Synchronous example: + + ```js + findAuthor() { + if (Math.random() > 0.5) { + throw new Error(); + } + return new Author(); + } + + try { + return findAuthor(); // succeed or fail + } catch(error) { + return findOtherAuther(); + } finally { + // always runs + // doesn't affect the return value + } + ``` + + Asynchronous example: + + ```js + findAuthor().catch(function(reason){ + return findOtherAuther(); + }).finally(function(){ + // author was either found, or not + }); + ``` + + @method finally + @param {Function} callback + @return {Promise} + */ + + + Promise.prototype.finally = function _finally(callback) { + var promise = this; + var constructor = promise.constructor; + + if (isFunction(callback)) { + return promise.then(function (value) { + return constructor.resolve(callback()).then(function () { + return value; + }); + }, function (reason) { + return constructor.resolve(callback()).then(function () { + throw reason; + }); + }); + } + + return promise.then(callback, callback); + }; + + return Promise; +}(); + +Promise$1.prototype.then = then; +Promise$1.all = all; +Promise$1.race = race; +Promise$1.resolve = resolve$1; +Promise$1.reject = reject$1; +Promise$1._setScheduler = setScheduler; +Promise$1._setAsap = setAsap; +Promise$1._asap = asap; + +/*global self*/ +function polyfill() { + var local = void 0; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } + + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } + + local.Promise = Promise$1; +} + +// Strange compat.. +Promise$1.polyfill = polyfill; +Promise$1.Promise = Promise$1; + +return Promise$1; + +}))); + + + + + +}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{"_process":39}],22:[function(require,module,exports){ +'use strict'; + +exports.__esModule = true; +exports.default = getFormData; +exports.getFieldData = getFieldData; +var NODE_LIST_CLASSES = { + '[object HTMLCollection]': true, + '[object NodeList]': true, + '[object RadioNodeList]': true + + // .type values for elements which can appear in .elements and should be ignored +};var IGNORED_ELEMENT_TYPES = { + 'button': true, + 'fieldset': true, + 'reset': true, + 'submit': true +}; + +var CHECKED_INPUT_TYPES = { + 'checkbox': true, + 'radio': true +}; + +var TRIM_RE = /^\s+|\s+$/g; + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * @param {HTMLFormElement} form + * @param {Object} options + * @return {Object.)>} an object containing + * submittable value(s) held in the form's .elements collection, with + * properties named as per element names or ids. + */ + +function getFormData(form) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { trim: false }; + + if (!form) { + throw new Error('A form is required by getFormData, was given form=' + form); + } + + var data = {}; + var elementName = void 0; + var elementNames = []; + var elementNameLookup = {}; + + // Get unique submittable element names for the form + for (var i = 0, l = form.elements.length; i < l; i++) { + var element = form.elements[i]; + if (IGNORED_ELEMENT_TYPES[element.type] || element.disabled) { + continue; + } + elementName = element.name || element.id; + if (elementName && !elementNameLookup[elementName]) { + elementNames.push(elementName); + elementNameLookup[elementName] = true; + } + } + + // Extract element data name-by-name for consistent handling of special cases + // around elements which contain multiple inputs. + for (var _i = 0, _l = elementNames.length; _i < _l; _i++) { + elementName = elementNames[_i]; + var value = getFieldData(form, elementName, options); + if (value != null) { + data[elementName] = value; + } + } + + return data; +} + +/** + * @param {HTMLFormElement} form + * @param {string} fieldName + * @param {Object} options + * @return {(string|Array.)} submittable value(s) in the form for a + * named element from its .elements collection, or null if there was no + * element with that name or the element had no submittable value(s). + */ +function getFieldData(form, fieldName) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { trim: false }; + + if (!form) { + throw new Error('A form is required by getFieldData, was given form=' + form); + } + if (!fieldName && toString.call(fieldName) !== '[object String]') { + throw new Error('A field name is required by getFieldData, was given fieldName=' + fieldName); + } + + var element = form.elements[fieldName]; + if (!element || element.disabled) { + return null; + } + + if (!NODE_LIST_CLASSES[toString.call(element)]) { + return getFormElementValue(element, options.trim); + } + + // Deal with multiple form controls which have the same name + var data = []; + var allRadios = true; + for (var i = 0, l = element.length; i < l; i++) { + if (element[i].disabled) { + continue; + } + if (allRadios && element[i].type !== 'radio') { + allRadios = false; + } + var value = getFormElementValue(element[i], options.trim); + if (value != null) { + data = data.concat(value); + } + } + + // Special case for an element with multiple same-named inputs which were all + // radio buttons: if there was a selected value, only return the value. + if (allRadios && data.length === 1) { + return data[0]; + } + + return data.length > 0 ? data : null; +} + +/** + * @param {HTMLElement} element a form element. + * @param {booleam} trim should values for text entry inputs be trimmed? + * @return {(string|Array.|File|Array.)} the element's submittable + * value(s), or null if it had none. + */ +function getFormElementValue(element, trim) { + var value = null; + var type = element.type; + + + if (type === 'select-one') { + if (element.options.length) { + value = element.options[element.selectedIndex].value; + } + return value; + } + + if (type === 'select-multiple') { + value = []; + for (var i = 0, l = element.options.length; i < l; i++) { + if (element.options[i].selected) { + value.push(element.options[i].value); + } + } + if (value.length === 0) { + value = null; + } + return value; + } + + // If a file input doesn't have a files attribute, fall through to using its + // value attribute. + if (type === 'file' && 'files' in element) { + if (element.multiple) { + value = slice.call(element.files); + if (value.length === 0) { + value = null; + } + } else { + // Should be null if not present, according to the spec + value = element.files[0]; + } + return value; + } + + if (!CHECKED_INPUT_TYPES[type]) { + value = trim ? element.value.replace(TRIM_RE, '') : element.value; + } else if (element.checked) { + value = element.value; + } + + return value; +} + +// For UMD build access to getFieldData +getFormData.getFieldData = getFieldData; +},{}],23:[function(require,module,exports){ +(function (Buffer){(function (){ +/* global Blob File */ + +/* + * Module requirements. + */ + +var isArray = require('isarray'); + +var toString = Object.prototype.toString; +var withNativeBlob = typeof Blob === 'function' || + typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]'; +var withNativeFile = typeof File === 'function' || + typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]'; + +/** + * Module exports. + */ + +module.exports = hasBinary; + +/** + * Checks for binary data. + * + * Supports Buffer, ArrayBuffer, Blob and File. + * + * @param {Object} anything + * @api public + */ + +function hasBinary (obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + if (isArray(obj)) { + for (var i = 0, l = obj.length; i < l; i++) { + if (hasBinary(obj[i])) { + return true; + } + } + return false; + } + + if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) || + (typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) || + (withNativeBlob && obj instanceof Blob) || + (withNativeFile && obj instanceof File) + ) { + return true; + } + + // see: https://github.com/Automattic/has-binary/pull/4 + if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) { + return hasBinary(obj.toJSON(), true); + } + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) { + return true; + } + } + + return false; +} + +}).call(this)}).call(this,require("buffer").Buffer) + +},{"buffer":10,"isarray":24}],24:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],25:[function(require,module,exports){ + +/** + * Module exports. + * + * Logic borrowed from Modernizr: + * + * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js + */ + +try { + module.exports = typeof XMLHttpRequest !== 'undefined' && + 'withCredentials' in new XMLHttpRequest(); +} catch (err) { + // if XMLHttp support is disabled in IE then it will throw + // when trying to create + module.exports = false; +} + +},{}],26:[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 +} + +},{}],27:[function(require,module,exports){ + +var indexOf = [].indexOf; + +module.exports = function(arr, obj){ + if (indexOf) return arr.indexOf(obj); + for (var i = 0; i < arr.length; ++i) { + if (arr[i] === obj) return i; + } + return -1; +}; +},{}],28:[function(require,module,exports){ +module.exports = function isShallowEqual (a, b) { + if (a === b) return true + for (var i in a) if (!(i in b)) return false + for (var i in b) if (a[i] !== b[i]) return false + return true +} + +},{}],29:[function(require,module,exports){ +(function (global){(function (){ +/* + * base64.js + * + * Licensed under the BSD 3-Clause License. + * http://opensource.org/licenses/BSD-3-Clause + * + * References: + * http://en.wikipedia.org/wiki/Base64 + */ +;(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' + ? module.exports = factory(global) + : typeof define === 'function' && define.amd + ? define(factory) : factory(global) +}(( + typeof self !== 'undefined' ? self + : typeof window !== 'undefined' ? window + : typeof global !== 'undefined' ? global +: this +), function(global) { + 'use strict'; + // existing version for noConflict() + global = global || {}; + var _Base64 = global.Base64; + var version = "2.6.4"; + // constants + var b64chars + = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + var b64tab = function(bin) { + var t = {}; + for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i; + return t; + }(b64chars); + var fromCharCode = String.fromCharCode; + // encoder stuff + var cb_utob = function(c) { + if (c.length < 2) { + var cc = c.charCodeAt(0); + return cc < 0x80 ? c + : cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6)) + + fromCharCode(0x80 | (cc & 0x3f))) + : (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + + fromCharCode(0x80 | ( cc & 0x3f))); + } else { + var cc = 0x10000 + + (c.charCodeAt(0) - 0xD800) * 0x400 + + (c.charCodeAt(1) - 0xDC00); + return (fromCharCode(0xf0 | ((cc >>> 18) & 0x07)) + + fromCharCode(0x80 | ((cc >>> 12) & 0x3f)) + + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + + fromCharCode(0x80 | ( cc & 0x3f))); + } + }; + var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g; + var utob = function(u) { + return u.replace(re_utob, cb_utob); + }; + var cb_encode = function(ccc) { + var padlen = [0, 2, 1][ccc.length % 3], + ord = ccc.charCodeAt(0) << 16 + | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) + | ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)), + chars = [ + b64chars.charAt( ord >>> 18), + b64chars.charAt((ord >>> 12) & 63), + padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63), + padlen >= 1 ? '=' : b64chars.charAt(ord & 63) + ]; + return chars.join(''); + }; + var btoa = global.btoa && typeof global.btoa == 'function' + ? function(b){ return global.btoa(b) } : function(b) { + if (b.match(/[^\x00-\xFF]/)) throw new RangeError( + 'The string contains invalid characters.' + ); + return b.replace(/[\s\S]{1,3}/g, cb_encode); + }; + var _encode = function(u) { + return btoa(utob(String(u))); + }; + var mkUriSafe = function (b64) { + return b64.replace(/[+\/]/g, function(m0) { + return m0 == '+' ? '-' : '_'; + }).replace(/=/g, ''); + }; + var encode = function(u, urisafe) { + return urisafe ? mkUriSafe(_encode(u)) : _encode(u); + }; + var encodeURI = function(u) { return encode(u, true) }; + var fromUint8Array; + if (global.Uint8Array) fromUint8Array = function(a, urisafe) { + // return btoa(fromCharCode.apply(null, a)); + var b64 = ''; + for (var i = 0, l = a.length; i < l; i += 3) { + var a0 = a[i], a1 = a[i+1], a2 = a[i+2]; + var ord = a0 << 16 | a1 << 8 | a2; + b64 += b64chars.charAt( ord >>> 18) + + b64chars.charAt((ord >>> 12) & 63) + + ( typeof a1 != 'undefined' + ? b64chars.charAt((ord >>> 6) & 63) : '=') + + ( typeof a2 != 'undefined' + ? b64chars.charAt( ord & 63) : '='); + } + return urisafe ? mkUriSafe(b64) : b64; + }; + // decoder stuff + 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 (fromCharCode((offset >>> 10) + 0xD800) + + fromCharCode((offset & 0x3FF) + 0xDC00)); + case 3: + return fromCharCode( + ((0x0f & cccc.charCodeAt(0)) << 12) + | ((0x3f & cccc.charCodeAt(1)) << 6) + | (0x3f & cccc.charCodeAt(2)) + ); + default: + return fromCharCode( + ((0x1f & cccc.charCodeAt(0)) << 6) + | (0x3f & cccc.charCodeAt(1)) + ); + } + }; + var btou = function(b) { + return b.replace(re_btou, cb_btou); + }; + var cb_decode = function(cccc) { + var len = cccc.length, + padlen = len % 4, + n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0) + | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0) + | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0) + | (len > 3 ? b64tab[cccc.charAt(3)] : 0), + chars = [ + fromCharCode( n >>> 16), + fromCharCode((n >>> 8) & 0xff), + fromCharCode( n & 0xff) + ]; + chars.length -= [0, 0, 2, 1][padlen]; + return chars.join(''); + }; + var _atob = global.atob && typeof global.atob == 'function' + ? function(a){ return global.atob(a) } : function(a){ + return a.replace(/\S{1,4}/g, cb_decode); + }; + var atob = function(a) { + return _atob(String(a).replace(/[^A-Za-z0-9\+\/]/g, '')); + }; + var _decode = function(a) { return btou(_atob(a)) }; + var _fromURI = function(a) { + return String(a).replace(/[-_]/g, function(m0) { + return m0 == '-' ? '+' : '/' + }).replace(/[^A-Za-z0-9\+\/]/g, ''); + }; + var decode = function(a){ + return _decode(_fromURI(a)); + }; + var toUint8Array; + if (global.Uint8Array) toUint8Array = function(a) { + return Uint8Array.from(atob(_fromURI(a)), function(c) { + return c.charCodeAt(0); + }); + }; + var noConflict = function() { + var Base64 = global.Base64; + global.Base64 = _Base64; + return Base64; + }; + // export Base64 + global.Base64 = { + VERSION: version, + atob: atob, + btoa: btoa, + fromBase64: decode, + toBase64: encode, + utob: utob, + encode: encode, + encodeURI: encodeURI, + btou: btou, + decode: decode, + noConflict: noConflict, + fromUint8Array: fromUint8Array, + toUint8Array: toUint8Array + }; + // if ES5 is available, make Base64.extendString() available + if (typeof Object.defineProperty === 'function') { + var noEnum = function(v){ + return {value:v,enumerable:false,writable:true,configurable:true}; + }; + global.Base64.extendString = function () { + Object.defineProperty( + String.prototype, 'fromBase64', noEnum(function () { + return decode(this) + })); + Object.defineProperty( + String.prototype, 'toBase64', noEnum(function (urisafe) { + return encode(this, urisafe) + })); + Object.defineProperty( + String.prototype, 'toBase64URI', noEnum(function () { + return encode(this, true) + })); + }; + } + // + // export Base64 to the namespace + // + if (global['Meteor']) { // Meteor.js + Base64 = global.Base64; + } + // module.exports and AMD are mutually exclusive. + // module.exports has precedence. + if (typeof module !== 'undefined' && module.exports) { + module.exports.Base64 = global.Base64; + } + else if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([], function(){ return global.Base64 }); + } + // that's it! + return {Base64: global.Base64} +})); + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],30:[function(require,module,exports){ +(function (global){(function (){ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ +var now = function() { + return root.Date.now(); +}; + +/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ +function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + result = wait - timeSinceLastCall; + + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = debounce; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],31:[function(require,module,exports){ +(function (global){(function (){ +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ + +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ +var now = function() { + return root.Date.now(); +}; + +/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ +function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + result = wait - timeSinceLastCall; + + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; +} + +/** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ +function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} + +module.exports = throttle; + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],32:[function(require,module,exports){ +'use strict'; +module.exports = Math.log2 || function (x) { + return Math.log(x) * Math.LOG2E; +}; + +},{}],33:[function(require,module,exports){ +'use strict'; + +function areInputsEqual(newInputs, lastInputs) { + if (newInputs.length !== lastInputs.length) { + return false; + } + for (var i = 0; i < newInputs.length; i++) { + if (newInputs[i] !== lastInputs[i]) { + return false; + } + } + return true; +} + +function memoizeOne(resultFn, isEqual) { + if (isEqual === void 0) { isEqual = areInputsEqual; } + var lastThis; + var lastArgs = []; + var lastResult; + var calledOnce = false; + function memoized() { + var newArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + newArgs[_i] = arguments[_i]; + } + if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) { + return lastResult; + } + lastResult = resultFn.apply(this, newArgs); + calledOnce = true; + lastThis = this; + lastArgs = newArgs; + return lastResult; + } + return memoized; +} + +module.exports = memoizeOne; + +},{}],34:[function(require,module,exports){ +var wildcard = require('wildcard'); +var reMimePartSplit = /[\/\+\.]/; + +/** + # mime-match + + A simple function to checker whether a target mime type matches a mime-type + pattern (e.g. image/jpeg matches image/jpeg OR image/*). + + ## Example Usage + + <<< example.js + +**/ +module.exports = function(target, pattern) { + function test(pattern) { + var result = wildcard(pattern, target, reMimePartSplit); + + // ensure that we have a valid mime type (should have two parts) + return result && result.length >= 2; + } + + return pattern ? test(pattern.split(';')[0]) : test; +}; + +},{"wildcard":68}],35:[function(require,module,exports){ +/** +* Create an event emitter with namespaces +* @name createNamespaceEmitter +* @example +* var emitter = require('./index')() +* +* emitter.on('*', function () { +* console.log('all events emitted', this.event) +* }) +* +* emitter.on('example', function () { +* console.log('example event emitted') +* }) +*/ +module.exports = function createNamespaceEmitter () { + var emitter = {} + var _fns = emitter._fns = {} + + /** + * Emit an event. Optionally namespace the event. Handlers are fired in the order in which they were added with exact matches taking precedence. Separate the namespace and event with a `:` + * @name emit + * @param {String} event – the name of the event, with optional namespace + * @param {...*} data – up to 6 arguments that are passed to the event listener + * @example + * emitter.emit('example') + * emitter.emit('demo:test') + * emitter.emit('data', { example: true}, 'a string', 1) + */ + emitter.emit = function emit (event, arg1, arg2, arg3, arg4, arg5, arg6) { + var toEmit = getListeners(event) + + if (toEmit.length) { + emitAll(event, toEmit, [arg1, arg2, arg3, arg4, arg5, arg6]) + } + } + + /** + * Create en event listener. + * @name on + * @param {String} event + * @param {Function} fn + * @example + * emitter.on('example', function () {}) + * emitter.on('demo', function () {}) + */ + emitter.on = function on (event, fn) { + if (!_fns[event]) { + _fns[event] = [] + } + + _fns[event].push(fn) + } + + /** + * Create en event listener that fires once. + * @name once + * @param {String} event + * @param {Function} fn + * @example + * emitter.once('example', function () {}) + * emitter.once('demo', function () {}) + */ + emitter.once = function once (event, fn) { + function one () { + fn.apply(this, arguments) + emitter.off(event, one) + } + this.on(event, one) + } + + /** + * Stop listening to an event. Stop all listeners on an event by only passing the event name. Stop a single listener by passing that event handler as a callback. + * You must be explicit about what will be unsubscribed: `emitter.off('demo')` will unsubscribe an `emitter.on('demo')` listener, + * `emitter.off('demo:example')` will unsubscribe an `emitter.on('demo:example')` listener + * @name off + * @param {String} event + * @param {Function} [fn] – the specific handler + * @example + * emitter.off('example') + * emitter.off('demo', function () {}) + */ + emitter.off = function off (event, fn) { + var keep = [] + + if (event && fn) { + var fns = this._fns[event] + var i = 0 + var l = fns ? fns.length : 0 + + for (i; i < l; i++) { + if (fns[i] !== fn) { + keep.push(fns[i]) + } + } + } + + keep.length ? this._fns[event] = keep : delete this._fns[event] + } + + function getListeners (e) { + var out = _fns[e] ? _fns[e] : [] + var idx = e.indexOf(':') + var args = (idx === -1) ? [e] : [e.substring(0, idx), e.substring(idx + 1)] + + var keys = Object.keys(_fns) + var i = 0 + var l = keys.length + + for (i; i < l; i++) { + var key = keys[i] + if (key === '*') { + out = out.concat(_fns[key]) + } + + if (args.length === 2 && args[0] === key) { + out = out.concat(_fns[key]) + break + } + } + + return out + } + + function emitAll (e, fns, args) { + var i = 0 + var l = fns.length + + for (i; i < l; i++) { + if (!fns[i]) break + fns[i].event = e + fns[i].apply(fns[i], args) + } + } + + return emitter +} + +},{}],36:[function(require,module,exports){ +/** + * Compiles a querystring + * Returns string representation of the object + * + * @param {Object} + * @api private + */ + +exports.encode = function (obj) { + var str = ''; + + for (var i in obj) { + if (obj.hasOwnProperty(i)) { + if (str.length) str += '&'; + str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); + } + } + + return str; +}; + +/** + * Parses a simple querystring into an object + * + * @param {String} qs + * @api private + */ + +exports.decode = function(qs){ + var qry = {}; + var pairs = qs.split('&'); + for (var i = 0, l = pairs.length; i < l; i++) { + var pair = pairs[i].split('='); + qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); + } + return qry; +}; + +},{}],37:[function(require,module,exports){ +/** + * Parses an URI + * + * @author Steven Levithan (MIT license) + * @api private + */ + +var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; + +var parts = [ + 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' +]; + +module.exports = function parseuri(str) { + var src = str, + b = str.indexOf('['), + e = str.indexOf(']'); + + if (b != -1 && e != -1) { + str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); + } + + var m = re.exec(str || ''), + uri = {}, + i = 14; + + while (i--) { + uri[parts[i]] = m[i] || ''; + } + + if (b != -1 && e != -1) { + uri.source = src; + uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); + uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); + uri.ipv6uri = true; + } + + return uri; +}; + +},{}],38:[function(require,module,exports){ +!function() { + 'use strict'; + function VNode() {} + function h(nodeName, attributes) { + var lastSimple, child, simple, i, children = EMPTY_CHILDREN; + for (i = arguments.length; i-- > 2; ) stack.push(arguments[i]); + if (attributes && null != attributes.children) { + if (!stack.length) stack.push(attributes.children); + delete attributes.children; + } + while (stack.length) if ((child = stack.pop()) && void 0 !== child.pop) for (i = child.length; i--; ) stack.push(child[i]); else { + if ('boolean' == typeof child) child = null; + if (simple = 'function' != typeof nodeName) if (null == child) child = ''; else if ('number' == typeof child) child = String(child); else if ('string' != typeof child) simple = !1; + if (simple && lastSimple) children[children.length - 1] += child; else if (children === EMPTY_CHILDREN) children = [ child ]; else children.push(child); + lastSimple = simple; + } + var p = new VNode(); + p.nodeName = nodeName; + p.children = children; + p.attributes = null == attributes ? void 0 : attributes; + p.key = null == attributes ? void 0 : attributes.key; + if (void 0 !== options.vnode) options.vnode(p); + return p; + } + function extend(obj, props) { + for (var i in props) obj[i] = props[i]; + return obj; + } + function cloneElement(vnode, props) { + return h(vnode.nodeName, extend(extend({}, vnode.attributes), props), arguments.length > 2 ? [].slice.call(arguments, 2) : vnode.children); + } + function enqueueRender(component) { + if (!component.__d && (component.__d = !0) && 1 == items.push(component)) (options.debounceRendering || defer)(rerender); + } + function rerender() { + var p, list = items; + items = []; + while (p = list.pop()) if (p.__d) renderComponent(p); + } + function isSameNodeType(node, vnode, hydrating) { + if ('string' == typeof vnode || 'number' == typeof vnode) return void 0 !== node.splitText; + if ('string' == typeof vnode.nodeName) return !node._componentConstructor && isNamedNode(node, vnode.nodeName); else return hydrating || node._componentConstructor === vnode.nodeName; + } + function isNamedNode(node, nodeName) { + return node.__n === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase(); + } + function getNodeProps(vnode) { + var props = extend({}, vnode.attributes); + props.children = vnode.children; + var defaultProps = vnode.nodeName.defaultProps; + if (void 0 !== defaultProps) for (var i in defaultProps) if (void 0 === props[i]) props[i] = defaultProps[i]; + return props; + } + function createNode(nodeName, isSvg) { + var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName); + node.__n = nodeName; + return node; + } + function removeNode(node) { + var parentNode = node.parentNode; + if (parentNode) parentNode.removeChild(node); + } + function setAccessor(node, name, old, value, isSvg) { + if ('className' === name) name = 'class'; + if ('key' === name) ; else if ('ref' === name) { + if (old) old(null); + if (value) value(node); + } else if ('class' === name && !isSvg) node.className = value || ''; else if ('style' === name) { + if (!value || 'string' == typeof value || 'string' == typeof old) node.style.cssText = value || ''; + if (value && 'object' == typeof value) { + if ('string' != typeof old) for (var i in old) if (!(i in value)) node.style[i] = ''; + for (var i in value) node.style[i] = 'number' == typeof value[i] && !1 === IS_NON_DIMENSIONAL.test(i) ? value[i] + 'px' : value[i]; + } + } else if ('dangerouslySetInnerHTML' === name) { + if (value) node.innerHTML = value.__html || ''; + } else if ('o' == name[0] && 'n' == name[1]) { + var useCapture = name !== (name = name.replace(/Capture$/, '')); + name = name.toLowerCase().substring(2); + if (value) { + if (!old) node.addEventListener(name, eventProxy, useCapture); + } else node.removeEventListener(name, eventProxy, useCapture); + (node.__l || (node.__l = {}))[name] = value; + } else if ('list' !== name && 'type' !== name && !isSvg && name in node) { + setProperty(node, name, null == value ? '' : value); + if (null == value || !1 === value) node.removeAttribute(name); + } else { + var ns = isSvg && name !== (name = name.replace(/^xlink:?/, '')); + if (null == value || !1 === value) if (ns) node.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase()); else node.removeAttribute(name); else if ('function' != typeof value) if (ns) node.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value); else node.setAttribute(name, value); + } + } + function setProperty(node, name, value) { + try { + node[name] = value; + } catch (e) {} + } + function eventProxy(e) { + return this.__l[e.type](options.event && options.event(e) || e); + } + function flushMounts() { + var c; + while (c = mounts.pop()) { + if (options.afterMount) options.afterMount(c); + if (c.componentDidMount) c.componentDidMount(); + } + } + function diff(dom, vnode, context, mountAll, parent, componentRoot) { + if (!diffLevel++) { + isSvgMode = null != parent && void 0 !== parent.ownerSVGElement; + hydrating = null != dom && !('__preactattr_' in dom); + } + var ret = idiff(dom, vnode, context, mountAll, componentRoot); + if (parent && ret.parentNode !== parent) parent.appendChild(ret); + if (!--diffLevel) { + hydrating = !1; + if (!componentRoot) flushMounts(); + } + return ret; + } + function idiff(dom, vnode, context, mountAll, componentRoot) { + var out = dom, prevSvgMode = isSvgMode; + if (null == vnode || 'boolean' == typeof vnode) vnode = ''; + if ('string' == typeof vnode || 'number' == typeof vnode) { + if (dom && void 0 !== dom.splitText && dom.parentNode && (!dom._component || componentRoot)) { + if (dom.nodeValue != vnode) dom.nodeValue = vnode; + } else { + out = document.createTextNode(vnode); + if (dom) { + if (dom.parentNode) dom.parentNode.replaceChild(out, dom); + recollectNodeTree(dom, !0); + } + } + out.__preactattr_ = !0; + return out; + } + var vnodeName = vnode.nodeName; + if ('function' == typeof vnodeName) return buildComponentFromVNode(dom, vnode, context, mountAll); + isSvgMode = 'svg' === vnodeName ? !0 : 'foreignObject' === vnodeName ? !1 : isSvgMode; + vnodeName = String(vnodeName); + if (!dom || !isNamedNode(dom, vnodeName)) { + out = createNode(vnodeName, isSvgMode); + if (dom) { + while (dom.firstChild) out.appendChild(dom.firstChild); + if (dom.parentNode) dom.parentNode.replaceChild(out, dom); + recollectNodeTree(dom, !0); + } + } + var fc = out.firstChild, props = out.__preactattr_, vchildren = vnode.children; + if (null == props) { + props = out.__preactattr_ = {}; + for (var a = out.attributes, i = a.length; i--; ) props[a[i].name] = a[i].value; + } + if (!hydrating && vchildren && 1 === vchildren.length && 'string' == typeof vchildren[0] && null != fc && void 0 !== fc.splitText && null == fc.nextSibling) { + if (fc.nodeValue != vchildren[0]) fc.nodeValue = vchildren[0]; + } else if (vchildren && vchildren.length || null != fc) innerDiffNode(out, vchildren, context, mountAll, hydrating || null != props.dangerouslySetInnerHTML); + diffAttributes(out, vnode.attributes, props); + isSvgMode = prevSvgMode; + return out; + } + function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) { + var j, c, f, vchild, child, originalChildren = dom.childNodes, children = [], keyed = {}, keyedLen = 0, min = 0, len = originalChildren.length, childrenLen = 0, vlen = vchildren ? vchildren.length : 0; + if (0 !== len) for (var i = 0; i < len; i++) { + var _child = originalChildren[i], props = _child.__preactattr_, key = vlen && props ? _child._component ? _child._component.__k : props.key : null; + if (null != key) { + keyedLen++; + keyed[key] = _child; + } else if (props || (void 0 !== _child.splitText ? isHydrating ? _child.nodeValue.trim() : !0 : isHydrating)) children[childrenLen++] = _child; + } + if (0 !== vlen) for (var i = 0; i < vlen; i++) { + vchild = vchildren[i]; + child = null; + var key = vchild.key; + if (null != key) { + if (keyedLen && void 0 !== keyed[key]) { + child = keyed[key]; + keyed[key] = void 0; + keyedLen--; + } + } else if (!child && min < childrenLen) for (j = min; j < childrenLen; j++) if (void 0 !== children[j] && isSameNodeType(c = children[j], vchild, isHydrating)) { + child = c; + children[j] = void 0; + if (j === childrenLen - 1) childrenLen--; + if (j === min) min++; + break; + } + child = idiff(child, vchild, context, mountAll); + f = originalChildren[i]; + if (child && child !== dom && child !== f) if (null == f) dom.appendChild(child); else if (child === f.nextSibling) removeNode(f); else dom.insertBefore(child, f); + } + if (keyedLen) for (var i in keyed) if (void 0 !== keyed[i]) recollectNodeTree(keyed[i], !1); + while (min <= childrenLen) if (void 0 !== (child = children[childrenLen--])) recollectNodeTree(child, !1); + } + function recollectNodeTree(node, unmountOnly) { + var component = node._component; + if (component) unmountComponent(component); else { + if (null != node.__preactattr_ && node.__preactattr_.ref) node.__preactattr_.ref(null); + if (!1 === unmountOnly || null == node.__preactattr_) removeNode(node); + removeChildren(node); + } + } + function removeChildren(node) { + node = node.lastChild; + while (node) { + var next = node.previousSibling; + recollectNodeTree(node, !0); + node = next; + } + } + function diffAttributes(dom, attrs, old) { + var name; + for (name in old) if ((!attrs || null == attrs[name]) && null != old[name]) setAccessor(dom, name, old[name], old[name] = void 0, isSvgMode); + for (name in attrs) if (!('children' === name || 'innerHTML' === name || name in old && attrs[name] === ('value' === name || 'checked' === name ? dom[name] : old[name]))) setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode); + } + function collectComponent(component) { + var name = component.constructor.name; + (components[name] || (components[name] = [])).push(component); + } + function createComponent(Ctor, props, context) { + var inst, list = components[Ctor.name]; + if (Ctor.prototype && Ctor.prototype.render) { + inst = new Ctor(props, context); + Component.call(inst, props, context); + } else { + inst = new Component(props, context); + inst.constructor = Ctor; + inst.render = doRender; + } + if (list) for (var i = list.length; i--; ) if (list[i].constructor === Ctor) { + inst.__b = list[i].__b; + list.splice(i, 1); + break; + } + return inst; + } + function doRender(props, state, context) { + return this.constructor(props, context); + } + function setComponentProps(component, props, opts, context, mountAll) { + if (!component.__x) { + component.__x = !0; + if (component.__r = props.ref) delete props.ref; + if (component.__k = props.key) delete props.key; + if (!component.base || mountAll) { + if (component.componentWillMount) component.componentWillMount(); + } else if (component.componentWillReceiveProps) component.componentWillReceiveProps(props, context); + if (context && context !== component.context) { + if (!component.__c) component.__c = component.context; + component.context = context; + } + if (!component.__p) component.__p = component.props; + component.props = props; + component.__x = !1; + if (0 !== opts) if (1 === opts || !1 !== options.syncComponentUpdates || !component.base) renderComponent(component, 1, mountAll); else enqueueRender(component); + if (component.__r) component.__r(component); + } + } + function renderComponent(component, opts, mountAll, isChild) { + if (!component.__x) { + var rendered, inst, cbase, props = component.props, state = component.state, context = component.context, previousProps = component.__p || props, previousState = component.__s || state, previousContext = component.__c || context, isUpdate = component.base, nextBase = component.__b, initialBase = isUpdate || nextBase, initialChildComponent = component._component, skip = !1; + if (isUpdate) { + component.props = previousProps; + component.state = previousState; + component.context = previousContext; + if (2 !== opts && component.shouldComponentUpdate && !1 === component.shouldComponentUpdate(props, state, context)) skip = !0; else if (component.componentWillUpdate) component.componentWillUpdate(props, state, context); + component.props = props; + component.state = state; + component.context = context; + } + component.__p = component.__s = component.__c = component.__b = null; + component.__d = !1; + if (!skip) { + rendered = component.render(props, state, context); + if (component.getChildContext) context = extend(extend({}, context), component.getChildContext()); + var toUnmount, base, childComponent = rendered && rendered.nodeName; + if ('function' == typeof childComponent) { + var childProps = getNodeProps(rendered); + inst = initialChildComponent; + if (inst && inst.constructor === childComponent && childProps.key == inst.__k) setComponentProps(inst, childProps, 1, context, !1); else { + toUnmount = inst; + component._component = inst = createComponent(childComponent, childProps, context); + inst.__b = inst.__b || nextBase; + inst.__u = component; + setComponentProps(inst, childProps, 0, context, !1); + renderComponent(inst, 1, mountAll, !0); + } + base = inst.base; + } else { + cbase = initialBase; + toUnmount = initialChildComponent; + if (toUnmount) cbase = component._component = null; + if (initialBase || 1 === opts) { + if (cbase) cbase._component = null; + base = diff(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, !0); + } + } + if (initialBase && base !== initialBase && inst !== initialChildComponent) { + var baseParent = initialBase.parentNode; + if (baseParent && base !== baseParent) { + baseParent.replaceChild(base, initialBase); + if (!toUnmount) { + initialBase._component = null; + recollectNodeTree(initialBase, !1); + } + } + } + if (toUnmount) unmountComponent(toUnmount); + component.base = base; + if (base && !isChild) { + var componentRef = component, t = component; + while (t = t.__u) (componentRef = t).base = base; + base._component = componentRef; + base._componentConstructor = componentRef.constructor; + } + } + if (!isUpdate || mountAll) mounts.unshift(component); else if (!skip) { + if (component.componentDidUpdate) component.componentDidUpdate(previousProps, previousState, previousContext); + if (options.afterUpdate) options.afterUpdate(component); + } + if (null != component.__h) while (component.__h.length) component.__h.pop().call(component); + if (!diffLevel && !isChild) flushMounts(); + } + } + function buildComponentFromVNode(dom, vnode, context, mountAll) { + var c = dom && dom._component, originalComponent = c, oldDom = dom, isDirectOwner = c && dom._componentConstructor === vnode.nodeName, isOwner = isDirectOwner, props = getNodeProps(vnode); + while (c && !isOwner && (c = c.__u)) isOwner = c.constructor === vnode.nodeName; + if (c && isOwner && (!mountAll || c._component)) { + setComponentProps(c, props, 3, context, mountAll); + dom = c.base; + } else { + if (originalComponent && !isDirectOwner) { + unmountComponent(originalComponent); + dom = oldDom = null; + } + c = createComponent(vnode.nodeName, props, context); + if (dom && !c.__b) { + c.__b = dom; + oldDom = null; + } + setComponentProps(c, props, 1, context, mountAll); + dom = c.base; + if (oldDom && dom !== oldDom) { + oldDom._component = null; + recollectNodeTree(oldDom, !1); + } + } + return dom; + } + function unmountComponent(component) { + if (options.beforeUnmount) options.beforeUnmount(component); + var base = component.base; + component.__x = !0; + if (component.componentWillUnmount) component.componentWillUnmount(); + component.base = null; + var inner = component._component; + if (inner) unmountComponent(inner); else if (base) { + if (base.__preactattr_ && base.__preactattr_.ref) base.__preactattr_.ref(null); + component.__b = base; + removeNode(base); + collectComponent(component); + removeChildren(base); + } + if (component.__r) component.__r(null); + } + function Component(props, context) { + this.__d = !0; + this.context = context; + this.props = props; + this.state = this.state || {}; + } + function render(vnode, parent, merge) { + return diff(merge, vnode, {}, !1, parent, !1); + } + var options = {}; + var stack = []; + var EMPTY_CHILDREN = []; + var defer = 'function' == typeof Promise ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout; + var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i; + var items = []; + var mounts = []; + var diffLevel = 0; + var isSvgMode = !1; + var hydrating = !1; + var components = {}; + extend(Component.prototype, { + setState: function(state, callback) { + var s = this.state; + if (!this.__s) this.__s = extend({}, s); + extend(s, 'function' == typeof state ? state(s, this.props) : state); + if (callback) (this.__h = this.__h || []).push(callback); + enqueueRender(this); + }, + forceUpdate: function(callback) { + if (callback) (this.__h = this.__h || []).push(callback); + renderComponent(this, 2); + }, + render: function() {} + }); + var preact = { + h: h, + createElement: h, + cloneElement: cloneElement, + Component: Component, + render: render, + rerender: rerender, + options: options + }; + if ('undefined' != typeof module) module.exports = preact; else self.preact = preact; +}(); + +},{}],39:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],40:[function(require,module,exports){ +var has = Object.prototype.hasOwnProperty + +/** + * Stringify an object for use in a query string. + * + * @param {Object} obj - The object. + * @param {string} prefix - When nesting, the parent key. + * keys in `obj` will be stringified as `prefix[key]`. + * @returns {string} + */ + +module.exports = function queryStringify (obj, prefix) { + var pairs = [] + for (var key in obj) { + if (!has.call(obj, key)) { + continue + } + + var value = obj[key] + var enkey = encodeURIComponent(key) + var pair + if (typeof value === 'object') { + pair = queryStringify(value, prefix ? prefix + '[' + enkey + ']' : enkey) + } else { + pair = (prefix ? prefix + '[' + enkey + ']' : enkey) + '=' + encodeURIComponent(value) + } + pairs.push(pair) + } + return pairs.join('&') +} + +},{}],41:[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; + +},{}],42:[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; +}; + +},{}],43:[function(require,module,exports){ +(function (global){(function (){ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ResizeObserver = factory()); +}(this, (function () { 'use strict'; + + /** + * A collection of shims that provide minimal functionality of the ES6 collections. + * + * These implementations are not meant to be used outside of the ResizeObserver + * modules as they cover only a limited range of use cases. + */ + /* eslint-disable require-jsdoc, valid-jsdoc */ + var MapShim = (function () { + if (typeof Map !== 'undefined') { + return Map; + } + /** + * Returns index in provided array that matches the specified key. + * + * @param {Array} arr + * @param {*} key + * @returns {number} + */ + function getIndex(arr, key) { + var result = -1; + arr.some(function (entry, index) { + if (entry[0] === key) { + result = index; + return true; + } + return false; + }); + return result; + } + return /** @class */ (function () { + function class_1() { + this.__entries__ = []; + } + Object.defineProperty(class_1.prototype, "size", { + /** + * @returns {boolean} + */ + get: function () { + return this.__entries__.length; + }, + enumerable: true, + configurable: true + }); + /** + * @param {*} key + * @returns {*} + */ + class_1.prototype.get = function (key) { + var index = getIndex(this.__entries__, key); + var entry = this.__entries__[index]; + return entry && entry[1]; + }; + /** + * @param {*} key + * @param {*} value + * @returns {void} + */ + class_1.prototype.set = function (key, value) { + var index = getIndex(this.__entries__, key); + if (~index) { + this.__entries__[index][1] = value; + } + else { + this.__entries__.push([key, value]); + } + }; + /** + * @param {*} key + * @returns {void} + */ + class_1.prototype.delete = function (key) { + var entries = this.__entries__; + var index = getIndex(entries, key); + if (~index) { + entries.splice(index, 1); + } + }; + /** + * @param {*} key + * @returns {void} + */ + class_1.prototype.has = function (key) { + return !!~getIndex(this.__entries__, key); + }; + /** + * @returns {void} + */ + class_1.prototype.clear = function () { + this.__entries__.splice(0); + }; + /** + * @param {Function} callback + * @param {*} [ctx=null] + * @returns {void} + */ + class_1.prototype.forEach = function (callback, ctx) { + if (ctx === void 0) { ctx = null; } + for (var _i = 0, _a = this.__entries__; _i < _a.length; _i++) { + var entry = _a[_i]; + callback.call(ctx, entry[1], entry[0]); + } + }; + return class_1; + }()); + })(); + + /** + * Detects whether window and document objects are available in current environment. + */ + var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && window.document === document; + + // Returns global object of a current environment. + var global$1 = (function () { + if (typeof global !== 'undefined' && global.Math === Math) { + return global; + } + if (typeof self !== 'undefined' && self.Math === Math) { + return self; + } + if (typeof window !== 'undefined' && window.Math === Math) { + return window; + } + // eslint-disable-next-line no-new-func + return Function('return this')(); + })(); + + /** + * A shim for the requestAnimationFrame which falls back to the setTimeout if + * first one is not supported. + * + * @returns {number} Requests' identifier. + */ + var requestAnimationFrame$1 = (function () { + if (typeof requestAnimationFrame === 'function') { + // It's required to use a bounded function because IE sometimes throws + // an "Invalid calling object" error if rAF is invoked without the global + // object on the left hand side. + return requestAnimationFrame.bind(global$1); + } + return function (callback) { return setTimeout(function () { return callback(Date.now()); }, 1000 / 60); }; + })(); + + // Defines minimum timeout before adding a trailing call. + var trailingTimeout = 2; + /** + * Creates a wrapper function which ensures that provided callback will be + * invoked only once during the specified delay period. + * + * @param {Function} callback - Function to be invoked after the delay period. + * @param {number} delay - Delay after which to invoke callback. + * @returns {Function} + */ + function throttle (callback, delay) { + var leadingCall = false, trailingCall = false, lastCallTime = 0; + /** + * Invokes the original callback function and schedules new invocation if + * the "proxy" was called during current request. + * + * @returns {void} + */ + function resolvePending() { + if (leadingCall) { + leadingCall = false; + callback(); + } + if (trailingCall) { + proxy(); + } + } + /** + * Callback invoked after the specified delay. It will further postpone + * invocation of the original function delegating it to the + * requestAnimationFrame. + * + * @returns {void} + */ + function timeoutCallback() { + requestAnimationFrame$1(resolvePending); + } + /** + * Schedules invocation of the original function. + * + * @returns {void} + */ + function proxy() { + var timeStamp = Date.now(); + if (leadingCall) { + // Reject immediately following calls. + if (timeStamp - lastCallTime < trailingTimeout) { + return; + } + // Schedule new call to be in invoked when the pending one is resolved. + // This is important for "transitions" which never actually start + // immediately so there is a chance that we might miss one if change + // happens amids the pending invocation. + trailingCall = true; + } + else { + leadingCall = true; + trailingCall = false; + setTimeout(timeoutCallback, delay); + } + lastCallTime = timeStamp; + } + return proxy; + } + + // Minimum delay before invoking the update of observers. + var REFRESH_DELAY = 20; + // A list of substrings of CSS properties used to find transition events that + // might affect dimensions of observed elements. + var transitionKeys = ['top', 'right', 'bottom', 'left', 'width', 'height', 'size', 'weight']; + // Check if MutationObserver is available. + var mutationObserverSupported = typeof MutationObserver !== 'undefined'; + /** + * Singleton controller class which handles updates of ResizeObserver instances. + */ + var ResizeObserverController = /** @class */ (function () { + /** + * Creates a new instance of ResizeObserverController. + * + * @private + */ + function ResizeObserverController() { + /** + * Indicates whether DOM listeners have been added. + * + * @private {boolean} + */ + this.connected_ = false; + /** + * Tells that controller has subscribed for Mutation Events. + * + * @private {boolean} + */ + this.mutationEventsAdded_ = false; + /** + * Keeps reference to the instance of MutationObserver. + * + * @private {MutationObserver} + */ + this.mutationsObserver_ = null; + /** + * A list of connected observers. + * + * @private {Array} + */ + this.observers_ = []; + this.onTransitionEnd_ = this.onTransitionEnd_.bind(this); + this.refresh = throttle(this.refresh.bind(this), REFRESH_DELAY); + } + /** + * Adds observer to observers list. + * + * @param {ResizeObserverSPI} observer - Observer to be added. + * @returns {void} + */ + ResizeObserverController.prototype.addObserver = function (observer) { + if (!~this.observers_.indexOf(observer)) { + this.observers_.push(observer); + } + // Add listeners if they haven't been added yet. + if (!this.connected_) { + this.connect_(); + } + }; + /** + * Removes observer from observers list. + * + * @param {ResizeObserverSPI} observer - Observer to be removed. + * @returns {void} + */ + ResizeObserverController.prototype.removeObserver = function (observer) { + var observers = this.observers_; + var index = observers.indexOf(observer); + // Remove observer if it's present in registry. + if (~index) { + observers.splice(index, 1); + } + // Remove listeners if controller has no connected observers. + if (!observers.length && this.connected_) { + this.disconnect_(); + } + }; + /** + * Invokes the update of observers. It will continue running updates insofar + * it detects changes. + * + * @returns {void} + */ + ResizeObserverController.prototype.refresh = function () { + var changesDetected = this.updateObservers_(); + // Continue running updates if changes have been detected as there might + // be future ones caused by CSS transitions. + if (changesDetected) { + this.refresh(); + } + }; + /** + * Updates every observer from observers list and notifies them of queued + * entries. + * + * @private + * @returns {boolean} Returns "true" if any observer has detected changes in + * dimensions of it's elements. + */ + ResizeObserverController.prototype.updateObservers_ = function () { + // Collect observers that have active observations. + var activeObservers = this.observers_.filter(function (observer) { + return observer.gatherActive(), observer.hasActive(); + }); + // Deliver notifications in a separate cycle in order to avoid any + // collisions between observers, e.g. when multiple instances of + // ResizeObserver are tracking the same element and the callback of one + // of them changes content dimensions of the observed target. Sometimes + // this may result in notifications being blocked for the rest of observers. + activeObservers.forEach(function (observer) { return observer.broadcastActive(); }); + return activeObservers.length > 0; + }; + /** + * Initializes DOM listeners. + * + * @private + * @returns {void} + */ + ResizeObserverController.prototype.connect_ = function () { + // Do nothing if running in a non-browser environment or if listeners + // have been already added. + if (!isBrowser || this.connected_) { + return; + } + // Subscription to the "Transitionend" event is used as a workaround for + // delayed transitions. This way it's possible to capture at least the + // final state of an element. + document.addEventListener('transitionend', this.onTransitionEnd_); + window.addEventListener('resize', this.refresh); + if (mutationObserverSupported) { + this.mutationsObserver_ = new MutationObserver(this.refresh); + this.mutationsObserver_.observe(document, { + attributes: true, + childList: true, + characterData: true, + subtree: true + }); + } + else { + document.addEventListener('DOMSubtreeModified', this.refresh); + this.mutationEventsAdded_ = true; + } + this.connected_ = true; + }; + /** + * Removes DOM listeners. + * + * @private + * @returns {void} + */ + ResizeObserverController.prototype.disconnect_ = function () { + // Do nothing if running in a non-browser environment or if listeners + // have been already removed. + if (!isBrowser || !this.connected_) { + return; + } + document.removeEventListener('transitionend', this.onTransitionEnd_); + window.removeEventListener('resize', this.refresh); + if (this.mutationsObserver_) { + this.mutationsObserver_.disconnect(); + } + if (this.mutationEventsAdded_) { + document.removeEventListener('DOMSubtreeModified', this.refresh); + } + this.mutationsObserver_ = null; + this.mutationEventsAdded_ = false; + this.connected_ = false; + }; + /** + * "Transitionend" event handler. + * + * @private + * @param {TransitionEvent} event + * @returns {void} + */ + ResizeObserverController.prototype.onTransitionEnd_ = function (_a) { + var _b = _a.propertyName, propertyName = _b === void 0 ? '' : _b; + // Detect whether transition may affect dimensions of an element. + var isReflowProperty = transitionKeys.some(function (key) { + return !!~propertyName.indexOf(key); + }); + if (isReflowProperty) { + this.refresh(); + } + }; + /** + * Returns instance of the ResizeObserverController. + * + * @returns {ResizeObserverController} + */ + ResizeObserverController.getInstance = function () { + if (!this.instance_) { + this.instance_ = new ResizeObserverController(); + } + return this.instance_; + }; + /** + * Holds reference to the controller's instance. + * + * @private {ResizeObserverController} + */ + ResizeObserverController.instance_ = null; + return ResizeObserverController; + }()); + + /** + * Defines non-writable/enumerable properties of the provided target object. + * + * @param {Object} target - Object for which to define properties. + * @param {Object} props - Properties to be defined. + * @returns {Object} Target object. + */ + var defineConfigurable = (function (target, props) { + for (var _i = 0, _a = Object.keys(props); _i < _a.length; _i++) { + var key = _a[_i]; + Object.defineProperty(target, key, { + value: props[key], + enumerable: false, + writable: false, + configurable: true + }); + } + return target; + }); + + /** + * Returns the global object associated with provided element. + * + * @param {Object} target + * @returns {Object} + */ + var getWindowOf = (function (target) { + // Assume that the element is an instance of Node, which means that it + // has the "ownerDocument" property from which we can retrieve a + // corresponding global object. + var ownerGlobal = target && target.ownerDocument && target.ownerDocument.defaultView; + // Return the local global object if it's not possible extract one from + // provided element. + return ownerGlobal || global$1; + }); + + // Placeholder of an empty content rectangle. + var emptyRect = createRectInit(0, 0, 0, 0); + /** + * Converts provided string to a number. + * + * @param {number|string} value + * @returns {number} + */ + function toFloat(value) { + return parseFloat(value) || 0; + } + /** + * Extracts borders size from provided styles. + * + * @param {CSSStyleDeclaration} styles + * @param {...string} positions - Borders positions (top, right, ...) + * @returns {number} + */ + function getBordersSize(styles) { + var positions = []; + for (var _i = 1; _i < arguments.length; _i++) { + positions[_i - 1] = arguments[_i]; + } + return positions.reduce(function (size, position) { + var value = styles['border-' + position + '-width']; + return size + toFloat(value); + }, 0); + } + /** + * Extracts paddings sizes from provided styles. + * + * @param {CSSStyleDeclaration} styles + * @returns {Object} Paddings box. + */ + function getPaddings(styles) { + var positions = ['top', 'right', 'bottom', 'left']; + var paddings = {}; + for (var _i = 0, positions_1 = positions; _i < positions_1.length; _i++) { + var position = positions_1[_i]; + var value = styles['padding-' + position]; + paddings[position] = toFloat(value); + } + return paddings; + } + /** + * Calculates content rectangle of provided SVG element. + * + * @param {SVGGraphicsElement} target - Element content rectangle of which needs + * to be calculated. + * @returns {DOMRectInit} + */ + function getSVGContentRect(target) { + var bbox = target.getBBox(); + return createRectInit(0, 0, bbox.width, bbox.height); + } + /** + * Calculates content rectangle of provided HTMLElement. + * + * @param {HTMLElement} target - Element for which to calculate the content rectangle. + * @returns {DOMRectInit} + */ + function getHTMLElementContentRect(target) { + // Client width & height properties can't be + // used exclusively as they provide rounded values. + var clientWidth = target.clientWidth, clientHeight = target.clientHeight; + // By this condition we can catch all non-replaced inline, hidden and + // detached elements. Though elements with width & height properties less + // than 0.5 will be discarded as well. + // + // Without it we would need to implement separate methods for each of + // those cases and it's not possible to perform a precise and performance + // effective test for hidden elements. E.g. even jQuery's ':visible' filter + // gives wrong results for elements with width & height less than 0.5. + if (!clientWidth && !clientHeight) { + return emptyRect; + } + var styles = getWindowOf(target).getComputedStyle(target); + var paddings = getPaddings(styles); + var horizPad = paddings.left + paddings.right; + var vertPad = paddings.top + paddings.bottom; + // Computed styles of width & height are being used because they are the + // only dimensions available to JS that contain non-rounded values. It could + // be possible to utilize the getBoundingClientRect if only it's data wasn't + // affected by CSS transformations let alone paddings, borders and scroll bars. + var width = toFloat(styles.width), height = toFloat(styles.height); + // Width & height include paddings and borders when the 'border-box' box + // model is applied (except for IE). + if (styles.boxSizing === 'border-box') { + // Following conditions are required to handle Internet Explorer which + // doesn't include paddings and borders to computed CSS dimensions. + // + // We can say that if CSS dimensions + paddings are equal to the "client" + // properties then it's either IE, and thus we don't need to subtract + // anything, or an element merely doesn't have paddings/borders styles. + if (Math.round(width + horizPad) !== clientWidth) { + width -= getBordersSize(styles, 'left', 'right') + horizPad; + } + if (Math.round(height + vertPad) !== clientHeight) { + height -= getBordersSize(styles, 'top', 'bottom') + vertPad; + } + } + // Following steps can't be applied to the document's root element as its + // client[Width/Height] properties represent viewport area of the window. + // Besides, it's as well not necessary as the itself neither has + // rendered scroll bars nor it can be clipped. + if (!isDocumentElement(target)) { + // In some browsers (only in Firefox, actually) CSS width & height + // include scroll bars size which can be removed at this step as scroll + // bars are the only difference between rounded dimensions + paddings + // and "client" properties, though that is not always true in Chrome. + var vertScrollbar = Math.round(width + horizPad) - clientWidth; + var horizScrollbar = Math.round(height + vertPad) - clientHeight; + // Chrome has a rather weird rounding of "client" properties. + // E.g. for an element with content width of 314.2px it sometimes gives + // the client width of 315px and for the width of 314.7px it may give + // 314px. And it doesn't happen all the time. So just ignore this delta + // as a non-relevant. + if (Math.abs(vertScrollbar) !== 1) { + width -= vertScrollbar; + } + if (Math.abs(horizScrollbar) !== 1) { + height -= horizScrollbar; + } + } + return createRectInit(paddings.left, paddings.top, width, height); + } + /** + * Checks whether provided element is an instance of the SVGGraphicsElement. + * + * @param {Element} target - Element to be checked. + * @returns {boolean} + */ + var isSVGGraphicsElement = (function () { + // Some browsers, namely IE and Edge, don't have the SVGGraphicsElement + // interface. + if (typeof SVGGraphicsElement !== 'undefined') { + return function (target) { return target instanceof getWindowOf(target).SVGGraphicsElement; }; + } + // If it's so, then check that element is at least an instance of the + // SVGElement and that it has the "getBBox" method. + // eslint-disable-next-line no-extra-parens + return function (target) { return (target instanceof getWindowOf(target).SVGElement && + typeof target.getBBox === 'function'); }; + })(); + /** + * Checks whether provided element is a document element (). + * + * @param {Element} target - Element to be checked. + * @returns {boolean} + */ + function isDocumentElement(target) { + return target === getWindowOf(target).document.documentElement; + } + /** + * Calculates an appropriate content rectangle for provided html or svg element. + * + * @param {Element} target - Element content rectangle of which needs to be calculated. + * @returns {DOMRectInit} + */ + function getContentRect(target) { + if (!isBrowser) { + return emptyRect; + } + if (isSVGGraphicsElement(target)) { + return getSVGContentRect(target); + } + return getHTMLElementContentRect(target); + } + /** + * Creates rectangle with an interface of the DOMRectReadOnly. + * Spec: https://drafts.fxtf.org/geometry/#domrectreadonly + * + * @param {DOMRectInit} rectInit - Object with rectangle's x/y coordinates and dimensions. + * @returns {DOMRectReadOnly} + */ + function createReadOnlyRect(_a) { + var x = _a.x, y = _a.y, width = _a.width, height = _a.height; + // If DOMRectReadOnly is available use it as a prototype for the rectangle. + var Constr = typeof DOMRectReadOnly !== 'undefined' ? DOMRectReadOnly : Object; + var rect = Object.create(Constr.prototype); + // Rectangle's properties are not writable and non-enumerable. + defineConfigurable(rect, { + x: x, y: y, width: width, height: height, + top: y, + right: x + width, + bottom: height + y, + left: x + }); + return rect; + } + /** + * Creates DOMRectInit object based on the provided dimensions and the x/y coordinates. + * Spec: https://drafts.fxtf.org/geometry/#dictdef-domrectinit + * + * @param {number} x - X coordinate. + * @param {number} y - Y coordinate. + * @param {number} width - Rectangle's width. + * @param {number} height - Rectangle's height. + * @returns {DOMRectInit} + */ + function createRectInit(x, y, width, height) { + return { x: x, y: y, width: width, height: height }; + } + + /** + * Class that is responsible for computations of the content rectangle of + * provided DOM element and for keeping track of it's changes. + */ + var ResizeObservation = /** @class */ (function () { + /** + * Creates an instance of ResizeObservation. + * + * @param {Element} target - Element to be observed. + */ + function ResizeObservation(target) { + /** + * Broadcasted width of content rectangle. + * + * @type {number} + */ + this.broadcastWidth = 0; + /** + * Broadcasted height of content rectangle. + * + * @type {number} + */ + this.broadcastHeight = 0; + /** + * Reference to the last observed content rectangle. + * + * @private {DOMRectInit} + */ + this.contentRect_ = createRectInit(0, 0, 0, 0); + this.target = target; + } + /** + * Updates content rectangle and tells whether it's width or height properties + * have changed since the last broadcast. + * + * @returns {boolean} + */ + ResizeObservation.prototype.isActive = function () { + var rect = getContentRect(this.target); + this.contentRect_ = rect; + return (rect.width !== this.broadcastWidth || + rect.height !== this.broadcastHeight); + }; + /** + * Updates 'broadcastWidth' and 'broadcastHeight' properties with a data + * from the corresponding properties of the last observed content rectangle. + * + * @returns {DOMRectInit} Last observed content rectangle. + */ + ResizeObservation.prototype.broadcastRect = function () { + var rect = this.contentRect_; + this.broadcastWidth = rect.width; + this.broadcastHeight = rect.height; + return rect; + }; + return ResizeObservation; + }()); + + var ResizeObserverEntry = /** @class */ (function () { + /** + * Creates an instance of ResizeObserverEntry. + * + * @param {Element} target - Element that is being observed. + * @param {DOMRectInit} rectInit - Data of the element's content rectangle. + */ + function ResizeObserverEntry(target, rectInit) { + var contentRect = createReadOnlyRect(rectInit); + // According to the specification following properties are not writable + // and are also not enumerable in the native implementation. + // + // Property accessors are not being used as they'd require to define a + // private WeakMap storage which may cause memory leaks in browsers that + // don't support this type of collections. + defineConfigurable(this, { target: target, contentRect: contentRect }); + } + return ResizeObserverEntry; + }()); + + var ResizeObserverSPI = /** @class */ (function () { + /** + * Creates a new instance of ResizeObserver. + * + * @param {ResizeObserverCallback} callback - Callback function that is invoked + * when one of the observed elements changes it's content dimensions. + * @param {ResizeObserverController} controller - Controller instance which + * is responsible for the updates of observer. + * @param {ResizeObserver} callbackCtx - Reference to the public + * ResizeObserver instance which will be passed to callback function. + */ + function ResizeObserverSPI(callback, controller, callbackCtx) { + /** + * Collection of resize observations that have detected changes in dimensions + * of elements. + * + * @private {Array} + */ + this.activeObservations_ = []; + /** + * Registry of the ResizeObservation instances. + * + * @private {Map} + */ + this.observations_ = new MapShim(); + if (typeof callback !== 'function') { + throw new TypeError('The callback provided as parameter 1 is not a function.'); + } + this.callback_ = callback; + this.controller_ = controller; + this.callbackCtx_ = callbackCtx; + } + /** + * Starts observing provided element. + * + * @param {Element} target - Element to be observed. + * @returns {void} + */ + ResizeObserverSPI.prototype.observe = function (target) { + if (!arguments.length) { + throw new TypeError('1 argument required, but only 0 present.'); + } + // Do nothing if current environment doesn't have the Element interface. + if (typeof Element === 'undefined' || !(Element instanceof Object)) { + return; + } + if (!(target instanceof getWindowOf(target).Element)) { + throw new TypeError('parameter 1 is not of type "Element".'); + } + var observations = this.observations_; + // Do nothing if element is already being observed. + if (observations.has(target)) { + return; + } + observations.set(target, new ResizeObservation(target)); + this.controller_.addObserver(this); + // Force the update of observations. + this.controller_.refresh(); + }; + /** + * Stops observing provided element. + * + * @param {Element} target - Element to stop observing. + * @returns {void} + */ + ResizeObserverSPI.prototype.unobserve = function (target) { + if (!arguments.length) { + throw new TypeError('1 argument required, but only 0 present.'); + } + // Do nothing if current environment doesn't have the Element interface. + if (typeof Element === 'undefined' || !(Element instanceof Object)) { + return; + } + if (!(target instanceof getWindowOf(target).Element)) { + throw new TypeError('parameter 1 is not of type "Element".'); + } + var observations = this.observations_; + // Do nothing if element is not being observed. + if (!observations.has(target)) { + return; + } + observations.delete(target); + if (!observations.size) { + this.controller_.removeObserver(this); + } + }; + /** + * Stops observing all elements. + * + * @returns {void} + */ + ResizeObserverSPI.prototype.disconnect = function () { + this.clearActive(); + this.observations_.clear(); + this.controller_.removeObserver(this); + }; + /** + * Collects observation instances the associated element of which has changed + * it's content rectangle. + * + * @returns {void} + */ + ResizeObserverSPI.prototype.gatherActive = function () { + var _this = this; + this.clearActive(); + this.observations_.forEach(function (observation) { + if (observation.isActive()) { + _this.activeObservations_.push(observation); + } + }); + }; + /** + * Invokes initial callback function with a list of ResizeObserverEntry + * instances collected from active resize observations. + * + * @returns {void} + */ + ResizeObserverSPI.prototype.broadcastActive = function () { + // Do nothing if observer doesn't have active observations. + if (!this.hasActive()) { + return; + } + var ctx = this.callbackCtx_; + // Create ResizeObserverEntry instance for every active observation. + var entries = this.activeObservations_.map(function (observation) { + return new ResizeObserverEntry(observation.target, observation.broadcastRect()); + }); + this.callback_.call(ctx, entries, ctx); + this.clearActive(); + }; + /** + * Clears the collection of active observations. + * + * @returns {void} + */ + ResizeObserverSPI.prototype.clearActive = function () { + this.activeObservations_.splice(0); + }; + /** + * Tells whether observer has active observations. + * + * @returns {boolean} + */ + ResizeObserverSPI.prototype.hasActive = function () { + return this.activeObservations_.length > 0; + }; + return ResizeObserverSPI; + }()); + + // Registry of internal observers. If WeakMap is not available use current shim + // for the Map collection as it has all required methods and because WeakMap + // can't be fully polyfilled anyway. + var observers = typeof WeakMap !== 'undefined' ? new WeakMap() : new MapShim(); + /** + * ResizeObserver API. Encapsulates the ResizeObserver SPI implementation + * exposing only those methods and properties that are defined in the spec. + */ + var ResizeObserver = /** @class */ (function () { + /** + * Creates a new instance of ResizeObserver. + * + * @param {ResizeObserverCallback} callback - Callback that is invoked when + * dimensions of the observed elements change. + */ + function ResizeObserver(callback) { + if (!(this instanceof ResizeObserver)) { + throw new TypeError('Cannot call a class as a function.'); + } + if (!arguments.length) { + throw new TypeError('1 argument required, but only 0 present.'); + } + var controller = ResizeObserverController.getInstance(); + var observer = new ResizeObserverSPI(callback, controller, this); + observers.set(this, observer); + } + return ResizeObserver; + }()); + // Expose public methods of ResizeObserver. + [ + 'observe', + 'unobserve', + 'disconnect' + ].forEach(function (method) { + ResizeObserver.prototype[method] = function () { + var _a; + return (_a = observers.get(this))[method].apply(_a, arguments); + }; + }); + + var index = (function () { + // Export existing implementation if available. + if (typeof global$1.ResizeObserver !== 'undefined') { + return global$1.ResizeObserver; + } + return ResizeObserver; + })(); + + return index; + +}))); + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) + +},{}],44:[function(require,module,exports){ +/*global Blob,File*/ + +/** + * Module requirements + */ + +var isArray = require('isarray'); +var isBuf = require('./is-buffer'); +var toString = Object.prototype.toString; +var withNativeBlob = typeof Blob === 'function' || (typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]'); +var withNativeFile = typeof File === 'function' || (typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]'); + +/** + * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder. + * Anything with blobs or files should be fed through removeBlobs before coming + * here. + * + * @param {Object} packet - socket.io event packet + * @return {Object} with deconstructed packet and list of buffers + * @api public + */ + +exports.deconstructPacket = function(packet) { + var buffers = []; + var packetData = packet.data; + var pack = packet; + pack.data = _deconstructPacket(packetData, buffers); + pack.attachments = buffers.length; // number of binary 'attachments' + return {packet: pack, buffers: buffers}; +}; + +function _deconstructPacket(data, buffers) { + if (!data) return data; + + if (isBuf(data)) { + var placeholder = { _placeholder: true, num: buffers.length }; + buffers.push(data); + return placeholder; + } else if (isArray(data)) { + var newData = new Array(data.length); + for (var i = 0; i < data.length; i++) { + newData[i] = _deconstructPacket(data[i], buffers); + } + return newData; + } else if (typeof data === 'object' && !(data instanceof Date)) { + var newData = {}; + for (var key in data) { + newData[key] = _deconstructPacket(data[key], buffers); + } + return newData; + } + return data; +} + +/** + * Reconstructs a binary packet from its placeholder packet and buffers + * + * @param {Object} packet - event packet with placeholders + * @param {Array} buffers - binary buffers to put in placeholder positions + * @return {Object} reconstructed packet + * @api public + */ + +exports.reconstructPacket = function(packet, buffers) { + packet.data = _reconstructPacket(packet.data, buffers); + packet.attachments = undefined; // no longer useful + return packet; +}; + +function _reconstructPacket(data, buffers) { + if (!data) return data; + + if (data && data._placeholder) { + return buffers[data.num]; // appropriate buffer (should be natural order anyway) + } else if (isArray(data)) { + for (var i = 0; i < data.length; i++) { + data[i] = _reconstructPacket(data[i], buffers); + } + } else if (typeof data === 'object') { + for (var key in data) { + data[key] = _reconstructPacket(data[key], buffers); + } + } + + return data; +} + +/** + * Asynchronously removes Blobs or Files from data via + * FileReader's readAsArrayBuffer method. Used before encoding + * data as msgpack. Calls callback with the blobless data. + * + * @param {Object} data + * @param {Function} callback + * @api private + */ + +exports.removeBlobs = function(data, callback) { + function _removeBlobs(obj, curKey, containingObject) { + if (!obj) return obj; + + // convert any blob + if ((withNativeBlob && obj instanceof Blob) || + (withNativeFile && obj instanceof File)) { + pendingBlobs++; + + // async filereader + var fileReader = new FileReader(); + fileReader.onload = function() { // this.result == arraybuffer + if (containingObject) { + containingObject[curKey] = this.result; + } + else { + bloblessData = this.result; + } + + // if nothing pending its callback time + if(! --pendingBlobs) { + callback(bloblessData); + } + }; + + fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer + } else if (isArray(obj)) { // handle array + for (var i = 0; i < obj.length; i++) { + _removeBlobs(obj[i], i, obj); + } + } else if (typeof obj === 'object' && !isBuf(obj)) { // and object + for (var key in obj) { + _removeBlobs(obj[key], key, obj); + } + } + } + + var pendingBlobs = 0; + var bloblessData = data; + _removeBlobs(bloblessData); + if (!pendingBlobs) { + callback(bloblessData); + } +}; + +},{"./is-buffer":46,"isarray":49}],45:[function(require,module,exports){ + +/** + * Module dependencies. + */ + +var debug = require('debug')('socket.io-parser'); +var Emitter = require('component-emitter'); +var binary = require('./binary'); +var isArray = require('isarray'); +var isBuf = require('./is-buffer'); + +/** + * Protocol version. + * + * @api public + */ + +exports.protocol = 4; + +/** + * Packet types. + * + * @api public + */ + +exports.types = [ + 'CONNECT', + 'DISCONNECT', + 'EVENT', + 'ACK', + 'ERROR', + 'BINARY_EVENT', + 'BINARY_ACK' +]; + +/** + * Packet type `connect`. + * + * @api public + */ + +exports.CONNECT = 0; + +/** + * Packet type `disconnect`. + * + * @api public + */ + +exports.DISCONNECT = 1; + +/** + * Packet type `event`. + * + * @api public + */ + +exports.EVENT = 2; + +/** + * Packet type `ack`. + * + * @api public + */ + +exports.ACK = 3; + +/** + * Packet type `error`. + * + * @api public + */ + +exports.ERROR = 4; + +/** + * Packet type 'binary event' + * + * @api public + */ + +exports.BINARY_EVENT = 5; + +/** + * Packet type `binary ack`. For acks with binary arguments. + * + * @api public + */ + +exports.BINARY_ACK = 6; + +/** + * Encoder constructor. + * + * @api public + */ + +exports.Encoder = Encoder; + +/** + * Decoder constructor. + * + * @api public + */ + +exports.Decoder = Decoder; + +/** + * A socket.io Encoder instance + * + * @api public + */ + +function Encoder() {} + +var ERROR_PACKET = exports.ERROR + '"encode error"'; + +/** + * Encode a packet as a single string if non-binary, or as a + * buffer sequence, depending on packet type. + * + * @param {Object} obj - packet object + * @param {Function} callback - function to handle encodings (likely engine.write) + * @return Calls callback with Array of encodings + * @api public + */ + +Encoder.prototype.encode = function(obj, callback){ + debug('encoding packet %j', obj); + + if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) { + encodeAsBinary(obj, callback); + } else { + var encoding = encodeAsString(obj); + callback([encoding]); + } +}; + +/** + * Encode packet as string. + * + * @param {Object} packet + * @return {String} encoded + * @api private + */ + +function encodeAsString(obj) { + + // first is type + var str = '' + obj.type; + + // attachments if we have them + if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) { + str += obj.attachments + '-'; + } + + // if we have a namespace other than `/` + // we append it followed by a comma `,` + if (obj.nsp && '/' !== obj.nsp) { + str += obj.nsp + ','; + } + + // immediately followed by the id + if (null != obj.id) { + str += obj.id; + } + + // json data + if (null != obj.data) { + var payload = tryStringify(obj.data); + if (payload !== false) { + str += payload; + } else { + return ERROR_PACKET; + } + } + + debug('encoded %j as %s', obj, str); + return str; +} + +function tryStringify(str) { + try { + return JSON.stringify(str); + } catch(e){ + return false; + } +} + +/** + * Encode packet as 'buffer sequence' by removing blobs, and + * deconstructing packet into object with placeholders and + * a list of buffers. + * + * @param {Object} packet + * @return {Buffer} encoded + * @api private + */ + +function encodeAsBinary(obj, callback) { + + function writeEncoding(bloblessData) { + var deconstruction = binary.deconstructPacket(bloblessData); + var pack = encodeAsString(deconstruction.packet); + var buffers = deconstruction.buffers; + + buffers.unshift(pack); // add packet info to beginning of data list + callback(buffers); // write all the buffers + } + + binary.removeBlobs(obj, writeEncoding); +} + +/** + * A socket.io Decoder instance + * + * @return {Object} decoder + * @api public + */ + +function Decoder() { + this.reconstructor = null; +} + +/** + * Mix in `Emitter` with Decoder. + */ + +Emitter(Decoder.prototype); + +/** + * Decodes an encoded packet string into packet JSON. + * + * @param {String} obj - encoded packet + * @return {Object} packet + * @api public + */ + +Decoder.prototype.add = function(obj) { + var packet; + if (typeof obj === 'string') { + packet = decodeString(obj); + if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json + this.reconstructor = new BinaryReconstructor(packet); + + // no attachments, labeled binary but no binary data to follow + if (this.reconstructor.reconPack.attachments === 0) { + this.emit('decoded', packet); + } + } else { // non-binary full packet + this.emit('decoded', packet); + } + } else if (isBuf(obj) || obj.base64) { // raw binary data + if (!this.reconstructor) { + throw new Error('got binary data when not reconstructing a packet'); + } else { + packet = this.reconstructor.takeBinaryData(obj); + if (packet) { // received final buffer + this.reconstructor = null; + this.emit('decoded', packet); + } + } + } else { + throw new Error('Unknown type: ' + obj); + } +}; + +/** + * Decode a packet String (JSON data) + * + * @param {String} str + * @return {Object} packet + * @api private + */ + +function decodeString(str) { + var i = 0; + // look up type + var p = { + type: Number(str.charAt(0)) + }; + + if (null == exports.types[p.type]) { + return error('unknown packet type ' + p.type); + } + + // look up attachments if type binary + if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) { + var buf = ''; + while (str.charAt(++i) !== '-') { + buf += str.charAt(i); + if (i == str.length) break; + } + if (buf != Number(buf) || str.charAt(i) !== '-') { + throw new Error('Illegal attachments'); + } + p.attachments = Number(buf); + } + + // look up namespace (if any) + if ('/' === str.charAt(i + 1)) { + p.nsp = ''; + while (++i) { + var c = str.charAt(i); + if (',' === c) break; + p.nsp += c; + if (i === str.length) break; + } + } else { + p.nsp = '/'; + } + + // look up id + var next = str.charAt(i + 1); + if ('' !== next && Number(next) == next) { + p.id = ''; + while (++i) { + var c = str.charAt(i); + if (null == c || Number(c) != c) { + --i; + break; + } + p.id += str.charAt(i); + if (i === str.length) break; + } + p.id = Number(p.id); + } + + // look up json data + if (str.charAt(++i)) { + var payload = tryParse(str.substr(i)); + var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload)); + if (isPayloadValid) { + p.data = payload; + } else { + return error('invalid payload'); + } + } + + debug('decoded %s as %j', str, p); + return p; +} + +function tryParse(str) { + try { + return JSON.parse(str); + } catch(e){ + return false; + } +} + +/** + * Deallocates a parser's resources + * + * @api public + */ + +Decoder.prototype.destroy = function() { + if (this.reconstructor) { + this.reconstructor.finishedReconstruction(); + } +}; + +/** + * A manager of a binary event's 'buffer sequence'. Should + * be constructed whenever a packet of type BINARY_EVENT is + * decoded. + * + * @param {Object} packet + * @return {BinaryReconstructor} initialized reconstructor + * @api private + */ + +function BinaryReconstructor(packet) { + this.reconPack = packet; + this.buffers = []; +} + +/** + * Method to be called when binary data received from connection + * after a BINARY_EVENT packet. + * + * @param {Buffer | ArrayBuffer} binData - the raw binary data received + * @return {null | Object} returns null if more binary data is expected or + * a reconstructed packet object if all buffers have been received. + * @api private + */ + +BinaryReconstructor.prototype.takeBinaryData = function(binData) { + this.buffers.push(binData); + if (this.buffers.length === this.reconPack.attachments) { // done with buffer list + var packet = binary.reconstructPacket(this.reconPack, this.buffers); + this.finishedReconstruction(); + return packet; + } + return null; +}; + +/** + * Cleans up binary packet reconstruction variables. + * + * @api private + */ + +BinaryReconstructor.prototype.finishedReconstruction = function() { + this.reconPack = null; + this.buffers = []; +}; + +function error(msg) { + return { + type: exports.ERROR, + data: 'parser error: ' + msg + }; +} + +},{"./binary":44,"./is-buffer":46,"component-emitter":13,"debug":47,"isarray":49}],46:[function(require,module,exports){ +(function (Buffer){(function (){ + +module.exports = isBuf; + +var withNativeBuffer = typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function'; +var withNativeArrayBuffer = typeof ArrayBuffer === 'function'; + +var isView = function (obj) { + return typeof ArrayBuffer.isView === 'function' ? ArrayBuffer.isView(obj) : (obj.buffer instanceof ArrayBuffer); +}; + +/** + * Returns true if obj is a buffer or an arraybuffer. + * + * @api private + */ + +function isBuf(obj) { + return (withNativeBuffer && Buffer.isBuffer(obj)) || + (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj))); +} + +}).call(this)}).call(this,require("buffer").Buffer) + +},{"buffer":10}],47:[function(require,module,exports){ +(function (process){(function (){ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', + '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', + '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', + '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', + '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', + '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', + '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', + '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', + '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', + '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', + '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} + +}).call(this)}).call(this,require('_process')) + +},{"./debug":48,"_process":39}],48:[function(require,module,exports){ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * Active `debug` instances. + */ +exports.instances = []; + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + var prevTime; + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + exports.instances.push(debug); + + return debug; +} + +function destroy () { + var index = exports.instances.indexOf(this); + if (index !== -1) { + exports.instances.splice(index, 1); + return true; + } else { + return false; + } +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var i; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < exports.instances.length; i++) { + var instance = exports.instances[i]; + instance.enabled = exports.enabled(instance.namespace); + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} + +},{"ms":50}],49:[function(require,module,exports){ +arguments[4][24][0].apply(exports,arguments) +},{"dup":24}],50:[function(require,module,exports){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} + +},{}],51:[function(require,module,exports){ +module.exports = toArray + +function toArray(list, index) { + var array = [] + + index = index || 0 + + for (var i = index || 0; i < list.length; i++) { + array[i - index] = list[i] + } + + return array +} + +},{}],52:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +var _isReactNative = _interopRequireDefault(require("./isReactNative")); + +var _uriToBlob = _interopRequireDefault(require("./uriToBlob")); + +var _isCordova = _interopRequireDefault(require("./isCordova")); + +var _readAsByteArray = _interopRequireDefault(require("./readAsByteArray")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} + +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} + +var FileSource = /*#__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); + + return Promise.resolve({ + value: value + }); + } + }, { + key: "close", + value: function close() {// Nothing to do here since we don't need to release any resources. + } + }]); + + return FileSource; +}(); + +var StreamSource = /*#__PURE__*/function () { + function StreamSource(reader, chunkSize) { + _classCallCheck(this, StreamSource); + + this._chunkSize = chunkSize; + 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; +}(); + +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 FileReader = /*#__PURE__*/function () { + function FileReader() { + _classCallCheck(this, FileReader); + } + + _createClass(FileReader, [{ + key: "openFile", + value: function openFile(input, chunkSize) { + // In React Native, when user selects a file, instead of a File or Blob, + // you usually get a file object {} with a uri property that contains + // a local path to the file. We use XMLHttpRequest to fetch + // the file blob, before uploading with tus. + if ((0, _isReactNative.default)() && input && typeof input.uri !== "undefined") { + return (0, _uriToBlob.default)(input.uri).then(function (blob) { + return new FileSource(blob); + })["catch"](function (err) { + throw new Error("tus: cannot fetch `file.uri` as Blob, make sure the uri is correct and accessible. " + err); + }); + } // Since we emulate the Blob type in our tests (not all target browsers + // support it), we cannot use `instanceof` for testing whether the input value + // can be handled. Instead, we simply check is the slice() function and the + // size property are available. + + + if (typeof input.slice === "function" && typeof input.size !== "undefined") { + return Promise.resolve(new FileSource(input)); + } + + if (typeof input.read === "function") { + chunkSize = +chunkSize; + + if (!isFinite(chunkSize)) { + return Promise.reject(new Error("cannot create source for stream without a finite value for the `chunkSize` option")); + } + + return Promise.resolve(new StreamSource(input, chunkSize)); + } + + return Promise.reject(new Error("source object may only be an instance of File, Blob, or Reader in this environment")); + } + }]); + + return FileReader; +}(); + +exports.default = FileReader; +},{"./isCordova":56,"./isReactNative":57,"./readAsByteArray":58,"./uriToBlob":59}],53:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = fingerprint; + +var _isReactNative = _interopRequireDefault(require("./isReactNative")); + +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) { + // 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 & hash; // Convert to 32bit integer + } + + return hash; +} +},{"./isReactNative":57}],54:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +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, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} +/* global window */ + + +var XHRHttpStack = /*#__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; +}(); + +exports.default = 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; +}(); +},{}],55:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "enableDebugLog", { + enumerable: true, + get: function () { + return _logger.enableDebugLog; + } +}); +Object.defineProperty(exports, "canStoreURLs", { + enumerable: true, + get: function () { + return _urlStorage.canStoreURLs; + } +}); +Object.defineProperty(exports, "HttpStack", { + enumerable: true, + get: function () { + return _httpStack.default; + } +}); +exports.isSupported = exports.defaultOptions = exports.Upload = void 0; + +var _upload = _interopRequireDefault(require("../upload")); + +var _noopUrlStorage = _interopRequireDefault(require("../noopUrlStorage")); + +var _logger = require("../logger"); + +var _urlStorage = require("./urlStorage"); + +var _httpStack = _interopRequireDefault(require("./httpStack")); + +var _fileReader = _interopRequireDefault(require("./fileReader")); + +var _fingerprint = _interopRequireDefault(require("./fingerprint")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function _typeof(obj) { + return typeof obj; + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(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, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + 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 + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); +} + +function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); +} + +function _createSuper(Derived) { + return function () { + var Super = _getPrototypeOf(Derived), + result; + + if (_isNativeReflectConstruct()) { + 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; + } + + 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 { + Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); + return true; + } catch (e) { + return false; + } +} + +function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); +} + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} +/* global window */ + + +var defaultOptions = _objectSpread({}, _upload.default.defaultOptions, { + httpStack: new _httpStack.default(), + fileReader: new _fileReader.default(), + urlStorage: _urlStorage.canStoreURLs ? new _urlStorage.WebStorageUrlStorage() : new _noopUrlStorage.default(), + fingerprint: _fingerprint.default +}); + +exports.defaultOptions = defaultOptions; + +var 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({}, defaultOptions, {}, options); + return _super.call(this, file, options); + } + + _createClass(Upload, null, [{ + key: "terminate", + value: function terminate(url, options, cb) { + options = _objectSpread({}, defaultOptions, {}, options); + return _upload.default.terminate(url, options, cb); + } + }]); + + return Upload; +}(_upload.default); + +exports.Upload = Upload; +var _window = window, + XMLHttpRequest = _window.XMLHttpRequest, + Blob = _window.Blob; +var isSupported = XMLHttpRequest && Blob && typeof Blob.prototype.slice === "function"; +exports.isSupported = isSupported; +},{"../logger":62,"../noopUrlStorage":63,"../upload":64,"./fileReader":52,"./fingerprint":53,"./httpStack":54,"./urlStorage":60}],56:[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 = isCordova; +exports.default = _default; +},{}],57:[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 = isReactNative; +exports.default = _default; +},{}],58:[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); + }); +} +},{}],59:[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(); + }); +} +},{}],60:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.WebStorageUrlStorage = exports.canStoreURLs = void 0; + +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, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} +/* global window, localStorage */ + + +var hasStorage = false; + +try { + hasStorage = "localStorage" in window; // Attempt to store and read entries from the local storage to detect Private + // Mode on Safari on iOS (see #49) + + var key = "tusSupport"; + localStorage.setItem(key, localStorage.getItem(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 = hasStorage; +exports.canStoreURLs = canStoreURLs; + +var 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; +}(); + +exports.WebStorageUrlStorage = WebStorageUrlStorage; +},{}],61:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function _typeof(obj) { + return typeof obj; + }; + } else { + _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +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 + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); +} + +function _createSuper(Derived) { + return function () { + var Super = _getPrototypeOf(Derived), + result; + + if (_isNativeReflectConstruct()) { + 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; + } + + 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; + } 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 { + Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); + return true; + } catch (e) { + return false; + } +} + +function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} + +function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); +} + +function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : 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 DetailedError; +}( /*#__PURE__*/_wrapNativeSuper(Error)); + +var _default = DetailedError; +exports.default = _default; +},{}],62:[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); +} +},{}],63:[function(require,module,exports){ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +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, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} +/* eslint no-unused-vars: "off" */ + + +var NoopUrlStorage = /*#__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; +}(); + +exports.default = NoopUrlStorage; +},{}],64:[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")); + +var _logger = require("./logger"); + +var _uuid = _interopRequireDefault(require("./uuid")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +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, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} +/* global window */ + + +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: null, + chunkSize: Infinity, + retryDelays: [0, 1000, 3000, 5000], + parallelUploads: 1, + 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) { + console.log("tus: The `resume` option has been removed in tus-js-client v2. Please use the URL storage API instead."); // eslint-disable-line no-console + } // The default options will already be added from the wrapper classes. + + + this.options = options; // 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._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. + ["uploadUrl", "uploadSize", "uploadLengthDeferred"].forEach(function (optionName) { + if (_this2.options[optionName]) { + _this2._emitError(new Error("tus: cannot use the ".concat(optionName, " option when parallelUploads is enabled"))); + } + }); + } + + 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; + } else { + return _this2.options.fileReader.openFile(file, _this2.options.chunkSize); + } + }).then(function (source) { + _this2._source = source; // 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 _this3 = this; + + var totalSize = this._size = this._source.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 generate the start and end position for the slices. + + var parts = splitSizeIntoParts(this._source.size, partCount, this._parallelUploadUrls); // 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({}, _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, + metadata: {}, + // Add the header to indicate the this is a partial upload. + headers: _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 !!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() { + // 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 (this.options.uploadLengthDeferred) { + this._size = null; + } else if (this.options.uploadSize != null) { + this._size = +this.options.uploadSize; + + if (isNaN(this._size)) { + this._emitError(new Error("tus: cannot convert `uploadSize` option into a number")); + + return; + } + } else { + this._size = this._source.size; + + if (this._size == null) { + this._emitError(new Error("tus: cannot automatically derive upload's size from input and must be specified manually using the `uploadSize` option")); + + return; + } + } // 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.url)); + 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, cb) { + var _this4 = this; + + if (typeof cb === "function") { + throw new Error("tus: the abort function does not accept a callback since v2 anymore; please use the returned Promise instead"); + } // 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(); + + this._source.close(); + } + + 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(); + + 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 (inStatusCategory(status, 400)) { + // Remove stored fingerprint and corresponding endpoint, + // on client errors since the file can not be found + _this7._removeFromUrlStorage(); + } // 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 (!_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 (isNaN(offset)) { + _this7._emitHttpError(req, res, "tus: invalid or missing offset value"); + + return; + } + + var length = parseInt(res.getHeader("Upload-Length"), 10); + + if (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(); + } // 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 " + _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; // 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 + (value && value.size ? value.size : 0); + req.setHeader("Upload-Length", _this9._size); + } + + if (value === null) { + return _this9._sendRequest(req); + } else { + _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 (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; // Only if a fingerprint was calculated for the input (i.e. not a stream), we can store the upload URL. + + + if (!this.options.storeFingerprintForResuming || !this._fingerprint) { + return; + } + + 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; + } + + this._urlStorage.addUpload(this._fingerprint, storedUpload).then(function (urlStorageKey) { + return _this11._urlStorageKey = urlStorageKey; + })["catch"](function (err) { + _this11._emitError(err); + }); + } + /** + * 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 cb = arguments.length > 2 ? arguments[2] : undefined; + + if (typeof options === "function" || typeof cb === "function") { + throw new Error("tus: the terminate function does not accept a callback since v2 anymore; please use the returned Promise instead"); + } + + 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({}, options, { + retryDelays: remainingDelays + }); + + return new Promise(function (resolve) { + return setTimeout(resolve, delay); + }).then(function () { + return BaseUpload.terminate(url, newOptions); + }); + }); + } + }]); + + return BaseUpload; +}(); + +function encodeMetadata(metadata) { + var encoded = []; + + for (var key in metadata) { + encoded.push(key + " " + _jsBase.Base64.encode(metadata[key])); + } + + return encoded.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 || {}; + + for (var name in headers) { + req.setHeader(name, headers[name]); + } + + 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(req, body, options) { + var onBeforeRequestPromise = typeof options.onBeforeRequest === "function" ? Promise.resolve(options.onBeforeRequest(req)) : Promise.resolve(); + return onBeforeRequestPromise.then(function () { + return req.send(body).then(function (res) { + var onAfterResponsePromise = typeof options.onAfterResponse === "function" ? Promise.resolve(options.onAfterResponse(req, res)) : Promise.resolve(); + return onAfterResponsePromise.then(function () { + return res; + }); + }); + }); +} +/** + * Checks whether the browser running this code has internet access. + * This function will always return true in the node.js environment + * + * @api private + */ + + +function isOnline() { + var online = true; + + if (typeof window !== "undefined" && "navigator" in window && window.navigator.onLine === false) { + online = false; + } + + return online; +} +/** + * Checks whether or not it is ok to retry a request. + * @param {Error} 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); + } + + 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. + * @param {string[]} previousUrls The upload URLs for previous parts. + * @return {object[]} + * @api private + */ + + +function splitSizeIntoParts(totalSize, partCount, previousUrls) { + 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; // Attach URLs from previous uploads, if available. + + if (previousUrls) { + parts.forEach(function (part, index) { + part.uploadUrl = previousUrls[index] || null; + }); + } + + return parts; +} + +BaseUpload.defaultOptions = defaultOptions; +var _default = BaseUpload; +exports.default = _default; +},{"./error":61,"./logger":62,"./uuid":65,"js-base64":29,"url-parse":66}],65:[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() { + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { + var r = Math.random() * 16 | 0, + v = c == "x" ? r : r & 0x3 | 0x8; + return v.toString(16); + }); +} +},{}],66:[function(require,module,exports){ +(function (global){(function (){ +'use strict'; + +var required = require('requires-port') + , qs = require('querystringify') + , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\// + , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i + , whitespace = '[\\x09\\x0A\\x0B\\x0C\\x0D\\x20\\xA0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF]' + , left = new RegExp('^'+ whitespace +'+'); + +/** + * Trim a given string. + * + * @param {String} str String to trim. + * @public + */ +function trimLeft(str) { + return (str ? str : '').toString().replace(left, ''); +} + +/** + * 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) { // Sanitize what is left of the address + return address.replace('\\', '/'); + }, + ['/', '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; +} + +/** + * @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. + * @return {ProtocolExtract} Extracted information. + * @private + */ +function extractProtocol(address) { + address = trimLeft(address); + var match = protocolre.exec(address); + + return { + protocol: match[1] ? match[1].toLowerCase() : '', + slashes: !!match[2], + rest: match[3] + }; +} + +/** + * 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); + + 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 || ''); + 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.slashes) instructions[3] = [/(.*)/, 'pathname']; + + for (; i < instructions.length; i++) { + instruction = instructions[i]; + + if (typeof instruction === 'function') { + address = instruction(address); + continue; + } + + parse = instruction[0]; + key = instruction[1]; + + if (parse !== parse) { + url[key] = address; + } else if ('string' === typeof parse) { + if (~(index = address.indexOf(parse))) { + 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); + } + + // + // 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) { + instruction = url.auth.split(':'); + url.username = instruction[0] || ''; + url.password = instruction[1] || ''; + } + + url.origin = url.protocol && url.host && url.protocol !== 'file:' + ? 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 (/:\d+$/.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; + + default: + url[part] = value; + } + + for (var i = 0; i < rules.length; i++) { + var ins = rules[i]; + + if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); + } + + url.origin = url.protocol && url.host && url.protocol !== 'file:' + ? 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 + , protocol = url.protocol; + + if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; + + var result = protocol + (url.slashes ? '//' : ''); + + if (url.username) { + result += url.username; + if (url.password) result += ':'+ url.password; + result += '@'; + } + + result += url.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":41,"requires-port":42}],67:[function(require,module,exports){ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (factory((global.WHATWGFetch = {}))); +}(this, (function (exports) { 'use strict'; + + var support = { + searchParams: 'URLSearchParams' in self, + iterable: 'Symbol' in self && 'iterator' in Symbol, + blob: + 'FileReader' in self && + 'Blob' in self && + (function() { + try { + new Blob(); + return true + } catch (e) { + return false + } + })(), + formData: 'FormData' in self, + arrayBuffer: 'ArrayBuffer' in self + }; + + function isDataView(obj) { + return obj && DataView.prototype.isPrototypeOf(obj) + } + + if (support.arrayBuffer) { + var viewClasses = [ + '[object Int8Array]', + '[object Uint8Array]', + '[object Uint8ClampedArray]', + '[object Int16Array]', + '[object Uint16Array]', + '[object Int32Array]', + '[object Uint32Array]', + '[object Float32Array]', + '[object Float64Array]' + ]; + + var isArrayBufferView = + ArrayBuffer.isView || + function(obj) { + return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 + }; + } + + function normalizeName(name) { + if (typeof name !== 'string') { + name = String(name); + } + if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) { + throw new TypeError('Invalid character in header field name') + } + return name.toLowerCase() + } + + function normalizeValue(value) { + if (typeof value !== 'string') { + value = String(value); + } + return value + } + + // Build a destructive iterator for the value list + function iteratorFor(items) { + var iterator = { + next: function() { + var value = items.shift(); + return {done: value === undefined, value: value} + } + }; + + if (support.iterable) { + iterator[Symbol.iterator] = function() { + return iterator + }; + } + + return iterator + } + + function Headers(headers) { + this.map = {}; + + if (headers instanceof Headers) { + headers.forEach(function(value, name) { + this.append(name, value); + }, this); + } else if (Array.isArray(headers)) { + headers.forEach(function(header) { + this.append(header[0], header[1]); + }, this); + } else if (headers) { + Object.getOwnPropertyNames(headers).forEach(function(name) { + this.append(name, headers[name]); + }, this); + } + } + + Headers.prototype.append = function(name, value) { + name = normalizeName(name); + value = normalizeValue(value); + var oldValue = this.map[name]; + this.map[name] = oldValue ? oldValue + ', ' + value : value; + }; + + Headers.prototype['delete'] = function(name) { + delete this.map[normalizeName(name)]; + }; + + Headers.prototype.get = function(name) { + name = normalizeName(name); + return this.has(name) ? this.map[name] : null + }; + + Headers.prototype.has = function(name) { + return this.map.hasOwnProperty(normalizeName(name)) + }; + + Headers.prototype.set = function(name, value) { + this.map[normalizeName(name)] = normalizeValue(value); + }; + + Headers.prototype.forEach = function(callback, thisArg) { + for (var name in this.map) { + if (this.map.hasOwnProperty(name)) { + callback.call(thisArg, this.map[name], name, this); + } + } + }; + + Headers.prototype.keys = function() { + var items = []; + this.forEach(function(value, name) { + items.push(name); + }); + return iteratorFor(items) + }; + + Headers.prototype.values = function() { + var items = []; + this.forEach(function(value) { + items.push(value); + }); + return iteratorFor(items) + }; + + Headers.prototype.entries = function() { + var items = []; + this.forEach(function(value, name) { + items.push([name, value]); + }); + return iteratorFor(items) + }; + + if (support.iterable) { + Headers.prototype[Symbol.iterator] = Headers.prototype.entries; + } + + function consumed(body) { + if (body.bodyUsed) { + return Promise.reject(new TypeError('Already read')) + } + body.bodyUsed = true; + } + + function fileReaderReady(reader) { + return new Promise(function(resolve, reject) { + reader.onload = function() { + resolve(reader.result); + }; + reader.onerror = function() { + reject(reader.error); + }; + }) + } + + function readBlobAsArrayBuffer(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsArrayBuffer(blob); + return promise + } + + function readBlobAsText(blob) { + var reader = new FileReader(); + var promise = fileReaderReady(reader); + reader.readAsText(blob); + return promise + } + + function readArrayBufferAsText(buf) { + var view = new Uint8Array(buf); + var chars = new Array(view.length); + + for (var i = 0; i < view.length; i++) { + chars[i] = String.fromCharCode(view[i]); + } + return chars.join('') + } + + function bufferClone(buf) { + if (buf.slice) { + return buf.slice(0) + } else { + var view = new Uint8Array(buf.byteLength); + view.set(new Uint8Array(buf)); + return view.buffer + } + } + + function Body() { + this.bodyUsed = false; + + this._initBody = function(body) { + this._bodyInit = body; + if (!body) { + this._bodyText = ''; + } else if (typeof body === 'string') { + this._bodyText = body; + } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { + this._bodyBlob = body; + } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { + this._bodyFormData = body; + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this._bodyText = body.toString(); + } else if (support.arrayBuffer && support.blob && isDataView(body)) { + this._bodyArrayBuffer = bufferClone(body.buffer); + // IE 10-11 can't handle a DataView body. + this._bodyInit = new Blob([this._bodyArrayBuffer]); + } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { + this._bodyArrayBuffer = bufferClone(body); + } else { + this._bodyText = body = Object.prototype.toString.call(body); + } + + if (!this.headers.get('content-type')) { + if (typeof body === 'string') { + this.headers.set('content-type', 'text/plain;charset=UTF-8'); + } else if (this._bodyBlob && this._bodyBlob.type) { + this.headers.set('content-type', this._bodyBlob.type); + } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { + this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8'); + } + } + }; + + if (support.blob) { + this.blob = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return Promise.resolve(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(new Blob([this._bodyArrayBuffer])) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as blob') + } else { + return Promise.resolve(new Blob([this._bodyText])) + } + }; + + this.arrayBuffer = function() { + if (this._bodyArrayBuffer) { + return consumed(this) || Promise.resolve(this._bodyArrayBuffer) + } else { + return this.blob().then(readBlobAsArrayBuffer) + } + }; + } + + this.text = function() { + var rejected = consumed(this); + if (rejected) { + return rejected + } + + if (this._bodyBlob) { + return readBlobAsText(this._bodyBlob) + } else if (this._bodyArrayBuffer) { + return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) + } else if (this._bodyFormData) { + throw new Error('could not read FormData body as text') + } else { + return Promise.resolve(this._bodyText) + } + }; + + if (support.formData) { + this.formData = function() { + return this.text().then(decode) + }; + } + + this.json = function() { + return this.text().then(JSON.parse) + }; + + return this + } + + // HTTP methods whose capitalization should be normalized + var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']; + + function normalizeMethod(method) { + var upcased = method.toUpperCase(); + return methods.indexOf(upcased) > -1 ? upcased : method + } + + function Request(input, options) { + options = options || {}; + var body = options.body; + + if (input instanceof Request) { + if (input.bodyUsed) { + throw new TypeError('Already read') + } + this.url = input.url; + this.credentials = input.credentials; + if (!options.headers) { + this.headers = new Headers(input.headers); + } + this.method = input.method; + this.mode = input.mode; + this.signal = input.signal; + if (!body && input._bodyInit != null) { + body = input._bodyInit; + input.bodyUsed = true; + } + } else { + this.url = String(input); + } + + this.credentials = options.credentials || this.credentials || 'same-origin'; + if (options.headers || !this.headers) { + this.headers = new Headers(options.headers); + } + this.method = normalizeMethod(options.method || this.method || 'GET'); + this.mode = options.mode || this.mode || null; + this.signal = options.signal || this.signal; + this.referrer = null; + + if ((this.method === 'GET' || this.method === 'HEAD') && body) { + throw new TypeError('Body not allowed for GET or HEAD requests') + } + this._initBody(body); + } + + Request.prototype.clone = function() { + return new Request(this, {body: this._bodyInit}) + }; + + function decode(body) { + var form = new FormData(); + body + .trim() + .split('&') + .forEach(function(bytes) { + if (bytes) { + var split = bytes.split('='); + var name = split.shift().replace(/\+/g, ' '); + var value = split.join('=').replace(/\+/g, ' '); + form.append(decodeURIComponent(name), decodeURIComponent(value)); + } + }); + return form + } + + function parseHeaders(rawHeaders) { + var headers = new Headers(); + // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space + // https://tools.ietf.org/html/rfc7230#section-3.2 + var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); + preProcessedHeaders.split(/\r?\n/).forEach(function(line) { + var parts = line.split(':'); + var key = parts.shift().trim(); + if (key) { + var value = parts.join(':').trim(); + headers.append(key, value); + } + }); + return headers + } + + Body.call(Request.prototype); + + function Response(bodyInit, options) { + if (!options) { + options = {}; + } + + this.type = 'default'; + this.status = options.status === undefined ? 200 : options.status; + this.ok = this.status >= 200 && this.status < 300; + this.statusText = 'statusText' in options ? options.statusText : 'OK'; + this.headers = new Headers(options.headers); + this.url = options.url || ''; + this._initBody(bodyInit); + } + + Body.call(Response.prototype); + + Response.prototype.clone = function() { + return new Response(this._bodyInit, { + status: this.status, + statusText: this.statusText, + headers: new Headers(this.headers), + url: this.url + }) + }; + + Response.error = function() { + var response = new Response(null, {status: 0, statusText: ''}); + response.type = 'error'; + return response + }; + + var redirectStatuses = [301, 302, 303, 307, 308]; + + Response.redirect = function(url, status) { + if (redirectStatuses.indexOf(status) === -1) { + throw new RangeError('Invalid status code') + } + + return new Response(null, {status: status, headers: {location: url}}) + }; + + exports.DOMException = self.DOMException; + try { + new exports.DOMException(); + } catch (err) { + exports.DOMException = function(message, name) { + this.message = message; + this.name = name; + var error = Error(message); + this.stack = error.stack; + }; + exports.DOMException.prototype = Object.create(Error.prototype); + exports.DOMException.prototype.constructor = exports.DOMException; + } + + function fetch(input, init) { + return new Promise(function(resolve, reject) { + var request = new Request(input, init); + + if (request.signal && request.signal.aborted) { + return reject(new exports.DOMException('Aborted', 'AbortError')) + } + + var xhr = new XMLHttpRequest(); + + function abortXhr() { + xhr.abort(); + } + + xhr.onload = function() { + var options = { + status: xhr.status, + statusText: xhr.statusText, + headers: parseHeaders(xhr.getAllResponseHeaders() || '') + }; + options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL'); + var body = 'response' in xhr ? xhr.response : xhr.responseText; + resolve(new Response(body, options)); + }; + + xhr.onerror = function() { + reject(new TypeError('Network request failed')); + }; + + xhr.ontimeout = function() { + reject(new TypeError('Network request failed')); + }; + + xhr.onabort = function() { + reject(new exports.DOMException('Aborted', 'AbortError')); + }; + + xhr.open(request.method, request.url, true); + + if (request.credentials === 'include') { + xhr.withCredentials = true; + } else if (request.credentials === 'omit') { + xhr.withCredentials = false; + } + + if ('responseType' in xhr && support.blob) { + xhr.responseType = 'blob'; + } + + request.headers.forEach(function(value, name) { + xhr.setRequestHeader(name, value); + }); + + if (request.signal) { + request.signal.addEventListener('abort', abortXhr); + + xhr.onreadystatechange = function() { + // DONE (success or failure) + if (xhr.readyState === 4) { + request.signal.removeEventListener('abort', abortXhr); + } + }; + } + + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); + }) + } + + fetch.polyfill = true; + + if (!self.fetch) { + self.fetch = fetch; + self.Headers = Headers; + self.Request = Request; + self.Response = Response; + } + + exports.Headers = Headers; + exports.Request = Request; + exports.Response = Response; + exports.fetch = fetch; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); + +},{}],68:[function(require,module,exports){ +/* jshint node: true */ +'use strict'; + +/** + # wildcard + + Very simple wildcard matching, which is designed to provide the same + functionality that is found in the + [eve](https://github.com/adobe-webplatform/eve) eventing library. + + ## Usage + + It works with strings: + + <<< examples/strings.js + + Arrays: + + <<< examples/arrays.js + + Objects (matching against keys): + + <<< examples/objects.js + + While the library works in Node, if you are are looking for file-based + wildcard matching then you should have a look at: + + +**/ + +function WildcardMatcher(text, separator) { + this.text = text = text || ''; + this.hasWild = ~text.indexOf('*'); + this.separator = separator; + this.parts = text.split(separator); +} + +WildcardMatcher.prototype.match = function(input) { + var matches = true; + var parts = this.parts; + var ii; + var partsCount = parts.length; + var testParts; + + if (typeof input == 'string' || input instanceof String) { + if (!this.hasWild && this.text != input) { + matches = false; + } else { + testParts = (input || '').split(this.separator); + for (ii = 0; matches && ii < partsCount; ii++) { + if (parts[ii] === '*') { + continue; + } else if (ii < testParts.length) { + matches = parts[ii] === testParts[ii]; + } else { + matches = false; + } + } + + // If matches, then return the component parts + matches = matches && testParts; + } + } + else if (typeof input.splice == 'function') { + matches = []; + + for (ii = input.length; ii--; ) { + if (this.match(input[ii])) { + matches[matches.length] = input[ii]; + } + } + } + else if (typeof input == 'object') { + matches = {}; + + for (var key in input) { + if (this.match(key)) { + matches[key] = input[key]; + } + } + } + + return matches; +}; + +module.exports = function(text, test, separator) { + var matcher = new WildcardMatcher(text, separator || /[\/\.]/); + if (typeof test != 'undefined') { + return matcher.match(test); + } + + return matcher; +}; + +},{}],69:[function(require,module,exports){ +'use strict'; + +var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') + , length = 64 + , map = {} + , seed = 0 + , i = 0 + , prev; + +/** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ +function encode(num) { + var encoded = ''; + + do { + encoded = alphabet[num % length] + encoded; + num = Math.floor(num / length); + } while (num > 0); + + return encoded; +} + +/** + * Return the integer value specified by the given string. + * + * @param {String} str The string to convert. + * @returns {Number} The integer value represented by the string. + * @api public + */ +function decode(str) { + var decoded = 0; + + for (i = 0; i < str.length; i++) { + decoded = decoded * length + map[str.charAt(i)]; + } + + return decoded; +} + +/** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ +function yeast() { + var now = encode(+new Date()); + + if (now !== prev) return seed = 0, prev = now; + return now +'.'+ encode(seed++); +} + +// +// Map each character to its index. +// +for (; i < length; i++) map[alphabet[i]] = i; + +// +// Expose the `yeast`, `encode` and `decode` functions. +// +yeast.encode = encode; +yeast.decode = decode; +module.exports = yeast; + +},{}],70:[function(require,module,exports){ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +var _require = require('@uppy/utils/lib/AbortController'), + AbortController = _require.AbortController, + createAbortError = _require.createAbortError; + +var delay = require('@uppy/utils/lib/delay'); + +var MB = 1024 * 1024; +var defaultOptions = { + limit: 1, + retryDelays: [0, 1000, 3000, 5000], + getChunkSize: function getChunkSize(file) { + return Math.ceil(file.size / 10000); + }, + onStart: function onStart() {}, + onProgress: function onProgress() {}, + onPartComplete: function onPartComplete() {}, + onSuccess: function onSuccess() {}, + onError: function onError(err) { + throw err; + } +}; + +function ensureInt(value) { + if (typeof value === 'string') { + return parseInt(value, 10); + } + + if (typeof value === 'number') { + return value; + } + + throw new TypeError('Expected a number'); +} + +var MultipartUploader = /*#__PURE__*/function () { + function MultipartUploader(file, options) { + this.options = _extends({}, defaultOptions, options); // Use default `getChunkSize` if it was null or something + + if (!this.options.getChunkSize) { + this.options.getChunkSize = defaultOptions.getChunkSize; + } + + this.file = file; + this.abortController = new AbortController(); + this.key = this.options.key || null; + this.uploadId = this.options.uploadId || null; + this.parts = []; // Do `this.createdPromise.then(OP)` to execute an operation `OP` _only_ if the + // upload was created already. That also ensures that the sequencing is right + // (so the `OP` definitely happens if the upload is created). + // + // This mostly exists to make `_abortUpload` work well: only sending the abort request if + // the upload was already created, and if the createMultipartUpload request is still in flight, + // aborting it immediately after it finishes. + + this.createdPromise = Promise.reject(); // eslint-disable-line prefer-promise-reject-errors + + this.isPaused = false; + this.partsInProgress = 0; + this.chunks = null; + this.chunkState = null; + + this._initChunks(); + + this.createdPromise.catch(function () {}); // silence uncaught rejection warning + } + /** + * Was this upload aborted? + * + * If yes, we may need to throw an AbortError. + * + * @returns {boolean} + */ + + + var _proto = MultipartUploader.prototype; + + _proto._aborted = function _aborted() { + return this.abortController.signal.aborted; + }; + + _proto._initChunks = function _initChunks() { + var chunks = []; + var desiredChunkSize = this.options.getChunkSize(this.file); // at least 5MB per request, at most 10k requests + + var minChunkSize = Math.max(5 * MB, Math.ceil(this.file.size / 10000)); + var chunkSize = Math.max(desiredChunkSize, minChunkSize); // Upload zero-sized files in one zero-sized chunk + + if (this.file.size === 0) { + chunks.push(this.file); + } else { + for (var i = 0; i < this.file.size; i += chunkSize) { + var end = Math.min(this.file.size, i + chunkSize); + chunks.push(this.file.slice(i, end)); + } + } + + this.chunks = chunks; + this.chunkState = chunks.map(function () { + return { + uploaded: 0, + busy: false, + done: false + }; + }); + }; + + _proto._createUpload = function _createUpload() { + var _this = this; + + this.createdPromise = Promise.resolve().then(function () { + return _this.options.createMultipartUpload(); + }); + return this.createdPromise.then(function (result) { + if (_this._aborted()) throw createAbortError(); + var valid = typeof result === 'object' && result && typeof result.uploadId === 'string' && typeof result.key === 'string'; + + if (!valid) { + throw new TypeError('AwsS3/Multipart: Got incorrect result from `createMultipartUpload()`, expected an object `{ uploadId, key }`.'); + } + + _this.key = result.key; + _this.uploadId = result.uploadId; + + _this.options.onStart(result); + + _this._uploadParts(); + }).catch(function (err) { + _this._onError(err); + }); + }; + + _proto._resumeUpload = function _resumeUpload() { + var _this2 = this; + + return Promise.resolve().then(function () { + return _this2.options.listParts({ + uploadId: _this2.uploadId, + key: _this2.key + }); + }).then(function (parts) { + if (_this2._aborted()) throw createAbortError(); + parts.forEach(function (part) { + var i = part.PartNumber - 1; + _this2.chunkState[i] = { + uploaded: ensureInt(part.Size), + etag: part.ETag, + done: true + }; // Only add if we did not yet know about this part. + + if (!_this2.parts.some(function (p) { + return p.PartNumber === part.PartNumber; + })) { + _this2.parts.push({ + PartNumber: part.PartNumber, + ETag: part.ETag + }); + } + }); + + _this2._uploadParts(); + }).catch(function (err) { + _this2._onError(err); + }); + }; + + _proto._uploadParts = function _uploadParts() { + var _this3 = this; + + if (this.isPaused) return; + var need = this.options.limit - this.partsInProgress; + if (need === 0) return; // All parts are uploaded. + + if (this.chunkState.every(function (state) { + return state.done; + })) { + this._completeUpload(); + + return; + } + + var candidates = []; + + for (var i = 0; i < this.chunkState.length; i++) { + var state = this.chunkState[i]; + if (state.done || state.busy) continue; + candidates.push(i); + + if (candidates.length >= need) { + break; + } + } + + candidates.forEach(function (index) { + _this3._uploadPartRetryable(index).then(function () { + // Continue uploading parts + _this3._uploadParts(); + }, function (err) { + _this3._onError(err); + }); + }); + }; + + _proto._retryable = function _retryable(_ref) { + var _this4 = this; + + var before = _ref.before, + attempt = _ref.attempt, + after = _ref.after; + var retryDelays = this.options.retryDelays; + var signal = this.abortController.signal; + if (before) before(); + + function shouldRetry(err) { + if (err.source && typeof err.source.status === 'number') { + var status = err.source.status; // 0 probably indicates network failure + + return status === 0 || status === 409 || status === 423 || status >= 500 && status < 600; + } + + return false; + } + + var doAttempt = function doAttempt(retryAttempt) { + return attempt().catch(function (err) { + if (_this4._aborted()) throw createAbortError(); + + if (shouldRetry(err) && retryAttempt < retryDelays.length) { + return delay(retryDelays[retryAttempt], { + signal: signal + }).then(function () { + return doAttempt(retryAttempt + 1); + }); + } else { + throw err; + } + }); + }; + + return doAttempt(0).then(function (result) { + if (after) after(); + return result; + }, function (err) { + if (after) after(); + throw err; + }); + }; + + _proto._uploadPartRetryable = function _uploadPartRetryable(index) { + var _this5 = this; + + return this._retryable({ + before: function before() { + _this5.partsInProgress += 1; + }, + attempt: function attempt() { + return _this5._uploadPart(index); + }, + after: function after() { + _this5.partsInProgress -= 1; + } + }); + }; + + _proto._uploadPart = function _uploadPart(index) { + var _this6 = this; + + var body = this.chunks[index]; + this.chunkState[index].busy = true; + return Promise.resolve().then(function () { + return _this6.options.prepareUploadPart({ + key: _this6.key, + uploadId: _this6.uploadId, + body: body, + number: index + 1 + }); + }).then(function (result) { + var valid = typeof result === 'object' && result && typeof result.url === 'string'; + + if (!valid) { + throw new TypeError('AwsS3/Multipart: Got incorrect result from `prepareUploadPart()`, expected an object `{ url }`.'); + } + + return result; + }).then(function (_ref2) { + var url = _ref2.url, + headers = _ref2.headers; + + if (_this6._aborted()) { + _this6.chunkState[index].busy = false; + throw createAbortError(); + } + + return _this6._uploadPartBytes(index, url, headers); + }); + }; + + _proto._onPartProgress = function _onPartProgress(index, sent, total) { + this.chunkState[index].uploaded = ensureInt(sent); + var totalUploaded = this.chunkState.reduce(function (n, c) { + return n + c.uploaded; + }, 0); + this.options.onProgress(totalUploaded, this.file.size); + }; + + _proto._onPartComplete = function _onPartComplete(index, etag) { + this.chunkState[index].etag = etag; + this.chunkState[index].done = true; + var part = { + PartNumber: index + 1, + ETag: etag + }; + this.parts.push(part); + this.options.onPartComplete(part); + }; + + _proto._uploadPartBytes = function _uploadPartBytes(index, url, headers) { + var _this7 = this; + + var body = this.chunks[index]; + var signal = this.abortController.signal; + var defer; + var promise = new Promise(function (resolve, reject) { + defer = { + resolve: resolve, + reject: reject + }; + }); + var xhr = new XMLHttpRequest(); + xhr.open('PUT', url, true); + + if (headers) { + Object.keys(headers).map(function (key) { + xhr.setRequestHeader(key, headers[key]); + }); + } + + xhr.responseType = 'text'; + + function cleanup() { + signal.removeEventListener('abort', onabort); + } + + function onabort() { + xhr.abort(); + } + + signal.addEventListener('abort', onabort); + xhr.upload.addEventListener('progress', function (ev) { + if (!ev.lengthComputable) return; + + _this7._onPartProgress(index, ev.loaded, ev.total); + }); + xhr.addEventListener('abort', function (ev) { + cleanup(); + _this7.chunkState[index].busy = false; + defer.reject(createAbortError()); + }); + xhr.addEventListener('load', function (ev) { + cleanup(); + _this7.chunkState[index].busy = false; + + if (ev.target.status < 200 || ev.target.status >= 300) { + var error = new Error('Non 2xx'); + error.source = ev.target; + defer.reject(error); + return; + } + + _this7._onPartProgress(index, body.size, body.size); // NOTE This must be allowed by CORS. + + + var etag = ev.target.getResponseHeader('ETag'); + + if (etag === null) { + defer.reject(new Error('AwsS3/Multipart: Could not read the ETag header. This likely means CORS is not configured correctly on the S3 Bucket. Seee https://uppy.io/docs/aws-s3-multipart#S3-Bucket-Configuration for instructions.')); + return; + } + + _this7._onPartComplete(index, etag); + + defer.resolve(); + }); + xhr.addEventListener('error', function (ev) { + cleanup(); + _this7.chunkState[index].busy = false; + var error = new Error('Unknown error'); + error.source = ev.target; + defer.reject(error); + }); + xhr.send(body); + return promise; + }; + + _proto._completeUpload = function _completeUpload() { + var _this8 = this; + + // Parts may not have completed uploading in sorted order, if limit > 1. + this.parts.sort(function (a, b) { + return a.PartNumber - b.PartNumber; + }); + return Promise.resolve().then(function () { + return _this8.options.completeMultipartUpload({ + key: _this8.key, + uploadId: _this8.uploadId, + parts: _this8.parts + }); + }).then(function (result) { + _this8.options.onSuccess(result); + }, function (err) { + _this8._onError(err); + }); + }; + + _proto._abortUpload = function _abortUpload() { + var _this9 = this; + + this.abortController.abort(); + this.createdPromise.then(function () { + _this9.options.abortMultipartUpload({ + key: _this9.key, + uploadId: _this9.uploadId + }); + }, function () {// if the creation failed we do not need to abort + }); + }; + + _proto._onError = function _onError(err) { + if (err && err.name === 'AbortError') { + return; + } + + this.options.onError(err); + }; + + _proto.start = function start() { + this.isPaused = false; + + if (this.uploadId) { + this._resumeUpload(); + } else { + this._createUpload(); + } + }; + + _proto.pause = function pause() { + this.abortController.abort(); // Swap it out for a new controller, because this instance may be resumed later. + + this.abortController = new AbortController(); + this.isPaused = true; + }; + + _proto.abort = function abort(opts) { + if (opts === void 0) { + opts = {}; + } + + var really = opts.really || false; + if (!really) return this.pause(); + + this._abortUpload(); + }; + + return MultipartUploader; +}(); + +module.exports = MultipartUploader; +},{"@uppy/utils/lib/AbortController":198,"@uppy/utils/lib/delay":207}],71:[function(require,module,exports){ +var _class, _temp; + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +var _require = require('@uppy/core'), + Plugin = _require.Plugin; + +var _require2 = require('@uppy/companion-client'), + Socket = _require2.Socket, + Provider = _require2.Provider, + RequestClient = _require2.RequestClient; + +var EventTracker = require('@uppy/utils/lib/EventTracker'); + +var emitSocketProgress = require('@uppy/utils/lib/emitSocketProgress'); + +var getSocketHost = require('@uppy/utils/lib/getSocketHost'); + +var RateLimitedQueue = require('@uppy/utils/lib/RateLimitedQueue'); + +var Uploader = require('./MultipartUploader'); + +function assertServerError(res) { + if (res && res.error) { + var error = new Error(res.message); + + _extends(error, res.error); + + throw error; + } + + return res; +} + +module.exports = (_temp = _class = /*#__PURE__*/function (_Plugin) { + _inheritsLoose(AwsS3Multipart, _Plugin); + + function AwsS3Multipart(uppy, opts) { + var _this; + + _this = _Plugin.call(this, uppy, opts) || this; + _this.type = 'uploader'; + _this.id = _this.opts.id || 'AwsS3Multipart'; + _this.title = 'AWS S3 Multipart'; + _this.client = new RequestClient(uppy, opts); + var defaultOptions = { + timeout: 30 * 1000, + limit: 0, + retryDelays: [0, 1000, 3000, 5000], + createMultipartUpload: _this.createMultipartUpload.bind(_assertThisInitialized(_this)), + listParts: _this.listParts.bind(_assertThisInitialized(_this)), + prepareUploadPart: _this.prepareUploadPart.bind(_assertThisInitialized(_this)), + abortMultipartUpload: _this.abortMultipartUpload.bind(_assertThisInitialized(_this)), + completeMultipartUpload: _this.completeMultipartUpload.bind(_assertThisInitialized(_this)) + }; + _this.opts = _extends({}, defaultOptions, opts); + _this.upload = _this.upload.bind(_assertThisInitialized(_this)); + _this.requests = new RateLimitedQueue(_this.opts.limit); + _this.uploaders = Object.create(null); + _this.uploaderEvents = Object.create(null); + _this.uploaderSockets = Object.create(null); + return _this; + } + /** + * Clean up all references for a file's upload: the MultipartUploader instance, + * any events related to the file, and the Companion WebSocket connection. + * + * Set `opts.abort` to tell S3 that the multipart upload is cancelled and must be removed. + * This should be done when the user cancels the upload, not when the upload is completed or errored. + */ + + + var _proto = AwsS3Multipart.prototype; + + _proto.resetUploaderReferences = function resetUploaderReferences(fileID, opts) { + if (opts === void 0) { + opts = {}; + } + + if (this.uploaders[fileID]) { + this.uploaders[fileID].abort({ + really: opts.abort || false + }); + this.uploaders[fileID] = null; + } + + if (this.uploaderEvents[fileID]) { + this.uploaderEvents[fileID].remove(); + this.uploaderEvents[fileID] = null; + } + + if (this.uploaderSockets[fileID]) { + this.uploaderSockets[fileID].close(); + this.uploaderSockets[fileID] = null; + } + }; + + _proto.assertHost = function assertHost(method) { + if (!this.opts.companionUrl) { + throw new Error("Expected a `companionUrl` option containing a Companion address, or if you are not using Companion, a custom `" + method + "` implementation."); + } + }; + + _proto.createMultipartUpload = function createMultipartUpload(file) { + this.assertHost('createMultipartUpload'); + var metadata = {}; + Object.keys(file.meta).map(function (key) { + if (file.meta[key] != null) { + metadata[key] = file.meta[key].toString(); + } + }); + return this.client.post('s3/multipart', { + filename: file.name, + type: file.type, + metadata: metadata + }).then(assertServerError); + }; + + _proto.listParts = function listParts(file, _ref) { + var key = _ref.key, + uploadId = _ref.uploadId; + this.assertHost('listParts'); + var filename = encodeURIComponent(key); + return this.client.get("s3/multipart/" + uploadId + "?key=" + filename).then(assertServerError); + }; + + _proto.prepareUploadPart = function prepareUploadPart(file, _ref2) { + var key = _ref2.key, + uploadId = _ref2.uploadId, + number = _ref2.number; + this.assertHost('prepareUploadPart'); + var filename = encodeURIComponent(key); + return this.client.get("s3/multipart/" + uploadId + "/" + number + "?key=" + filename).then(assertServerError); + }; + + _proto.completeMultipartUpload = function completeMultipartUpload(file, _ref3) { + var key = _ref3.key, + uploadId = _ref3.uploadId, + parts = _ref3.parts; + this.assertHost('completeMultipartUpload'); + var filename = encodeURIComponent(key); + var uploadIdEnc = encodeURIComponent(uploadId); + return this.client.post("s3/multipart/" + uploadIdEnc + "/complete?key=" + filename, { + parts: parts + }).then(assertServerError); + }; + + _proto.abortMultipartUpload = function abortMultipartUpload(file, _ref4) { + var key = _ref4.key, + uploadId = _ref4.uploadId; + this.assertHost('abortMultipartUpload'); + var filename = encodeURIComponent(key); + var uploadIdEnc = encodeURIComponent(uploadId); + return this.client.delete("s3/multipart/" + uploadIdEnc + "?key=" + filename).then(assertServerError); + }; + + _proto.uploadFile = function uploadFile(file) { + var _this2 = this; + + return new Promise(function (resolve, reject) { + var onStart = function onStart(data) { + var cFile = _this2.uppy.getFile(file.id); + + _this2.uppy.setFileState(file.id, { + s3Multipart: _extends({}, cFile.s3Multipart, { + key: data.key, + uploadId: data.uploadId + }) + }); + }; + + var onProgress = function onProgress(bytesUploaded, bytesTotal) { + _this2.uppy.emit('upload-progress', file, { + uploader: _this2, + bytesUploaded: bytesUploaded, + bytesTotal: bytesTotal + }); + }; + + var onError = function onError(err) { + _this2.uppy.log(err); + + _this2.uppy.emit('upload-error', file, err); + + queuedRequest.done(); + + _this2.resetUploaderReferences(file.id); + + reject(err); + }; + + var onSuccess = function onSuccess(result) { + var uploadResp = { + body: _extends({}, result), + uploadURL: result.location + }; + queuedRequest.done(); + + _this2.resetUploaderReferences(file.id); + + _this2.uppy.emit('upload-success', file, uploadResp); + + if (result.location) { + _this2.uppy.log('Download ' + upload.file.name + ' from ' + result.location); + } + + resolve(upload); + }; + + var onPartComplete = function onPartComplete(part) { + var cFile = _this2.uppy.getFile(file.id); + + if (!cFile) { + return; + } + + _this2.uppy.emit('s3-multipart:part-uploaded', cFile, part); + }; + + var upload = new Uploader(file.data, _extends({ + // .bind to pass the file object to each handler. + createMultipartUpload: _this2.opts.createMultipartUpload.bind(_this2, file), + listParts: _this2.opts.listParts.bind(_this2, file), + prepareUploadPart: _this2.opts.prepareUploadPart.bind(_this2, file), + completeMultipartUpload: _this2.opts.completeMultipartUpload.bind(_this2, file), + abortMultipartUpload: _this2.opts.abortMultipartUpload.bind(_this2, file), + getChunkSize: _this2.opts.getChunkSize ? _this2.opts.getChunkSize.bind(_this2) : null, + onStart: onStart, + onProgress: onProgress, + onError: onError, + onSuccess: onSuccess, + onPartComplete: onPartComplete, + limit: _this2.opts.limit || 5, + retryDelays: _this2.opts.retryDelays || [] + }, file.s3Multipart)); + _this2.uploaders[file.id] = upload; + _this2.uploaderEvents[file.id] = new EventTracker(_this2.uppy); + + var queuedRequest = _this2.requests.run(function () { + if (!file.isPaused) { + upload.start(); + } // Don't do anything here, the caller will take care of cancelling the upload itself + // using resetUploaderReferences(). This is because resetUploaderReferences() has to be + // called when this request is still in the queue, and has not been started yet, too. At + // that point this cancellation function is not going to be called. + + + return function () {}; + }); + + _this2.onFileRemove(file.id, function (removed) { + queuedRequest.abort(); + + _this2.resetUploaderReferences(file.id, { + abort: true + }); + + resolve("upload " + removed.id + " was removed"); + }); + + _this2.onCancelAll(file.id, function () { + queuedRequest.abort(); + + _this2.resetUploaderReferences(file.id, { + abort: true + }); + + resolve("upload " + file.id + " was canceled"); + }); + + _this2.onFilePause(file.id, function (isPaused) { + if (isPaused) { + // Remove this file from the queue so another file can start in its place. + queuedRequest.abort(); + upload.pause(); + } else { + // Resuming an upload should be queued, else you could pause and then resume a queued upload to make it skip the queue. + queuedRequest.abort(); + queuedRequest = _this2.requests.run(function () { + upload.start(); + return function () {}; + }); + } + }); + + _this2.onPauseAll(file.id, function () { + queuedRequest.abort(); + upload.pause(); + }); + + _this2.onResumeAll(file.id, function () { + queuedRequest.abort(); + + if (file.error) { + upload.abort(); + } + + queuedRequest = _this2.requests.run(function () { + upload.start(); + return function () {}; + }); + }); + + if (!file.isRestored) { + _this2.uppy.emit('upload-started', file, upload); + } + }); + }; + + _proto.uploadRemote = function uploadRemote(file) { + var _this3 = this; + + this.resetUploaderReferences(file.id); + this.uppy.emit('upload-started', file); + + if (file.serverToken) { + return this.connectToServerSocket(file); + } + + return new Promise(function (resolve, reject) { + var Client = file.remote.providerOptions.provider ? Provider : RequestClient; + var client = new Client(_this3.uppy, file.remote.providerOptions); + client.post(file.remote.url, _extends({}, file.remote.body, { + protocol: 's3-multipart', + size: file.data.size, + metadata: file.meta + })).then(function (res) { + _this3.uppy.setFileState(file.id, { + serverToken: res.token + }); + + file = _this3.uppy.getFile(file.id); + return file; + }).then(function (file) { + return _this3.connectToServerSocket(file); + }).then(function () { + resolve(); + }).catch(function (err) { + _this3.uppy.emit('upload-error', file, err); + + reject(err); + }); + }); + }; + + _proto.connectToServerSocket = function connectToServerSocket(file) { + var _this4 = this; + + return new Promise(function (resolve, reject) { + var token = file.serverToken; + var host = getSocketHost(file.remote.companionUrl); + var socket = new Socket({ + target: host + "/api/" + token, + autoOpen: false + }); + _this4.uploaderSockets[file.id] = socket; + _this4.uploaderEvents[file.id] = new EventTracker(_this4.uppy); + + _this4.onFileRemove(file.id, function (removed) { + queuedRequest.abort(); + socket.send('pause', {}); + + _this4.resetUploaderReferences(file.id, { + abort: true + }); + + resolve("upload " + file.id + " was removed"); + }); + + _this4.onFilePause(file.id, function (isPaused) { + if (isPaused) { + // Remove this file from the queue so another file can start in its place. + queuedRequest.abort(); + socket.send('pause', {}); + } else { + // Resuming an upload should be queued, else you could pause and then resume a queued upload to make it skip the queue. + queuedRequest.abort(); + queuedRequest = _this4.requests.run(function () { + socket.send('resume', {}); + return function () {}; + }); + } + }); + + _this4.onPauseAll(file.id, function () { + queuedRequest.abort(); + socket.send('pause', {}); + }); + + _this4.onCancelAll(file.id, function () { + queuedRequest.abort(); + socket.send('pause', {}); + + _this4.resetUploaderReferences(file.id); + + resolve("upload " + file.id + " was canceled"); + }); + + _this4.onResumeAll(file.id, function () { + queuedRequest.abort(); + + if (file.error) { + socket.send('pause', {}); + } + + queuedRequest = _this4.requests.run(function () { + socket.send('resume', {}); + }); + }); + + _this4.onRetry(file.id, function () { + // Only do the retry if the upload is actually in progress; + // else we could try to send these messages when the upload is still queued. + // We may need a better check for this since the socket may also be closed + // for other reasons, like network failures. + if (socket.isOpen) { + socket.send('pause', {}); + socket.send('resume', {}); + } + }); + + _this4.onRetryAll(file.id, function () { + if (socket.isOpen) { + socket.send('pause', {}); + socket.send('resume', {}); + } + }); + + socket.on('progress', function (progressData) { + return emitSocketProgress(_this4, progressData, file); + }); + socket.on('error', function (errData) { + _this4.uppy.emit('upload-error', file, new Error(errData.error)); + + _this4.resetUploaderReferences(file.id); + + queuedRequest.done(); + reject(new Error(errData.error)); + }); + socket.on('success', function (data) { + var uploadResp = { + uploadURL: data.url + }; + + _this4.uppy.emit('upload-success', file, uploadResp); + + _this4.resetUploaderReferences(file.id); + + queuedRequest.done(); + resolve(); + }); + + var queuedRequest = _this4.requests.run(function () { + socket.open(); + + if (file.isPaused) { + socket.send('pause', {}); + } + + return function () {}; + }); + }); + }; + + _proto.upload = function upload(fileIDs) { + var _this5 = this; + + if (fileIDs.length === 0) return Promise.resolve(); + var promises = fileIDs.map(function (id) { + var file = _this5.uppy.getFile(id); + + if (file.isRemote) { + return _this5.uploadRemote(file); + } + + return _this5.uploadFile(file); + }); + return Promise.all(promises); + }; + + _proto.onFileRemove = function onFileRemove(fileID, cb) { + this.uploaderEvents[fileID].on('file-removed', function (file) { + if (fileID === file.id) cb(file.id); + }); + }; + + _proto.onFilePause = function onFilePause(fileID, cb) { + this.uploaderEvents[fileID].on('upload-pause', function (targetFileID, isPaused) { + if (fileID === targetFileID) { + // const isPaused = this.uppy.pauseResume(fileID) + cb(isPaused); + } + }); + }; + + _proto.onRetry = function onRetry(fileID, cb) { + this.uploaderEvents[fileID].on('upload-retry', function (targetFileID) { + if (fileID === targetFileID) { + cb(); + } + }); + }; + + _proto.onRetryAll = function onRetryAll(fileID, cb) { + var _this6 = this; + + this.uploaderEvents[fileID].on('retry-all', function (filesToRetry) { + if (!_this6.uppy.getFile(fileID)) return; + cb(); + }); + }; + + _proto.onPauseAll = function onPauseAll(fileID, cb) { + var _this7 = this; + + this.uploaderEvents[fileID].on('pause-all', function () { + if (!_this7.uppy.getFile(fileID)) return; + cb(); + }); + }; + + _proto.onCancelAll = function onCancelAll(fileID, cb) { + var _this8 = this; + + this.uploaderEvents[fileID].on('cancel-all', function () { + if (!_this8.uppy.getFile(fileID)) return; + cb(); + }); + }; + + _proto.onResumeAll = function onResumeAll(fileID, cb) { + var _this9 = this; + + this.uploaderEvents[fileID].on('resume-all', function () { + if (!_this9.uppy.getFile(fileID)) return; + cb(); + }); + }; + + _proto.install = function install() { + var _this$uppy$getState = this.uppy.getState(), + capabilities = _this$uppy$getState.capabilities; + + this.uppy.setState({ + capabilities: _extends({}, capabilities, { + resumableUploads: true + }) + }); + this.uppy.addUploader(this.upload); + }; + + _proto.uninstall = function uninstall() { + var _this$uppy$getState2 = this.uppy.getState(), + capabilities = _this$uppy$getState2.capabilities; + + this.uppy.setState({ + capabilities: _extends({}, capabilities, { + resumableUploads: false + }) + }); + this.uppy.removeUploader(this.upload); + }; + + return AwsS3Multipart; +}(Plugin), _class.VERSION = "1.8.14", _temp); +},{"./MultipartUploader":70,"@uppy/companion-client":81,"@uppy/core":84,"@uppy/utils/lib/EventTracker":199,"@uppy/utils/lib/RateLimitedQueue":203,"@uppy/utils/lib/emitSocketProgress":208,"@uppy/utils/lib/getSocketHost":223}],72:[function(require,module,exports){ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +var cuid = require('cuid'); + +var _require = require('@uppy/companion-client'), + Provider = _require.Provider, + RequestClient = _require.RequestClient, + Socket = _require.Socket; + +var emitSocketProgress = require('@uppy/utils/lib/emitSocketProgress'); + +var getSocketHost = require('@uppy/utils/lib/getSocketHost'); + +var EventTracker = require('@uppy/utils/lib/EventTracker'); + +var ProgressTimeout = require('@uppy/utils/lib/ProgressTimeout'); + +var NetworkError = require('@uppy/utils/lib/NetworkError'); + +var isNetworkError = require('@uppy/utils/lib/isNetworkError'); // See XHRUpload + + +function buildResponseError(xhr, error) { + // No error message + if (!error) error = new Error('Upload error'); // Got an error message string + + if (typeof error === 'string') error = new Error(error); // Got something else + + if (!(error instanceof Error)) { + error = _extends(new Error('Upload error'), { + data: error + }); + } + + if (isNetworkError(xhr)) { + error = new NetworkError(error, xhr); + return error; + } + + error.request = xhr; + return error; +} // See XHRUpload + + +function setTypeInBlob(file) { + var dataWithUpdatedType = file.data.slice(0, file.data.size, file.meta.type); + return dataWithUpdatedType; +} + +module.exports = /*#__PURE__*/function () { + function MiniXHRUpload(uppy, opts) { + this.uppy = uppy; + this.opts = _extends({ + validateStatus: function validateStatus(status, responseText, response) { + return status >= 200 && status < 300; + } + }, opts); + this.requests = opts.__queue; + this.uploaderEvents = Object.create(null); + this.i18n = opts.i18n; + } + + var _proto = MiniXHRUpload.prototype; + + _proto._getOptions = function _getOptions(file) { + var uppy = this.uppy; + var overrides = uppy.getState().xhrUpload; + + var opts = _extends({}, this.opts, overrides || {}, file.xhrUpload || {}, { + headers: {} + }); + + _extends(opts.headers, this.opts.headers); + + if (overrides) { + _extends(opts.headers, overrides.headers); + } + + if (file.xhrUpload) { + _extends(opts.headers, file.xhrUpload.headers); + } + + return opts; + }; + + _proto.uploadFile = function uploadFile(id, current, total) { + var file = this.uppy.getFile(id); + + if (file.error) { + throw new Error(file.error); + } else if (file.isRemote) { + return this._uploadRemoteFile(file, current, total); + } + + return this._uploadLocalFile(file, current, total); + }; + + _proto._addMetadata = function _addMetadata(formData, meta, opts) { + var metaFields = Array.isArray(opts.metaFields) ? opts.metaFields // Send along all fields by default. + : Object.keys(meta); + metaFields.forEach(function (item) { + formData.append(item, meta[item]); + }); + }; + + _proto._createFormDataUpload = function _createFormDataUpload(file, opts) { + var formPost = new FormData(); + + this._addMetadata(formPost, file.meta, opts); + + var dataWithUpdatedType = setTypeInBlob(file); + + if (file.name) { + formPost.append(opts.fieldName, dataWithUpdatedType, file.meta.name); + } else { + formPost.append(opts.fieldName, dataWithUpdatedType); + } + + return formPost; + }; + + _proto._createBareUpload = function _createBareUpload(file, opts) { + return file.data; + }; + + _proto._onFileRemoved = function _onFileRemoved(fileID, cb) { + this.uploaderEvents[fileID].on('file-removed', function (file) { + if (fileID === file.id) cb(file.id); + }); + }; + + _proto._onRetry = function _onRetry(fileID, cb) { + this.uploaderEvents[fileID].on('upload-retry', function (targetFileID) { + if (fileID === targetFileID) { + cb(); + } + }); + }; + + _proto._onRetryAll = function _onRetryAll(fileID, cb) { + var _this = this; + + this.uploaderEvents[fileID].on('retry-all', function (filesToRetry) { + if (!_this.uppy.getFile(fileID)) return; + cb(); + }); + }; + + _proto._onCancelAll = function _onCancelAll(fileID, cb) { + var _this2 = this; + + this.uploaderEvents[fileID].on('cancel-all', function () { + if (!_this2.uppy.getFile(fileID)) return; + cb(); + }); + }; + + _proto._uploadLocalFile = function _uploadLocalFile(file, current, total) { + var _this3 = this; + + var opts = this._getOptions(file); + + this.uppy.log("uploading " + current + " of " + total); + return new Promise(function (resolve, reject) { + // This is done in index.js in the S3 plugin. + // this.uppy.emit('upload-started', file) + var data = opts.formData ? _this3._createFormDataUpload(file, opts) : _this3._createBareUpload(file, opts); + var xhr = new XMLHttpRequest(); + _this3.uploaderEvents[file.id] = new EventTracker(_this3.uppy); + var timer = new ProgressTimeout(opts.timeout, function () { + xhr.abort(); + queuedRequest.done(); + var error = new Error(_this3.i18n('timedOut', { + seconds: Math.ceil(opts.timeout / 1000) + })); + + _this3.uppy.emit('upload-error', file, error); + + reject(error); + }); + var id = cuid(); + xhr.upload.addEventListener('loadstart', function (ev) { + _this3.uppy.log("[AwsS3/XHRUpload] " + id + " started"); + }); + xhr.upload.addEventListener('progress', function (ev) { + _this3.uppy.log("[AwsS3/XHRUpload] " + id + " progress: " + ev.loaded + " / " + ev.total); // Begin checking for timeouts when progress starts, instead of loading, + // to avoid timing out requests on browser concurrency queue + + + timer.progress(); + + if (ev.lengthComputable) { + _this3.uppy.emit('upload-progress', file, { + uploader: _this3, + bytesUploaded: ev.loaded, + bytesTotal: ev.total + }); + } + }); + xhr.addEventListener('load', function (ev) { + _this3.uppy.log("[AwsS3/XHRUpload] " + id + " finished"); + + timer.done(); + queuedRequest.done(); + + if (_this3.uploaderEvents[file.id]) { + _this3.uploaderEvents[file.id].remove(); + + _this3.uploaderEvents[file.id] = null; + } + + if (opts.validateStatus(ev.target.status, xhr.responseText, xhr)) { + var body = opts.getResponseData(xhr.responseText, xhr); + var uploadURL = body[opts.responseUrlFieldName]; + var uploadResp = { + status: ev.target.status, + body: body, + uploadURL: uploadURL + }; + + _this3.uppy.emit('upload-success', file, uploadResp); + + if (uploadURL) { + _this3.uppy.log("Download " + file.name + " from " + uploadURL); + } + + return resolve(file); + } else { + var _body = opts.getResponseData(xhr.responseText, xhr); + + var error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr)); + var response = { + status: ev.target.status, + body: _body + }; + + _this3.uppy.emit('upload-error', file, error, response); + + return reject(error); + } + }); + xhr.addEventListener('error', function (ev) { + _this3.uppy.log("[AwsS3/XHRUpload] " + id + " errored"); + + timer.done(); + queuedRequest.done(); + + if (_this3.uploaderEvents[file.id]) { + _this3.uploaderEvents[file.id].remove(); + + _this3.uploaderEvents[file.id] = null; + } + + var error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr)); + + _this3.uppy.emit('upload-error', file, error); + + return reject(error); + }); + xhr.open(opts.method.toUpperCase(), opts.endpoint, true); // IE10 does not allow setting `withCredentials` and `responseType` + // before `open()` is called. + + xhr.withCredentials = opts.withCredentials; + + if (opts.responseType !== '') { + xhr.responseType = opts.responseType; + } + + Object.keys(opts.headers).forEach(function (header) { + xhr.setRequestHeader(header, opts.headers[header]); + }); + + var queuedRequest = _this3.requests.run(function () { + xhr.send(data); + return function () { + timer.done(); + xhr.abort(); + }; + }, { + priority: 1 + }); + + _this3._onFileRemoved(file.id, function () { + queuedRequest.abort(); + reject(new Error('File removed')); + }); + + _this3._onCancelAll(file.id, function () { + queuedRequest.abort(); + reject(new Error('Upload cancelled')); + }); + }); + }; + + _proto._uploadRemoteFile = function _uploadRemoteFile(file, current, total) { + var _this4 = this; + + var opts = this._getOptions(file); + + return new Promise(function (resolve, reject) { + // This is done in index.js in the S3 plugin. + // this.uppy.emit('upload-started', file) + var fields = {}; + var metaFields = Array.isArray(opts.metaFields) ? opts.metaFields // Send along all fields by default. + : Object.keys(file.meta); + metaFields.forEach(function (name) { + fields[name] = file.meta[name]; + }); + var Client = file.remote.providerOptions.provider ? Provider : RequestClient; + var client = new Client(_this4.uppy, file.remote.providerOptions); + client.post(file.remote.url, _extends({}, file.remote.body, { + endpoint: opts.endpoint, + size: file.data.size, + fieldname: opts.fieldName, + metadata: fields, + httpMethod: opts.method, + useFormData: opts.formData, + headers: opts.headers + })).then(function (res) { + var token = res.token; + var host = getSocketHost(file.remote.companionUrl); + var socket = new Socket({ + target: host + "/api/" + token, + autoOpen: false + }); + _this4.uploaderEvents[file.id] = new EventTracker(_this4.uppy); + + _this4._onFileRemoved(file.id, function () { + socket.send('pause', {}); + queuedRequest.abort(); + resolve("upload " + file.id + " was removed"); + }); + + _this4._onCancelAll(file.id, function () { + socket.send('pause', {}); + queuedRequest.abort(); + resolve("upload " + file.id + " was canceled"); + }); + + _this4._onRetry(file.id, function () { + socket.send('pause', {}); + socket.send('resume', {}); + }); + + _this4._onRetryAll(file.id, function () { + socket.send('pause', {}); + socket.send('resume', {}); + }); + + socket.on('progress', function (progressData) { + return emitSocketProgress(_this4, progressData, file); + }); + socket.on('success', function (data) { + var body = opts.getResponseData(data.response.responseText, data.response); + var uploadURL = body[opts.responseUrlFieldName]; + var uploadResp = { + status: data.response.status, + body: body, + uploadURL: uploadURL + }; + + _this4.uppy.emit('upload-success', file, uploadResp); + + queuedRequest.done(); + + if (_this4.uploaderEvents[file.id]) { + _this4.uploaderEvents[file.id].remove(); + + _this4.uploaderEvents[file.id] = null; + } + + return resolve(); + }); + socket.on('error', function (errData) { + var resp = errData.response; + var error = resp ? opts.getResponseError(resp.responseText, resp) : _extends(new Error(errData.error.message), { + cause: errData.error + }); + + _this4.uppy.emit('upload-error', file, error); + + queuedRequest.done(); + + if (_this4.uploaderEvents[file.id]) { + _this4.uploaderEvents[file.id].remove(); + + _this4.uploaderEvents[file.id] = null; + } + + reject(error); + }); + + var queuedRequest = _this4.requests.run(function () { + socket.open(); + + if (file.isPaused) { + socket.send('pause', {}); + } + + return function () { + return socket.close(); + }; + }); + }).catch(function (err) { + _this4.uppy.emit('upload-error', file, err); + + reject(err); + }); + }); + }; + + return MiniXHRUpload; +}(); +},{"@uppy/companion-client":81,"@uppy/utils/lib/EventTracker":199,"@uppy/utils/lib/NetworkError":201,"@uppy/utils/lib/ProgressTimeout":202,"@uppy/utils/lib/emitSocketProgress":208,"@uppy/utils/lib/getSocketHost":223,"@uppy/utils/lib/isNetworkError":230,"cuid":16}],73:[function(require,module,exports){ +var _class, _temp; + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +/** + * This plugin is currently a A Big Hack™! The core reason for that is how this plugin + * interacts with Uppy's current pipeline design. The pipeline can handle files in steps, + * including preprocessing, uploading, and postprocessing steps. This plugin initially + * was designed to do its work in a preprocessing step, and let XHRUpload deal with the + * actual file upload as an uploading step. However, Uppy runs steps on all files at once, + * sequentially: first, all files go through a preprocessing step, then, once they are all + * done, they go through the uploading step. + * + * For S3, this causes severely broken behaviour when users upload many files. The + * preprocessing step will request S3 upload URLs that are valid for a short time only, + * but it has to do this for _all_ files, which can take a long time if there are hundreds + * or even thousands of files. By the time the uploader step starts, the first URLs may + * already have expired. If not, the uploading might take such a long time that later URLs + * will expire before some files can be uploaded. + * + * The long-term solution to this problem is to change the upload pipeline so that files + * can be sent to the next step individually. That requires a breakig change, so it is + * planned for Uppy v2. + * + * In the mean time, this plugin is stuck with a hackier approach: the necessary parts + * of the XHRUpload implementation were copied into this plugin, as the MiniXHRUpload + * class, and this plugin calls into it immediately once it receives an upload URL. + * This isn't as nicely modular as we'd like and requires us to maintain two copies of + * the XHRUpload code, but at least it's not horrifically broken :) + */ +// If global `URL` constructor is available, use it +var URL_ = typeof URL === 'function' ? URL : require('url-parse'); + +var _require = require('@uppy/core'), + Plugin = _require.Plugin; + +var Translator = require('@uppy/utils/lib/Translator'); + +var RateLimitedQueue = require('@uppy/utils/lib/RateLimitedQueue'); + +var settle = require('@uppy/utils/lib/settle'); + +var hasProperty = require('@uppy/utils/lib/hasProperty'); + +var _require2 = require('@uppy/companion-client'), + RequestClient = _require2.RequestClient; + +var qsStringify = require('qs-stringify'); + +var MiniXHRUpload = require('./MiniXHRUpload'); + +var isXml = require('./isXml'); + +function resolveUrl(origin, link) { + return origin ? new URL_(link, origin).toString() : new URL_(link).toString(); +} +/** + * Get the contents of a named tag in an XML source string. + * + * @param {string} source - The XML source string. + * @param {string} tagName - The name of the tag. + * @returns {string} The contents of the tag, or the empty string if the tag does not exist. + */ + + +function getXmlValue(source, tagName) { + var start = source.indexOf("<" + tagName + ">"); + var end = source.indexOf("", start); + return start !== -1 && end !== -1 ? source.slice(start + tagName.length + 2, end) : ''; +} + +function assertServerError(res) { + if (res && res.error) { + var error = new Error(res.message); + + _extends(error, res.error); + + throw error; + } + + return res; +} // warning deduplication flag: see `getResponseData()` XHRUpload option definition + + +var warnedSuccessActionStatus = false; +module.exports = (_temp = _class = /*#__PURE__*/function (_Plugin) { + _inheritsLoose(AwsS3, _Plugin); + + function AwsS3(uppy, opts) { + var _this; + + _this = _Plugin.call(this, uppy, opts) || this; + _this.type = 'uploader'; + _this.id = _this.opts.id || 'AwsS3'; + _this.title = 'AWS S3'; + _this.defaultLocale = { + strings: { + timedOut: 'Upload stalled for %{seconds} seconds, aborting.' + } + }; + var defaultOptions = { + timeout: 30 * 1000, + limit: 0, + metaFields: [], + // have to opt in + getUploadParameters: _this.getUploadParameters.bind(_assertThisInitialized(_this)) + }; + _this.opts = _extends({}, defaultOptions, opts); + + _this.i18nInit(); + + _this.client = new RequestClient(uppy, opts); + _this.handleUpload = _this.handleUpload.bind(_assertThisInitialized(_this)); + _this.requests = new RateLimitedQueue(_this.opts.limit); + return _this; + } + + var _proto = AwsS3.prototype; + + _proto.setOptions = function setOptions(newOpts) { + _Plugin.prototype.setOptions.call(this, newOpts); + + this.i18nInit(); + }; + + _proto.i18nInit = function i18nInit() { + this.translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale]); + this.i18n = this.translator.translate.bind(this.translator); + this.setPluginState(); // so that UI re-renders and we see the updated locale + }; + + _proto.getUploadParameters = function getUploadParameters(file) { + if (!this.opts.companionUrl) { + throw new Error('Expected a `companionUrl` option containing a Companion address.'); + } + + var filename = file.meta.name; + var type = file.meta.type; + var metadata = {}; + this.opts.metaFields.forEach(function (key) { + if (file.meta[key] != null) { + metadata[key] = file.meta[key].toString(); + } + }); + var query = qsStringify({ + filename: filename, + type: type, + metadata: metadata + }); + return this.client.get("s3/params?" + query).then(assertServerError); + }; + + _proto.validateParameters = function validateParameters(file, params) { + var valid = typeof params === 'object' && params && typeof params.url === 'string' && (typeof params.fields === 'object' || params.fields == null); + + if (!valid) { + var err = new TypeError("AwsS3: got incorrect result from 'getUploadParameters()' for file '" + file.name + "', expected an object '{ url, method, fields, headers }' but got '" + JSON.stringify(params) + "' instead.\nSee https://uppy.io/docs/aws-s3/#getUploadParameters-file for more on the expected format."); + console.error(err); + throw err; + } + + var methodIsValid = params.method == null || /^(put|post)$/i.test(params.method); + + if (!methodIsValid) { + var _err = new TypeError("AwsS3: got incorrect method from 'getUploadParameters()' for file '" + file.name + "', expected 'put' or 'post' but got '" + params.method + "' instead.\nSee https://uppy.io/docs/aws-s3/#getUploadParameters-file for more on the expected format."); + + console.error(_err); + throw _err; + } + }; + + _proto.handleUpload = function handleUpload(fileIDs) { + var _this2 = this; + + /** + * keep track of `getUploadParameters()` responses + * so we can cancel the calls individually using just a file ID + * + * @type {object.} + */ + var paramsPromises = Object.create(null); + + function onremove(file) { + var id = file.id; + + if (hasProperty(paramsPromises, id)) { + paramsPromises[id].abort(); + } + } + + this.uppy.on('file-removed', onremove); + fileIDs.forEach(function (id) { + var file = _this2.uppy.getFile(id); + + _this2.uppy.emit('upload-started', file); + }); + var getUploadParameters = this.requests.wrapPromiseFunction(function (file) { + return _this2.opts.getUploadParameters(file); + }); + var numberOfFiles = fileIDs.length; + return settle(fileIDs.map(function (id, index) { + paramsPromises[id] = getUploadParameters(_this2.uppy.getFile(id)); + return paramsPromises[id].then(function (params) { + delete paramsPromises[id]; + + var file = _this2.uppy.getFile(id); + + _this2.validateParameters(file, params); + + var _params$method = params.method, + method = _params$method === void 0 ? 'post' : _params$method, + url = params.url, + fields = params.fields, + headers = params.headers; + var xhrOpts = { + method: method, + formData: method.toLowerCase() === 'post', + endpoint: url, + metaFields: fields ? Object.keys(fields) : [] + }; + + if (headers) { + xhrOpts.headers = headers; + } + + _this2.uppy.setFileState(file.id, { + meta: _extends({}, file.meta, fields), + xhrUpload: xhrOpts + }); + + return _this2._uploader.uploadFile(file.id, index, numberOfFiles); + }).catch(function (error) { + delete paramsPromises[id]; + + var file = _this2.uppy.getFile(id); + + _this2.uppy.emit('upload-error', file, error); + }); + })).then(function (settled) { + // cleanup. + _this2.uppy.off('file-removed', onremove); + + return settled; + }); + }; + + _proto.install = function install() { + var uppy = this.uppy; + this.uppy.addUploader(this.handleUpload); // Get the response data from a successful XMLHttpRequest instance. + // `content` is the S3 response as a string. + // `xhr` is the XMLHttpRequest instance. + + function defaultGetResponseData(content, xhr) { + var opts = this; // If no response, we've hopefully done a PUT request to the file + // in the bucket on its full URL. + + if (!isXml(content, xhr)) { + if (opts.method.toUpperCase() === 'POST') { + if (!warnedSuccessActionStatus) { + uppy.log('[AwsS3] No response data found, make sure to set the success_action_status AWS SDK option to 201. See https://uppy.io/docs/aws-s3/#POST-Uploads', 'warning'); + warnedSuccessActionStatus = true; + } // The responseURL won't contain the object key. Give up. + + + return { + location: null + }; + } // responseURL is not available in older browsers. + + + if (!xhr.responseURL) { + return { + location: null + }; + } // Trim the query string because it's going to be a bunch of presign + // parameters for a PUT request—doing a GET request with those will + // always result in an error + + + return { + location: xhr.responseURL.replace(/\?.*$/, '') + }; + } + + return { + // Some S3 alternatives do not reply with an absolute URL. + // Eg DigitalOcean Spaces uses /$bucketName/xyz + location: resolveUrl(xhr.responseURL, getXmlValue(content, 'Location')), + bucket: getXmlValue(content, 'Bucket'), + key: getXmlValue(content, 'Key'), + etag: getXmlValue(content, 'ETag') + }; + } // Get the error data from a failed XMLHttpRequest instance. + // `content` is the S3 response as a string. + // `xhr` is the XMLHttpRequest instance. + + + function defaultGetResponseError(content, xhr) { + // If no response, we don't have a specific error message, use the default. + if (!isXml(content, xhr)) { + return; + } + + var error = getXmlValue(content, 'Message'); + return new Error(error); + } + + var xhrOptions = { + fieldName: 'file', + responseUrlFieldName: 'location', + timeout: this.opts.timeout, + // Share the rate limiting queue with XHRUpload. + __queue: this.requests, + responseType: 'text', + getResponseData: this.opts.getResponseData || defaultGetResponseData, + getResponseError: defaultGetResponseError + }; // Only for MiniXHRUpload, remove once we can depend on XHRUpload directly again + + xhrOptions.i18n = this.i18n; // Revert to `this.uppy.use(XHRUpload)` once the big comment block at the top of + // this file is solved + + this._uploader = new MiniXHRUpload(this.uppy, xhrOptions); + }; + + _proto.uninstall = function uninstall() { + this.uppy.removePreProcessor(this.handleUpload); + }; + + return AwsS3; +}(Plugin), _class.VERSION = "1.7.8", _temp); +},{"./MiniXHRUpload":72,"./isXml":74,"@uppy/companion-client":81,"@uppy/core":84,"@uppy/utils/lib/RateLimitedQueue":203,"@uppy/utils/lib/Translator":204,"@uppy/utils/lib/hasProperty":227,"@uppy/utils/lib/settle":237,"qs-stringify":40,"url-parse":66}],74:[function(require,module,exports){ +/** + * Remove parameters like `charset=utf-8` from the end of a mime type string. + * + * @param {string} mimeType - The mime type string that may have optional parameters. + * @returns {string} The "base" mime type, i.e. only 'category/type'. + */ +function removeMimeParameters(mimeType) { + return mimeType.replace(/;.*$/, ''); +} +/** + * Check if a response contains XML based on the response object and its text content. + * + * @param {string} content - The text body of the response. + * @param {object|XMLHttpRequest} xhr - The XHR object or response object from Companion. + * @returns {bool} Whether the content is (probably) XML. + */ + + +function isXml(content, xhr) { + var rawContentType = xhr.headers ? xhr.headers['content-type'] : xhr.getResponseHeader('Content-Type'); + + if (typeof rawContentType === 'string') { + var contentType = removeMimeParameters(rawContentType).toLowerCase(); + + if (contentType === 'application/xml' || contentType === 'text/xml') { + return true; + } // GCS uses text/html for some reason + // https://github.com/transloadit/uppy/issues/896 + + + if (contentType === 'text/html' && /^<\?xml /.test(content)) { + return true; + } + } + + return false; +} + +module.exports = isXml; +},{}],75:[function(require,module,exports){ +var _class, _temp; + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var _require = require('@uppy/core'), + Plugin = _require.Plugin; + +var _require2 = require('@uppy/companion-client'), + Provider = _require2.Provider; + +var _require3 = require('@uppy/provider-views'), + ProviderViews = _require3.ProviderViews; + +var _require4 = require('preact'), + h = _require4.h; + +module.exports = (_temp = _class = /*#__PURE__*/function (_Plugin) { + _inheritsLoose(Box, _Plugin); + + function Box(uppy, opts) { + var _this; + + _this = _Plugin.call(this, uppy, opts) || this; + _this.id = _this.opts.id || 'Box'; + Provider.initPlugin(_assertThisInitialized(_this), opts); + _this.title = _this.opts.title || 'Box'; + + _this.icon = function () { + return h("svg", { + "aria-hidden": "true", + focusable: "false", + width: "32", + height: "32", + viewBox: "0 0 32 32" + }, h("g", { + fill: "none", + "fill-rule": "evenodd" + }, h("rect", { + class: "uppy-ProviderIconBg", + fill: "#0061D5", + width: "32", + height: "32", + rx: "16" + }), h("g", { + fill: "#fff", + "fill-rule": "nonzero" + }, h("path", { + d: "m16.4 13.5c-1.6 0-3 0.9-3.7 2.2-0.7-1.3-2.1-2.2-3.7-2.2-1 0-1.8 0.3-2.5 0.8v-3.6c-0.1-0.3-0.5-0.7-1-0.7s-0.8 0.4-0.8 0.8v7c0 2.3 1.9 4.2 4.2 4.2 1.6 0 3-0.9 3.7-2.2 0.7 1.3 2.1 2.2 3.7 2.2 2.3 0 4.2-1.9 4.2-4.2 0.1-2.4-1.8-4.3-4.1-4.3m-7.5 6.8c-1.4 0-2.5-1.1-2.5-2.5s1.1-2.5 2.5-2.5 2.5 1.1 2.5 2.5-1.1 2.5-2.5 2.5m7.5 0c-1.4 0-2.5-1.1-2.5-2.5s1.1-2.5 2.5-2.5 2.5 1.1 2.5 2.5-1.1 2.5-2.5 2.5" + }), h("path", { + d: "m27.2 20.6l-2.3-2.8 2.3-2.8c0.3-0.4 0.2-0.9-0.2-1.2s-1-0.2-1.3 0.2l-2 2.4-2-2.4c-0.3-0.4-0.9-0.4-1.3-0.2-0.4 0.3-0.5 0.8-0.2 1.2l2.3 2.8-2.3 2.8c-0.3 0.4-0.2 0.9 0.2 1.2s1 0.2 1.3-0.2l2-2.4 2 2.4c0.3 0.4 0.9 0.4 1.3 0.2 0.4-0.3 0.4-0.8 0.2-1.2" + })))); + }; + + _this.provider = new Provider(uppy, { + companionUrl: _this.opts.companionUrl, + companionHeaders: _this.opts.companionHeaders || _this.opts.serverHeaders, + provider: 'box', + pluginId: _this.id + }); + _this.onFirstRender = _this.onFirstRender.bind(_assertThisInitialized(_this)); + _this.render = _this.render.bind(_assertThisInitialized(_this)); + return _this; + } + + var _proto = Box.prototype; + + _proto.install = function install() { + this.view = new ProviderViews(this, { + provider: this.provider + }); + var target = this.opts.target; + + if (target) { + this.mount(target, this); + } + }; + + _proto.uninstall = function uninstall() { + this.view.tearDown(); + this.unmount(); + }; + + _proto.onFirstRender = function onFirstRender() { + return this.view.getFolder(); + }; + + _proto.render = function render(state) { + return this.view.render(state); + }; + + return Box; +}(Plugin), _class.VERSION = "0.3.7", _temp); +},{"@uppy/companion-client":81,"@uppy/core":84,"@uppy/provider-views":148,"preact":38}],76:[function(require,module,exports){ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +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; } 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 { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } + +function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } + +function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } + +function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } + +var AuthError = /*#__PURE__*/function (_Error) { + _inheritsLoose(AuthError, _Error); + + function AuthError() { + var _this; + + _this = _Error.call(this, 'Authorization required') || this; + _this.name = 'AuthError'; + _this.isAuthError = true; + return _this; + } + + return AuthError; +}( /*#__PURE__*/_wrapNativeSuper(Error)); + +module.exports = AuthError; +},{}],77:[function(require,module,exports){ +'use strict'; + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var qsStringify = require('qs-stringify'); + +var RequestClient = require('./RequestClient'); + +var tokenStorage = require('./tokenStorage'); + +var _getName = function _getName(id) { + return id.split('-').map(function (s) { + return s.charAt(0).toUpperCase() + s.slice(1); + }).join(' '); +}; + +module.exports = /*#__PURE__*/function (_RequestClient) { + _inheritsLoose(Provider, _RequestClient); + + function Provider(uppy, opts) { + var _this; + + _this = _RequestClient.call(this, uppy, opts) || this; + _this.provider = opts.provider; + _this.id = _this.provider; + _this.name = _this.opts.name || _getName(_this.id); + _this.pluginId = _this.opts.pluginId; + _this.tokenKey = "companion-" + _this.pluginId + "-auth-token"; + _this.companionKeysParams = _this.opts.companionKeysParams; + _this.preAuthToken = null; + return _this; + } + + var _proto = Provider.prototype; + + _proto.headers = function headers() { + var _this2 = this; + + return Promise.all([_RequestClient.prototype.headers.call(this), this.getAuthToken()]).then(function (_ref) { + var headers = _ref[0], + token = _ref[1]; + var authHeaders = {}; + + if (token) { + authHeaders['uppy-auth-token'] = token; + } + + if (_this2.companionKeysParams) { + authHeaders['uppy-credentials-params'] = btoa(JSON.stringify({ + params: _this2.companionKeysParams + })); + } + + return _extends({}, headers, authHeaders); + }); + }; + + _proto.onReceiveResponse = function onReceiveResponse(response) { + response = _RequestClient.prototype.onReceiveResponse.call(this, response); + var plugin = this.uppy.getPlugin(this.pluginId); + var oldAuthenticated = plugin.getPluginState().authenticated; + var authenticated = oldAuthenticated ? response.status !== 401 : response.status < 400; + plugin.setPluginState({ + authenticated: authenticated + }); + return response; + } // @todo(i.olarewaju) consider whether or not this method should be exposed + ; + + _proto.setAuthToken = function setAuthToken(token) { + return this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token); + }; + + _proto.getAuthToken = function getAuthToken() { + return this.uppy.getPlugin(this.pluginId).storage.getItem(this.tokenKey); + }; + + _proto.authUrl = function authUrl(queries) { + if (queries === void 0) { + queries = {}; + } + + if (this.preAuthToken) { + queries.uppyPreAuthToken = this.preAuthToken; + } + + var strigifiedQueries = qsStringify(queries); + strigifiedQueries = strigifiedQueries ? "?" + strigifiedQueries : strigifiedQueries; + return this.hostname + "/" + this.id + "/connect" + strigifiedQueries; + }; + + _proto.fileUrl = function fileUrl(id) { + return this.hostname + "/" + this.id + "/get/" + id; + }; + + _proto.fetchPreAuthToken = function fetchPreAuthToken() { + var _this3 = this; + + if (!this.companionKeysParams) { + return Promise.resolve(); + } + + return this.post(this.id + "/preauth/", { + params: this.companionKeysParams + }).then(function (res) { + _this3.preAuthToken = res.token; + }).catch(function (err) { + _this3.uppy.log("[CompanionClient] unable to fetch preAuthToken " + err, 'warning'); + }); + }; + + _proto.list = function list(directory) { + return this.get(this.id + "/list/" + (directory || '')); + }; + + _proto.logout = function logout() { + var _this4 = this; + + return this.get(this.id + "/logout").then(function (response) { + return Promise.all([response, _this4.uppy.getPlugin(_this4.pluginId).storage.removeItem(_this4.tokenKey)]); + }).then(function (_ref2) { + var response = _ref2[0]; + return response; + }); + }; + + Provider.initPlugin = function initPlugin(plugin, opts, defaultOpts) { + plugin.type = 'acquirer'; + plugin.files = []; + + if (defaultOpts) { + plugin.opts = _extends({}, defaultOpts, opts); + } + + if (opts.serverUrl || opts.serverPattern) { + throw new Error('`serverUrl` and `serverPattern` have been renamed to `companionUrl` and `companionAllowedHosts` respectively in the 0.30.5 release. Please consult the docs (for example, https://uppy.io/docs/instagram/ for the Instagram plugin) and use the updated options.`'); + } + + if (opts.companionAllowedHosts) { + var pattern = opts.companionAllowedHosts; // validate companionAllowedHosts param + + if (typeof pattern !== 'string' && !Array.isArray(pattern) && !(pattern instanceof RegExp)) { + throw new TypeError(plugin.id + ": the option \"companionAllowedHosts\" must be one of string, Array, RegExp"); + } + + plugin.opts.companionAllowedHosts = pattern; + } else { + // does not start with https:// + if (/^(?!https?:\/\/).*$/i.test(opts.companionUrl)) { + plugin.opts.companionAllowedHosts = "https://" + opts.companionUrl.replace(/^\/\//, ''); + } else { + plugin.opts.companionAllowedHosts = opts.companionUrl; + } + } + + plugin.storage = plugin.opts.storage || tokenStorage; + }; + + return Provider; +}(RequestClient); +},{"./RequestClient":78,"./tokenStorage":82,"qs-stringify":40}],78:[function(require,module,exports){ +'use strict'; + +var _class, _temp; + +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } + +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } + +var AuthError = require('./AuthError'); + +var fetchWithNetworkError = require('@uppy/utils/lib/fetchWithNetworkError'); // Remove the trailing slash so we can always safely append /xyz. + + +function stripSlash(url) { + return url.replace(/\/$/, ''); +} + +module.exports = (_temp = _class = /*#__PURE__*/function () { + function RequestClient(uppy, opts) { + this.uppy = uppy; + this.opts = opts; + this.onReceiveResponse = this.onReceiveResponse.bind(this); + this.allowedHeaders = ['accept', 'content-type', 'uppy-auth-token']; + this.preflightDone = false; + } + + var _proto = RequestClient.prototype; + + _proto.headers = function headers() { + var userHeaders = this.opts.companionHeaders || this.opts.serverHeaders || {}; + return Promise.resolve(_extends({}, this.defaultHeaders, userHeaders)); + }; + + _proto._getPostResponseFunc = function _getPostResponseFunc(skip) { + var _this = this; + + return function (response) { + if (!skip) { + return _this.onReceiveResponse(response); + } + + return response; + }; + }; + + _proto.onReceiveResponse = function onReceiveResponse(response) { + var state = this.uppy.getState(); + var companion = state.companion || {}; + var host = this.opts.companionUrl; + var headers = response.headers; // Store the self-identified domain name for the Companion instance we just hit. + + if (headers.has('i-am') && headers.get('i-am') !== companion[host]) { + var _extends2; + + this.uppy.setState({ + companion: _extends({}, companion, (_extends2 = {}, _extends2[host] = headers.get('i-am'), _extends2)) + }); + } + + return response; + }; + + _proto._getUrl = function _getUrl(url) { + if (/^(https?:|)\/\//.test(url)) { + return url; + } + + return this.hostname + "/" + url; + }; + + _proto._json = function _json(res) { + if (res.status === 401) { + throw new AuthError(); + } + + if (res.status < 200 || res.status > 300) { + var errMsg = "Failed request with status: " + res.status + ". " + res.statusText; + return res.json().then(function (errData) { + errMsg = errData.message ? errMsg + " message: " + errData.message : errMsg; + errMsg = errData.requestId ? errMsg + " request-Id: " + errData.requestId : errMsg; + throw new Error(errMsg); + }).catch(function () { + throw new Error(errMsg); + }); + } + + return res.json(); + }; + + _proto.preflight = function preflight(path) { + var _this2 = this; + + if (this.preflightDone) { + return Promise.resolve(this.allowedHeaders.slice()); + } + + return fetch(this._getUrl(path), { + method: 'OPTIONS' + }).then(function (response) { + if (response.headers.has('access-control-allow-headers')) { + _this2.allowedHeaders = response.headers.get('access-control-allow-headers').split(',').map(function (headerName) { + return headerName.trim().toLowerCase(); + }); + } + + _this2.preflightDone = true; + return _this2.allowedHeaders.slice(); + }).catch(function (err) { + _this2.uppy.log("[CompanionClient] unable to make preflight request " + err, 'warning'); + + _this2.preflightDone = true; + return _this2.allowedHeaders.slice(); + }); + }; + + _proto.preflightAndHeaders = function preflightAndHeaders(path) { + var _this3 = this; + + return Promise.all([this.preflight(path), this.headers()]).then(function (_ref) { + var allowedHeaders = _ref[0], + headers = _ref[1]; + // filter to keep only allowed Headers + Object.keys(headers).forEach(function (header) { + if (allowedHeaders.indexOf(header.toLowerCase()) === -1) { + _this3.uppy.log("[CompanionClient] excluding unallowed header " + header); + + delete headers[header]; + } + }); + return headers; + }); + }; + + _proto.get = function get(path, skipPostResponse) { + var _this4 = this; + + return this.preflightAndHeaders(path).then(function (headers) { + return fetchWithNetworkError(_this4._getUrl(path), { + method: 'get', + headers: headers, + credentials: _this4.opts.companionCookiesRule || 'same-origin' + }); + }).then(this._getPostResponseFunc(skipPostResponse)).then(function (res) { + return _this4._json(res); + }).catch(function (err) { + err = err.isAuthError ? err : new Error("Could not get " + _this4._getUrl(path) + ". " + err); + return Promise.reject(err); + }); + }; + + _proto.post = function post(path, data, skipPostResponse) { + var _this5 = this; + + return this.preflightAndHeaders(path).then(function (headers) { + return fetchWithNetworkError(_this5._getUrl(path), { + method: 'post', + headers: headers, + credentials: _this5.opts.companionCookiesRule || 'same-origin', + body: JSON.stringify(data) + }); + }).then(this._getPostResponseFunc(skipPostResponse)).then(function (res) { + return _this5._json(res); + }).catch(function (err) { + err = err.isAuthError ? err : new Error("Could not post " + _this5._getUrl(path) + ". " + err); + return Promise.reject(err); + }); + }; + + _proto.delete = function _delete(path, data, skipPostResponse) { + var _this6 = this; + + return this.preflightAndHeaders(path).then(function (headers) { + return fetchWithNetworkError(_this6.hostname + "/" + path, { + method: 'delete', + headers: headers, + credentials: _this6.opts.companionCookiesRule || 'same-origin', + body: data ? JSON.stringify(data) : null + }); + }).then(this._getPostResponseFunc(skipPostResponse)).then(function (res) { + return _this6._json(res); + }).catch(function (err) { + err = err.isAuthError ? err : new Error("Could not delete " + _this6._getUrl(path) + ". " + err); + return Promise.reject(err); + }); + }; + + _createClass(RequestClient, [{ + key: "hostname", + get: function get() { + var _this$uppy$getState = this.uppy.getState(), + companion = _this$uppy$getState.companion; + + var host = this.opts.companionUrl; + return stripSlash(companion && companion[host] ? companion[host] : host); + } + }, { + key: "defaultHeaders", + get: function get() { + return { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'Uppy-Versions': "@uppy/companion-client=" + RequestClient.VERSION + }; + } + }]); + + return RequestClient; +}(), _class.VERSION = "1.8.3", _temp); +},{"./AuthError":76,"@uppy/utils/lib/fetchWithNetworkError":209}],79:[function(require,module,exports){ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var RequestClient = require('./RequestClient'); + +var _getName = function _getName(id) { + return id.split('-').map(function (s) { + return s.charAt(0).toUpperCase() + s.slice(1); + }).join(' '); +}; + +module.exports = /*#__PURE__*/function (_RequestClient) { + _inheritsLoose(SearchProvider, _RequestClient); + + function SearchProvider(uppy, opts) { + var _this; + + _this = _RequestClient.call(this, uppy, opts) || this; + _this.provider = opts.provider; + _this.id = _this.provider; + _this.name = _this.opts.name || _getName(_this.id); + _this.pluginId = _this.opts.pluginId; + return _this; + } + + var _proto = SearchProvider.prototype; + + _proto.fileUrl = function fileUrl(id) { + return this.hostname + "/search/" + this.id + "/get/" + id; + }; + + _proto.search = function search(text, queries) { + queries = queries ? "&" + queries : ''; + return this.get("search/" + this.id + "/list?q=" + encodeURIComponent(text) + queries); + }; + + return SearchProvider; +}(RequestClient); +},{"./RequestClient":78}],80:[function(require,module,exports){ +var ee = require('namespace-emitter'); + +module.exports = /*#__PURE__*/function () { + function UppySocket(opts) { + this.opts = opts; + this._queued = []; + this.isOpen = false; + this.emitter = ee(); + this._handleMessage = this._handleMessage.bind(this); + this.close = this.close.bind(this); + this.emit = this.emit.bind(this); + this.on = this.on.bind(this); + this.once = this.once.bind(this); + this.send = this.send.bind(this); + + if (!opts || opts.autoOpen !== false) { + this.open(); + } + } + + var _proto = UppySocket.prototype; + + _proto.open = function open() { + var _this = this; + + this.socket = new WebSocket(this.opts.target); + + this.socket.onopen = function (e) { + _this.isOpen = true; + + while (_this._queued.length > 0 && _this.isOpen) { + var first = _this._queued[0]; + + _this.send(first.action, first.payload); + + _this._queued = _this._queued.slice(1); + } + }; + + this.socket.onclose = function (e) { + _this.isOpen = false; + }; + + this.socket.onmessage = this._handleMessage; + }; + + _proto.close = function close() { + if (this.socket) { + this.socket.close(); + } + }; + + _proto.send = function send(action, payload) { + // attach uuid + if (!this.isOpen) { + this._queued.push({ + action: action, + payload: payload + }); + + return; + } + + this.socket.send(JSON.stringify({ + action: action, + payload: payload + })); + }; + + _proto.on = function on(action, handler) { + this.emitter.on(action, handler); + }; + + _proto.emit = function emit(action, payload) { + this.emitter.emit(action, payload); + }; + + _proto.once = function once(action, handler) { + this.emitter.once(action, handler); + }; + + _proto._handleMessage = function _handleMessage(e) { + try { + var message = JSON.parse(e.data); + this.emit(message.action, message.payload); + } catch (err) { + console.log(err); + } + }; + + return UppySocket; +}(); +},{"namespace-emitter":35}],81:[function(require,module,exports){ +'use strict'; +/** + * Manages communications with Companion + */ + +var RequestClient = require('./RequestClient'); + +var Provider = require('./Provider'); + +var SearchProvider = require('./SearchProvider'); + +var Socket = require('./Socket'); + +module.exports = { + RequestClient: RequestClient, + Provider: Provider, + SearchProvider: SearchProvider, + Socket: Socket +}; +},{"./Provider":77,"./RequestClient":78,"./SearchProvider":79,"./Socket":80}],82:[function(require,module,exports){ +'use strict'; +/** + * This module serves as an Async wrapper for LocalStorage + */ + +module.exports.setItem = function (key, value) { + return new Promise(function (resolve) { + localStorage.setItem(key, value); + resolve(); + }); +}; + +module.exports.getItem = function (key) { + return Promise.resolve(localStorage.getItem(key)); +}; + +module.exports.removeItem = function (key) { + return new Promise(function (resolve) { + localStorage.removeItem(key); + resolve(); + }); +}; +},{}],83:[function(require,module,exports){ +function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } + +var preact = require('preact'); + +var findDOMElement = require('@uppy/utils/lib/findDOMElement'); +/** + * Defer a frequent call to the microtask queue. + */ + + +function debounce(fn) { + var calling = null; + var latestArgs = null; + return function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + latestArgs = args; + + if (!calling) { + calling = Promise.resolve().then(function () { + calling = null; // At this point `args` may be different from the most + // recent state, if multiple calls happened since this task + // was queued. So we use the `latestArgs`, which definitely + // is the most recent call. + + return fn.apply(void 0, latestArgs); + }); + } + + return calling; + }; +} +/** + * Boilerplate that all Plugins share - and should not be used + * directly. It also shows which methods final plugins should implement/override, + * this deciding on structure. + * + * @param {object} main Uppy core object + * @param {object} object with plugin options + * @returns {Array|string} files or success/fail message + */ + + +module.exports = /*#__PURE__*/function () { + function Plugin(uppy, opts) { + this.uppy = uppy; + this.opts = opts || {}; + this.update = this.update.bind(this); + this.mount = this.mount.bind(this); + this.install = this.install.bind(this); + this.uninstall = this.uninstall.bind(this); + } + + var _proto = Plugin.prototype; + + _proto.getPluginState = function getPluginState() { + var _this$uppy$getState = this.uppy.getState(), + plugins = _this$uppy$getState.plugins; + + return plugins[this.id] || {}; + }; + + _proto.setPluginState = function setPluginState(update) { + var _extends2; + + var _this$uppy$getState2 = this.uppy.getState(), + plugins = _this$uppy$getState2.plugins; + + this.uppy.setState({ + plugins: _extends({}, plugins, (_extends2 = {}, _extends2[this.id] = _extends({}, plugins[this.id], update), _extends2)) + }); + }; + + _proto.setOptions = function setOptions(newOpts) { + this.opts = _extends({}, this.opts, newOpts); + this.setPluginState(); // so that UI re-renders with new options + }; + + _proto.update = function update(state) { + if (typeof this.el === 'undefined') { + return; + } + + if (this._updateUI) { + this._updateUI(state); + } + } // Called after every state update, after everything's mounted. Debounced. + ; + + _proto.afterUpdate = function afterUpdate() {} + /** + * Called when plugin is mounted, whether in DOM or into another plugin. + * Needed because sometimes plugins are mounted separately/after `install`, + * so this.el and this.parent might not be available in `install`. + * This is the case with @uppy/react plugins, for example. + */ + ; + + _proto.onMount = function onMount() {} + /** + * Check if supplied `target` is a DOM element or an `object`. + * If it’s an object — target is a plugin, and we search `plugins` + * for a plugin with same name and return its target. + * + * @param {string|object} target + * + */ + ; + + _proto.mount = function mount(target, plugin) { + var _this = this; + + var callerPluginName = plugin.id; + var targetElement = findDOMElement(target); + + if (targetElement) { + this.isTargetDOMEl = true; // API for plugins that require a synchronous rerender. + + this.rerender = function (state) { + // plugin could be removed, but this.rerender is debounced below, + // so it could still be called even after uppy.removePlugin or uppy.close + // hence the check + if (!_this.uppy.getPlugin(_this.id)) return; + _this.el = preact.render(_this.render(state), targetElement, _this.el); + + _this.afterUpdate(); + }; + + this._updateUI = debounce(this.rerender); + this.uppy.log("Installing " + callerPluginName + " to a DOM element '" + target + "'"); // clear everything inside the target container + + if (this.opts.replaceTargetContent) { + targetElement.innerHTML = ''; + } + + this.el = preact.render(this.render(this.uppy.getState()), targetElement); + this.onMount(); + return this.el; + } + + var targetPlugin; + + if (typeof target === 'object' && target instanceof Plugin) { + // Targeting a plugin *instance* + targetPlugin = target; + } else if (typeof target === 'function') { + // Targeting a plugin type + var Target = target; // Find the target plugin instance. + + this.uppy.iteratePlugins(function (plugin) { + if (plugin instanceof Target) { + targetPlugin = plugin; + return false; + } + }); + } + + if (targetPlugin) { + this.uppy.log("Installing " + callerPluginName + " to " + targetPlugin.id); + this.parent = targetPlugin; + this.el = targetPlugin.addTarget(plugin); + this.onMount(); + return this.el; + } + + this.uppy.log("Not installing " + callerPluginName); + var message = "Invalid target option given to " + callerPluginName + "."; + + if (typeof target === 'function') { + message += ' The given target is not a Plugin class. ' + 'Please check that you\'re not specifying a React Component instead of a plugin. ' + 'If you are using @uppy/* packages directly, make sure you have only 1 version of @uppy/core installed: ' + 'run `npm ls @uppy/core` on the command line and verify that all the versions match and are deduped correctly.'; + } else { + message += 'If you meant to target an HTML element, please make sure that the element exists. ' + 'Check that the