Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Uppy direct S3 multipart uploads in composer (#14051)

Martin Brennand295a16dab99
diff --git a/app/assets/javascripts/discourse-shims.js b/app/assets/javascripts/discourse-shims.js
index 71ce8478e37..3f038c12d85 100644
--- a/app/assets/javascripts/discourse-shims.js
+++ b/app/assets/javascripts/discourse-shims.js
@@ -32,7 +32,7 @@ define("@popperjs/core", ["exports"], function (__exports__) {
define("@uppy/core", ["exports"], function (__exports__) {
__exports__.default = window.Uppy.Core;
- __exports__.Plugin = window.Uppy.Plugin;
+ __exports__.BasePlugin = window.Uppy.BasePlugin;
});
define("@uppy/aws-s3", ["exports"], function (__exports__) {
diff --git a/app/assets/javascripts/discourse/app/lib/uppy-checksum-plugin.js b/app/assets/javascripts/discourse/app/lib/uppy-checksum-plugin.js
index 4cd0cea0476..3e74b36252f 100644
--- a/app/assets/javascripts/discourse/app/lib/uppy-checksum-plugin.js
+++ b/app/assets/javascripts/discourse/app/lib/uppy-checksum-plugin.js
@@ -1,8 +1,8 @@
-import { Plugin } from "@uppy/core";
+import { BasePlugin } from "@uppy/core";
import { warn } from "@ember/debug";
import { Promise } from "rsvp";
-export default class UppyChecksum extends Plugin {
+export default class UppyChecksum extends BasePlugin {
constructor(uppy, opts) {
super(uppy, opts);
this.id = opts.id || "uppy-checksum";
diff --git a/app/assets/javascripts/discourse/app/lib/uppy-media-optimization-plugin.js b/app/assets/javascripts/discourse/app/lib/uppy-media-optimization-plugin.js
index 3ba4cc8fca0..dcf3c3121ba 100644
--- a/app/assets/javascripts/discourse/app/lib/uppy-media-optimization-plugin.js
+++ b/app/assets/javascripts/discourse/app/lib/uppy-media-optimization-plugin.js
@@ -1,8 +1,8 @@
-import { Plugin } from "@uppy/core";
+import { BasePlugin } from "@uppy/core";
import { warn } from "@ember/debug";
import { Promise } from "rsvp";
-export default class UppyMediaOptimization extends Plugin {
+export default class UppyMediaOptimization extends BasePlugin {
constructor(uppy, opts) {
super(uppy, opts);
this.id = opts.id || "uppy-media-optimization";
@@ -30,7 +30,10 @@ export default class UppyMediaOptimization extends Plugin {
id: "discourse.uppy-media-optimization",
});
} else {
- this.uppy.setFileState(fileId, { data: optimizedFile });
+ this.uppy.setFileState(fileId, {
+ data: optimizedFile,
+ size: optimizedFile.size,
+ });
}
this.uppy.emit("preprocess-complete", this.pluginClass, file);
})
diff --git a/app/assets/javascripts/discourse/app/mixins/composer-upload-uppy.js b/app/assets/javascripts/discourse/app/mixins/composer-upload-uppy.js
index d7b88d7de43..97cd755e4a3 100644
--- a/app/assets/javascripts/discourse/app/mixins/composer-upload-uppy.js
+++ b/app/assets/javascripts/discourse/app/mixins/composer-upload-uppy.js
@@ -1,10 +1,12 @@
import Mixin from "@ember/object/mixin";
+import { ajax } from "discourse/lib/ajax";
import { deepMerge } from "discourse-common/lib/object";
import UppyChecksum from "discourse/lib/uppy-checksum-plugin";
import UppyMediaOptimization from "discourse/lib/uppy-media-optimization-plugin";
import Uppy from "@uppy/core";
import DropTarget from "@uppy/drop-target";
import XHRUpload from "@uppy/xhr-upload";
+import AwsS3Multipart from "@uppy/aws-s3-multipart";
import { warn } from "@ember/debug";
import I18n from "I18n";
import getURL from "discourse-common/lib/get-url";
@@ -70,6 +72,7 @@ export default Mixin.create({
_bindUploadTarget() {
this.placeholders = {};
+ this._inProgressUploads = 0;
this._preProcessorStatus = {};
this.fileInputEl = document.getElementById("file-uploader");
const isPrivateMessage = this.get("composer.privateMessage");
@@ -140,9 +143,12 @@ export default Mixin.create({
// name for the preprocess-X events.
this._trackPreProcessorStatus(UppyChecksum);
- // TODO (martin) support for direct S3 uploads will come later, for now
- // we just want the regular /uploads.json endpoint to work well
- this._useXHRUploads();
+ // hidden setting like enable_experimental_image_uploader
+ if (this.siteSettings.enable_direct_s3_uploads) {
+ this._useS3MultipartUploads();
+ } else {
+ this._useXHRUploads();
+ }
// TODO (martin) develop upload handler guidance and an API to use; will
// likely be using uppy plugins for this
@@ -171,6 +177,7 @@ export default Mixin.create({
});
files.forEach((file) => {
+ this._inProgressUploads++;
const placeholder = this._uploadPlaceholder(file);
this.placeholders[file.id] = {
uploadPlaceholder: placeholder,
@@ -199,14 +206,7 @@ export default Mixin.create({
this.appEvents.trigger("composer:upload-success", file.name, upload);
});
- this._uppyInstance.on("upload-error", (file, error, response) => {
- this._resetUpload(file, { removePlaceholder: true });
-
- if (!this.userCancelled) {
- displayErrorForUpload(response, this.siteSettings, file.name);
- this.appEvents.trigger("composer:upload-error", file);
- }
- });
+ this._uppyInstance.on("upload-error", this._handleUploadError.bind(this));
this._uppyInstance.on("complete", () => {
this.appEvents.trigger("composer:all-uploads-complete");
@@ -235,6 +235,20 @@ export default Mixin.create({
this._setupPreprocessing();
},
+ _handleUploadError(file, error, response) {
+ this._inProgressUploads--;
+ this._resetUpload(file, { removePlaceholder: true });
+
+ if (!this.userCancelled) {
+ displayErrorForUpload(response || error, this.siteSettings, file.name);
+ this.appEvents.trigger("composer:upload-error", file);
+ }
+
+ if (this._inProgressUploads === 0) {
+ this._reset();
+ }
+ },
+
_setupPreprocessing() {
Object.keys(this.uploadProcessorActions).forEach((action) => {
switch (action) {
@@ -343,6 +357,99 @@ export default Mixin.create({
});
},
+ _useS3MultipartUploads() {
+ const self = this;
+
+ this._uppyInstance.use(AwsS3Multipart, {
+ // controls how many simultaneous _chunks_ are uploaded, not files,
+ // which in turn controls the minimum number of chunks presigned
+ // in each batch (limit / 2)
+ //
+ // the default, and minimum, chunk size is 5mb. we can control the
+ // chunk size via getChunkSize(file), so we may want to increase
+ // the chunk size for larger files
+ limit: 10,
+
+ createMultipartUpload(file) {
+ return ajax("/uploads/create-multipart.json", {
+ type: "POST",
+ data: {
+ file_name: file.name,
+ file_size: file.size,
+ upload_type: file.meta.upload_type,
+ },
+ // uppy is inconsistent, an error here fires the upload-error event
+ }).then((data) => {
+ file.meta.unique_identifier = data.unique_identifier;
+ return {
+ uploadId: data.external_upload_identifier,
+ key: data.key,
+ };
+ });
+ },
+
+ prepareUploadParts(file, partData) {
+ return (
+ ajax("/uploads/batch-presign-multipart-parts.json", {
+ type: "POST",
+ data: {
+ part_numbers: partData.partNumbers,
+ unique_identifier: file.meta.unique_identifier,
+ },
+ })
+ .then((data) => {
+ return { presignedUrls: data.presigned_urls };
+ })
+ // uppy is inconsistent, an error here does not fire the upload-error event
+ .catch((err) => {
+ self._handleUploadError(file, err);
+ })
+ );
+ },
+
+ completeMultipartUpload(file, data) {
+ const parts = data.parts.map((part) => {
+ return { part_number: part.PartNumber, etag: part.ETag };
+ });
+ return ajax("/uploads/complete-multipart.json", {
+ type: "POST",
+ contentType: "application/json",
+ data: JSON.stringify({
+ parts,
+ unique_identifier: file.meta.unique_identifier,
+ }),
+ // uppy is inconsistent, an error here fires the upload-error event
+ }).then((responseData) => {
+ return responseData;
+ });
+ },
+
+ abortMultipartUpload(file, { key, uploadId }) {
+ // if the user cancels the upload before the key and uploadId
+ // are stored from the createMultipartUpload response then they
+ // will not be set, and we don't have to abort the upload because
+ // it will not exist yet
+ if (!key || !uploadId) {
+ return;
+ }
+
+ return ajax("/uploads/abort-multipart.json", {
+ type: "POST",
+ data: {
+ external_upload_identifier: uploadId,
+ },
+ // uppy is inconsistent, an error here does not fire the upload-error event
+ }).catch((err) => {
+ self._handleUploadError(file, err);
+ });
+ },
+
+ // we will need a listParts function at some point when we want to
+ // resume multipart uploads; this is used by uppy to figure out
+ // what parts are uploaded and which still need to be
+ });
+ },
+
_reset() {
this._uppyInstance?.reset();
this.setProperties({
diff --git a/app/assets/javascripts/discourse/app/mixins/uppy-upload.js b/app/assets/javascripts/discourse/app/mixins/uppy-upload.js
index d4d0d4770d9..101fce1ccc9 100644
--- a/app/assets/javascripts/discourse/app/mixins/uppy-upload.js
+++ b/app/assets/javascripts/discourse/app/mixins/uppy-upload.js
@@ -175,7 +175,11 @@ export default Mixin.create({
this.set("usingS3Uploads", true);
this._uppyInstance.use(AwsS3, {
getUploadParameters: (file) => {
- const data = { file_name: file.name, type: this.type };
+ const data = {
+ file_name: file.name,
+ file_size: file.size,
+ type: this.type,
+ };
// the sha1 checksum is set by the UppyChecksum plugin, except
// for in cases where the browser does not support the required
diff --git a/app/controllers/uploads_controller.rb b/app/controllers/uploads_controller.rb
index 2048a9fc169..0a5c0bb0560 100644
--- a/app/controllers/uploads_controller.rb
+++ b/app/controllers/uploads_controller.rb
@@ -9,14 +9,30 @@ class UploadsController < ApplicationController
protect_from_forgery except: :show
before_action :is_asset_path, :apply_cdn_headers, only: [:show, :show_short, :show_secure]
- before_action :external_store_check, only: [:show_secure, :generate_presigned_put, :complete_external_upload]
+ before_action :external_store_check, only: [
+ :show_secure,
+ :generate_presigned_put,
+ :complete_external_upload,
+ :create_multipart,
+ :batch_presign_multipart_parts,
+ :abort_multipart,
+ :complete_multipart
+ ]
+ before_action :direct_s3_uploads_check, only: [
+ :generate_presigned_put,
+ :complete_external_upload,
+ :create_multipart,
+ :batch_presign_multipart_parts,
+ :abort_multipart,
+ :complete_multipart
+ ]
+ before_action :can_upload_external?, only: [:create_multipart, :generate_presigned_put]
SECURE_REDIRECT_GRACE_SECONDS = 5
- PRESIGNED_PUT_RATE_LIMIT_PER_MINUTE = 5
-
- def external_store_check
- return render_404 if !Discourse.store.external?
- end
+ PRESIGNED_PUT_RATE_LIMIT_PER_MINUTE = 10
+ CREATE_MULTIPART_RATE_LIMIT_PER_MINUTE = 10
+ COMPLETE_MULTIPART_RATE_LIMIT_PER_MINUTE = 10
+ BATCH_PRESIGN_RATE_LIMIT_PER_MINUTE = 10
def create
# capture current user for block later on
@@ -193,15 +209,21 @@ class UploadsController < ApplicationController
end
def generate_presigned_put
- return render_404 if !SiteSetting.enable_direct_s3_uploads
-
RateLimiter.new(
current_user, "generate-presigned-put-upload-stub", PRESIGNED_PUT_RATE_LIMIT_PER_MINUTE, 1.minute
).performed!
file_name = params.require(:file_name)
+ file_size = params.require(:file_size).to_i
type = params.require(:type)
+ if file_size_too_big?(file_name, file_size)
+ return render_json_error(
+ I18n.t("upload.attachments.too_large", max_size_kb: SiteSetting.max_attachment_size_kb),
+ status: 422
+ )
+ end
+
# don't want people posting arbitrary S3 metadata so we just take the
# one we need. all of these will be converted to x-amz-meta- metadata
# fields in S3 so it's best to use dashes in the names for consistency
@@ -225,33 +247,37 @@ class UploadsController < ApplicationController
key: key,
created_by: current_user,
original_filename: file_name,
- upload_type: type
+ upload_type: type,
+ filesize: file_size
)
render json: { url: url, key: key, unique_identifier: upload_stub.unique_identifier }
end
def complete_external_upload
- return render_404 if !SiteSetting.enable_direct_s3_uploads
-
unique_identifier = params.require(:unique_identifier)
external_upload_stub = ExternalUploadStub.find_by(
unique_identifier: unique_identifier, created_by: current_user
)
return render_404 if external_upload_stub.blank?
- raise Discourse::InvalidAccess if external_upload_stub.created_by_id != current_user.id
- external_upload_manager = ExternalUploadManager.new(external_upload_stub)
+ complete_external_upload_via_manager(external_upload_stub)
+ end
+ def complete_external_upload_via_manager(external_upload_stub)
+ external_upload_manager = ExternalUploadManager.new(external_upload_stub)
hijack do
begin
upload = external_upload_manager.promote_to_upload!
if upload.errors.empty?
- external_upload_manager.destroy!
+ external_upload_stub.destroy!
render json: UploadsController.serialize_upload(upload), status: 200
else
render_json_error(upload.errors.to_hash.values.flatten, status: 422)
end
+ rescue ExternalUploadManager::SizeMismatchError => err
+ debug_upload_error(err, "upload.size_mismatch_failure", additional_detail: err.message)
+ render_json_error(I18n.t("upload.failed"), status: 422)
rescue ExternalUploadManager::ChecksumMismatchError => err
debug_upload_error(err, "upload.checksum_mismatch_failure")
render_json_error(I18n.t("upload.failed"), status: 422)
@@ -270,6 +296,179 @@ class UploadsController < ApplicationController
end
end
+ def create_multipart
+ RateLimiter.new(
+ current_user, "create-multipart-upload", CREATE_MULTIPART_RATE_LIMIT_PER_MINUTE, 1.minute
+ ).performed!
+
+ file_name = params.require(:file_name)
+ file_size = params.require(:file_size).to_i
+ upload_type = params.require(:upload_type)
+ content_type = MiniMime.lookup_by_filename(file_name)&.content_type
+
+ if file_size_too_big?(file_name, file_size)
+ return render_json_error(
+ I18n.t("upload.attachments.too_large", max_size_kb: SiteSetting.max_attachment_size_kb),
+ status: 422
+ )
+ end
+
+ begin
+ multipart_upload = Discourse.store.create_multipart(
+ file_name, content_type
+ )
+ rescue Aws::S3::Errors::ServiceError => err
+ debug_upload_error(err, "upload.create_mutlipart_failure")
+ return render_json_error(I18n.t("upload.failed"), status: 422)
+ end
+
+ upload_stub = ExternalUploadStub.create!(
+ key: multipart_upload[:key],
+ created_by: current_user,
+ original_filename: file_name,
+ upload_type: upload_type,
+ external_upload_identifier: multipart_upload[:upload_id],
+ multipart: true,
+ filesize: file_size
+ )
+
+ render json: {
+ external_upload_identifier: upload_stub.external_upload_identifier,
+ key: upload_stub.key,
+ unique_identifier: upload_stub.unique_identifier
+ }
+ end
+
+ def batch_presign_multipart_parts
+ part_numbers = params.require(:part_numbers)
+ unique_identifier = params.require(:unique_identifier)
+
+ RateLimiter.new(
+ current_user, "batch-presign", BATCH_PRESIGN_RATE_LIMIT_PER_MINUTE, 1.minute
+ ).performed!
+
+ part_numbers = part_numbers.map do |part_number|
+ validate_part_number(part_number)
+ end
+
+ external_upload_stub = ExternalUploadStub.find_by(
+ unique_identifier: unique_identifier, created_by: current_user
+ )
+ return render_404 if external_upload_stub.blank?
+
+ if !multipart_upload_exists?(external_upload_stub)
+ return render_404
+ end
+
+ presigned_urls = {}
+ part_numbers.each do |part_number|
+ presigned_urls[part_number] = Discourse.store.presign_multipart_part(
+ upload_id: external_upload_stub.external_upload_identifier,
+ key: external_upload_stub.key,
+ part_number: part_number
+ )
+ end
+
+ render json: { presigned_urls: presigned_urls }
+ end
+
+ def validate_part_number(part_number)
+ part_number = part_number.to_i
+ if !part_number.between?(1, 10000)
+ raise Discourse::InvalidParameters.new(
+ "Each part number should be between 1 and 10000"
+ )
+ end
+ part_number
+ end
+
+ def multipart_upload_exists?(external_upload_stub)
+ begin
+ Discourse.store.list_multipart_parts(
+ upload_id: external_upload_stub.external_upload_identifier, key: external_upload_stub.key
+ )
+ rescue Aws::S3::Errors::NoSuchUpload => err
+ debug_upload_error(err, "upload.external_upload_not_found", { additional_detail: "path: #{external_upload_stub.key}" })
+ return false
+ end
+ true
+ end
+
+ def abort_multipart
+ external_upload_identifier = params.require(:external_upload_identifier)
+ external_upload_stub = ExternalUploadStub.find_by(
+ external_upload_identifier: external_upload_identifier
+ )
+
+ # The stub could have already been deleted by an earlier error via
+ # ExternalUploadManager, so we consider this a great success if the
+ # stub is already gone.
+ return render json: success_json if external_upload_stub.blank?
+
+ return render_404 if external_upload_stub.created_by_id != current_user.id
+
+ begin
+ Discourse.store.abort_multipart(
+ upload_id: external_upload_stub.external_upload_identifier,
+ key: external_upload_stub.key
+ )
+ rescue Aws::S3::Errors::ServiceError => err
+ debug_upload_error(err, "upload.abort_mutlipart_failure", additional_detail: "external upload stub id: #{external_upload_stub.id}")
+ return render_json_error(I18n.t("upload.failed"), status: 422)
+ end
+
+ external_upload_stub.destroy!
+
+ render json: success_json
+ end
+
+ def complete_multipart
+ unique_identifier = params.require(:unique_identifier)
+ parts = params.require(:parts)
+
+ RateLimiter.new(
+ current_user, "complete-multipart-upload", COMPLETE_MULTIPART_RATE_LIMIT_PER_MINUTE, 1.minute
+ ).performed!
+
+ external_upload_stub = ExternalUploadStub.find_by(
+ unique_identifier: unique_identifier, created_by: current_user
+ )
+ return render_404 if external_upload_stub.blank?
+
+ if !multipart_upload_exists?(external_upload_stub)
+ return render_404
+ end
+
+ parts = parts.map do |part|
+ part_number = part[:part_number]
+ etag = part[:etag]
+ part_number = validate_part_number(part_number)
+
+ if etag.blank?
+ raise Discourse::InvalidParameters.new("All parts must have an etag and a valid part number")
+ end
+
+ # this is done so it's an array of hashes rather than an array of
+ # ActionController::Parameters
+ { part_number: part_number, etag: etag }
+ end.sort_by do |part|
+ part[:part_number]
+ end
+
+ begin
+ complete_response = Discourse.store.complete_multipart(
+ upload_id: external_upload_stub.external_upload_identifier,
+ key: external_upload_stub.key,
+ parts: parts
+ )
+ rescue Aws::S3::Errors::ServiceError => err
+ debug_upload_error(err, "upload.complete_mutlipart_failure", additional_detail: "external upload stub id: #{external_upload_stub.id}")
+ return render_json_error(I18n.t("upload.failed"), status: 422)
+ end
+
+ complete_external_upload_via_manager(external_upload_stub)
+ end
+
protected
def force_download?
@@ -339,6 +538,25 @@ class UploadsController < ApplicationController
private
+ def external_store_check
+ return render_404 if !Discourse.store.external?
+ end
+
+ def direct_s3_uploads_check
+ return render_404 if !SiteSetting.enable_direct_s3_uploads
+ end
+
+ def can_upload_external?
+ raise Discourse::InvalidAccess if !guardian.can_upload_external?
+ end
+
+ # We can pre-emptively check size for attachments, but not for images
+ # as they may be further reduced in size by UploadCreator (at this point
+ # they may have already been reduced in size by preprocessors)
+ def file_size_too_big?(file_name, file_size)
+ !FileHelper.is_supported_image?(file_name) && file_size >= SiteSetting.max_attachment_size_kb.kilobytes
+ end
+
def send_file_local_upload(upload)
opts = {
filename: upload.original_filename,
@@ -357,8 +575,8 @@ class UploadsController < ApplicationController
send_file(file_path, opts)
end
- def debug_upload_error(translation_key, err)
+ def debug_upload_error(err, translation_key, translation_params = {})
return if !SiteSetting.enable_upload_debug_mode
- Discourse.warn_exception(err, message: I18n.t(translation_key))
+ Discourse.warn_exception(err, message: I18n.t(translation_key, translation_params))
end
end
diff --git a/app/models/external_upload_stub.rb b/app/models/external_upload_stub.rb
index 82a20ff2064..6f50a042ecf 100644
--- a/app/models/external_upload_stub.rb
+++ b/app/models/external_upload_stub.rb
@@ -5,9 +5,14 @@ require "digest/sha1"
class ExternalUploadStub < ActiveRecord::Base
CREATED_EXPIRY_HOURS = 1
UPLOADED_EXPIRY_HOURS = 24
+ FAILED_EXPIRY_HOURS = 48
belongs_to :created_by, class_name: 'User'
+ validates :filesize, numericality: {
+ allow_nil: false, only_integer: true, greater_than_or_equal_to: 1
+ }
+
scope :expired_created, -> {
where(
"status = ? AND created_at <= ?",
@@ -33,7 +38,6 @@ class ExternalUploadStub < ActiveRecord::Base
@statuses ||= Enum.new(
created: 1,
uploaded: 2,
- failed: 3
)
end
@@ -50,19 +54,23 @@ end
#
# Table name: external_upload_stubs
#
-# id :bigint not null, primary key
-# key :string not null
-# original_filename :string not null
-# status :integer default(1), not null
-# unique_identifier :uuid not null
-# created_by_id :integer not null
-# upload_type :string not null
-# created_at :datetime not null
-# updated_at :datetime not null
+# id :bigint not null, primary key
+# key :string not null
+# original_filename :string not null
+# status :integer default(1), not null
+# unique_identifier :uuid not null
+# created_by_id :integer not null
+# upload_type :string not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# multipart :boolean default(FALSE), not null
+# external_upload_identifier :string
+# filesize :bigint not null
#
# Indexes
#
-# index_external_upload_stubs_on_created_by_id (created_by_id)
-# index_external_upload_stubs_on_key (key) UNIQUE
-# index_external_upload_stubs_on_status (status)
+# index_external_upload_stubs_on_created_by_id (created_by_id)
+# index_external_upload_stubs_on_external_upload_identifier (external_upload_identifier)
+# index_external_upload_stubs_on_key (key) UNIQUE
+# index_external_upload_stubs_on_status (status)
#
diff --git a/app/services/external_upload_manager.rb b/app/services/external_upload_manager.rb
index aacfb99ecad..aa0e7040b2f 100644
--- a/app/services/external_upload_manager.rb
+++ b/app/services/external_upload_manager.rb
@@ -2,13 +2,24 @@
class ExternalUploadManager
DOWNLOAD_LIMIT = 100.megabytes
+ SIZE_MISMATCH_BAN_MINUTES = 5
+ BAN_USER_REDIS_PREFIX = "ban_user_from_external_uploads_"
class ChecksumMismatchError < StandardError; end
class DownloadFailedError < StandardError; end
class CannotPromoteError < StandardError; end
+ class SizeMismatchError < StandardError; end
attr_reader :external_upload_stub
+ def self.ban_user_from_external_uploads!(user:, ban_minutes: 5)
+ Discourse.redis.setex("#{BAN_USER_REDIS_PREFIX}#{user.id}", ban_minutes.minutes.to_i, "1")
+ end
+
+ def self.user_banned?(user)
+ Discourse.redis.get("#{BAN_USER_REDIS_PREFIX}#{user.id}") == "1"
+ end
+
def initialize(external_upload_stub)
@external_upload_stub = external_upload_stub
end
@@ -31,6 +42,19 @@ class ExternalUploadManager
# variable as well to check.
tempfile = nil
should_download = external_size < DOWNLOAD_LIMIT
+
+ # We require that the file size is specified ahead of time, and compare
+ # it here to make sure that people are not uploading excessively large
+ # files to the external provider. If this happens, the user will be banned
+ # from uploading to the external provider for N minutes.
+ if external_size != external_upload_stub.filesize
+ ExternalUploadManager.ban_user_from_external_uploads!(
+ user: external_upload_stub.created_by,
+ ban_minutes: SIZE_MISMATCH_BAN_MINUTES
+ )
+ raise SizeMismatchError.new("expected: #{external_upload_stub.filesize}, actual: #{external_size}")
+ end
+
if should_download
tempfile = download(external_upload_stub.key, external_upload_stub.upload_type)
@@ -60,16 +84,17 @@ class ExternalUploadManager
external_upload_stub.created_by_id
)
rescue
- external_upload_stub.update!(status: ExternalUploadStub.statuses[:failed])
+ # We don't need to do anything special to abort multipart uploads here,
+ # because at this point (calling promote_to_upload!), the multipart
+ # upload would already be complete.
+ Discourse.store.delete_file(external_upload_stub.key)
+ external_upload_stub.destroy!
+
raise
ensure
tempfile&.close!
end
- def destroy!
- external_upload_stub.destroy!
- end
-
private
def download(key, type)
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index d7150cf44c2..c19136c70cf 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -4009,6 +4009,11 @@ en:
png_to_jpg_conversion_failure_message: "An error happened when converting from PNG to JPG."
optimize_failure_message: "An error occurred while optimizing the uploaded image."
download_failure: "Downloading the file from the external provider failed."
+ size_mismatch_failure: "The size of the file uploaded to S3 did not match the external upload stub's intended size. %{additional_detail}"
+ create_mutlipart_failure: "Failed to create multipart upload in the external store."
+ abort_mutlipart_failure: "Failed to abort multipart upload in the external store."
+ complete_mutlipart_failure: "Failed to complete multipart upload in the external store."
+ external_upload_not_found: "The upload was not found in the external store. %{additional_detail}"
checksum_mismatch_failure: "The checksum of the file you uploaded does not match. The file contents may have changed on upload. Please try again."
cannot_promote_failure: "The upload cannot be completed, it may have already completed or previously failed."
attachments:
diff --git a/config/routes.rb b/config/routes.rb
index 28cb935b343..c7737d9fce0 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -541,8 +541,15 @@ Discourse::Application.routes.draw do
post "uploads" => "uploads#create"
post "uploads/lookup-urls" => "uploads#lookup_urls"
- post "uploads/generate-presigned-put" => "uploads#generate_presigned_put"
- post "uploads/complete-external-upload" => "uploads#complete_external_upload"
+ # direct to s3 uploads
+ post "uploads/generate-presigned-put" => "uploads#generate_presigned_put", format: :json
+ post "uploads/complete-external-upload" => "uploads#complete_external_upload", format: :json
+
+ # multipart uploads
+ post "uploads/create-multipart" => "uploads#create_multipart", format: :json
+ post "uploads/complete-multipart" => "uploads#complete_multipart", format: :json
+ post "uploads/abort-multipart" => "uploads#abort_multipart", format: :json
+ post "uploads/batch-presign-multipart-parts" => "uploads#batch_presign_multipart_parts", format: :json
# used to download original images
get "uploads/:site/:sha(.:extension)" => "uploads#show", constraints: { site: /\w+/, sha: /\h{40}/, extension: /[a-z0-9\._]+/i }
diff --git a/db/migrate/20210812033033_add_multipart_and_size_columns_to_external_upload_stubs.rb b/db/migrate/20210812033033_add_multipart_and_size_columns_to_external_upload_stubs.rb
new file mode 100644
index 00000000000..97fdb885ec1
--- /dev/null
+++ b/db/migrate/20210812033033_add_multipart_and_size_columns_to_external_upload_stubs.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+class AddMultipartAndSizeColumnsToExternalUploadStubs < ActiveRecord::Migration[6.1]
+ def up
+ add_column :external_upload_stubs, :multipart, :boolean, default: false, null: false
+ add_column :external_upload_stubs, :external_upload_identifier, :string, null: true
+ add_column :external_upload_stubs, :filesize, :bigint
+
+ add_index :external_upload_stubs, :external_upload_identifier
+
+ # this feature is not actively used yet so this will be safe, also the rows in this
+ # table are regularly deleted
+ DB.exec("UPDATE external_upload_stubs SET filesize = 0 WHERE filesize IS NULL")
+
+ change_column_null :external_upload_stubs, :filesize, false
+ end
+
+ def down
+ remove_column :external_upload_stubs, :multipart
+ remove_column :external_upload_stubs, :external_upload_identifier
+ remove_column :external_upload_stubs, :filesize
+ end
+end
diff --git a/lib/file_store/s3_store.rb b/lib/file_store/s3_store.rb
index 2c85c77eba2..66642ec91d8 100644
--- a/lib/file_store/s3_store.rb
+++ b/lib/file_store/s3_store.rb
@@ -97,12 +97,13 @@ module FileStore
# if this fails, it will throw an exception
if opts[:move_existing] && opts[:existing_external_upload_key]
+ original_path = opts[:existing_external_upload_key]
path, etag = s3_helper.copy(
- opts[:existing_external_upload_key],
+ original_path,
path,
options: options
)
- s3_helper.delete_object(opts[:existing_external_upload_key])
+ delete_file(original_path)
else
path, etag = s3_helper.upload(file, path, options)
end
@@ -111,6 +112,12 @@ module FileStore
[File.join(absolute_base_url, path), etag]
end
+ def delete_file(path)
+ # delete the object outright without moving to tombstone,
+ # not recommended for most use cases
+ s3_helper.delete_object(path)
+ end
+
def remove_file(url, path)
return unless has_been_uploaded?(url)
# copy the removed file to tombstone
@@ -217,7 +224,15 @@ module FileStore
def signed_url_for_temporary_upload(file_name, expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS, metadata: {})
key = temporary_upload_path(file_name)
- presigned_put_url(key, expires_in: expires_in, metadata: metadata)
+ presigned_url(
+ key,
+ method: :put_object,
+ expires_in: expires_in,
+ opts: {
+ metadata: metadata,
+ acl: "private"
+ }
+ )
end
def temporary_upload_path(file_name)
@@ -297,17 +312,72 @@ module FileStore
FileUtils.mv(old_upload_path, public_upload_path) if old_upload_path
end
+ def abort_multipart(key:, upload_id:)
+ s3_helper.s3_client.abort_multipart_upload(
+ bucket: s3_bucket_name,
+ key: key,
+ upload_id: upload_id
+ )
+ end
+
+ def create_multipart(file_name, content_type)
+ key = temporary_upload_path(file_name)
+ response = s3_helper.s3_client.create_multipart_upload(
+ acl: "private",
+ bucket: s3_bucket_name,
+ key: key,
+ content_type: content_type
+ )
+ { upload_id: response.upload_id, key: key }
+ end
+
+ def presign_multipart_part(upload_id:, key:, part_number:)
+ presigned_url(
+ key,
+ method: :upload_part,
+ expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS,
+ opts: {
+ part_number: part_number,
+ upload_id: upload_id
+ }
+ )
+ end
+
+ def list_multipart_parts(upload_id:, key:)
+ s3_helper.s3_client.list_parts(
+ bucket: s3_bucket_name,
+ key: key,
+ upload_id: upload_id
+ )
+ end
+
+ def complete_multipart(upload_id:, key:, parts:)
+ s3_helper.s3_client.complete_multipart_upload(
+ bucket: s3_bucket_name,
+ key: key,
+ upload_id: upload_id,
+ multipart_upload: {
+ parts: parts
+ }
+ )
+ end
+
private
- def presigned_put_url(key, expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS, metadata: {})
+ def presigned_url(
+ key,
+ method:,
+ expires_in: S3Helper::UPLOAD_URL_EXPIRES_AFTER_SECONDS,
+ opts: {}
+ )
signer = Aws::S3::Presigner.new(client: s3_helper.s3_client)
signer.presigned_url(
- :put_object,
- bucket: s3_bucket_name,
- key: key,
- acl: "private",
- expires_in: expires_in,
- metadata: metadata
+ method,
+ {
+ bucket: s3_bucket_name,
+ key: key,
+ expires_in: expires_in,
+ }.merge(opts)
)
end
diff --git a/lib/guardian/user_guardian.rb b/lib/guardian/user_guardian.rb
index cd9dda0921e..ef13588cef2 100644
--- a/lib/guardian/user_guardian.rb
+++ b/lib/guardian/user_guardian.rb
@@ -176,6 +176,10 @@ module UserGuardian
(is_me?(user) && user.has_trust_level?(SiteSetting.min_trust_level_to_allow_user_card_background.to_i)) || is_staff?
end
+ def can_upload_external?
+ !ExternalUploadManager.user_banned?(user)
+ end
+
def can_delete_sso_record?(user)
SiteSetting.enable_discourse_connect && user && is_admin?
end
diff --git a/lib/upload_creator.rb b/lib/upload_creator.rb
index d29a3c5d2b5..affbe78775a 100644
--- a/lib/upload_creator.rb
+++ b/lib/upload_creator.rb
@@ -32,6 +32,9 @@ class UploadCreator
@opts = opts
@filesize = @opts[:filesize] if @opts[:external_upload_too_big]
@opts[:validate] = opts[:skip_validations].present? ? !ActiveRecord::Type::Boolean.new.cast(opts[:skip_validations]) : true
+
+ # TODO (martin) Validate @opts[:type] to make sure only blessed types are passed
+ # in, since the clientside can pass any type it wants.
end
def create_for(user_id)
@@ -50,6 +53,11 @@ class UploadCreator
# so we have not downloaded it to a tempfile. no modifications can be made to the
# file in this case because it does not exist; we simply move it to its new location
# in S3
+ #
+ # TODO (martin) I've added a bunch of external_upload_too_big checks littered
+ # throughout the UploadCreator code. It would be better to have two seperate
+ # classes with shared methods, rather than doing all these checks all over the
+ # place. Needs a refactor.
external_upload_too_big = @opts[:external_upload_too_big]
sha1_before_changes = Upload.generate_digest(@file) if @file
diff --git a/spec/components/guardian/user_guardian_spec.rb b/spec/components/guardian/user_guardian_spec.rb
index 63f8b3a5e77..f07a4062b30 100644
--- a/spec/components/guardian/user_guardian_spec.rb
+++ b/spec/components/guardian/user_guardian_spec.rb
@@ -492,4 +492,17 @@ describe UserGuardian do
end
end
end
+
+ describe "#can_upload_external?" do
+ after { Discourse.redis.flushdb }
+
+ it "is true by default" do
+ expect(Guardian.new(user).can_upload_external?).to eq(true)
+ end
+
+ it "is false if the user has been banned from external uploads for a time period" do
+ ExternalUploadManager.ban_user_from_external_uploads!(user: user)
+ expect(Guardian.new(user).can_upload_external?).to eq(false)
+ end
+ end
end
diff --git a/spec/fabricators/external_upload_stub_fabricator.rb b/spec/fabricators/external_upload_stub_fabricator.rb
index 57d26d10a3b..ce7b1ec6163 100644
--- a/spec/fabricators/external_upload_stub_fabricator.rb
+++ b/spec/fabricators/external_upload_stub_fabricator.rb
@@ -5,15 +5,18 @@ Fabricator(:external_upload_stub) do
original_filename "test.txt"
key { Discourse.store.temporary_upload_path("test.txt") }
upload_type "card_background"
+ filesize 1024
status 1
end
Fabricator(:image_external_upload_stub, from: :external_upload_stub) do
original_filename "logo.png"
+ filesize 1024
key { Discourse.store.temporary_upload_path("logo.png") }
end
Fabricator(:attachment_external_upload_stub, from: :external_upload_stub) do
original_filename "file.pdf"
+ filesize 1024
key { Discourse.store.temporary_upload_path("file.pdf") }
end
diff --git a/spec/requests/uploads_controller_spec.rb b/spec/requests/uploads_controller_spec.rb
index 737c992d522..c50711a952a 100644
--- a/spec/requests/uploads_controller_spec.rb
+++ b/spec/requests/uploads_controller_spec.rb
@@ -721,7 +721,9 @@ describe UploadsController do
end
it "generates a presigned URL and creates an external upload stub" do
- post "/uploads/generate-presigned-put.json", params: { file_name: "test.png", type: "card_background" }
+ post "/uploads/generate-presigned-put.json", params: {
+ file_name: "test.png", type: "card_background", file_size: 1024
+ }
expect(response.status).to eq(200)
result = response.parsed_body
@@ -730,7 +732,8 @@ describe UploadsController do
unique_identifier: result["unique_identifier"],
original_filename: "test.png",
created_by: user,
- upload_type: "card_background"
+ upload_type: "card_background",
+ filesize: 1024
)
expect(external_upload_stub.exists?).to eq(true)
expect(result["key"]).to include(FileStore::S3Store::TEMPORARY_UPLOAD_PREFIX)
@@ -742,6 +745,7 @@ describe UploadsController do
post "/uploads/generate-presigned-put.json", {
params: {
file_name: "test.png",
+ file_size: 1024,
type: "card_background",
metadata: {
"sha1-checksum" => "testing",
@@ -761,8 +765,8 @@ describe UploadsController do
RateLimiter.clear_all!
stub_const(UploadsController, "PRESIGNED_PUT_RATE_LIMIT_PER_MINUTE", 1) do
- post "/uploads/generate-presigned-put.json", params: { file_name: "test.png", type: "card_background" }
- post "/uploads/generate-presigned-put.json", params: { file_name: "test.png", type: "card_background" }
+ post "/uploads/generate-presigned-put.json", params: { file_name: "test.png", type: "card_background", file_size: 1024 }
+ post "/uploads/generate-presigned-put.json", params: { file_name: "test.png", type: "card_background", file_size: 1024 }
end
expect(response.status).to eq(429)
end
@@ -774,7 +778,566 @@ describe UploadsController do
end
it "returns 404" do
- post "/uploads/generate-presigned-put.json", params: { file_name: "test.png", type: "card_background" }
+ post "/uploads/generate-presigned-put.json", params: { file_name: "test.png", type: "card_background", file_size: 1024 }
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+
+ describe "#create_multipart" do
+ context "when the store is external" do
+ let(:mock_multipart_upload_id) { "ibZBv_75gd9r8lH_gqXatLdxMVpAlj6CFTR.OwyF3953YdwbcQnMA2BLGn8Lx12fQNICtMw5KyteFeHw.Sjng--" }
+
+ before do
+ sign_in(user)
+ SiteSetting.enable_direct_s3_uploads = true
+ setup_s3
+ FileStore::S3Store.any_instance.stubs(:temporary_upload_path).returns(
+ "uploads/default/test_0/temp/28fccf8259bbe75b873a2bd2564b778c/test.png"
+ )
+ end
+
+ it "errors if the correct params are not provided" do
+ post "/uploads/create-multipart.json", params: { file_name: "test.png" }
+ expect(response.status).to eq(400)
+ post "/uploads/create-multipart.json", params: { upload_type: "composer" }
+ expect(response.status).to eq(400)
+ post "/uploads/create-multipart.json", params: { content_type: "image/jpeg" }
+ expect(response.status).to eq(400)
+ end
+
+ it "returns 422 when the create request errors" do
+ FileStore::S3Store.any_instance.stubs(:create_multipart).raises(Aws::S3::Errors::ServiceError.new({}, "test"))
+ post "/uploads/create-multipart.json", {
+ params: {
+ file_name: "test.png",
+ file_size: 1024,
+ upload_type: "composer",
+ content_type: "image/png"
+ }
+ }
+ expect(response.status).to eq(422)
+ end
+
+ it "returns 422 when the file is an attachment and it's too big" do
+ SiteSetting.max_attachment_size_kb = 1000
+ post "/uploads/create-multipart.json", {
+ params: {
+ file_name: "test.zip",
+ file_size: 9999999,
+ upload_type: "composer",
+ content_type: "application/zip"
+ }
+ }
+ expect(response.status).to eq(422)
+ expect(response.body).to include(I18n.t("upload.attachments.too_large", max_size_kb: SiteSetting.max_attachment_size_kb))
+ end
+
+ def stub_create_multipart_request
+ create_multipart_result = <<~BODY
+ <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n
+ <InitiateMultipartUploadResult>
+ <Bucket>s3-upload-bucket</Bucket>
+ <Key>uploads/default/test_0/temp/28fccf8259bbe75b873a2bd2564b778c/test.png</Key>
+ <UploadId>#{mock_multipart_upload_id}</UploadId>
+ </InitiateMultipartUploadResult>
+ BODY
+ stub_request(
+ :post,
+ "https://s3-upload-bucket.s3.us-west-1.amazonaws.com/uploads/default/test_0/temp/28fccf8259bbe75b873a2bd2564b778c/test.png?uploads"
+ ).to_return({ status: 200, body: create_multipart_result })
+ end
+
+ it "creates a multipart upload and creates an external upload stub that is marked as multipart" do
+ stub_create_multipart_request
+ post "/uploads/create-multipart.json", {
+ params: {
+ file_name: "test.png",
+ file_size: 1024,
+ upload_type: "composer",
+ content_type: "image/png"
+ }
+ }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body
+
+ external_upload_stub = ExternalUploadStub.where(
+ unique_identifier: result["unique_identifier"],
+ original_filename: "test.png",
+ created_by: user,
+ upload_type: "composer",
+ key: result["key"],
+ external_upload_identifier: mock_multipart_upload_id,
+ multipart: true,
+ filesize: 1024
+ )
+ expect(external_upload_stub.exists?).to eq(true)
+ expect(result["key"]).to include(FileStore::S3Store::TEMPORARY_UPLOAD_PREFIX)
+ expect(result["external_upload_identifier"]).to eq(mock_multipart_upload_id)
+ expect(result["key"]).to eq(external_upload_stub.last.key)
+ end
+
+ it "rate limits" do
+ RateLimiter.enable
+ RateLimiter.clear_all!
+
+ stub_create_multipart_request
+ stub_const(UploadsController, "CREATE_MULTIPART_RATE_LIMIT_PER_MINUTE", 1) do
+ post "/uploads/create-multipart.json", params: {
+ file_name: "test.png",
+ upload_type: "composer",
+ content_type: "image/png",
+ file_size: 1024
+ }
+ expect(response.status).to eq(200)
+
+ post "/uploads/create-multipart.json", params: {
+ file_name: "test.png",
+ upload_type: "composer",
+ content_type: "image/png",
+ file_size: 1024
+ }
+ expect(response.status).to eq(429)
+ end
+ end
+ end
+
+ context "when the store is not external" do
+ before do
+ sign_in(user)
+ end
+
+ it "returns 404" do
+ post "/uploads/create-multipart.json", params: {
+ file_name: "test.png",
+ upload_type: "composer",
+ content_type: "image/png",
+ file_size: 1024
+ }
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+
+ describe "#batch_presign_multipart_parts" do
+ fab!(:mock_multipart_upload_id) { "ibZBv_75gd9r8lH_gqXatLdxMVpAlj6CFTR.OwyF3953YdwbcQnMA2BLGn8Lx12fQNICtMw5KyteFeHw.Sjng--" }
+ fab!(:external_upload_stub) do
+ Fabricate(:image_external_upload_stub, created_by: user, multipart: true, external_upload_identifier: mock_multipart_upload_id)
+ end
+
+ context "when the store is external" do
+ before do
+ sign_in(user)
+ SiteSetting.enable_direct_s3_uploads = true
+ setup_s3
+ end
+
+ def stub_list_multipart_request
+ list_multipart_result = <<~BODY
+ <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n
+ <ListPartsResult>
+ <Bucket>s3-upload-bucket</Bucket>
+ <Key>#{external_upload_stub.key}</Key>
+ <UploadId>#{mock_multipart_upload_id}</UploadId>
+ <PartNumberMarker>0</PartNumberMarker>
+ <NextPartNumberMarker>0</NextPartNumberMarker>
+ <MaxParts>1</MaxParts>
+ <IsTruncated>false</IsTruncated>
+ <Part>
+ <ETag>test</ETag>
+ <LastModified>#{Time.zone.now}</LastModified>
+ <PartNumber>1</PartNumber>
+ <Size>#{5.megabytes}</Size>
+ </Part>
+ <Initiator>
+ <DisplayName>test-upload-user</DisplayName>
+ <ID>arn:aws:iam::123:user/test-upload-user</ID>
+ </Initiator>
+ <Owner>
+ <DisplayName></DisplayName>
+ <ID>12345</ID>
+ </Owner>
+ <StorageClass>STANDARD</StorageClass>
+ </ListPartsResult>
+ BODY
+ stub_request(:get, "https://s3-upload-bucket.s3.us-west-1.amazonaws.com/#{external_upload_stub.key}?uploadId=#{mock_multipart_upload_id}").to_return({ status: 200, body: list_multipart_result })
+ end
+
+ it "errors if the correct params are not provided" do
+ post "/uploads/batch-presign-multipart-parts.json", params: {}
+ expect(response.status).to eq(400)
+ end
+
+ it "errors if the part_numbers do not contain numbers between 1 and 10000" do
+ post "/uploads/batch-presign-multipart-parts.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ part_numbers: [-1, 0, 1, 2, 3, 4]
+ }
+ expect(response.status).to eq(400)
+ expect(response.body).to include("You supplied invalid parameters to the request: Each part number should be between 1 and 10000")
+ post "/uploads/batch-presign-multipart-parts.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ part_numbers: [3, 4, "blah"]
+ }
+ expect(response.status).to eq(400)
+ expect(response.body).to include("You supplied invalid parameters to the request: Each part number should be between 1 and 10000")
+ end
+
+ it "returns 404 when the upload stub does not exist" do
+ post "/uploads/batch-presign-multipart-parts.json", params: {
+ unique_identifier: "unknown",
+ part_numbers: [1, 2, 3]
+ }
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when the upload stub does not belong to the user" do
+ external_upload_stub.update!(created_by: Fabricate(:user))
+ post "/uploads/batch-presign-multipart-parts.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ part_numbers: [1, 2, 3]
+ }
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when the multipart upload does not exist" do
+ FileStore::S3Store.any_instance.stubs(:list_multipart_parts).raises(Aws::S3::Errors::NoSuchUpload.new("test", "test"))
+ post "/uploads/batch-presign-multipart-parts.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ part_numbers: [1, 2, 3]
+ }
+ expect(response.status).to eq(404)
+ end
+
+ it "returns an object with the presigned URLs with the part numbers as keys" do
+ stub_list_multipart_request
+ post "/uploads/batch-presign-multipart-parts.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ part_numbers: [2, 3, 4]
+ }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body
+ expect(result["presigned_urls"].keys).to eq(["2", "3", "4"])
+ expect(result["presigned_urls"]["2"]).to include("?partNumber=2&uploadId=#{mock_multipart_upload_id}")
+ expect(result["presigned_urls"]["3"]).to include("?partNumber=3&uploadId=#{mock_multipart_upload_id}")
+ expect(result["presigned_urls"]["4"]).to include("?partNumber=4&uploadId=#{mock_multipart_upload_id}")
+ end
+
+ it "rate limits" do
+ RateLimiter.enable
+ RateLimiter.clear_all!
+
+ stub_const(UploadsController, "BATCH_PRESIGN_RATE_LIMIT_PER_MINUTE", 1) do
+ stub_list_multipart_request
+ post "/uploads/batch-presign-multipart-parts.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ part_numbers: [1, 2, 3]
+ }
+
+ expect(response.status).to eq(200)
+
+ post "/uploads/batch-presign-multipart-parts.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ part_numbers: [1, 2, 3]
+ }
+
+ expect(response.status).to eq(429)
+ end
+ end
+ end
+
+ context "when the store is not external" do
+ before do
+ sign_in(user)
+ end
+
+ it "returns 404" do
+ post "/uploads/batch-presign-multipart-parts.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ part_numbers: [1, 2, 3]
+ }
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+
+ describe "#complete_multipart" do
+ let(:upload_base_url) { "https://#{SiteSetting.s3_upload_bucket}.s3.#{SiteSetting.s3_region}.amazonaws.com" }
+ let(:mock_multipart_upload_id) { "ibZBv_75gd9r8lH_gqXatLdxMVpAlj6CFTR.OwyF3953YdwbcQnMA2BLGn8Lx12fQNICtMw5KyteFeHw.Sjng--" }
+ let!(:external_upload_stub) do
+ Fabricate(:image_external_upload_stub, created_by: user, multipart: true, external_upload_identifier: mock_multipart_upload_id)
+ end
+
+ context "when the store is external" do
+ before do
+ sign_in(user)
+ SiteSetting.enable_direct_s3_uploads = true
+ setup_s3
+ end
+
+ def stub_list_multipart_request
+ list_multipart_result = <<~BODY
+ <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n
+ <ListPartsResult>
+ <Bucket>s3-upload-bucket</Bucket>
+ <Key>#{external_upload_stub.key}</Key>
+ <UploadId>#{mock_multipart_upload_id}</UploadId>
+ <PartNumberMarker>0</PartNumberMarker>
+ <NextPartNumberMarker>0</NextPartNumberMarker>
+ <MaxParts>1</MaxParts>
+ <IsTruncated>false</IsTruncated>
+ <Part>
+ <ETag>test</ETag>
+ <LastModified>#{Time.zone.now}</LastModified>
+ <PartNumber>1</PartNumber>
+ <Size>#{5.megabytes}</Size>
+ </Part>
+ <Initiator>
+ <DisplayName>test-upload-user</DisplayName>
+ <ID>arn:aws:iam::123:user/test-upload-user</ID>
+ </Initiator>
+ <Owner>
+ <DisplayName></DisplayName>
+ <ID>12345</ID>
+ </Owner>
+ <StorageClass>STANDARD</StorageClass>
+ </ListPartsResult>
+ BODY
+ stub_request(:get, "#{upload_base_url}/#{external_upload_stub.key}?uploadId=#{mock_multipart_upload_id}").to_return({ status: 200, body: list_multipart_result })
+ end
+
+ it "errors if the correct params are not provided" do
+ post "/uploads/complete-multipart.json", params: {}
+ expect(response.status).to eq(400)
+ end
+
+ it "errors if the part_numbers do not contain numbers between 1 and 10000" do
+ stub_list_multipart_request
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ parts: [{ part_number: -1, etag: "test1" }]
+ }
+ expect(response.status).to eq(400)
+ expect(response.body).to include("You supplied invalid parameters to the request: Each part number should be between 1 and 10000")
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ parts: [{ part_number: 20001, etag: "test1" }]
+ }
+ expect(response.status).to eq(400)
+ expect(response.body).to include("You supplied invalid parameters to the request: Each part number should be between 1 and 10000")
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ parts: [{ part_number: "blah", etag: "test1" }]
+ }
+ expect(response.status).to eq(400)
+ expect(response.body).to include("You supplied invalid parameters to the request: Each part number should be between 1 and 10000")
+ end
+
+ it "errors if any of the parts objects have missing values" do
+ stub_list_multipart_request
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ parts: [{ part_number: 1 }]
+ }
+ expect(response.status).to eq(400)
+ expect(response.body).to include("All parts must have an etag")
+ end
+
+ it "returns 404 when the upload stub does not exist" do
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: "unknown",
+ parts: [{ part_number: 1, etag: "test1" }]
+ }
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 422 when the complete request errors" do
+ FileStore::S3Store.any_instance.stubs(:complete_multipart).raises(Aws::S3::Errors::ServiceError.new({}, "test"))
+ stub_list_multipart_request
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ parts: [{ part_number: 1, etag: "test1" }]
+ }
+ expect(response.status).to eq(422)
+ end
+
+ it "returns 404 when the upload stub does not belong to the user" do
+ external_upload_stub.update!(created_by: Fabricate(:user))
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ parts: [{ part_number: 1, etag: "test1" }]
+ }
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 404 when the multipart upload does not exist" do
+ FileStore::S3Store.any_instance.stubs(:list_multipart_parts).raises(Aws::S3::Errors::NoSuchUpload.new("test", "test"))
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ parts: [{ part_number: 1, etag: "test1" }]
+ }
+ expect(response.status).to eq(404)
+ end
+
+ it "completes the multipart upload, creates the Upload record, and returns a serialized Upload record" do
+ temp_location = "#{upload_base_url}/#{external_upload_stub.key}"
+ stub_list_multipart_request
+ stub_request(
+ :post,
+ "#{temp_location}?uploadId=#{external_upload_stub.external_upload_identifier}"
+ ).with(
+ body: "<CompleteMultipartUpload xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">\n <Part>\n <ETag>test1</ETag>\n <PartNumber>1</PartNumber>\n </Part>\n <Part>\n <ETag>test2</ETag>\n <PartNumber>2</PartNumber>\n </Part>\n</CompleteMultipartUpload>\n"
+ ).to_return(status: 200, body: <<~XML)
+ <?xml version="1.0" encoding="UTF-8"?>
+ <CompleteMultipartUploadResult>
+ <Location>#{temp_location}</Location>
+ <Bucket>s3-upload-bucket</Bucket>
+ <Key>#{external_upload_stub.key}</Key>
+ <ETag>testfinal</ETag>
+ </CompleteMultipartUploadResult>
+ XML
+
+ # all the functionality for ExternalUploadManager is already tested along
+ # with stubs to S3 in its own test, we can just stub the response here
+ upload = Fabricate(:upload)
+ ExternalUploadManager.any_instance.stubs(:promote_to_upload!).returns(upload)
+
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: external_upload_stub.unique_identifier,
+ parts: [{ part_number: 1, etag: "test1" }, { part_number: 2, etag: "test2" }]
+ }
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body
+ expect(result[:upload]).to eq(JSON.parse(UploadSerializer.new(upload).to_json)[:upload])
+ end
+
+ it "rate limits" do
+ RateLimiter.enable
+ RateLimiter.clear_all!
+
+ stub_const(UploadsController, "COMPLETE_MULTIPART_RATE_LIMIT_PER_MINUTE", 1) do
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: "blah",
+ parts: [{ part_number: 1, etag: "test1" }, { part_number: 2, etag: "test2" }]
+ }
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: "blah",
+ parts: [{ part_number: 1, etag: "test1" }, { part_number: 2, etag: "test2" }]
+ }
+ end
+ expect(response.status).to eq(429)
+ end
+ end
+
+ context "when the store is not external" do
+ before do
+ sign_in(user)
+ end
+
+ it "returns 404" do
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: external_upload_stub.external_upload_identifier,
+ parts: [
+ {
+ part_number: 1,
+ etag: "test1"
+ },
+ {
+ part_number: 2,
+ etag: "test2"
+ }
+ ]
+ }
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+
+ describe "#abort_multipart" do
+ let(:upload_base_url) { "https://#{SiteSetting.s3_upload_bucket}.s3.#{SiteSetting.s3_region}.amazonaws.com" }
+ let(:mock_multipart_upload_id) { "ibZBv_75gd9r8lH_gqXatLdxMVpAlj6CFTR.OwyF3953YdwbcQnMA2BLGn8Lx12fQNICtMw5KyteFeHw.Sjng--" }
+ let!(:external_upload_stub) do
+ Fabricate(:image_external_upload_stub, created_by: user, multipart: true, external_upload_identifier: mock_multipart_upload_id)
+ end
+
+ context "when the store is external" do
+ before do
+ sign_in(user)
+ SiteSetting.enable_direct_s3_uploads = true
+ setup_s3
+ end
+
+ def stub_abort_request
+ temp_location = "#{upload_base_url}/#{external_upload_stub.key}"
+ stub_request(
+ :delete,
+ "#{temp_location}?uploadId=#{external_upload_stub.external_upload_identifier}"
+ ).to_return(status: 200, body: "")
+ end
+
+ it "errors if the correct params are not provided" do
+ post "/uploads/abort-multipart.json", params: {}
+ expect(response.status).to eq(400)
+ end
+
+ it "returns 200 when the stub does not exist, assumes it has already been deleted" do
+ FileStore::S3Store.any_instance.expects(:abort_multipart).never
+ post "/uploads/abort-multipart.json", params: {
+ external_upload_identifier: "unknown",
+ }
+ expect(response.status).to eq(200)
+ end
+
+ it "returns 404 when the upload stub does not belong to the user" do
+ external_upload_stub.update!(created_by: Fabricate(:user))
+ post "/uploads/abort-multipart.json", params: {
+ external_upload_identifier: external_upload_stub.external_upload_identifier
+ }
+ expect(response.status).to eq(404)
+ end
+
+ it "aborts the multipart upload and deletes the stub" do
+ stub_abort_request
+
+ post "/uploads/abort-multipart.json", params: {
+ external_upload_identifier: external_upload_stub.external_upload_identifier
+ }
+
+ expect(response.status).to eq(200)
+ expect(ExternalUploadStub.exists?(id: external_upload_stub.id)).to eq(false)
+ end
+
+ it "returns 422 when the abort request errors" do
+ FileStore::S3Store.any_instance.stubs(:abort_multipart).raises(Aws::S3::Errors::ServiceError.new({}, "test"))
+ post "/uploads/abort-multipart.json", params: {
+ external_upload_identifier: external_upload_stub.external_upload_identifier
+ }
+ expect(response.status).to eq(422)
+ end
+ end
+
+ context "when the store is not external" do
+ before do
+ sign_in(user)
+ end
+
+ it "returns 404" do
+ post "/uploads/complete-multipart.json", params: {
+ unique_identifier: external_upload_stub.external_upload_identifier,
+ parts: [
+ {
+ part_number: 1,
+ etag: "test1"
+ },
+ {
+ part_number: 2,
+ etag: "test2"
+ }
+ ]
+ }
expect(response.status).to eq(404)
end
end
@@ -786,7 +1349,7 @@ describe UploadsController do
end
context "when the store is external" do
- fab!(:external_upload_stub) { Fabricate(:external_upload_stub, created_by: user) }
+ fab!(:external_upload_stub) { Fabricate(:image_external_upload_stub, created_by: user) }
let(:upload) { Fabricate(:upload) }
before do
@@ -813,6 +1376,13 @@ describe UploadsController do
expect(response.parsed_body["errors"].first).to eq(I18n.t("upload.failed"))
end
+ it "handles SizeMismatchError" do
+ ExternalUploadManager.any_instance.stubs(:promote_to_upload!).raises(ExternalUploadManager::SizeMismatchError.new("expected: 10, actual: 1000"))
+ post "/uploads/complete-external-upload.json", params: { unique_identifier: external_upload_stub.unique_identifier }
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"].first).to eq(I18n.t("upload.failed"))
+ end
+
it "handles CannotPromoteError" do
ExternalUploadManager.any_instance.stubs(:promote_to_upload!).raises(ExternalUploadManager::CannotPromoteError)
post "/uploads/complete-external-upload.json", params: { unique_identifier: external_upload_stub.unique_identifier }
diff --git a/spec/services/external_upload_manager_spec.rb b/spec/services/external_upload_manager_spec.rb
index 59a7ad92818..aafad046341 100644
--- a/spec/services/external_upload_manager_spec.rb
+++ b/spec/services/external_upload_manager_spec.rb
@@ -31,6 +31,15 @@ RSpec.describe ExternalUploadManager do
stub_delete_object
end
+ describe "#ban_user_from_external_uploads!" do
+ after { Discourse.redis.flushdb }
+
+ it "bans the user from external uploads using a redis key" do
+ ExternalUploadManager.ban_user_from_external_uploads!(user: user)
+ expect(ExternalUploadManager.user_banned?(user)).to eq(true)
+ end
+ end
+
describe "#can_promote?" do
it "returns false if the external stub status is not created" do
external_upload_stub.update!(status: ExternalUploadStub.statuses[:uploaded])
@@ -40,7 +49,7 @@ RSpec.describe ExternalUploadManager do
describe "#promote_to_upload!" do
context "when stubbed upload is < DOWNLOAD_LIMIT (small enough to download + generate sha)" do
- let!(:external_upload_stub) { Fabricate(:image_external_upload_stub, created_by: user) }
+ let!(:external_upload_stub) { Fabricate(:image_external_upload_stub, created_by: user, filesize: object_size) }
let(:object_size) { 1.megabyte }
let(:object_file) { logo_file }
@@ -114,18 +123,36 @@ RSpec.describe ExternalUploadManager do
context "when the downloaded file sha1 does not match the client sha1" do
let(:client_sha1) { "blahblah" }
- it "raises an error and marks upload as failed" do
+ it "raises an error, deletes the stub" do
expect { subject.promote_to_upload! }.to raise_error(ExternalUploadManager::ChecksumMismatchError)
- expect(external_upload_stub.reload.status).to eq(ExternalUploadStub.statuses[:failed])
+ expect(ExternalUploadStub.exists?(id: external_upload_stub.id)).to eq(false)
end
end
end
+
+ context "when the downloaded file size does not match the expected file size for the upload stub" do
+ before do
+ external_upload_stub.update!(filesize: 10)
+ end
+
+ after { Discourse.redis.flushdb }
+
+ it "raises an error, deletes the file immediately, and prevents the user from uploading external files for a few minutes" do
+ expect { subject.promote_to_upload! }.to raise_error(ExternalUploadManager::SizeMismatchError)
+ expect(ExternalUploadStub.exists?(id: external_upload_stub.id)).to eq(false)
+ expect(Discourse.redis.get("#{ExternalUploadManager::BAN_USER_REDIS_PREFIX}#{external_upload_stub.created_by_id}")).to eq("1")
+ expect(WebMock).to have_requested(
+ :delete,
+ "#{upload_base_url}/#{external_upload_stub.key}"
+ )
+ end
+ end
end
context "when stubbed upload is > DOWNLOAD_LIMIT (too big to download, generate a fake sha)" do
let(:object_size) { 200.megabytes }
let(:object_file) { pdf_file }
- let!(:external_upload_stub) { Fabricate(:attachment_external_upload_stub, created_by: user) }
+ let!(:external_upload_stub) { Fabricate(:attachment_external_upload_stub, created_by: user, filesize: object_size) }
before do
UploadCreator.any_instance.stubs(:generate_fake_sha1_hash).returns("testbc60eb18e8f974cbfae8bb0f069c3a311024")
diff --git a/vendor/assets/javascripts/uppy.js b/vendor/assets/javascripts/uppy.js
index 36cf75c3923..ef9e4517322 100644
--- a/vendor/assets/javascripts/uppy.js
+++ b/vendor/assets/javascripts/uppy.js
@@ -1,4 +1,18 @@
(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<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
+// We need a custom build of Uppy because we do not use webpack for
+// our JS modules/build. The only way to get what you want from Uppy
+// is to use the webpack modules or to include the entire Uppy project
+// including all plugins in a single JS file. This way we can just
+// use the plugins we actually want.
+window.Uppy = {}
+Uppy.Core = require('./packages/@uppy/core/lib/index.js')
+Uppy.BasePlugin = Uppy.Core.BasePlugin
+Uppy.XHRUpload = require('./packages/@uppy/xhr-upload/lib/index.js')
+Uppy.AwsS3 = require('./packages/@uppy/aws-s3/lib/index.js')
+Uppy.AwsS3Multipart = require('./packages/@uppy/aws-s3-multipart/lib/index.js')
+Uppy.DropTarget = require('./packages/@uppy/drop-target/lib/index.js')
+
+},{"./packages/@uppy/aws-s3-multipart/lib/index.js":14,"./packages/@uppy/aws-s3/lib/index.js":34,"./packages/@uppy/core/lib/index.js":60,"./packages/@uppy/drop-target/lib/index.js":75,"./packages/@uppy/xhr-upload/lib/index.js":83}],2:[function(require,module,exports){
// Adapted from https://github.com/Flet/prettier-bytes/
// Changing 1000 bytes to 1024, so we can keep uppercase KB vs kB
// ISC License (c) Dan Flettre https://github.com/Flet/prettier-bytes/blob/master/LICENSE
@@ -31,4672 +45,2845 @@ module.exports = function prettierBytes (num) {
}
}
-},{}],2:[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;
- }
-};
+},{}],3:[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
+ */
-function ensureInt(value) {
- if (typeof value === 'string') {
- return parseInt(value, 10);
- }
+var fingerprint = require('./lib/fingerprint.js');
+var pad = require('./lib/pad.js');
+var getRandomValue = require('./lib/getRandomValue.js');
- if (typeof value === 'number') {
- return value;
- }
+var c = 0,
+ blockSize = 4,
+ base = 36,
+ discreteValues = Math.pow(base, blockSize);
- throw new TypeError('Expected a number');
+function randomBlock () {
+ return pad((getRandomValue() *
+ discreteValues << 0)
+ .toString(base), blockSize);
}
-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();
+function safeCounter () {
+ c = c < discreteValues ? c : 0;
+ c++; // this is not subliminal
+ return c - 1;
+}
- this.createdPromise.catch(function () {}); // silence uncaught rejection warning
- }
- /**
- * Was this upload aborted?
- *
- * If yes, we may need to throw an AbortError.
- *
- * @returns {boolean}
- */
+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),
- var _proto = MultipartUploader.prototype;
+ // Prevent same-machine collisions.
+ counter = pad(safeCounter().toString(base), blockSize),
- _proto._aborted = function _aborted() {
- return this.abortController.signal.aborted;
- };
+ // A few chars to generate distinct ids for different
+ // clients (so different computers are far less
+ // likely to generate the same id)
+ print = fingerprint(),
- _proto._initChunks = function _initChunks() {
- var chunks = [];
- var desiredChunkSize = this.options.getChunkSize(this.file); // at least 5MB per request, at most 10k requests
+ // Grab some more chars from Math.random()
+ random = randomBlock() + randomBlock();
- 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
+ return letter + timestamp + counter + print + random;
+}
- 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));
- }
- }
+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);
- this.chunks = chunks;
- this.chunkState = chunks.map(function () {
- return {
- uploaded: 0,
- busy: false,
- done: false
- };
- });
- };
+ return date.slice(-2) +
+ counter + print + random;
+};
- _proto._createUpload = function _createUpload() {
- var _this = this;
+cuid.isCuid = function isCuid (stringToCheck) {
+ if (typeof stringToCheck !== 'string') return false;
+ if (stringToCheck.startsWith('c')) return true;
+ return false;
+};
- 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';
+cuid.isSlug = function isSlug (stringToCheck) {
+ if (typeof stringToCheck !== 'string') return false;
+ var stringLength = stringToCheck.length;
+ if (stringLength >= 7 && stringLength <= 10) return true;
+ return false;
+};
- if (!valid) {
- throw new TypeError('AwsS3/Multipart: Got incorrect result from `createMultipartUpload()`, expected an object `{ uploadId, key }`.');
- }
+cuid.fingerprint = fingerprint;
- _this.key = result.key;
- _this.uploadId = result.uploadId;
+module.exports = cuid;
- _this.options.onStart(result);
+},{"./lib/fingerprint.js":4,"./lib/getRandomValue.js":5,"./lib/pad.js":6}],4:[function(require,module,exports){
+var pad = require('./pad.js');
- _this._uploadParts();
- }).catch(function (err) {
- _this._onError(err);
- });
- };
+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);
- _proto._resumeUpload = function _resumeUpload() {
- var _this2 = this;
+module.exports = function fingerprint () {
+ return clientId;
+};
- 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
- });
- }
- });
+},{"./pad.js":6}],5:[function(require,module,exports){
- _this2._uploadParts();
- }).catch(function (err) {
- _this2._onError(err);
- });
- };
+var getRandomValue;
- _proto._uploadParts = function _uploadParts() {
- var _this3 = this;
+var crypto = typeof window !== 'undefined' &&
+ (window.crypto || window.msCrypto) ||
+ typeof self !== 'undefined' &&
+ self.crypto;
- if (this.isPaused) return;
- var need = this.options.limit - this.partsInProgress;
- if (need === 0) return; // All parts are uploaded.
+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;
+}
- if (this.chunkState.every(function (state) {
- return state.done;
- })) {
- this._completeUpload();
+module.exports = getRandomValue;
- return;
- }
+},{}],6:[function(require,module,exports){
+module.exports = function pad (num, size) {
+ var s = '000000000' + num;
+ return s.substr(s.length - size);
+};
- var candidates = [];
+},{}],7:[function(require,module,exports){
+(function (global){(function (){
+/**
+ * lodash (Custom Build) <https://lodash.com/>
+ * Build: `lodash modularize exports="npm" -o ./`
+ * Copyright jQuery Foundation and other contributors <https://jquery.org/>
+ * Released under MIT license <https://lodash.com/license>
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ */
- for (var i = 0; i < this.chunkState.length; i++) {
- var state = this.chunkState[i];
- if (state.done || state.busy) continue;
- candidates.push(i);
+/** Used as the `TypeError` message for "Functions" methods. */
+var FUNC_ERROR_TEXT = 'Expected a function';
- if (candidates.length >= need) {
- break;
- }
- }
+/** Used as references for various `Number` constants. */
+var NAN = 0 / 0;
- candidates.forEach(function (index) {
- _this3._uploadPartRetryable(index).then(function () {
- // Continue uploading parts
- _this3._uploadParts();
- }, function (err) {
- _this3._onError(err);
- });
- });
- };
+/** `Object#toString` result references. */
+var symbolTag = '[object Symbol]';
- _proto._retryable = function _retryable(_ref) {
- var _this4 = this;
+/** Used to match leading and trailing whitespace. */
+var reTrim = /^\s+|\s+$/g;
- var before = _ref.before,
- attempt = _ref.attempt,
- after = _ref.after;
- var retryDelays = this.options.retryDelays;
- var signal = this.abortController.signal;
- if (before) before();
+/** Used to detect bad signed hexadecimal string values. */
+var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
- function shouldRetry(err) {
- if (err.source && typeof err.source.status === 'number') {
- var status = err.source.status; // 0 probably indicates network failure
+/** Used to detect binary string values. */
+var reIsBinary = /^0b[01]+$/i;
- return status === 0 || status === 409 || status === 423 || status >= 500 && status < 600;
- }
+/** Used to detect octal string values. */
+var reIsOctal = /^0o[0-7]+$/i;
- return false;
- }
+/** Built-in method references without a dependency on `root`. */
+var freeParseInt = parseInt;
- var doAttempt = function doAttempt(retryAttempt) {
- return attempt().catch(function (err) {
- if (_this4._aborted()) throw createAbortError();
+/** Detect free variable `global` from Node.js. */
+var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
- if (shouldRetry(err) && retryAttempt < retryDelays.length) {
- return delay(retryDelays[retryAttempt], {
- signal: signal
- }).then(function () {
- return doAttempt(retryAttempt + 1);
- });
- }
+/** Detect free variable `self`. */
+var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
- throw err;
- });
- };
+/** Used as a reference to the global object. */
+var root = freeGlobal || freeSelf || Function('return this')();
- return doAttempt(0).then(function (result) {
- if (after) after();
- return result;
- }, function (err) {
- if (after) after();
- throw err;
- });
- };
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
- _proto._uploadPartRetryable = function _uploadPartRetryable(index) {
- var _this5 = this;
+/**
+ * Used to resolve the
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
+ * of values.
+ */
+var objectToString = objectProto.toString;
- return this._retryable({
- before: function before() {
- _this5.partsInProgress += 1;
- },
- attempt: function attempt() {
- return _this5._uploadPart(index);
- },
- after: function after() {
- _this5.partsInProgress -= 1;
- }
- });
- };
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMax = Math.max,
+ nativeMin = Math.min;
- _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';
+/**
+ * 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();
+};
- if (!valid) {
- throw new TypeError('AwsS3/Multipart: Got incorrect result from `prepareUploadPart()`, expected an object `{ url }`.');
- }
+/**
+ * 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;
- return result;
- }).then(function (_ref2) {
- var url = _ref2.url,
- headers = _ref2.headers;
+ 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;
+ }
- if (_this6._aborted()) {
- _this6.chunkState[index].busy = false;
- throw createAbortError();
- }
+ function invokeFunc(time) {
+ var args = lastArgs,
+ thisArg = lastThis;
- return _this6._uploadPartBytes(index, url, headers);
- });
- };
+ lastArgs = lastThis = undefined;
+ lastInvokeTime = time;
+ result = func.apply(thisArg, args);
+ return result;
+ }
- _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);
- };
+ 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;
+ }
- _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);
- };
+ function remainingWait(time) {
+ var timeSinceLastCall = time - lastCallTime,
+ timeSinceLastInvoke = time - lastInvokeTime,
+ result = wait - timeSinceLastCall;
- _proto._uploadPartBytes = function _uploadPartBytes(index, url, headers) {
- var _this7 = this;
+ return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
+ }
- 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);
+ function shouldInvoke(time) {
+ var timeSinceLastCall = time - lastCallTime,
+ timeSinceLastInvoke = time - lastInvokeTime;
- if (headers) {
- Object.keys(headers).map(function (key) {
- xhr.setRequestHeader(key, headers[key]);
- });
+ // 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));
+ }
- xhr.responseType = 'text';
+ function trailingEdge(time) {
+ timerId = undefined;
- function cleanup() {
- signal.removeEventListener('abort', onabort);
+ // 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 onabort() {
- xhr.abort();
+ function cancel() {
+ if (timerId !== undefined) {
+ clearTimeout(timerId);
}
+ lastInvokeTime = 0;
+ lastArgs = lastCallTime = lastThis = timerId = undefined;
+ }
- 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.
+ function flush() {
+ return timerId === undefined ? result : trailingEdge(now());
+ }
+ function debounced() {
+ var time = now(),
+ isInvoking = shouldInvoke(time);
- var etag = ev.target.getResponseHeader('ETag');
+ lastArgs = arguments;
+ lastThis = this;
+ lastCallTime = time;
- 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. See https://uppy.io/docs/aws-s3-multipart#S3-Bucket-Configuration for instructions.'));
- return;
+ if (isInvoking) {
+ if (timerId === undefined) {
+ return leadingEdge(lastCallTime);
+ }
+ if (maxing) {
+ // Handle invocations in a tight loop.
+ timerId = setTimeout(timerExpired, wait);
+ return invokeFunc(lastCallTime);
}
-
- _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 = {};
+ if (timerId === undefined) {
+ timerId = setTimeout(timerExpired, wait);
}
-
- var really = opts.really || false;
- if (!really) return this.pause();
-
- this._abortUpload();
- };
-
- return MultipartUploader;
-}();
-
-module.exports = MultipartUploader;
-},{"@uppy/utils/lib/AbortController":21,"@uppy/utils/lib/delay":27}],3:[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; _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-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 result;
}
-
- return res;
+ debounced.cancel = cancel;
+ debounced.flush = flush;
+ return debounced;
}
-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);
-
- var cFile = _this2.uppy.getFile(file.id);
-
- _this2.uppy.emit('upload-success', cFile || 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 () {};
- });
- }); // Don't double-emit upload-started for Golden Retriever-restored files that were already started
-
-
- if (!file.progress.uploadStarted || !file.isRestored) {
- _this2.uppy.emit('upload-started', file);
- }
- });
- };
-
- _proto.uploadRemote = function uploadRemote(file) {
- var _this3 = this;
-
- this.resetUploaderReferences(file.id); // Don't double-emit upload-started for Golden Retriever-restored files that were already started
-
- if (!file.progress.uploadStarted || !file.isRestored) {
- 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.18", _temp);
-},{"./MultipartUploader":2,"@uppy/companion-client":12,"@uppy/core":15,"@uppy/utils/lib/EventTracker":22,"@uppy/utils/lib/RateLimitedQueue":25,"@uppy/utils/lib/emitSocketProgress":28,"@uppy/utils/lib/getSocketHost":40}],4:[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);
- }
-
- 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":12,"@uppy/utils/lib/EventTracker":22,"@uppy/utils/lib/NetworkError":23,"@uppy/utils/lib/ProgressTimeout":24,"@uppy/utils/lib/emitSocketProgress":28,"@uppy/utils/lib/getSocketHost":40,"@uppy/utils/lib/isNetworkError":44,"cuid":50}],5:[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; _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-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 breaking change, so it is
- * planned for some future Uppy version.
- *
- * 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("</" + tagName + ">", 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.<string, Promise>}
- */
- 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.removeUploader(this.handleUpload);
- };
-
- return AwsS3;
-}(Plugin), _class.VERSION = "1.7.12", _temp);
-},{"./MiniXHRUpload":4,"./isXml":6,"@uppy/companion-client":12,"@uppy/core":15,"@uppy/utils/lib/RateLimitedQueue":25,"@uppy/utils/lib/Translator":26,"@uppy/utils/lib/hasProperty":42,"@uppy/utils/lib/settle":46,"qs-stringify":58,"url-parse":61}],6:[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;
-},{}],7:[function(require,module,exports){
-'use strict';
-
-function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, 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 { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], 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;
-},{}],8:[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; _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-var qsStringify = require('qs-stringify');
-
-var URL = require('url-parse');
-
-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 = new URL(opts.companionUrl).origin;
- }
- }
-
- plugin.storage = plugin.opts.storage || tokenStorage;
- };
-
- return Provider;
-}(RequestClient);
-},{"./RequestClient":9,"./tokenStorage":13,"qs-stringify":58,"url-parse":61}],9:[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) {
- if (!err.isAuthError) {
- err.message = "Could not get " + _this4._getUrl(path) + ". " + err.message;
- }
-
- 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) {
- if (!err.isAuthError) {
- err.message = "Could not post " + _this5._getUrl(path) + ". " + err.message;
- }
-
- 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) {
- if (!err.isAuthError) {
- err.message = "Could not delete " + _this6._getUrl(path) + ". " + err.message;
- }
-
- 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.10.2", _temp);
-},{"./AuthError":7,"@uppy/utils/lib/fetchWithNetworkError":29}],10:[function(require,module,exports){
-'use strict';
-
-function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-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;
+/**
+ * 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;
- _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;
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
}
-
- 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":9}],11:[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();
- }
+ 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
+ });
+}
- 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":56}],12:[function(require,module,exports){
-'use strict';
/**
- * Manages communications with Companion
+ * 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');
+}
-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":8,"./RequestClient":9,"./SearchProvider":10,"./Socket":11}],13:[function(require,module,exports){
-'use strict';
/**
- * This module serves as an Async wrapper for LocalStorage
+ * 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';
+}
-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();
- });
-};
-},{}],14:[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.
+ * 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 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;
- };
+function isSymbol(value) {
+ return typeof value == 'symbol' ||
+ (isObjectLike(value) && objectToString.call(value) == symbolTag);
}
+
/**
- * 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.
+ * 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
*
- * @param {object} main Uppy core object
- * @param {object} object with plugin options
- * @returns {Array|string} files or success/fail message
+ * _.toNumber(Infinity);
+ * // => Infinity
+ *
+ * _.toNumber('3.2');
+ * // => 3.2
*/
-
-
-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);
+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);
+}
- var _proto = Plugin.prototype;
+module.exports = throttle;
- _proto.getPluginState = function getPluginState() {
- var _this$uppy$getState = this.uppy.getState(),
- plugins = _this$uppy$getState.plugins;
+}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],8:[function(require,module,exports){
+var wildcard = require('wildcard');
+var reMimePartSplit = /[\/\+\.]/;
- return plugins[this.id] || {};
- };
+/**
+ # mime-match
- _proto.setPluginState = function setPluginState(update) {
- var _extends2;
+ A simple function to checker whether a target mime type matches a mime-type
+ pattern (e.g. image/jpeg matches image/jpeg OR image/*).
- var _this$uppy$getState2 = this.uppy.getState(),
- plugins = _this$uppy$getState2.plugins;
+ ## Example Usage
- this.uppy.setState({
- plugins: _extends({}, plugins, (_extends2 = {}, _extends2[this.id] = _extends({}, plugins[this.id], update), _extends2))
- });
- };
+ <<< example.js
- _proto.setOptions = function setOptions(newOpts) {
- this.opts = _extends({}, this.opts, newOpts);
- this.setPluginState(); // so that UI re-renders with new options
- };
+**/
+module.exports = function(target, pattern) {
+ function test(pattern) {
+ var result = wildcard(pattern, target, reMimePartSplit);
- _proto.update = function update(state) {
- if (typeof this.el === 'undefined') {
- return;
- }
+ // ensure that we have a valid mime type (should have two parts)
+ return result && result.length >= 2;
+ }
- if (this._updateUI) {
- this._updateUI(state);
- }
- } // Called after every state update, after everything's mounted. Debounced.
- ;
+ return pattern ? test(pattern.split(';')[0]) : test;
+};
- _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.
- */
- ;
+},{"wildcard":12}],9:[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 = {}
- _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.
+ * 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)
- this.uppy.iteratePlugins(function (plugin) {
- if (plugin instanceof Target) {
- targetPlugin = plugin;
- return false;
- }
- });
+ if (toEmit.length) {
+ emitAll(event, toEmit, [arg1, arg2, arg3, arg4, arg5, arg6])
}
+ }
- if (targetPlugin) {
- this.uppy.log("Installing " + callerPluginName + " to " + targetPlugin.id);
- this.parent = targetPlugin;
- this.el = targetPlugin.addTarget(plugin);
- this.onMount();
- return this.el;
+ /**
+ * 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] = []
}
- this.uppy.log("Not installing " + callerPluginName);
- var message = "Invalid target option given to " + callerPluginName + ".";
+ _fns[event].push(fn)
+ }
- 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 <script> tag initializing Uppy is right before the closing </body> tag at the end of the page. ' + '(see https://github.com/transloadit/uppy/issues/1042)\n\n' + 'If you meant to target a plugin, please confirm that your `import` statements or `require` calls are correct.';
+ /**
+ * 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)
+ }
- throw new Error(message);
- };
-
- _proto.render = function render(state) {
- throw new Error('Extend the render method to add your plugin to a DOM element');
- };
+ /**
+ * 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 = []
- _proto.addTarget = function addTarget(plugin) {
- throw new Error('Extend the addTarget method to add your plugin to another plugin\'s target');
- };
+ if (event && fn) {
+ var fns = this._fns[event]
+ var i = 0
+ var l = fns ? fns.length : 0
- _proto.unmount = function unmount() {
- if (this.isTargetDOMEl && this.el && this.el.parentNode) {
- this.el.parentNode.removeChild(this.el);
+ for (i; i < l; i++) {
+ if (fns[i] !== fn) {
+ keep.push(fns[i])
+ }
+ }
}
- };
- _proto.install = function install() {};
+ keep.length ? this._fns[event] = keep : delete this._fns[event]
+ }
- _proto.uninstall = function uninstall() {
- this.unmount();
- };
+ 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)]
- return Plugin;
-}();
-},{"@uppy/utils/lib/findDOMElement":30,"preact":57}],15:[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 keys = Object.keys(_fns)
+ var i = 0
+ var l = keys.length
-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); } }
+ for (i; i < l; i++) {
+ var key = keys[i]
+ if (key === '*') {
+ out = out.concat(_fns[key])
+ }
-function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+ if (args.length === 2 && args[0] === key) {
+ out = out.concat(_fns[key])
+ break
+ }
+ }
-function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
+ return out
+ }
-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 emitAll (e, fns, args) {
+ var i = 0
+ var l = fns.length
-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); }
+ for (i; i < l; i++) {
+ if (!fns[i]) break
+ fns[i].event = e
+ fns[i].apply(fns[i], args)
+ }
+ }
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
+ return emitter
+}
-function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
+},{}],10:[function(require,module,exports){
+var n,l,u,t,i,o,r,f,e={},c=[],s=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function a(n,l){for(var u in l)n[u]=l[u];return n}function p(n){var l=n.parentNode;l&&l.removeChild(n)}function v(l,u,t){var i,o,r,f={};for(r in u)"key"==r?i=u[r]:"ref"==r?o=u[r]:f[r]=u[r];if(arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):t),"function"==typeof l&&null!=l.defaultProps)for(r in l.defaultProps)void 0===f[r]&&(f[r]=l.defaultProps[r]);return h(l,f,i,o,null)}function h(n,t,i,o,r){var f={type:n,props:t,key:i,ref:o,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==r?++u:r};return null!=l.vnode&&l.vnode(f),f}function y(n){return n.children}function d(n,l){this.props=n,this.context=l}function _(n,l){if(null==l)return n.__?_(n.__,n.__.__k.indexOf(n)+1):null;for(var u;l<n.__k.length;l++)if(null!=(u=n.__k[l])&&null!=u.__e)return u.__e;return"function"==typeof n.type?_(n):null}function k(n){var l,u;if(null!=(n=n.__)&&null!=n.__c){for(n.__e=n.__c.base=null,l=0;l<n.__k.length;l++)if(null!=(u=n.__k[l])&&null!=u.__e){n.__e=n.__c.base=u.__e;break}return k(n)}}function x(n){(!n.__d&&(n.__d=!0)&&i.push(n)&&!b.__r++||r!==l.debounceRendering)&&((r=l.debounceRendering)||o)(b)}function b(){for(var n;b.__r=i.length;)n=i.sort(function(n,l){return n.__v.__b-l.__v.__b}),i=[],n.some(function(n){var l,u,t,i,o,r;n.__d&&(o=(i=(l=n).__v).__e,(r=l.__P)&&(u=[],(t=a({},i)).__v=i.__v+1,I(r,i,t,l.__n,void 0!==r.ownerSVGElement,null!=i.__h?[o]:null,u,null==o?_(i):o,i.__h),T(u,i),i.__e!=o&&k(i)))})}function m(n,l,u,t,i,o,r,f,s,a){var p,v,d,k,x,b,m,A=t&&t.__k||c,P=A.length;for(u.__k=[],p=0;p<l.length;p++)if(null!=(k=u.__k[p]=null==(k=l[p])||"boolean"==typeof k?null:"string"==typeof k||"number"==typeof k||"bigint"==typeof k?h(null,k,null,null,k):Array.isArray(k)?h(y,{children:k},null,null,null):k.__b>0?h(k.type,k.props,k.key,null,k.__v):k)){if(k.__=u,k.__b=u.__b+1,null===(d=A[p])||d&&k.key==d.key&&k.type===d.type)A[p]=void 0;else for(v=0;v<P;v++){if((d=A[v])&&k.key==d.key&&k.type===d.type){A[v]=void 0;break}d=null}I(n,k,d=d||e,i,o,r,f,s,a),x=k.__e,(v=k.ref)&&d.ref!=v&&(m||(m=[]),d.ref&&m.push(d.ref,null,k),m.push(v,k.__c||x,k)),null!=x?(null==b&&(b=x),"function"==typeof k.type&&null!=k.__k&&k.__k===d.__k?k.__d=s=g(k,s,n):s=w(n,k,d,A,x,s),a||"option"!==u.type?"function"==typeof u.type&&(u.__d=s):n.value=""):s&&d.__e==s&&s.parentNode!=n&&(s=_(d))}for(u.__e=b,p=P;p--;)null!=A[p]&&("function"==typeof u.type&&null!=A[p].__e&&A[p].__e==u.__d&&(u.__d=_(t,p+1)),L(A[p],A[p]));if(m)for(p=0;p<m.length;p++)z(m[p],m[++p],m[++p])}function g(n,l,u){var t,i;for(t=0;t<n.__k.length;t++)(i=n.__k[t])&&(i.__=n,l="function"==typeof i.type?g(i,l,u):w(u,i,i,n.__k,i.__e,l));return l}function w(n,l,u,t,i,o){var r,f,e;if(void 0!==l.__d)r=l.__d,l.__d=void 0;else if(null==u||i!=o||null==i.parentNode)n:if(null==o||o.parentNode!==n)n.appendChild(i),r=null;else{for(f=o,e=0;(f=f.nextSibling)&&e<t.length;e+=2)if(f==i)break n;n.insertBefore(i,o),r=o}return void 0!==r?r:i.nextSibling}function A(n,l,u,t,i){var o;for(o in u)"children"===o||"key"===o||o in l||C(n,o,null,u[o],t);for(o in l)i&&"function"!=typeof l[o]||"children"===o||"key"===o||"value"===o||"checked"===o||u[o]===l[o]||C(n,o,l[o],u[o],t)}function P(n,l,u){"-"===l[0]?n.setProperty(l,u):n[l]=null==u?"":"number"!=typeof u||s.test(l)?u:u+"px"}function C(n,l,u,t,i){var o;n:if("style"===l)if("string"==typeof u)n.style.cssText=u;else{if("string"==typeof t&&(n.style.cssText=t=""),t)for(l in t)u&&l in u||P(n.style,l,"");if(u)for(l in u)t&&u[l]===t[l]||P(n.style,l,u[l])}else if("o"===l[0]&&"n"===l[1])o=l!==(l=l.replace(/Capture$/,"")),l=l.toLowerCase()in n?l.toLowerCase().slice(2):l.slice(2),n.l||(n.l={}),n.l[l+o]=u,u?t||n.addEventListener(l,o?H:$,o):n.removeEventListener(l,o?H:$,o);else if("dangerouslySetInnerHTML"!==l){if(i)l=l.replace(/xlink[H:h]/,"h").replace(/sName$/,"s");else if("href"!==l&&"list"!==l&&"form"!==l&&"tabIndex"!==l&&"download"!==l&&l in n)try{n[l]=null==u?"":u;break n}catch(n){}"function"==typeof u||(null!=u&&(!1!==u||"a"===l[0]&&"r"===l[1])?n.setAttribute(l,u):n.removeAttribute(l))}}function $(n){this.l[n.type+!1](l.event?l.event(n):n)}function H(n){this.l[n.type+!0](l.event?l.event(n):n)}function I(n,u,t,i,o,r,f,e,c){var s,p,v,h,_,k,x,b,g,w,A,P=u.type;if(void 0!==u.constructor)return null;null!=t.__h&&(c=t.__h,e=u.__e=t.__e,u.__h=null,r=[e]),(s=l.__b)&&s(u);try{n:if("function"==typeof P){if(b=u.props,g=(s=P.contextType)&&i[s.__c],w=s?g?g.props.value:s.__:i,t.__c?x=(p=u.__c=t.__c).__=p.__E:("prototype"in P&&P.prototype.render?u.__c=p=new P(b,w):(u.__c=p=new d(b,w),p.constructor=P,p.render=M),g&&g.sub(p),p.props=b,p.state||(p.state={}),p.context=w,p.__n=i,v=p.__d=!0,p.__h=[]),null==p.__s&&(p.__s=p.state),null!=P.getDerivedStateFromProps&&(p.__s==p.state&&(p.__s=a({},p.__s)),a(p.__s,P.getDerivedStateFromProps(b,p.__s))),h=p.props,_=p.state,v)null==P.getDerivedStateFromProps&&null!=p.componentWillMount&&p.componentWillMount(),null!=p.componentDidMount&&p.__h.push(p.componentDidMount);else{if(null==P.getDerivedStateFromProps&&b!==h&&null!=p.componentWillReceiveProps&&p.componentWillReceiveProps(b,w),!p.__e&&null!=p.shouldComponentUpdate&&!1===p.shouldComponentUpdate(b,p.__s,w)||u.__v===t.__v){p.props=b,p.state=p.__s,u.__v!==t.__v&&(p.__d=!1),p.__v=u,u.__e=t.__e,u.__k=t.__k,u.__k.forEach(function(n){n&&(n.__=u)}),p.__h.length&&f.push(p);break n}null!=p.componentWillUpdate&&p.componentWillUpdate(b,p.__s,w),null!=p.componentDidUpdate&&p.__h.push(function(){p.componentDidUpdate(h,_,k)})}p.context=w,p.props=b,p.state=p.__s,(s=l.__r)&&s(u),p.__d=!1,p.__v=u,p.__P=n,s=p.render(p.props,p.state,p.context),p.state=p.__s,null!=p.getChildContext&&(i=a(a({},i),p.getChildContext())),v||null==p.getSnapshotBeforeUpdate||(k=p.getSnapshotBeforeUpdate(h,_)),A=null!=s&&s.type===y&&null==s.key?s.props.children:s,m(n,Array.isArray(A)?A:[A],u,t,i,o,r,f,e,c),p.base=u.__e,u.__h=null,p.__h.length&&f.push(p),x&&(p.__E=p.__=null),p.__e=!1}else null==r&&u.__v===t.__v?(u.__k=t.__k,u.__e=t.__e):u.__e=j(t.__e,u,t,i,o,r,f,c);(s=l.diffed)&&s(u)}catch(n){u.__v=null,(c||null!=r)&&(u.__e=e,u.__h=!!c,r[r.indexOf(e)]=null),l.__e(n,u,t)}}function T(n,u){l.__c&&l.__c(u,n),n.some(function(u){try{n=u.__h,u.__h=[],n.some(function(n){n.call(u)})}catch(n){l.__e(n,u.__v)}})}function j(l,u,t,i,o,r,f,c){var s,a,v,h=t.props,y=u.props,d=u.type,k=0;if("svg"===d&&(o=!0),null!=r)for(;k<r.length;k++)if((s=r[k])&&(s===l||(d?s.localName==d:3==s.nodeType))){l=s,r[k]=null;break}if(null==l){if(null===d)return document.createTextNode(y);l=o?document.createElementNS("http://www.w3.org/2000/svg",d):document.createElement(d,y.is&&y),r=null,c=!1}if(null===d)h===y||c&&l.data===y||(l.data=y);else{if(r=r&&n.call(l.childNodes),a=(h=t.props||e).dangerouslySetInnerHTML,v=y.dangerouslySetInnerHTML,!c){if(null!=r)for(h={},k=0;k<l.attributes.length;k++)h[l.attributes[k].name]=l.attributes[k].value;(v||a)&&(v&&(a&&v.__html==a.__html||v.__html===l.innerHTML)||(l.innerHTML=v&&v.__html||""))}if(A(l,y,h,o,c),v)u.__k=[];else if(k=u.props.children,m(l,Array.isArray(k)?k:[k],u,t,i,o&&"foreignObject"!==d,r,f,r?r[0]:t.__k&&_(t,0),c),null!=r)for(k=r.length;k--;)null!=r[k]&&p(r[k]);c||("value"in y&&void 0!==(k=y.value)&&(k!==l.value||"progress"===d&&!k)&&C(l,"value",k,h.value,!1),"checked"in y&&void 0!==(k=y.checked)&&k!==l.checked&&C(l,"checked",k,h.checked,!1))}return l}function z(n,u,t){try{"function"==typeof n?n(u):n.current=u}catch(n){l.__e(n,t)}}function L(n,u,t){var i,o;if(l.unmount&&l.unmount(n),(i=n.ref)&&(i.current&&i.current!==n.__e||z(i,null,u)),null!=(i=n.__c)){if(i.componentWillUnmount)try{i.componentWillUnmount()}catch(n){l.__e(n,u)}i.base=i.__P=null}if(i=n.__k)for(o=0;o<i.length;o++)i[o]&&L(i[o],u,"function"!=typeof n.type);t||null==n.__e||p(n.__e),n.__e=n.__d=void 0}function M(n,l,u){return this.constructor(n,u)}function N(u,t,i){var o,r,f;l.__&&l.__(u,t),r=(o="function"==typeof i)?null:i&&i.__k||t.__k,f=[],I(t,u=(!o&&i||t).__k=v(y,null,[u]),r||e,e,void 0!==t.ownerSVGElement,!o&&i?[i]:r?null:t.firstChild?n.call(t.childNodes):null,f,!o&&i?i:r?r.__e:t.firstChild,o),T(f,u)}n=c.slice,l={__e:function(n,l){for(var u,t,i;l=l.__;)if((u=l.__c)&&!u.__)try{if((t=u.constructor)&&null!=t.getDerivedStateFromError&&(u.setState(t.getDerivedStateFromError(n)),i=u.__d),null!=u.componentDidCatch&&(u.componentDidCatch(n),i=u.__d),i)return u.__E=u}catch(l){n=l}throw n}},u=0,t=function(n){return null!=n&&void 0===n.constructor},d.prototype.setState=function(n,l){var u;u=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=a({},this.state),"function"==typeof n&&(n=n(a({},u),this.props)),n&&a(u,n),null!=n&&this.__v&&(l&&this.__h.push(l),x(this))},d.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),x(this))},d.prototype.render=y,i=[],o="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,b.__r=0,f=0,exports.render=N,exports.hydrate=function n(l,u){N(l,u,n)},exports.createElement=v,exports.h=v,exports.Fragment=y,exports.createRef=function(){return{current:null}},exports.isValidElement=t,exports.Component=d,exports.cloneElement=function(l,u,t){var i,o,r,f=a({},l.props);for(r in u)"key"==r?i=u[r]:"ref"==r?o=u[r]:f[r]=u[r];return arguments.length>2&&(f.children=arguments.length>3?n.call(arguments,2):t),h(l.type,f,i||l.key,o||l.ref,null)},exports.createContext=function(n,l){var u={__c:l="__cC"+f++,__:n,Consumer:function(n,l){return n.children(l)},Provider:function(n){var u,t;return this.getChildContext||(u=[],(t={})[l]=this,this.getChildContext=function(){return t},this.shouldComponentUpdate=function(n){this.props.value!==n.value&&u.some(x)},this.sub=function(n){u.push(n);var l=n.componentWillUnmount;n.componentWillUnmount=function(){u.splice(u.indexOf(n),1),l&&l.call(n)}}),n.children}};return u.Provider.__=u.Consumer.contextType=u},exports.toChildArray=function n(l,u){return u=u||[],null==l||"boolean"==typeof l||(Array.isArray(l)?l.some(function(l){n(l,u)}):u.push(l)),u},exports.options=l;
-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); }
+},{}],11:[function(require,module,exports){
+var has = Object.prototype.hasOwnProperty
-/* global AggregateError */
-var Translator = require('@uppy/utils/lib/Translator');
+/**
+ * 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}
+ */
-var ee = require('namespace-emitter');
+module.exports = function queryStringify (obj, prefix) {
+ var pairs = []
+ for (var key in obj) {
+ if (!has.call(obj, key)) {
+ continue
+ }
-var cuid = require('cuid');
+ 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('&')
+}
-var throttle = require('lodash.throttle');
+},{}],12:[function(require,module,exports){
+/* jshint node: true */
+'use strict';
-var prettierBytes = require('@transloadit/prettier-bytes');
+/**
+ # wildcard
-var match = require('mime-match');
+ 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.
-var DefaultStore = require('@uppy/store-default');
+ ## Usage
-var getFileType = require('@uppy/utils/lib/getFileType');
+ It works with strings:
-var getFileNameAndExtension = require('@uppy/utils/lib/getFileNameAndExtension');
+ <<< examples/strings.js
-var generateFileID = require('@uppy/utils/lib/generateFileID');
+ Arrays:
-var findIndex = require('@uppy/utils/lib/findIndex');
+ <<< examples/arrays.js
-var supportsUploadProgress = require('./supportsUploadProgress');
+ Objects (matching against keys):
-var _require = require('./loggers'),
- justErrorsLogger = _require.justErrorsLogger,
- debugLogger = _require.debugLogger;
+ <<< examples/objects.js
-var Plugin = require('./Plugin');
+ While the library works in Node, if you are are looking for file-based
+ wildcard matching then you should have a look at:
-var _require2 = require('../package.json'),
- version = _require2.version; // Exported from here.
+ <https://github.com/isaacs/node-glob>
+**/
+function WildcardMatcher(text, separator) {
+ this.text = text = text || '';
+ this.hasWild = ~text.indexOf('*');
+ this.separator = separator;
+ this.parts = text.split(separator);
+}
-var RestrictionError = /*#__PURE__*/function (_Error) {
- _inheritsLoose(RestrictionError, _Error);
+WildcardMatcher.prototype.match = function(input) {
+ var matches = true;
+ var parts = this.parts;
+ var ii;
+ var partsCount = parts.length;
+ var testParts;
- function RestrictionError() {
- var _this;
+ 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;
+ }
+ }
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
+ // If matches, then return the component parts
+ matches = matches && testParts;
}
-
- _this = _Error.call.apply(_Error, [this].concat(args)) || this;
- _this.isRestriction = true;
- return _this;
}
+ else if (typeof input.splice == 'function') {
+ matches = [];
- return RestrictionError;
-}( /*#__PURE__*/_wrapNativeSuper(Error));
-/**
- * Uppy Core module.
- * Manages plugins, state updates, acts as an event bus,
- * adds/removes files and metadata.
- */
-
-
-var Uppy = /*#__PURE__*/function () {
- /**
- * Instantiate Uppy
- *
- * @param {object} opts — Uppy options
- */
- function Uppy(opts) {
- var _this2 = this;
-
- this.defaultLocale = {
- strings: {
- addBulkFilesFailed: {
- 0: 'Failed to add %{smart_count} file due to an internal error',
- 1: 'Failed to add %{smart_count} files due to internal errors'
- },
- youCanOnlyUploadX: {
- 0: 'You can only upload %{smart_count} file',
- 1: 'You can only upload %{smart_count} files'
- },
- youHaveToAtLeastSelectX: {
- 0: 'You have to select at least %{smart_count} file',
- 1: 'You have to select at least %{smart_count} files'
- },
- // The default `exceedsSize2` string only combines the `exceedsSize` string (%{backwardsCompat}) with the size.
- // Locales can override `exceedsSize2` to specify a different word order. This is for backwards compat with
- // Uppy 1.9.x and below which did a naive concatenation of `exceedsSize2 + size` instead of using a locale-specific
- // substitution.
- // TODO: In 2.0 `exceedsSize2` should be removed in and `exceedsSize` updated to use substitution.
- exceedsSize2: '%{backwardsCompat} %{size}',
- exceedsSize: '%{file} exceeds maximum allowed size of',
- inferiorSize: 'This file is smaller than the allowed size of %{size}',
- youCanOnlyUploadFileTypes: 'You can only upload: %{types}',
- noNewAlreadyUploading: 'Cannot add new files: already uploading',
- noDuplicates: 'Cannot add the duplicate file \'%{fileName}\', it already exists',
- companionError: 'Connection with Companion failed',
- companionUnauthorizeHint: 'To unauthorize to your %{provider} account, please go to %{url}',
- failedToUpload: 'Failed to upload %{file}',
- noInternetConnection: 'No Internet connection',
- connectedToInternet: 'Connected to the Internet',
- // Strings for remote providers
- noFilesFound: 'You have no files or folders here',
- selectX: {
- 0: 'Select %{smart_count}',
- 1: 'Select %{smart_count}'
- },
- selectAllFilesFromFolderNamed: 'Select all files from folder %{name}',
- unselectAllFilesFromFolderNamed: 'Unselect all files from folder %{name}',
- selectFileNamed: 'Select file %{name}',
- unselectFileNamed: 'Unselect file %{name}',
- openFolderNamed: 'Open folder %{name}',
- cancel: 'Cancel',
- logOut: 'Log out',
- filter: 'Filter',
- resetFilter: 'Reset filter',
- loading: 'Loading...',
- authenticateWithTitle: 'Please authenticate with %{pluginName} to select files',
- authenticateWith: 'Connect to %{pluginName}',
- searchImages: 'Search for images',
- enterTextToSearch: 'Enter text to search for images',
- backToSearch: 'Back to Search',
- emptyFolderAdded: 'No files were added from empty folder',
- folderAdded: {
- 0: 'Added %{smart_count} file from %{folder}',
- 1: 'Added %{smart_count} files from %{folder}'
- }
+ for (ii = input.length; ii--; ) {
+ if (this.match(input[ii])) {
+ matches[matches.length] = input[ii];
}
- };
- var defaultOptions = {
- id: 'uppy',
- autoProceed: false,
- allowMultipleUploads: true,
- debug: false,
- restrictions: {
- maxFileSize: null,
- minFileSize: null,
- maxTotalFileSize: null,
- maxNumberOfFiles: null,
- minNumberOfFiles: null,
- allowedFileTypes: null
- },
- meta: {},
- onBeforeFileAdded: function onBeforeFileAdded(currentFile) {
- return currentFile;
- },
- onBeforeUpload: function onBeforeUpload(files) {
- return files;
- },
- store: DefaultStore(),
- logger: justErrorsLogger,
- infoTimeout: 5000
- }; // Merge default options with the ones set by user,
- // making sure to merge restrictions too
-
- this.opts = _extends({}, defaultOptions, opts, {
- restrictions: _extends({}, defaultOptions.restrictions, opts && opts.restrictions)
- }); // Support debug: true for backwards-compatability, unless logger is set in opts
- // opts instead of this.opts to avoid comparing objects — we set logger: justErrorsLogger in defaultOptions
-
- if (opts && opts.logger && opts.debug) {
- this.log('You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.', 'warning');
- } else if (opts && opts.debug) {
- this.opts.logger = debugLogger;
}
+ }
+ else if (typeof input == 'object') {
+ matches = {};
- this.log("Using Core v" + this.constructor.VERSION);
-
- if (this.opts.restrictions.allowedFileTypes && this.opts.restrictions.allowedFileTypes !== null && !Array.isArray(this.opts.restrictions.allowedFileTypes)) {
- throw new TypeError('`restrictions.allowedFileTypes` must be an array');
+ for (var key in input) {
+ if (this.match(key)) {
+ matches[key] = input[key];
+ }
}
+ }
- this.i18nInit(); // Container for different types of plugins
-
- this.plugins = {};
- this.getState = this.getState.bind(this);
- this.getPlugin = this.getPlugin.bind(this);
- this.setFileMeta = this.setFileMeta.bind(this);
- this.setFileState = this.setFileState.bind(this);
- this.log = this.log.bind(this);
- this.info = this.info.bind(this);
- this.hideInfo = this.hideInfo.bind(this);
- this.addFile = this.addFile.bind(this);
- this.removeFile = this.removeFile.bind(this);
- this.pauseResume = this.pauseResume.bind(this);
- this.validateRestrictions = this.validateRestrictions.bind(this); // ___Why throttle at 500ms?
- // - We must throttle at >250ms for superfocus in Dashboard to work well
- // (because animation takes 0.25s, and we want to wait for all animations to be over before refocusing).
- // [Practical Check]: if thottle is at 100ms, then if you are uploading a file,
- // and click 'ADD MORE FILES', - focus won't activate in Firefox.
- // - We must throttle at around >500ms to avoid performance lags.
- // [Practical Check] Firefox, try to upload a big file for a prolonged period of time. Laptop will start to heat up.
-
- this.calculateProgress = throttle(this.calculateProgress.bind(this), 500, {
- leading: true,
- trailing: true
- });
- this.updateOnlineStatus = this.updateOnlineStatus.bind(this);
- this.resetProgress = this.resetProgress.bind(this);
- this.pauseAll = this.pauseAll.bind(this);
- this.resumeAll = this.resumeAll.bind(this);
- this.retryAll = this.retryAll.bind(this);
- this.cancelAll = this.cancelAll.bind(this);
- this.retryUpload = this.retryUpload.bind(this);
- this.upload = this.upload.bind(this);
- this.emitter = ee();
- this.on = this.on.bind(this);
- this.off = this.off.bind(this);
- this.once = this.emitter.once.bind(this.emitter);
- this.emit = this.emitter.emit.bind(this.emitter);
- this.preProcessors = [];
- this.uploaders = [];
- this.postProcessors = [];
- this.store = this.opts.store;
- this.setState({
- plugins: {},
- files: {},
- currentUploads: {},
- allowNewUpload: true,
- capabilities: {
- uploadProgress: supportsUploadProgress(),
- individualCancellation: true,
- resumableUploads: false
- },
- totalProgress: 0,
- meta: _extends({}, this.opts.meta),
- info: {
- isHidden: true,
- type: 'info',
- message: ''
- },
- recoveredState: null
- });
- this.storeUnsubscribe = this.store.subscribe(function (prevState, nextState, patch) {
- _this2.emit('state-update', prevState, nextState, patch);
-
- _this2.updateAll(nextState);
- }); // Exposing uppy object on window for debugging and testing
+ return matches;
+};
- if (this.opts.debug && typeof window !== 'undefined') {
- window[this.opts.id] = this;
- }
+module.exports = function(text, test, separator) {
+ var matcher = new WildcardMatcher(text, separator || /[\/\.]/);
+ if (typeof test != 'undefined') {
+ return matcher.match(test);
+ }
- this.addListeners(); // Re-enable if we’ll need some capabilities on boot, like isMobileDevice
- // this._setCapabilities()
- } // _setCapabilities = () => {
- // const capabilities = {
- // isMobileDevice: isMobileDevice()
- // }
- // this.setState({
- // ...this.getState().capabilities,
- // capabilities
- // })
- // }
+ return matcher;
+};
+},{}],13:[function(require,module,exports){
+"use strict";
- var _proto = Uppy.prototype;
+function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }
- _proto.on = function on(event, callback) {
- this.emitter.on(event, callback);
- return this;
- };
+var id = 0;
- _proto.off = function off(event, callback) {
- this.emitter.off(event, callback);
- return this;
- }
- /**
- * Iterate on all plugins and run `update` on them.
- * Called each time state changes.
- *
- */
- ;
+function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; }
- _proto.updateAll = function updateAll(state) {
- this.iteratePlugins(function (plugin) {
- plugin.update(state);
- });
- }
- /**
- * Updates state with a patch
- *
- * @param {object} patch {foo: 'bar'}
- */
- ;
+const {
+ AbortController,
+ createAbortError
+} = require('@uppy/utils/lib/AbortController');
- _proto.setState = function setState(patch) {
- this.store.setState(patch);
- }
- /**
- * Returns current state.
- *
- * @returns {object}
- */
- ;
+const delay = require('@uppy/utils/lib/delay');
- _proto.getState = function getState() {
- return this.store.getState();
- }
- /**
- * Back compat for when uppy.state is used instead of uppy.getState().
- */
- ;
+const MB = 1024 * 1024;
+const defaultOptions = {
+ limit: 1,
+ retryDelays: [0, 1000, 3000, 5000],
- /**
- * Shorthand to set state for a specific file.
- */
- _proto.setFileState = function setFileState(fileID, state) {
- var _extends2;
+ getChunkSize(file) {
+ return Math.ceil(file.size / 10000);
+ },
- if (!this.getState().files[fileID]) {
- throw new Error("Can\u2019t set state for " + fileID + " (the file could have been removed)");
- }
+ onStart() {},
- this.setState({
- files: _extends({}, this.getState().files, (_extends2 = {}, _extends2[fileID] = _extends({}, this.getState().files[fileID], state), _extends2))
- });
- };
+ onProgress() {},
- _proto.i18nInit = function i18nInit() {
- this.translator = new Translator([this.defaultLocale, this.opts.locale]);
- this.locale = this.translator.locale;
- this.i18n = this.translator.translate.bind(this.translator);
- this.i18nArray = this.translator.translateArray.bind(this.translator);
- };
+ onPartComplete() {},
- _proto.setOptions = function setOptions(newOpts) {
- this.opts = _extends({}, this.opts, newOpts, {
- restrictions: _extends({}, this.opts.restrictions, newOpts && newOpts.restrictions)
- });
+ onSuccess() {},
- if (newOpts.meta) {
- this.setMeta(newOpts.meta);
- }
+ onError(err) {
+ throw err;
+ }
- this.i18nInit();
+};
- if (newOpts.locale) {
- this.iteratePlugins(function (plugin) {
- plugin.setOptions();
- });
- } // Note: this is not the preact `setState`, it's an internal function that has the same name.
+function ensureInt(value) {
+ if (typeof value === 'string') {
+ return parseInt(value, 10);
+ }
+ if (typeof value === 'number') {
+ return value;
+ }
- this.setState(); // so that UI re-renders with new options
- };
+ throw new TypeError('Expected a number');
+}
- _proto.resetProgress = function resetProgress() {
- var defaultProgress = {
- percentage: 0,
- bytesUploaded: 0,
- uploadComplete: false,
- uploadStarted: null
- };
+var _aborted = /*#__PURE__*/_classPrivateFieldLooseKey("aborted");
- var files = _extends({}, this.getState().files);
+var _initChunks = /*#__PURE__*/_classPrivateFieldLooseKey("initChunks");
- var updatedFiles = {};
- Object.keys(files).forEach(function (fileID) {
- var updatedFile = _extends({}, files[fileID]);
+var _createUpload = /*#__PURE__*/_classPrivateFieldLooseKey("createUpload");
- updatedFile.progress = _extends({}, updatedFile.progress, defaultProgress);
- updatedFiles[fileID] = updatedFile;
- });
- this.setState({
- files: updatedFiles,
- totalProgress: 0
- });
- this.emit('reset-progress');
- };
+var _resumeUpload = /*#__PURE__*/_classPrivateFieldLooseKey("resumeUpload");
- _proto.addPreProcessor = function addPreProcessor(fn) {
- this.preProcessors.push(fn);
- };
+var _uploadParts = /*#__PURE__*/_classPrivateFieldLooseKey("uploadParts");
- _proto.removePreProcessor = function removePreProcessor(fn) {
- var i = this.preProcessors.indexOf(fn);
+var _retryable = /*#__PURE__*/_classPrivateFieldLooseKey("retryable");
- if (i !== -1) {
- this.preProcessors.splice(i, 1);
- }
- };
+var _prepareUploadParts = /*#__PURE__*/_classPrivateFieldLooseKey("prepareUploadParts");
- _proto.addPostProcessor = function addPostProcessor(fn) {
- this.postProcessors.push(fn);
- };
+var _uploadPartRetryable = /*#__PURE__*/_classPrivateFieldLooseKey("uploadPartRetryable");
- _proto.removePostProcessor = function removePostProcessor(fn) {
- var i = this.postProcessors.indexOf(fn);
+var _uploadPart = /*#__PURE__*/_classPrivateFieldLooseKey("uploadPart");
- if (i !== -1) {
- this.postProcessors.splice(i, 1);
- }
- };
+var _onPartProgress = /*#__PURE__*/_classPrivateFieldLooseKey("onPartProgress");
- _proto.addUploader = function addUploader(fn) {
- this.uploaders.push(fn);
- };
+var _onPartComplete = /*#__PURE__*/_classPrivateFieldLooseKey("onPartComplete");
- _proto.removeUploader = function removeUploader(fn) {
- var i = this.uploaders.indexOf(fn);
+var _uploadPartBytes = /*#__PURE__*/_classPrivateFieldLooseKey("uploadPartBytes");
- if (i !== -1) {
- this.uploaders.splice(i, 1);
- }
- };
+var _completeUpload = /*#__PURE__*/_classPrivateFieldLooseKey("completeUpload");
- _proto.setMeta = function setMeta(data) {
- var updatedMeta = _extends({}, this.getState().meta, data);
+var _abortUpload = /*#__PURE__*/_classPrivateFieldLooseKey("abortUpload");
- var updatedFiles = _extends({}, this.getState().files);
+var _onError = /*#__PURE__*/_classPrivateFieldLooseKey("onError");
- Object.keys(updatedFiles).forEach(function (fileID) {
- updatedFiles[fileID] = _extends({}, updatedFiles[fileID], {
- meta: _extends({}, updatedFiles[fileID].meta, data)
- });
+class MultipartUploader {
+ constructor(file, options) {
+ Object.defineProperty(this, _onError, {
+ value: _onError2
});
- this.log('Adding metadata:');
- this.log(data);
- this.setState({
- meta: updatedMeta,
- files: updatedFiles
+ Object.defineProperty(this, _abortUpload, {
+ value: _abortUpload2
});
- };
-
- _proto.setFileMeta = function setFileMeta(fileID, data) {
- var updatedFiles = _extends({}, this.getState().files);
+ Object.defineProperty(this, _completeUpload, {
+ value: _completeUpload2
+ });
+ Object.defineProperty(this, _uploadPartBytes, {
+ value: _uploadPartBytes2
+ });
+ Object.defineProperty(this, _onPartComplete, {
+ value: _onPartComplete2
+ });
+ Object.defineProperty(this, _onPartProgress, {
+ value: _onPartProgress2
+ });
+ Object.defineProperty(this, _uploadPart, {
+ value: _uploadPart2
+ });
+ Object.defineProperty(this, _uploadPartRetryable, {
+ value: _uploadPartRetryable2
+ });
+ Object.defineProperty(this, _prepareUploadParts, {
+ value: _prepareUploadParts2
+ });
+ Object.defineProperty(this, _retryable, {
+ value: _retryable2
+ });
+ Object.defineProperty(this, _uploadParts, {
+ value: _uploadParts2
+ });
+ Object.defineProperty(this, _resumeUpload, {
+ value: _resumeUpload2
+ });
+ Object.defineProperty(this, _createUpload, {
+ value: _createUpload2
+ });
+ Object.defineProperty(this, _initChunks, {
+ value: _initChunks2
+ });
+ Object.defineProperty(this, _aborted, {
+ value: _aborted2
+ });
+ this.options = { ...defaultOptions,
+ ...options
+ }; // Use default `getChunkSize` if it was null or something
- if (!updatedFiles[fileID]) {
- this.log('Was trying to set metadata for a file that has been removed: ', fileID);
- return;
+ if (!this.options.getChunkSize) {
+ this.options.getChunkSize = defaultOptions.getChunkSize;
}
- var newMeta = _extends({}, updatedFiles[fileID].meta, data);
+ 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.
- updatedFiles[fileID] = _extends({}, updatedFiles[fileID], {
- meta: newMeta
- });
- this.setState({
- files: updatedFiles
- });
+ this.createdPromise = Promise.reject(); // eslint-disable-line prefer-promise-reject-errors
+
+ this.isPaused = false;
+ this.partsInProgress = 0;
+ this.chunks = null;
+ this.chunkState = null;
+ this.lockedCandidatesForBatch = [];
+
+ _classPrivateFieldLooseBase(this, _initChunks)[_initChunks]();
+
+ this.createdPromise.catch(() => {}); // silence uncaught rejection warning
}
/**
- * Get a file object.
+ * Was this upload aborted?
*
- * @param {string} fileID The ID of the file object to return.
+ * If yes, we may need to throw an AbortError.
+ *
+ * @returns {boolean}
*/
- ;
- _proto.getFile = function getFile(fileID) {
- return this.getState().files[fileID];
+
+ start() {
+ this.isPaused = false;
+
+ if (this.uploadId) {
+ _classPrivateFieldLooseBase(this, _resumeUpload)[_resumeUpload]();
+ } else {
+ _classPrivateFieldLooseBase(this, _createUpload)[_createUpload]();
+ }
}
- /**
- * Get all files in an array.
- */
- ;
- _proto.getFiles = function getFiles() {
- var _this$getState = this.getState(),
- files = _this$getState.files;
+ pause() {
+ this.abortController.abort(); // Swap it out for a new controller, because this instance may be resumed later.
- return Object.keys(files).map(function (fileID) {
- return files[fileID];
- });
+ this.abortController = new AbortController();
+ this.isPaused = true;
}
- /**
- * A public wrapper for _checkRestrictions — checks if a file passes a set of restrictions.
- * For use in UI pluigins (like Providers), to disallow selecting files that won’t pass restrictions.
- *
- * @param {object} file object to check
- * @param {Array} [files] array to check maxNumberOfFiles and maxTotalFileSize
- * @returns {object} { result: true/false, reason: why file didn’t pass restrictions }
- */
- ;
- _proto.validateRestrictions = function validateRestrictions(file, files) {
- try {
- this.checkRestrictions(file, files);
- return {
- result: true
- };
- } catch (err) {
- return {
- result: false,
- reason: err.message
- };
- }
+ abort(opts = {}) {
+ const really = opts.really || false;
+ if (!really) return this.pause();
+
+ _classPrivateFieldLooseBase(this, _abortUpload)[_abortUpload]();
}
- /**
- * Check if file passes a set of restrictions set in options: maxFileSize, minFileSize,
- * maxNumberOfFiles and allowedFileTypes.
- *
- * @param {object} file object to check
- * @param {Array} [files] array to check maxNumberOfFiles and maxTotalFileSize
- * @private
- */
- ;
- _proto.checkRestrictions = function checkRestrictions(file, files) {
- if (files === void 0) {
- files = this.getFiles();
- }
+}
- var _this$opts$restrictio = this.opts.restrictions,
- maxFileSize = _this$opts$restrictio.maxFileSize,
- minFileSize = _this$opts$restrictio.minFileSize,
- maxTotalFileSize = _this$opts$restrictio.maxTotalFileSize,
- maxNumberOfFiles = _this$opts$restrictio.maxNumberOfFiles,
- allowedFileTypes = _this$opts$restrictio.allowedFileTypes;
+function _aborted2() {
+ return this.abortController.signal.aborted;
+}
- if (maxNumberOfFiles) {
- if (files.length + 1 > maxNumberOfFiles) {
- throw new RestrictionError("" + this.i18n('youCanOnlyUploadX', {
- smart_count: maxNumberOfFiles
- }));
- }
+function _initChunks2() {
+ const chunks = [];
+ const desiredChunkSize = this.options.getChunkSize(this.file); // at least 5MB per request, at most 10k requests
+
+ const minChunkSize = Math.max(5 * MB, Math.ceil(this.file.size / 10000));
+ const 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 (let i = 0; i < this.file.size; i += chunkSize) {
+ const end = Math.min(this.file.size, i + chunkSize);
+ chunks.push(this.file.slice(i, end));
}
+ }
- if (allowedFileTypes) {
- var isCorrectFileType = allowedFileTypes.some(function (type) {
- // check if this is a mime-type
- if (type.indexOf('/') > -1) {
- if (!file.type) return false;
- return match(file.type.replace(/;.*?$/, ''), type);
- } // otherwise this is likely an extension
+ this.chunks = chunks;
+ this.chunkState = chunks.map(() => ({
+ uploaded: 0,
+ busy: false,
+ done: false
+ }));
+}
+function _createUpload2() {
+ this.createdPromise = Promise.resolve().then(() => this.options.createMultipartUpload());
+ return this.createdPromise.then(result => {
+ if (_classPrivateFieldLooseBase(this, _aborted)[_aborted]()) throw createAbortError();
+ const valid = typeof result === 'object' && result && typeof result.uploadId === 'string' && typeof result.key === 'string';
- if (type[0] === '.' && file.extension) {
- return file.extension.toLowerCase() === type.substr(1).toLowerCase();
- }
+ if (!valid) {
+ throw new TypeError('AwsS3/Multipart: Got incorrect result from `createMultipartUpload()`, expected an object `{ uploadId, key }`.');
+ }
- return false;
- });
+ this.key = result.key;
+ this.uploadId = result.uploadId;
+ this.options.onStart(result);
- if (!isCorrectFileType) {
- var allowedFileTypesString = allowedFileTypes.join(', ');
- throw new RestrictionError(this.i18n('youCanOnlyUploadFileTypes', {
- types: allowedFileTypesString
- }));
+ _classPrivateFieldLooseBase(this, _uploadParts)[_uploadParts]();
+ }).catch(err => {
+ _classPrivateFieldLooseBase(this, _onError)[_onError](err);
+ });
+}
+
+async function _resumeUpload2() {
+ try {
+ const parts = await this.options.listParts({
+ uploadId: this.uploadId,
+ key: this.key
+ });
+ if (_classPrivateFieldLooseBase(this, _aborted)[_aborted]()) throw createAbortError();
+ parts.forEach(part => {
+ const i = part.PartNumber - 1;
+ this.chunkState[i] = {
+ uploaded: ensureInt(part.Size),
+ etag: part.ETag,
+ done: true
+ }; // Only add if we did not yet know about this part.
+
+ if (!this.parts.some(p => p.PartNumber === part.PartNumber)) {
+ this.parts.push({
+ PartNumber: part.PartNumber,
+ ETag: part.ETag
+ });
}
- } // We can't check maxTotalFileSize if the size is unknown.
+ });
+ _classPrivateFieldLooseBase(this, _uploadParts)[_uploadParts]();
+ } catch (err) {
+ _classPrivateFieldLooseBase(this, _onError)[_onError](err);
+ }
+}
- if (maxTotalFileSize && file.size != null) {
- var totalFilesSize = 0;
- totalFilesSize += file.size;
- files.forEach(function (f) {
- totalFilesSize += f.size;
- });
+function _uploadParts2() {
+ if (this.isPaused) return; // All parts are uploaded.
- if (totalFilesSize > maxTotalFileSize) {
- throw new RestrictionError(this.i18n('exceedsSize2', {
- backwardsCompat: this.i18n('exceedsSize'),
- size: prettierBytes(maxTotalFileSize),
- file: file.name
- }));
- }
- } // We can't check maxFileSize if the size is unknown.
+ if (this.chunkState.every(state => state.done)) {
+ _classPrivateFieldLooseBase(this, _completeUpload)[_completeUpload]();
+ return;
+ } // For a 100MB file, with the default min chunk size of 5MB and a limit of 10:
+ //
+ // Total 20 parts
+ // ---------
+ // Need 1 is 10
+ // Need 2 is 5
+ // Need 3 is 5
- if (maxFileSize && file.size != null) {
- if (file.size > maxFileSize) {
- throw new RestrictionError(this.i18n('exceedsSize2', {
- backwardsCompat: this.i18n('exceedsSize'),
- size: prettierBytes(maxFileSize),
- file: file.name
- }));
- }
- } // We can't check minFileSize if the size is unknown.
+ const need = this.options.limit - this.partsInProgress;
+ const completeChunks = this.chunkState.filter(state => state.done).length;
+ const remainingChunks = this.chunks.length - completeChunks;
+ let minNeeded = Math.ceil(this.options.limit / 2);
- if (minFileSize && file.size != null) {
- if (file.size < minFileSize) {
- throw new RestrictionError(this.i18n('inferiorSize', {
- size: prettierBytes(minFileSize)
- }));
- }
- }
+ if (minNeeded > remainingChunks) {
+ minNeeded = remainingChunks;
}
- /**
- * Check if minNumberOfFiles restriction is reached before uploading.
- *
- * @private
- */
- ;
- _proto.checkMinNumberOfFiles = function checkMinNumberOfFiles(files) {
- var minNumberOfFiles = this.opts.restrictions.minNumberOfFiles;
+ if (need < minNeeded) return;
+ const candidates = [];
- if (Object.keys(files).length < minNumberOfFiles) {
- throw new RestrictionError("" + this.i18n('youHaveToAtLeastSelectX', {
- smart_count: minNumberOfFiles
- }));
+ for (let i = 0; i < this.chunkState.length; i++) {
+ if (this.lockedCandidatesForBatch.includes(i)) continue;
+ const state = this.chunkState[i];
+ if (state.done || state.busy) continue;
+ candidates.push(i);
+
+ if (candidates.length >= need) {
+ break;
}
}
- /**
- * Logs an error, sets Informer message, then throws the error.
- * Emits a 'restriction-failed' event if it’s a restriction error
- *
- * @param {object | string} err — Error object or plain string message
- * @param {object} [options]
- * @param {boolean} [options.showInformer=true] — Sometimes developer might want to show Informer manually
- * @param {object} [options.file=null] — File object used to emit the restriction error
- * @param {boolean} [options.throwErr=true] — Errors shouldn’t be thrown, for example, in `upload-error` event
- * @private
- */
- ;
- _proto.showOrLogErrorAndThrow = function showOrLogErrorAndThrow(err, _temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- _ref$showInformer = _ref.showInformer,
- showInformer = _ref$showInformer === void 0 ? true : _ref$showInformer,
- _ref$file = _ref.file,
- file = _ref$file === void 0 ? null : _ref$file,
- _ref$throwErr = _ref.throwErr,
- throwErr = _ref$throwErr === void 0 ? true : _ref$throwErr;
+ if (candidates.length === 0) return;
- var message = typeof err === 'object' ? err.message : err;
- var details = typeof err === 'object' && err.details ? err.details : ''; // Restriction errors should be logged, but not as errors,
- // as they are expected and shown in the UI.
+ _classPrivateFieldLooseBase(this, _prepareUploadParts)[_prepareUploadParts](candidates).then(result => {
+ candidates.forEach(index => {
+ const partNumber = index + 1;
+ const prePreparedPart = {
+ url: result.presignedUrls[partNumber],
+ headers: result.headers
+ };
+
+ _classPrivateFieldLooseBase(this, _uploadPartRetryable)[_uploadPartRetryable](index, prePreparedPart).then(() => {
+ _classPrivateFieldLooseBase(this, _uploadParts)[_uploadParts]();
+ }, err => {
+ _classPrivateFieldLooseBase(this, _onError)[_onError](err);
+ });
+ });
+ });
+}
- var logMessageWithDetails = message;
+function _retryable2({
+ before,
+ attempt,
+ after
+}) {
+ const {
+ retryDelays
+ } = this.options;
+ const {
+ signal
+ } = this.abortController;
+ if (before) before();
- if (details) {
- logMessageWithDetails += " " + details;
+ function shouldRetry(err) {
+ if (err.source && typeof err.source.status === 'number') {
+ const {
+ status
+ } = err.source; // 0 probably indicates network failure
+
+ return status === 0 || status === 409 || status === 423 || status >= 500 && status < 600;
}
- if (err.isRestriction) {
- this.log(logMessageWithDetails);
- this.emit('restriction-failed', file, err);
- } else {
- this.log(logMessageWithDetails, 'error');
- } // Sometimes informer has to be shown manually by the developer,
- // for example, in `onBeforeFileAdded`.
+ return false;
+ }
+ const doAttempt = retryAttempt => attempt().catch(err => {
+ if (_classPrivateFieldLooseBase(this, _aborted)[_aborted]()) throw createAbortError();
- if (showInformer) {
- this.info({
- message: message,
- details: details
- }, 'error', this.opts.infoTimeout);
+ if (shouldRetry(err) && retryAttempt < retryDelays.length) {
+ return delay(retryDelays[retryAttempt], {
+ signal
+ }).then(() => doAttempt(retryAttempt + 1));
}
- if (throwErr) {
- throw typeof err === 'object' ? err : new Error(err);
- }
- };
+ throw err;
+ });
- _proto.assertNewUploadAllowed = function assertNewUploadAllowed(file) {
- var _this$getState2 = this.getState(),
- allowNewUpload = _this$getState2.allowNewUpload;
+ return doAttempt(0).then(result => {
+ if (after) after();
+ return result;
+ }, err => {
+ if (after) after();
+ throw err;
+ });
+}
- if (allowNewUpload === false) {
- this.showOrLogErrorAndThrow(new RestrictionError(this.i18n('noNewAlreadyUploading')), {
- file: file
- });
- }
- }
- /**
- * Create a file state object based on user-provided `addFile()` options.
- *
- * Note this is extremely side-effectful and should only be done when a file state object will be added to state immediately afterward!
- *
- * The `files` value is passed in because it may be updated by the caller without updating the store.
- */
- ;
-
- _proto.checkAndCreateFileStateObject = function checkAndCreateFileStateObject(files, f) {
- var fileType = getFileType(f);
- var file = f;
- file.type = fileType;
- var onBeforeFileAddedResult = this.opts.onBeforeFileAdded(file, files);
-
- if (onBeforeFileAddedResult === false) {
- // Don’t show UI info for this error, as it should be done by the developer
- this.showOrLogErrorAndThrow(new RestrictionError('Cannot add the file because onBeforeFileAdded returned false.'), {
- showInformer: false,
- file: file
- });
- }
+async function _prepareUploadParts2(candidates) {
+ this.lockedCandidatesForBatch.push(...candidates);
+ const result = await this.options.prepareUploadParts({
+ key: this.key,
+ uploadId: this.uploadId,
+ partNumbers: candidates.map(index => index + 1)
+ });
+ const valid = typeof (result == null ? void 0 : result.presignedUrls) === 'object';
- if (typeof onBeforeFileAddedResult === 'object' && onBeforeFileAddedResult) {
- file = onBeforeFileAddedResult;
- }
+ if (!valid) {
+ throw new TypeError('AwsS3/Multipart: Got incorrect result from `prepareUploadParts()`, expected an object `{ presignedUrls }`.');
+ }
- var fileName;
+ return result;
+}
- if (file.name) {
- fileName = file.name;
- } else if (fileType.split('/')[0] === 'image') {
- fileName = fileType.split('/')[0] + "." + fileType.split('/')[1];
- } else {
- fileName = 'noname';
+function _uploadPartRetryable2(index, prePreparedPart) {
+ return _classPrivateFieldLooseBase(this, _retryable)[_retryable]({
+ before: () => {
+ this.partsInProgress += 1;
+ },
+ attempt: () => _classPrivateFieldLooseBase(this, _uploadPart)[_uploadPart](index, prePreparedPart),
+ after: () => {
+ this.partsInProgress -= 1;
}
+ });
+}
- var fileExtension = getFileNameAndExtension(fileName).extension;
- var isRemote = file.isRemote || false;
- var fileID = generateFileID(file);
+function _uploadPart2(index, prePreparedPart) {
+ const body = this.chunks[index];
+ this.chunkState[index].busy = true;
+ const valid = typeof (prePreparedPart == null ? void 0 : prePreparedPart.url) === 'string';
- if (files[fileID] && !files[fileID].isGhost) {
- this.showOrLogErrorAndThrow(new RestrictionError(this.i18n('noDuplicates', {
- fileName: fileName
- })), {
- file: file
- });
- }
+ if (!valid) {
+ throw new TypeError('AwsS3/Multipart: Got incorrect result for `prePreparedPart`, expected an object `{ url }`.');
+ }
- var meta = file.meta || {};
- meta.name = fileName;
- meta.type = fileType; // `null` means the size is unknown.
+ const {
+ url,
+ headers
+ } = prePreparedPart;
- var size = Number.isFinite(file.data.size) ? file.data.size : null;
- var newFile = {
- source: file.source || '',
- id: fileID,
- name: fileName,
- extension: fileExtension || '',
- meta: _extends({}, this.getState().meta, meta),
- type: fileType,
- data: file.data,
- progress: {
- percentage: 0,
- bytesUploaded: 0,
- bytesTotal: size,
- uploadComplete: false,
- uploadStarted: null
- },
- size: size,
- isRemote: isRemote,
- remote: file.remote || '',
- preview: file.preview
- };
+ if (_classPrivateFieldLooseBase(this, _aborted)[_aborted]()) {
+ this.chunkState[index].busy = false;
+ throw createAbortError();
+ }
- try {
- var filesArray = Object.keys(files).map(function (i) {
- return files[i];
- });
- this.checkRestrictions(newFile, filesArray);
- } catch (err) {
- this.showOrLogErrorAndThrow(err, {
- file: newFile
- });
- }
+ return _classPrivateFieldLooseBase(this, _uploadPartBytes)[_uploadPartBytes](index, url, headers);
+}
- return newFile;
- } // Schedule an upload if `autoProceed` is enabled.
- ;
+function _onPartProgress2(index, sent, total) {
+ this.chunkState[index].uploaded = ensureInt(sent);
+ const totalUploaded = this.chunkState.reduce((n, c) => n + c.uploaded, 0);
+ this.options.onProgress(totalUploaded, this.file.size);
+}
- _proto.startIfAutoProceed = function startIfAutoProceed() {
- var _this3 = this;
+function _onPartComplete2(index, etag) {
+ this.chunkState[index].etag = etag;
+ this.chunkState[index].done = true;
+ const part = {
+ PartNumber: index + 1,
+ ETag: etag
+ };
+ this.parts.push(part);
+ this.options.onPartComplete(part);
+}
- if (this.opts.autoProceed && !this.scheduledAutoProceed) {
- this.scheduledAutoProceed = setTimeout(function () {
- _this3.scheduledAutoProceed = null;
+function _uploadPartBytes2(index, url, headers) {
+ const body = this.chunks[index];
+ const {
+ signal
+ } = this.abortController;
+ let defer;
+ const promise = new Promise((resolve, reject) => {
+ defer = {
+ resolve,
+ reject
+ };
+ });
+ const xhr = new XMLHttpRequest();
+ xhr.open('PUT', url, true);
- _this3.upload().catch(function (err) {
- if (!err.isRestriction) {
- _this3.log(err.stack || err.message || err);
- }
- });
- }, 4);
- }
+ if (headers) {
+ Object.keys(headers).map(key => {
+ xhr.setRequestHeader(key, headers[key]);
+ });
}
- /**
- * Add a new file to `state.files`. This will run `onBeforeFileAdded`,
- * try to guess file type in a clever way, check file against restrictions,
- * and start an upload if `autoProceed === true`.
- *
- * @param {object} file object to add
- * @returns {string} id for the added file
- */
- ;
- _proto.addFile = function addFile(file) {
- var _extends3;
+ xhr.responseType = 'text';
- this.assertNewUploadAllowed(file);
+ function cleanup() {
+ signal.removeEventListener('abort', onabort);
+ }
- var _this$getState3 = this.getState(),
- files = _this$getState3.files;
+ function onabort() {
+ xhr.abort();
+ }
- var newFile = this.checkAndCreateFileStateObject(files, file); // Users are asked to re-select recovered files without data,
- // and to keep the progress, meta and everthing else, we only replace said data
+ signal.addEventListener('abort', onabort);
+ xhr.upload.addEventListener('progress', ev => {
+ if (!ev.lengthComputable) return;
- if (files[newFile.id] && files[newFile.id].isGhost) {
- newFile = _extends({}, files[newFile.id], {
- data: file.data,
- isGhost: false
- });
- this.log("Replaced the blob in the restored ghost file: " + newFile.name + ", " + newFile.id);
- }
+ _classPrivateFieldLooseBase(this, _onPartProgress)[_onPartProgress](index, ev.loaded, ev.total);
+ });
+ xhr.addEventListener('abort', ev => {
+ cleanup();
+ this.chunkState[index].busy = false;
+ defer.reject(createAbortError());
+ });
+ xhr.addEventListener('load', ev => {
+ cleanup();
+ this.chunkState[index].busy = false;
- this.setState({
- files: _extends({}, files, (_extends3 = {}, _extends3[newFile.id] = newFile, _extends3))
- });
- this.emit('file-added', newFile);
- this.emit('files-added', [newFile]);
- this.log("Added file: " + newFile.name + ", " + newFile.id + ", mime type: " + newFile.type);
- this.startIfAutoProceed();
- return newFile.id;
- }
- /**
- * Add multiple files to `state.files`. See the `addFile()` documentation.
- *
- * If an error occurs while adding a file, it is logged and the user is notified.
- * This is good for UI plugins, but not for programmatic use.
- * Programmatic users should usually still use `addFile()` on individual files.
- */
- ;
+ if (ev.target.status < 200 || ev.target.status >= 300) {
+ const error = new Error('Non 2xx');
+ error.source = ev.target;
+ defer.reject(error);
+ return;
+ }
- _proto.addFiles = function addFiles(fileDescriptors) {
- var _this4 = this;
+ _classPrivateFieldLooseBase(this, _onPartProgress)[_onPartProgress](index, body.size, body.size); // NOTE This must be allowed by CORS.
- this.assertNewUploadAllowed(); // create a copy of the files object only once
- var files = _extends({}, this.getState().files);
+ const etag = ev.target.getResponseHeader('ETag');
- var newFiles = [];
- var errors = [];
+ 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. See https://uppy.io/docs/aws-s3-multipart#S3-Bucket-Configuration for instructions.'));
+ return;
+ }
- for (var i = 0; i < fileDescriptors.length; i++) {
- try {
- var newFile = this.checkAndCreateFileStateObject(files, fileDescriptors[i]); // Users are asked to re-select recovered files without data,
- // and to keep the progress, meta and everthing else, we only replace said data
+ _classPrivateFieldLooseBase(this, _onPartComplete)[_onPartComplete](index, etag);
- if (files[newFile.id] && files[newFile.id].isGhost) {
- newFile = _extends({}, files[newFile.id], {
- data: fileDescriptors[i].data,
- isGhost: false
- });
- this.log("Replaced blob in a ghost file: " + newFile.name + ", " + newFile.id);
- }
+ defer.resolve();
+ });
+ xhr.addEventListener('error', ev => {
+ cleanup();
+ this.chunkState[index].busy = false;
+ const error = new Error('Unknown error');
+ error.source = ev.target;
+ defer.reject(error);
+ });
+ xhr.send(body);
+ return promise;
+}
- files[newFile.id] = newFile;
- newFiles.push(newFile);
- } catch (err) {
- if (!err.isRestriction) {
- errors.push(err);
- }
- }
- }
+async function _completeUpload2() {
+ // Parts may not have completed uploading in sorted order, if limit > 1.
+ this.parts.sort((a, b) => a.PartNumber - b.PartNumber);
- this.setState({
- files: files
+ try {
+ const result = await this.options.completeMultipartUpload({
+ key: this.key,
+ uploadId: this.uploadId,
+ parts: this.parts
});
- newFiles.forEach(function (newFile) {
- _this4.emit('file-added', newFile);
+ this.options.onSuccess(result);
+ } catch (err) {
+ _classPrivateFieldLooseBase(this, _onError)[_onError](err);
+ }
+}
+
+function _abortUpload2() {
+ this.abortController.abort();
+ this.createdPromise.then(() => {
+ this.options.abortMultipartUpload({
+ key: this.key,
+ uploadId: this.uploadId
});
- this.emit('files-added', newFiles);
+ }, () => {// if the creation failed we do not need to abort
+ });
+}
- if (newFiles.length > 5) {
- this.log("Added batch of " + newFiles.length + " files");
- } else {
- Object.keys(newFiles).forEach(function (fileID) {
- _this4.log("Added file: " + newFiles[fileID].name + "\n id: " + newFiles[fileID].id + "\n type: " + newFiles[fileID].type);
- });
- }
+function _onError2(err) {
+ if (err && err.name === 'AbortError') {
+ return;
+ }
- if (newFiles.length > 0) {
- this.startIfAutoProceed();
- }
+ this.options.onError(err);
+}
- if (errors.length > 0) {
- var message = 'Multiple errors occurred while adding files:\n';
- errors.forEach(function (subError) {
- message += "\n * " + subError.message;
- });
- this.info({
- message: this.i18n('addBulkFilesFailed', {
- smart_count: errors.length
- }),
- details: message
- }, 'error', this.opts.infoTimeout);
+module.exports = MultipartUploader;
+},{"@uppy/utils/lib/AbortController":23,"@uppy/utils/lib/delay":27}],14:[function(require,module,exports){
+"use strict";
- if (typeof AggregateError === 'function') {
- throw new AggregateError(errors, message);
- } else {
- var err = new Error(message);
- err.errors = errors;
- throw err;
- }
- }
- };
+var _class, _temp;
- _proto.removeFiles = function removeFiles(fileIDs, reason) {
- var _this5 = this;
+const {
+ BasePlugin
+} = require('@uppy/core');
- var _this$getState4 = this.getState(),
- files = _this$getState4.files,
- currentUploads = _this$getState4.currentUploads;
+const {
+ Socket,
+ Provider,
+ RequestClient
+} = require('@uppy/companion-client');
- var updatedFiles = _extends({}, files);
+const EventTracker = require('@uppy/utils/lib/EventTracker');
- var updatedUploads = _extends({}, currentUploads);
+const emitSocketProgress = require('@uppy/utils/lib/emitSocketProgress');
- var removedFiles = Object.create(null);
- fileIDs.forEach(function (fileID) {
- if (files[fileID]) {
- removedFiles[fileID] = files[fileID];
- delete updatedFiles[fileID];
- }
- }); // Remove files from the `fileIDs` list in each upload.
+const getSocketHost = require('@uppy/utils/lib/getSocketHost');
- function fileIsNotRemoved(uploadFileID) {
- return removedFiles[uploadFileID] === undefined;
- }
+const {
+ RateLimitedQueue
+} = require('@uppy/utils/lib/RateLimitedQueue');
- Object.keys(updatedUploads).forEach(function (uploadID) {
- var newFileIDs = currentUploads[uploadID].fileIDs.filter(fileIsNotRemoved); // Remove the upload if no files are associated with it anymore.
+const Uploader = require('./MultipartUploader');
- if (newFileIDs.length === 0) {
- delete updatedUploads[uploadID];
- return;
- }
+function assertServerError(res) {
+ if (res && res.error) {
+ const error = new Error(res.message);
+ Object.assign(error, res.error);
+ throw error;
+ }
- updatedUploads[uploadID] = _extends({}, currentUploads[uploadID], {
- fileIDs: newFileIDs
+ return res;
+}
+
+module.exports = (_temp = _class = class AwsS3Multipart extends BasePlugin {
+ constructor(uppy, opts) {
+ super(uppy, opts);
+ this.type = 'uploader';
+ this.id = this.opts.id || 'AwsS3Multipart';
+ this.title = 'AWS S3 Multipart';
+ this.client = new RequestClient(uppy, opts);
+ const defaultOptions = {
+ timeout: 30 * 1000,
+ limit: 0,
+ retryDelays: [0, 1000, 3000, 5000],
+ createMultipartUpload: this.createMultipartUpload.bind(this),
+ listParts: this.listParts.bind(this),
+ prepareUploadParts: this.prepareUploadParts.bind(this),
+ abortMultipartUpload: this.abortMultipartUpload.bind(this),
+ completeMultipartUpload: this.completeMultipartUpload.bind(this)
+ };
+ this.opts = { ...defaultOptions,
+ ...opts
+ };
+ this.upload = this.upload.bind(this);
+ this.requests = new RateLimitedQueue(this.opts.limit);
+ this.uploaders = Object.create(null);
+ this.uploaderEvents = Object.create(null);
+ this.uploaderSockets = Object.create(null);
+ }
+ /**
+ * 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.
+ */
+
+
+ resetUploaderReferences(fileID, opts = {}) {
+ if (this.uploaders[fileID]) {
+ this.uploaders[fileID].abort({
+ really: opts.abort || false
});
- });
- var stateUpdate = {
- currentUploads: updatedUploads,
- files: updatedFiles
- }; // If all files were removed - allow new uploads,
- // and clear recoveredState
+ this.uploaders[fileID] = null;
+ }
- if (Object.keys(updatedFiles).length === 0) {
- stateUpdate.allowNewUpload = true;
- stateUpdate.error = null;
- stateUpdate.recoveredState = null;
+ if (this.uploaderEvents[fileID]) {
+ this.uploaderEvents[fileID].remove();
+ this.uploaderEvents[fileID] = null;
}
- this.setState(stateUpdate);
- this.calculateTotalProgress();
- var removedFileIDs = Object.keys(removedFiles);
- removedFileIDs.forEach(function (fileID) {
- _this5.emit('file-removed', removedFiles[fileID], reason);
+ if (this.uploaderSockets[fileID]) {
+ this.uploaderSockets[fileID].close();
+ this.uploaderSockets[fileID] = null;
+ }
+ }
+
+ 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.`);
+ }
+ }
+
+ createMultipartUpload(file) {
+ this.assertHost('createMultipartUpload');
+ const metadata = {};
+ Object.keys(file.meta).map(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
+ }).then(assertServerError);
+ }
+
+ listParts(file, {
+ key,
+ uploadId
+ }) {
+ this.assertHost('listParts');
+ const filename = encodeURIComponent(key);
+ return this.client.get(`s3/multipart/${uploadId}?key=${filename}`).then(assertServerError);
+ }
- if (removedFileIDs.length > 5) {
- this.log("Removed " + removedFileIDs.length + " files");
- } else {
- this.log("Removed files: " + removedFileIDs.join(', '));
- }
- };
+ prepareUploadParts(file, {
+ key,
+ uploadId,
+ partNumbers
+ }) {
+ this.assertHost('prepareUploadParts');
+ const filename = encodeURIComponent(key);
+ return this.client.get(`s3/multipart/${uploadId}/batch?key=${filename}?partNumbers=${partNumbers.join(',')}`).then(assertServerError);
+ }
- _proto.removeFile = function removeFile(fileID, reason) {
- if (reason === void 0) {
- reason = null;
- }
+ completeMultipartUpload(file, {
+ key,
+ uploadId,
+ parts
+ }) {
+ this.assertHost('completeMultipartUpload');
+ const filename = encodeURIComponent(key);
+ const uploadIdEnc = encodeURIComponent(uploadId);
+ return this.client.post(`s3/multipart/${uploadIdEnc}/complete?key=${filename}`, {
+ parts
+ }).then(assertServerError);
+ }
- this.removeFiles([fileID], reason);
- };
+ abortMultipartUpload(file, {
+ key,
+ uploadId
+ }) {
+ this.assertHost('abortMultipartUpload');
+ const filename = encodeURIComponent(key);
+ const uploadIdEnc = encodeURIComponent(uploadId);
+ return this.client.delete(`s3/multipart/${uploadIdEnc}?key=${filename}`).then(assertServerError);
+ }
- _proto.pauseResume = function pauseResume(fileID) {
- if (!this.getState().capabilities.resumableUploads || this.getFile(fileID).uploadComplete) {
- return undefined;
- }
+ uploadFile(file) {
+ return new Promise((resolve, reject) => {
+ const onStart = data => {
+ const cFile = this.uppy.getFile(file.id);
+ this.uppy.setFileState(file.id, {
+ s3Multipart: { ...cFile.s3Multipart,
+ key: data.key,
+ uploadId: data.uploadId
+ }
+ });
+ };
- var wasPaused = this.getFile(fileID).isPaused || false;
- var isPaused = !wasPaused;
- this.setFileState(fileID, {
- isPaused: isPaused
- });
- this.emit('upload-pause', fileID, isPaused);
- return isPaused;
- };
+ const onProgress = (bytesUploaded, bytesTotal) => {
+ this.uppy.emit('upload-progress', file, {
+ uploader: this,
+ bytesUploaded,
+ bytesTotal
+ });
+ };
- _proto.pauseAll = function pauseAll() {
- var updatedFiles = _extends({}, this.getState().files);
+ const onError = err => {
+ this.uppy.log(err);
+ this.uppy.emit('upload-error', file, err);
+ queuedRequest.done();
+ this.resetUploaderReferences(file.id);
+ reject(err);
+ };
- var inProgressUpdatedFiles = Object.keys(updatedFiles).filter(function (file) {
- return !updatedFiles[file].progress.uploadComplete && updatedFiles[file].progress.uploadStarted;
- });
- inProgressUpdatedFiles.forEach(function (file) {
- var updatedFile = _extends({}, updatedFiles[file], {
- isPaused: true
- });
+ const onSuccess = result => {
+ const uploadResp = {
+ body: { ...result
+ },
+ uploadURL: result.location
+ };
+ queuedRequest.done();
+ this.resetUploaderReferences(file.id);
+ const cFile = this.uppy.getFile(file.id);
+ this.uppy.emit('upload-success', cFile || file, uploadResp);
- updatedFiles[file] = updatedFile;
- });
- this.setState({
- files: updatedFiles
- });
- this.emit('pause-all');
- };
+ if (result.location) {
+ this.uppy.log(`Download ${upload.file.name} from ${result.location}`);
+ }
- _proto.resumeAll = function resumeAll() {
- var updatedFiles = _extends({}, this.getState().files);
+ resolve(upload);
+ };
- var inProgressUpdatedFiles = Object.keys(updatedFiles).filter(function (file) {
- return !updatedFiles[file].progress.uploadComplete && updatedFiles[file].progress.uploadStarted;
- });
- inProgressUpdatedFiles.forEach(function (file) {
- var updatedFile = _extends({}, updatedFiles[file], {
- isPaused: false,
- error: null
- });
+ const onPartComplete = part => {
+ const cFile = this.uppy.getFile(file.id);
- updatedFiles[file] = updatedFile;
- });
- this.setState({
- files: updatedFiles
- });
- this.emit('resume-all');
- };
+ if (!cFile) {
+ return;
+ }
- _proto.retryAll = function retryAll() {
- var updatedFiles = _extends({}, this.getState().files);
+ this.uppy.emit('s3-multipart:part-uploaded', cFile, part);
+ };
- var filesToRetry = Object.keys(updatedFiles).filter(function (file) {
- return updatedFiles[file].error;
- });
- filesToRetry.forEach(function (file) {
- var updatedFile = _extends({}, updatedFiles[file], {
- isPaused: false,
- error: null
+ const upload = new Uploader(file.data, {
+ // .bind to pass the file object to each handler.
+ createMultipartUpload: this.opts.createMultipartUpload.bind(this, file),
+ listParts: this.opts.listParts.bind(this, file),
+ prepareUploadParts: this.opts.prepareUploadParts.bind(this, file),
+ completeMultipartUpload: this.opts.completeMultipartUpload.bind(this, file),
+ abortMultipartUpload: this.opts.abortMultipartUpload.bind(this, file),
+ getChunkSize: this.opts.getChunkSize ? this.opts.getChunkSize.bind(this) : null,
+ onStart,
+ onProgress,
+ onError,
+ onSuccess,
+ onPartComplete,
+ limit: this.opts.limit || 5,
+ retryDelays: this.opts.retryDelays || [],
+ ...file.s3Multipart
});
+ this.uploaders[file.id] = upload;
+ this.uploaderEvents[file.id] = new EventTracker(this.uppy);
+ let queuedRequest = this.requests.run(() => {
+ 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.
- updatedFiles[file] = updatedFile;
- });
- this.setState({
- files: updatedFiles,
- error: null
- });
- this.emit('retry-all', filesToRetry);
- if (filesToRetry.length === 0) {
- return Promise.resolve({
- successful: [],
- failed: []
+ return () => {};
});
- }
-
- var uploadID = this.createUpload(filesToRetry, {
- forceAllowNewUpload: true // create new upload even if allowNewUpload: false
+ this.onFileRemove(file.id, removed => {
+ queuedRequest.abort();
+ this.resetUploaderReferences(file.id, {
+ abort: true
+ });
+ resolve(`upload ${removed.id} was removed`);
+ });
+ this.onCancelAll(file.id, () => {
+ queuedRequest.abort();
+ this.resetUploaderReferences(file.id, {
+ abort: true
+ });
+ resolve(`upload ${file.id} was canceled`);
+ });
+ this.onFilePause(file.id, 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 = this.requests.run(() => {
+ upload.start();
+ return () => {};
+ });
+ }
+ });
+ this.onPauseAll(file.id, () => {
+ queuedRequest.abort();
+ upload.pause();
+ });
+ this.onResumeAll(file.id, () => {
+ queuedRequest.abort();
- });
- return this.runUpload(uploadID);
- };
+ if (file.error) {
+ upload.abort();
+ }
- _proto.cancelAll = function cancelAll() {
- this.emit('cancel-all');
+ queuedRequest = this.requests.run(() => {
+ upload.start();
+ return () => {};
+ });
+ }); // Don't double-emit upload-started for Golden Retriever-restored files that were already started
- var _this$getState5 = this.getState(),
- files = _this$getState5.files;
+ if (!file.progress.uploadStarted || !file.isRestored) {
+ this.uppy.emit('upload-started', file);
+ }
+ });
+ }
- var fileIDs = Object.keys(files);
+ uploadRemote(file) {
+ this.resetUploaderReferences(file.id); // Don't double-emit upload-started for Golden Retriever-restored files that were already started
- if (fileIDs.length) {
- this.removeFiles(fileIDs, 'cancel-all');
+ if (!file.progress.uploadStarted || !file.isRestored) {
+ this.uppy.emit('upload-started', file);
}
- this.setState({
- totalProgress: 0,
- error: null,
- recoveredState: null
- });
- };
-
- _proto.retryUpload = function retryUpload(fileID) {
- this.setFileState(fileID, {
- error: null,
- isPaused: false
- });
- this.emit('upload-retry', fileID);
- var uploadID = this.createUpload([fileID], {
- forceAllowNewUpload: true // create new upload even if allowNewUpload: false
+ if (file.serverToken) {
+ return this.connectToServerSocket(file);
+ }
+ return new Promise((resolve, reject) => {
+ const Client = file.remote.providerOptions.provider ? Provider : RequestClient;
+ const client = new Client(this.uppy, file.remote.providerOptions);
+ client.post(file.remote.url, { ...file.remote.body,
+ protocol: 's3-multipart',
+ size: file.data.size,
+ metadata: file.meta
+ }).then(res => {
+ this.uppy.setFileState(file.id, {
+ serverToken: res.token
+ });
+ file = this.uppy.getFile(file.id);
+ return file;
+ }).then(file => {
+ return this.connectToServerSocket(file);
+ }).then(() => {
+ resolve();
+ }).catch(err => {
+ this.uppy.emit('upload-error', file, err);
+ reject(err);
+ });
});
- return this.runUpload(uploadID);
- };
+ }
- _proto.reset = function reset() {
- this.cancelAll();
- };
+ connectToServerSocket(file) {
+ return new Promise((resolve, reject) => {
+ const token = file.serverToken;
+ const host = getSocketHost(file.remote.companionUrl);
+ const socket = new Socket({
+ target: `${host}/api/${token}`,
+ autoOpen: false
+ });
+ this.uploaderSockets[file.id] = socket;
+ this.uploaderEvents[file.id] = new EventTracker(this.uppy);
+ this.onFileRemove(file.id, removed => {
+ queuedRequest.abort();
+ socket.send('pause', {});
+ this.resetUploaderReferences(file.id, {
+ abort: true
+ });
+ resolve(`upload ${file.id} was removed`);
+ });
+ this.onFilePause(file.id, 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 = this.requests.run(() => {
+ socket.send('resume', {});
+ return () => {};
+ });
+ }
+ });
+ this.onPauseAll(file.id, () => {
+ queuedRequest.abort();
+ socket.send('pause', {});
+ });
+ this.onCancelAll(file.id, () => {
+ queuedRequest.abort();
+ socket.send('pause', {});
+ this.resetUploaderReferences(file.id);
+ resolve(`upload ${file.id} was canceled`);
+ });
+ this.onResumeAll(file.id, () => {
+ queuedRequest.abort();
- _proto.logout = function logout() {
- this.iteratePlugins(function (plugin) {
- if (plugin.provider && plugin.provider.logout) {
- plugin.provider.logout();
- }
- });
- };
+ if (file.error) {
+ socket.send('pause', {});
+ }
- _proto.calculateProgress = function calculateProgress(file, data) {
- if (!this.getFile(file.id)) {
- this.log("Not setting progress for a file that has been removed: " + file.id);
- return;
- } // bytesTotal may be null or zero; in that case we can't divide by it
+ queuedRequest = this.requests.run(() => {
+ socket.send('resume', {});
+ });
+ });
+ this.onRetry(file.id, () => {
+ // 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', {});
+ }
+ });
+ this.onRetryAll(file.id, () => {
+ if (socket.isOpen) {
+ socket.send('pause', {});
+ socket.send('resume', {});
+ }
+ });
+ socket.on('progress', progressData => emitSocketProgress(this, progressData, file));
+ socket.on('error', errData => {
+ this.uppy.emit('upload-error', file, new Error(errData.error));
+ this.resetUploaderReferences(file.id);
+ queuedRequest.done();
+ reject(new Error(errData.error));
+ });
+ socket.on('success', data => {
+ const uploadResp = {
+ uploadURL: data.url
+ };
+ this.uppy.emit('upload-success', file, uploadResp);
+ this.resetUploaderReferences(file.id);
+ queuedRequest.done();
+ resolve();
+ });
+ let queuedRequest = this.requests.run(() => {
+ socket.open();
+ if (file.isPaused) {
+ socket.send('pause', {});
+ }
- var canHavePercentage = Number.isFinite(data.bytesTotal) && data.bytesTotal > 0;
- this.setFileState(file.id, {
- progress: _extends({}, this.getFile(file.id).progress, {
- bytesUploaded: data.bytesUploaded,
- bytesTotal: data.bytesTotal,
- percentage: canHavePercentage // TODO(goto-bus-stop) flooring this should probably be the choice of the UI?
- // we get more accurate calculations if we don't round this at all.
- ? Math.round(data.bytesUploaded / data.bytesTotal * 100) : 0
- })
+ return () => {};
+ });
});
- this.calculateTotalProgress();
- };
+ }
- _proto.calculateTotalProgress = function calculateTotalProgress() {
- // calculate total progress, using the number of files currently uploading,
- // multiplied by 100 and the summ of individual progress of each file
- var files = this.getFiles();
- var inProgress = files.filter(function (file) {
- return file.progress.uploadStarted || file.progress.preprocess || file.progress.postprocess;
- });
+ upload(fileIDs) {
+ if (fileIDs.length === 0) return Promise.resolve();
+ const promises = fileIDs.map(id => {
+ const file = this.uppy.getFile(id);
- if (inProgress.length === 0) {
- this.emit('progress', 0);
- this.setState({
- totalProgress: 0
- });
- return;
- }
+ if (file.isRemote) {
+ return this.uploadRemote(file);
+ }
- var sizedFiles = inProgress.filter(function (file) {
- return file.progress.bytesTotal != null;
+ return this.uploadFile(file);
});
- var unsizedFiles = inProgress.filter(function (file) {
- return file.progress.bytesTotal == null;
- });
-
- if (sizedFiles.length === 0) {
- var progressMax = inProgress.length * 100;
- var currentProgress = unsizedFiles.reduce(function (acc, file) {
- return acc + file.progress.percentage;
- }, 0);
-
- var _totalProgress = Math.round(currentProgress / progressMax * 100);
+ return Promise.all(promises);
+ }
- this.setState({
- totalProgress: _totalProgress
- });
- return;
- }
+ onFileRemove(fileID, cb) {
+ this.uploaderEvents[fileID].on('file-removed', file => {
+ if (fileID === file.id) cb(file.id);
+ });
+ }
- var totalSize = sizedFiles.reduce(function (acc, file) {
- return acc + file.progress.bytesTotal;
- }, 0);
- var averageSize = totalSize / sizedFiles.length;
- totalSize += averageSize * unsizedFiles.length;
- var uploadedSize = 0;
- sizedFiles.forEach(function (file) {
- uploadedSize += file.progress.bytesUploaded;
+ onFilePause(fileID, cb) {
+ this.uploaderEvents[fileID].on('upload-pause', (targetFileID, isPaused) => {
+ if (fileID === targetFileID) {
+ // const isPaused = this.uppy.pauseResume(fileID)
+ cb(isPaused);
+ }
});
- unsizedFiles.forEach(function (file) {
- uploadedSize += averageSize * (file.progress.percentage || 0) / 100;
+ }
+
+ onRetry(fileID, cb) {
+ this.uploaderEvents[fileID].on('upload-retry', targetFileID => {
+ if (fileID === targetFileID) {
+ cb();
+ }
});
- var totalProgress = totalSize === 0 ? 0 : Math.round(uploadedSize / totalSize * 100); // hot fix, because:
- // uploadedSize ended up larger than totalSize, resulting in 1325% total
+ }
- if (totalProgress > 100) {
- totalProgress = 100;
- }
+ onRetryAll(fileID, cb) {
+ this.uploaderEvents[fileID].on('retry-all', filesToRetry => {
+ if (!this.uppy.getFile(fileID)) return;
+ cb();
+ });
+ }
- this.setState({
- totalProgress: totalProgress
+ onPauseAll(fileID, cb) {
+ this.uploaderEvents[fileID].on('pause-all', () => {
+ if (!this.uppy.getFile(fileID)) return;
+ cb();
});
- this.emit('progress', totalProgress);
}
- /**
- * Registers listeners for all global actions, like:
- * `error`, `file-removed`, `upload-progress`
- */
- ;
- _proto.addListeners = function addListeners() {
- var _this6 = this;
+ onCancelAll(fileID, cb) {
+ this.uploaderEvents[fileID].on('cancel-all', () => {
+ if (!this.uppy.getFile(fileID)) return;
+ cb();
+ });
+ }
- /**
- * @param {Error} error
- * @param {object} [file]
- * @param {object} [response]
- */
- var errorHandler = function errorHandler(error, file, response) {
- var errorMsg = error.message || 'Unknown error';
+ onResumeAll(fileID, cb) {
+ this.uploaderEvents[fileID].on('resume-all', () => {
+ if (!this.uppy.getFile(fileID)) return;
+ cb();
+ });
+ }
- if (error.details) {
- errorMsg += " " + error.details;
+ install() {
+ const {
+ capabilities
+ } = this.uppy.getState();
+ this.uppy.setState({
+ capabilities: { ...capabilities,
+ resumableUploads: true
}
+ });
+ this.uppy.addUploader(this.upload);
+ }
- _this6.setState({
- error: errorMsg
- });
-
- if (file != null) {
- _this6.setFileState(file.id, {
- error: errorMsg,
- response: response
- });
+ uninstall() {
+ const {
+ capabilities
+ } = this.uppy.getState();
+ this.uppy.setState({
+ capabilities: { ...capabilities,
+ resumableUploads: false
}
- };
+ });
+ this.uppy.removeUploader(this.upload);
+ }
- this.on('error', errorHandler);
- this.on('upload-error', function (file, error, response) {
- errorHandler(error, file, response);
+}, _class.VERSION = require('../package.json').version, _temp);
+},{"../package.json":32,"./MultipartUploader":13,"@uppy/companion-client":20,"@uppy/core":60,"@uppy/utils/lib/EventTracker":24,"@uppy/utils/lib/RateLimitedQueue":26,"@uppy/utils/lib/emitSocketProgress":28,"@uppy/utils/lib/getSocketHost":31}],15:[function(require,module,exports){
+'use strict';
- if (typeof error === 'object' && error.message) {
- var newError = new Error(error.message);
- newError.details = error.message;
+class AuthError extends Error {
+ constructor() {
+ super('Authorization required');
+ this.name = 'AuthError';
+ this.isAuthError = true;
+ }
- if (error.details) {
- newError.details += " " + error.details;
- }
+}
- newError.message = _this6.i18n('failedToUpload', {
- file: file.name
- });
+module.exports = AuthError;
+},{}],16:[function(require,module,exports){
+'use strict';
- _this6.showOrLogErrorAndThrow(newError, {
- throwErr: false
- });
- } else {
- _this6.showOrLogErrorAndThrow(error, {
- throwErr: false
- });
- }
- });
- this.on('upload', function () {
- _this6.setState({
- error: null
- });
- });
- this.on('upload-started', function (file) {
- if (!_this6.getFile(file.id)) {
- _this6.log("Not setting progress for a file that has been removed: " + file.id);
+const qsStringify = require('qs-stringify');
- return;
- }
+const RequestClient = require('./RequestClient');
- _this6.setFileState(file.id, {
- progress: {
- uploadStarted: Date.now(),
- uploadComplete: false,
- percentage: 0,
- bytesUploaded: 0,
- bytesTotal: file.size
- }
- });
- });
- this.on('upload-progress', this.calculateProgress);
- this.on('upload-success', function (file, uploadResp) {
- if (!_this6.getFile(file.id)) {
- _this6.log("Not setting progress for a file that has been removed: " + file.id);
+const tokenStorage = require('./tokenStorage');
- return;
- }
+const _getName = id => {
+ return id.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');
+};
- var currentProgress = _this6.getFile(file.id).progress;
+module.exports = class Provider extends RequestClient {
+ constructor(uppy, opts) {
+ super(uppy, opts);
+ 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;
+ }
- _this6.setFileState(file.id, {
- progress: _extends({}, currentProgress, {
- postprocess: _this6.postProcessors.length > 0 ? {
- mode: 'indeterminate'
- } : null,
- uploadComplete: true,
- percentage: 100,
- bytesUploaded: currentProgress.bytesTotal
- }),
- response: uploadResp,
- uploadURL: uploadResp.uploadURL,
- isPaused: false
- });
+ headers() {
+ return Promise.all([super.headers(), this.getAuthToken()]).then(([headers, token]) => {
+ const authHeaders = {};
- _this6.calculateTotalProgress();
- });
- this.on('preprocess-progress', function (file, progress) {
- if (!_this6.getFile(file.id)) {
- _this6.log("Not setting progress for a file that has been removed: " + file.id);
+ if (token) {
+ authHeaders['uppy-auth-token'] = token;
+ }
- return;
+ if (this.companionKeysParams) {
+ authHeaders['uppy-credentials-params'] = btoa(JSON.stringify({
+ params: this.companionKeysParams
+ }));
}
- _this6.setFileState(file.id, {
- progress: _extends({}, _this6.getFile(file.id).progress, {
- preprocess: progress
- })
- });
+ return { ...headers,
+ ...authHeaders
+ };
});
- this.on('preprocess-complete', function (file) {
- if (!_this6.getFile(file.id)) {
- _this6.log("Not setting progress for a file that has been removed: " + file.id);
+ }
- return;
- }
+ onReceiveResponse(response) {
+ response = super.onReceiveResponse(response);
+ const plugin = this.uppy.getPlugin(this.pluginId);
+ const oldAuthenticated = plugin.getPluginState().authenticated;
+ const authenticated = oldAuthenticated ? response.status !== 401 : response.status < 400;
+ plugin.setPluginState({
+ authenticated
+ });
+ return response;
+ }
- var files = _extends({}, _this6.getState().files);
+ setAuthToken(token) {
+ return this.uppy.getPlugin(this.pluginId).storage.setItem(this.tokenKey, token);
+ }
- files[file.id] = _extends({}, files[file.id], {
- progress: _extends({}, files[file.id].progress)
- });
- delete files[file.id].progress.preprocess;
+ getAuthToken() {
+ return this.uppy.getPlugin(this.pluginId).storage.getItem(this.tokenKey);
+ }
- _this6.setState({
- files: files
- });
- });
- this.on('postprocess-progress', function (file, progress) {
- if (!_this6.getFile(file.id)) {
- _this6.log("Not setting progress for a file that has been removed: " + file.id);
+ authUrl(queries = {}) {
+ if (this.preAuthToken) {
+ queries.uppyPreAuthToken = this.preAuthToken;
+ }
- return;
- }
+ let strigifiedQueries = qsStringify(queries);
+ strigifiedQueries = strigifiedQueries ? `?${strigifiedQueries}` : strigifiedQueries;
+ return `${this.hostname}/${this.id}/connect${strigifiedQueries}`;
+ }
- _this6.setFileState(file.id, {
- progress: _extends({}, _this6.getState().files[file.id].progress, {
- postprocess: progress
- })
- });
+ fileUrl(id) {
+ return `${this.hostname}/${this.id}/get/${id}`;
+ }
+
+ fetchPreAuthToken() {
+ if (!this.companionKeysParams) {
+ return Promise.resolve();
+ }
+
+ return this.post(`${this.id}/preauth/`, {
+ params: this.companionKeysParams
+ }).then(res => {
+ this.preAuthToken = res.token;
+ }).catch(err => {
+ this.uppy.log(`[CompanionClient] unable to fetch preAuthToken ${err}`, 'warning');
});
- this.on('postprocess-complete', function (file) {
- if (!_this6.getFile(file.id)) {
- _this6.log("Not setting progress for a file that has been removed: " + file.id);
+ }
- return;
- }
+ list(directory) {
+ return this.get(`${this.id}/list/${directory || ''}`);
+ }
- var files = _extends({}, _this6.getState().files);
+ logout() {
+ return this.get(`${this.id}/logout`).then(response => Promise.all([response, this.uppy.getPlugin(this.pluginId).storage.removeItem(this.tokenKey)])).then(([response]) => response);
+ }
- files[file.id] = _extends({}, files[file.id], {
- progress: _extends({}, files[file.id].progress)
- });
- delete files[file.id].progress.postprocess; // TODO should we set some kind of `fullyComplete` property on the file object
- // so it's easier to see that the file is upload…fully complete…rather than
- // what we have to do now (`uploadComplete && !postprocess`)
+ static initPlugin(plugin, opts, defaultOpts) {
+ plugin.type = 'acquirer';
+ plugin.files = [];
- _this6.setState({
- files: files
- });
- });
- this.on('restored', function () {
- // Files may have changed--ensure progress is still accurate.
- _this6.calculateTotalProgress();
- }); // show informer if offline
+ if (defaultOpts) {
+ plugin.opts = { ...defaultOpts,
+ ...opts
+ };
+ }
- if (typeof window !== 'undefined' && window.addEventListener) {
- window.addEventListener('online', function () {
- return _this6.updateOnlineStatus();
- });
- window.addEventListener('offline', function () {
- return _this6.updateOnlineStatus();
- });
- setTimeout(function () {
- return _this6.updateOnlineStatus();
- }, 3000);
+ 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.`');
}
- };
- _proto.updateOnlineStatus = function updateOnlineStatus() {
- var online = typeof window.navigator.onLine !== 'undefined' ? window.navigator.onLine : true;
+ if (opts.companionAllowedHosts) {
+ const pattern = opts.companionAllowedHosts; // validate companionAllowedHosts param
- if (!online) {
- this.emit('is-offline');
- this.info(this.i18n('noInternetConnection'), 'error', 0);
- this.wasOffline = true;
- } else {
- this.emit('is-online');
+ 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`);
+ }
- if (this.wasOffline) {
- this.emit('back-online');
- this.info(this.i18n('connectedToInternet'), 'success', 3000);
- this.wasOffline = false;
+ 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 = new URL(opts.companionUrl).origin;
}
}
- };
- _proto.getID = function getID() {
- return this.opts.id;
+ plugin.storage = plugin.opts.storage || tokenStorage;
}
- /**
- * Registers a plugin with Core.
- *
- * @param {object} Plugin object
- * @param {object} [opts] object with options to be passed to Plugin
- * @returns {object} self for chaining
- */
- // eslint-disable-next-line no-shadow
- ;
- _proto.use = function use(Plugin, opts) {
- if (typeof Plugin !== 'function') {
- var msg = "Expected a plugin class, but got " + (Plugin === null ? 'null' : typeof Plugin) + "." + ' Please verify that the plugin was imported and spelled correctly.';
- throw new TypeError(msg);
- } // Instantiate
+};
+},{"./RequestClient":17,"./tokenStorage":21,"qs-stringify":11}],17:[function(require,module,exports){
+'use strict';
+var _class, _getPostResponseFunc, _getUrl, _errorHandler, _temp;
- var plugin = new Plugin(this, opts);
- var pluginId = plugin.id;
- this.plugins[plugin.type] = this.plugins[plugin.type] || [];
+function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }
- if (!pluginId) {
- throw new Error('Your plugin must have an id');
- }
+var id = 0;
- if (!plugin.type) {
- throw new Error('Your plugin must have a type');
- }
+function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; }
- var existsPluginAlready = this.getPlugin(pluginId);
+const fetchWithNetworkError = require('@uppy/utils/lib/fetchWithNetworkError');
- if (existsPluginAlready) {
- var _msg = "Already found a plugin named '" + existsPluginAlready.id + "'. " + ("Tried to use: '" + pluginId + "'.\n") + 'Uppy plugins must have unique `id` options. See https://uppy.io/docs/plugins/#id.';
+const AuthError = require('./AuthError'); // Remove the trailing slash so we can always safely append /xyz.
- throw new Error(_msg);
- }
- if (Plugin.VERSION) {
- this.log("Using " + pluginId + " v" + Plugin.VERSION);
- }
+function stripSlash(url) {
+ return url.replace(/\/$/, '');
+}
- this.plugins[plugin.type].push(plugin);
- plugin.install();
- return this;
+async function handleJSONResponse(res) {
+ if (res.status === 401) {
+ throw new AuthError();
}
- /**
- * Find one Plugin by name.
- *
- * @param {string} id plugin id
- * @returns {object|boolean}
- */
- ;
-
- _proto.getPlugin = function getPlugin(id) {
- var foundPlugin = null;
- this.iteratePlugins(function (plugin) {
- if (plugin.id === id) {
- foundPlugin = plugin;
- return false;
- }
+
+ const jsonPromise = res.json();
+
+ if (res.status < 200 || res.status > 300) {
+ let errMsg = `Failed request with status: ${res.status}. ${res.statusText}`;
+
+ try {
+ const errData = await jsonPromise;
+ errMsg = errData.message ? `${errMsg} message: ${errData.message}` : errMsg;
+ errMsg = errData.requestId ? `${errMsg} request-Id: ${errData.requestId}` : errMsg;
+ } finally {
+ // eslint-disable-next-line no-unsafe-finally
+ throw new Error(errMsg);
+ }
+ }
+
+ return jsonPromise;
+}
+
+module.exports = (_temp = (_getPostResponseFunc = /*#__PURE__*/_classPrivateFieldLooseKey("getPostResponseFunc"), _getUrl = /*#__PURE__*/_classPrivateFieldLooseKey("getUrl"), _errorHandler = /*#__PURE__*/_classPrivateFieldLooseKey("errorHandler"), _class = class RequestClient {
+ // eslint-disable-next-line global-require
+ constructor(uppy, opts) {
+ Object.defineProperty(this, _errorHandler, {
+ value: _errorHandler2
+ });
+ Object.defineProperty(this, _getUrl, {
+ value: _getUrl2
});
- return foundPlugin;
+ Object.defineProperty(this, _getPostResponseFunc, {
+ writable: true,
+ value: skip => response => skip ? response : this.onReceiveResponse(response)
+ });
+ this.uppy = uppy;
+ this.opts = opts;
+ this.onReceiveResponse = this.onReceiveResponse.bind(this);
+ this.allowedHeaders = ['accept', 'content-type', 'uppy-auth-token'];
+ this.preflightDone = false;
}
- /**
- * Iterate through all `use`d plugins.
- *
- * @param {Function} method that will be run on each plugin
- */
- ;
- _proto.iteratePlugins = function iteratePlugins(method) {
- var _this7 = this;
+ get hostname() {
+ const {
+ companion
+ } = this.uppy.getState();
+ const host = this.opts.companionUrl;
+ return stripSlash(companion && companion[host] ? companion[host] : host);
+ }
- Object.keys(this.plugins).forEach(function (pluginType) {
- _this7.plugins[pluginType].forEach(method);
+ headers() {
+ const userHeaders = this.opts.companionHeaders || {};
+ return Promise.resolve({ ...RequestClient.defaultHeaders,
+ ...userHeaders
});
}
- /**
- * Uninstall and remove a plugin.
- *
- * @param {object} instance The plugin instance to remove.
- */
- ;
- _proto.removePlugin = function removePlugin(instance) {
- var _extends4;
+ onReceiveResponse(response) {
+ const state = this.uppy.getState();
+ const companion = state.companion || {};
+ const host = this.opts.companionUrl;
+ const {
+ headers
+ } = response; // Store the self-identified domain name for the Companion instance we just hit.
- this.log("Removing plugin " + instance.id);
- this.emit('plugin-remove', instance);
+ if (headers.has('i-am') && headers.get('i-am') !== companion[host]) {
+ this.uppy.setState({
+ companion: { ...companion,
+ [host]: headers.get('i-am')
+ }
+ });
+ }
- if (instance.uninstall) {
- instance.uninstall();
+ return response;
+ }
+
+ preflight(path) {
+ if (this.preflightDone) {
+ return Promise.resolve(this.allowedHeaders.slice());
}
- var list = this.plugins[instance.type].slice(); // list.indexOf failed here, because Vue3 converted the plugin instance
- // to a Proxy object, which failed the strict comparison test:
- // obj !== objProxy
+ return fetch(_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path), {
+ method: 'OPTIONS'
+ }).then(response => {
+ if (response.headers.has('access-control-allow-headers')) {
+ this.allowedHeaders = response.headers.get('access-control-allow-headers').split(',').map(headerName => headerName.trim().toLowerCase());
+ }
- var index = findIndex(list, function (item) {
- return item.id === instance.id;
+ this.preflightDone = true;
+ return this.allowedHeaders.slice();
+ }).catch(err => {
+ this.uppy.log(`[CompanionClient] unable to make preflight request ${err}`, 'warning');
+ this.preflightDone = true;
+ return this.allowedHeaders.slice();
});
+ }
- if (index !== -1) {
- list.splice(index, 1);
- this.plugins[instance.type] = list;
- }
+ preflightAndHeaders(path) {
+ return Promise.all([this.preflight(path), this.headers()]).then(([allowedHeaders, headers]) => {
+ // filter to keep only allowed Headers
+ Object.keys(headers).forEach(header => {
+ if (!allowedHeaders.includes(header.toLowerCase())) {
+ this.uppy.log(`[CompanionClient] excluding disallowed header ${header}`);
+ delete headers[header]; // eslint-disable-line no-param-reassign
+ }
+ });
+ return headers;
+ });
+ }
+
+ get(path, skipPostResponse) {
+ const method = 'get';
+ return this.preflightAndHeaders(path).then(headers => fetchWithNetworkError(_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path), {
+ method,
+ headers,
+ credentials: this.opts.companionCookiesRule || 'same-origin'
+ })).then(_classPrivateFieldLooseBase(this, _getPostResponseFunc)[_getPostResponseFunc](skipPostResponse)).then(handleJSONResponse).catch(_classPrivateFieldLooseBase(this, _errorHandler)[_errorHandler](method, path));
+ }
- var state = this.getState();
- var updatedState = {
- plugins: _extends({}, state.plugins, (_extends4 = {}, _extends4[instance.id] = undefined, _extends4))
- };
- this.setState(updatedState);
+ post(path, data, skipPostResponse) {
+ const method = 'post';
+ return this.preflightAndHeaders(path).then(headers => fetchWithNetworkError(_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path), {
+ method,
+ headers,
+ credentials: this.opts.companionCookiesRule || 'same-origin',
+ body: JSON.stringify(data)
+ })).then(_classPrivateFieldLooseBase(this, _getPostResponseFunc)[_getPostResponseFunc](skipPostResponse)).then(handleJSONResponse).catch(_classPrivateFieldLooseBase(this, _errorHandler)[_errorHandler](method, path));
}
- /**
- * Uninstall all plugins and close down this Uppy instance.
- */
- ;
- _proto.close = function close() {
- var _this8 = this;
+ delete(path, data, skipPostResponse) {
+ const method = 'delete';
+ return this.preflightAndHeaders(path).then(headers => fetchWithNetworkError(`${this.hostname}/${path}`, {
+ method,
+ headers,
+ credentials: this.opts.companionCookiesRule || 'same-origin',
+ body: data ? JSON.stringify(data) : null
+ })).then(_classPrivateFieldLooseBase(this, _getPostResponseFunc)[_getPostResponseFunc](skipPostResponse)).then(handleJSONResponse).catch(_classPrivateFieldLooseBase(this, _errorHandler)[_errorHandler](method, path));
+ }
- this.log("Closing Uppy instance " + this.opts.id + ": removing all files and uninstalling plugins");
- this.reset();
- this.storeUnsubscribe();
- this.iteratePlugins(function (plugin) {
- _this8.removePlugin(plugin);
- });
+}), _class.VERSION = require('../package.json').version, _class.defaultHeaders = {
+ Accept: 'application/json',
+ 'Content-Type': 'application/json',
+ 'Uppy-Versions': `@uppy/companion-client=${_class.VERSION}`
+}, _temp);
+
+function _getUrl2(url) {
+ if (/^(https?:|)\/\//.test(url)) {
+ return url;
}
- /**
- * Set info message in `state.info`, so that UI plugins like `Informer`
- * can display the message.
- *
- * @param {string | object} message Message to be displayed by the informer
- * @param {string} [type]
- * @param {number} [duration]
- */
- ;
- _proto.info = function info(message, type, duration) {
- if (type === void 0) {
- type = 'info';
- }
+ return `${this.hostname}/${url}`;
+}
+
+function _errorHandler2(method, path) {
+ return err => {
+ var _err;
- if (duration === void 0) {
- duration = 3000;
+ if (!((_err = err) != null && _err.isAuthError)) {
+ const error = new Error(`Could not ${method} ${_classPrivateFieldLooseBase(this, _getUrl)[_getUrl](path)}`);
+ error.cause = err;
+ err = error; // eslint-disable-line no-param-reassign
}
- var isComplexMessage = typeof message === 'object';
- this.setState({
- info: {
- isHidden: false,
- type: type,
- message: isComplexMessage ? message.message : message,
- details: isComplexMessage ? message.details : null
- }
- });
- this.emit('info-visible');
- clearTimeout(this.infoTimeoutID);
+ return Promise.reject(err);
+ };
+}
+},{"../package.json":22,"./AuthError":15,"@uppy/utils/lib/fetchWithNetworkError":29}],18:[function(require,module,exports){
+'use strict';
- if (duration === 0) {
- this.infoTimeoutID = undefined;
- return;
- } // hide the informer after `duration` milliseconds
+const RequestClient = require('./RequestClient');
+const _getName = id => {
+ return id.split('-').map(s => s.charAt(0).toUpperCase() + s.slice(1)).join(' ');
+};
- this.infoTimeoutID = setTimeout(this.hideInfo, duration);
- };
+module.exports = class SearchProvider extends RequestClient {
+ constructor(uppy, opts) {
+ super(uppy, opts);
+ this.provider = opts.provider;
+ this.id = this.provider;
+ this.name = this.opts.name || _getName(this.id);
+ this.pluginId = this.opts.pluginId;
+ }
- _proto.hideInfo = function hideInfo() {
- var newInfo = _extends({}, this.getState().info, {
- isHidden: true
- });
+ fileUrl(id) {
+ return `${this.hostname}/search/${this.id}/get/${id}`;
+ }
- this.setState({
- info: newInfo
- });
- this.emit('info-hidden');
+ search(text, queries) {
+ queries = queries ? `&${queries}` : '';
+ return this.get(`search/${this.id}/list?q=${encodeURIComponent(text)}${queries}`);
}
- /**
- * Passes messages to a function, provided in `opts.logger`.
- * If `opts.logger: Uppy.debugLogger` or `opts.debug: true`, logs to the browser console.
- *
- * @param {string|object} message to log
- * @param {string} [type] optional `error` or `warning`
- */
- ;
- _proto.log = function log(message, type) {
- var logger = this.opts.logger;
+};
+},{"./RequestClient":17}],19:[function(require,module,exports){
+"use strict";
- switch (type) {
- case 'error':
- logger.error(message);
- break;
+var _queued, _emitter, _isOpen, _socket, _handleMessage;
- case 'warning':
- logger.warn(message);
- break;
+let _Symbol$for, _Symbol$for2;
- default:
- logger.debug(message);
- break;
+function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }
+
+var id = 0;
+
+function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; }
+
+const ee = require('namespace-emitter');
+
+module.exports = (_queued = /*#__PURE__*/_classPrivateFieldLooseKey("queued"), _emitter = /*#__PURE__*/_classPrivateFieldLooseKey("emitter"), _isOpen = /*#__PURE__*/_classPrivateFieldLooseKey("isOpen"), _socket = /*#__PURE__*/_classPrivateFieldLooseKey("socket"), _handleMessage = /*#__PURE__*/_classPrivateFieldLooseKey("handleMessage"), _Symbol$for = Symbol.for('uppy test: getSocket'), _Symbol$for2 = Symbol.for('uppy test: getQueued'), class UppySocket {
+ constructor(opts) {
+ Object.defineProperty(this, _queued, {
+ writable: true,
+ value: []
+ });
+ Object.defineProperty(this, _emitter, {
+ writable: true,
+ value: ee()
+ });
+ Object.defineProperty(this, _isOpen, {
+ writable: true,
+ value: false
+ });
+ Object.defineProperty(this, _socket, {
+ writable: true,
+ value: void 0
+ });
+ Object.defineProperty(this, _handleMessage, {
+ writable: true,
+ value: e => {
+ try {
+ const message = JSON.parse(e.data);
+ this.emit(message.action, message.payload);
+ } catch (err) {
+ // TODO: use a more robust error handler.
+ console.log(err); // eslint-disable-line no-console
+ }
+ }
+ });
+ this.opts = opts;
+
+ if (!opts || opts.autoOpen !== false) {
+ this.open();
}
}
- /**
- * Obsolete, event listeners are now added in the constructor.
- */
- ;
- _proto.run = function run() {
- this.log('Calling run() is no longer necessary.', 'warning');
- return this;
+ get isOpen() {
+ return _classPrivateFieldLooseBase(this, _isOpen)[_isOpen];
}
- /**
- * Restore an upload by its ID.
- */
- ;
- _proto.restore = function restore(uploadID) {
- this.log("Core: attempting to restore upload \"" + uploadID + "\"");
-
- if (!this.getState().currentUploads[uploadID]) {
- this.removeUpload(uploadID);
- return Promise.reject(new Error('Nonexistent upload'));
- }
+ [_Symbol$for]() {
+ return _classPrivateFieldLooseBase(this, _socket)[_socket];
+ }
- return this.runUpload(uploadID);
+ [_Symbol$for2]() {
+ return _classPrivateFieldLooseBase(this, _queued)[_queued];
}
- /**
- * Create an upload for a bunch of files.
- *
- * @param {Array<string>} fileIDs File IDs to include in this upload.
- * @returns {string} ID of this upload.
- */
- ;
- _proto.createUpload = function createUpload(fileIDs, opts) {
- var _extends5;
+ open() {
+ _classPrivateFieldLooseBase(this, _socket)[_socket] = new WebSocket(this.opts.target);
- if (opts === void 0) {
- opts = {};
- }
+ _classPrivateFieldLooseBase(this, _socket)[_socket].onopen = () => {
+ _classPrivateFieldLooseBase(this, _isOpen)[_isOpen] = true;
- // uppy.retryAll sets this to true — when retrying we want to ignore `allowNewUpload: false`
- var _opts = opts,
- _opts$forceAllowNewUp = _opts.forceAllowNewUpload,
- forceAllowNewUpload = _opts$forceAllowNewUp === void 0 ? false : _opts$forceAllowNewUp;
+ while (_classPrivateFieldLooseBase(this, _queued)[_queued].length > 0 && _classPrivateFieldLooseBase(this, _isOpen)[_isOpen]) {
+ const first = _classPrivateFieldLooseBase(this, _queued)[_queued].shift();
- var _this$getState6 = this.getState(),
- allowNewUpload = _this$getState6.allowNewUpload,
- currentUploads = _this$getState6.currentUploads;
+ this.send(first.action, first.payload);
+ }
+ };
- if (!allowNewUpload && !forceAllowNewUpload) {
- throw new Error('Cannot create a new upload: already uploading.');
- }
+ _classPrivateFieldLooseBase(this, _socket)[_socket].onclose = () => {
+ _classPrivateFieldLooseBase(this, _isOpen)[_isOpen] = false;
+ };
- var uploadID = cuid();
- this.emit('upload', {
- id: uploadID,
- fileIDs: fileIDs
- });
- this.setState({
- allowNewUpload: this.opts.allowMultipleUploads !== false,
- currentUploads: _extends({}, currentUploads, (_extends5 = {}, _extends5[uploadID] = {
- fileIDs: fileIDs,
- step: 0,
- result: {}
- }, _extends5))
- });
- return uploadID;
- };
+ _classPrivateFieldLooseBase(this, _socket)[_socket].onmessage = _classPrivateFieldLooseBase(this, _handleMessage)[_handleMessage];
+ }
- _proto.getUpload = function getUpload(uploadID) {
- var _this$getState7 = this.getState(),
- currentUploads = _this$getState7.currentUploads;
+ close() {
+ var _classPrivateFieldLoo;
- return currentUploads[uploadID];
+ (_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _socket)[_socket]) == null ? void 0 : _classPrivateFieldLoo.close();
}
- /**
- * Add data to an upload's result object.
- *
- * @param {string} uploadID The ID of the upload.
- * @param {object} data Data properties to add to the result object.
- */
- ;
- _proto.addResultData = function addResultData(uploadID, data) {
- var _extends6;
+ send(action, payload) {
+ // attach uuid
+ if (!_classPrivateFieldLooseBase(this, _isOpen)[_isOpen]) {
+ _classPrivateFieldLooseBase(this, _queued)[_queued].push({
+ action,
+ payload
+ });
- if (!this.getUpload(uploadID)) {
- this.log("Not setting result for an upload that has been removed: " + uploadID);
return;
}
- var _this$getState8 = this.getState(),
- currentUploads = _this$getState8.currentUploads;
-
- var currentUpload = _extends({}, currentUploads[uploadID], {
- result: _extends({}, currentUploads[uploadID].result, data)
- });
+ _classPrivateFieldLooseBase(this, _socket)[_socket].send(JSON.stringify({
+ action,
+ payload
+ }));
+ }
- this.setState({
- currentUploads: _extends({}, currentUploads, (_extends6 = {}, _extends6[uploadID] = currentUpload, _extends6))
- });
+ on(action, handler) {
+ _classPrivateFieldLooseBase(this, _emitter)[_emitter].on(action, handler);
}
- /**
- * Remove an upload, eg. if it has been canceled or completed.
- *
- * @param {string} uploadID The ID of the upload.
- */
- ;
- _proto.removeUpload = function removeUpload(uploadID) {
- var currentUploads = _extends({}, this.getState().currentUploads);
+ emit(action, payload) {
+ _classPrivateFieldLooseBase(this, _emitter)[_emitter].emit(action, payload);
+ }
- delete currentUploads[uploadID];
- this.setState({
- currentUploads: currentUploads
- });
+ once(action, handler) {
+ _classPrivateFieldLooseBase(this, _emitter)[_emitter].once(action, handler);
}
- /**
- * Run an upload. This picks up where it left off in case the upload is being restored.
- *
- * @private
- */
- ;
-
- _proto.runUpload = function runUpload(uploadID) {
- var _this9 = this;
-
- var uploadData = this.getState().currentUploads[uploadID];
- var restoreStep = uploadData.step;
- var steps = [].concat(this.preProcessors, this.uploaders, this.postProcessors);
- var lastStep = Promise.resolve();
- steps.forEach(function (fn, step) {
- // Skip this step if we are restoring and have already completed this step before.
- if (step < restoreStep) {
- return;
- }
- lastStep = lastStep.then(function () {
- var _extends7;
+});
+},{"namespace-emitter":9}],20:[function(require,module,exports){
+'use strict';
+/**
+ * Manages communications with Companion
+ */
- var _this9$getState = _this9.getState(),
- currentUploads = _this9$getState.currentUploads;
+const RequestClient = require('./RequestClient');
- var currentUpload = currentUploads[uploadID];
+const Provider = require('./Provider');
- if (!currentUpload) {
- return;
- }
+const SearchProvider = require('./SearchProvider');
- var updatedUpload = _extends({}, currentUpload, {
- step: step
- });
+const Socket = require('./Socket');
- _this9.setState({
- currentUploads: _extends({}, currentUploads, (_extends7 = {}, _extends7[uploadID] = updatedUpload, _extends7))
- }); // TODO give this the `updatedUpload` object as its only parameter maybe?
- // Otherwise when more metadata may be added to the upload this would keep getting more parameters
- // eslint-disable-next-line consistent-return
+module.exports = {
+ RequestClient,
+ Provider,
+ SearchProvider,
+ Socket
+};
+},{"./Provider":16,"./RequestClient":17,"./SearchProvider":18,"./Socket":19}],21:[function(require,module,exports){
+'use strict';
+/**
+ * This module serves as an Async wrapper for LocalStorage
+ */
+module.exports.setItem = (key, value) => {
+ return new Promise(resolve => {
+ localStorage.setItem(key, value);
+ resolve();
+ });
+};
- return fn(updatedUpload.fileIDs, uploadID);
- }).then(function () {
- return null;
- });
- }); // Not returning the `catch`ed promise, because we still want to return a rejected
- // promise from this method if the upload failed.
+module.exports.getItem = key => {
+ return Promise.resolve(localStorage.getItem(key));
+};
- lastStep.catch(function (err) {
- _this9.emit('error', err, uploadID);
+module.exports.removeItem = key => {
+ return new Promise(resolve => {
+ localStorage.removeItem(key);
+ resolve();
+ });
+};
+},{}],22:[function(require,module,exports){
+module.exports={
+ "name": "@uppy/companion-client",
+ "description": "Client library for communication with Companion. Intended for use in Uppy plugins.",
+ "version": "2.0.0-alpha.0",
+ "license": "MIT",
+ "main": "lib/index.js",
+ "types": "types/index.d.ts",
+ "keywords": [
+ "file uploader",
+ "uppy",
+ "uppy-plugin",
+ "companion",
+ "provider"
+ ],
+ "homepage": "https://uppy.io",
+ "bugs": {
+ "url": "https://github.com/transloadit/uppy/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/transloadit/uppy.git"
+ },
+ "dependencies": {
+ "@uppy/utils": "file:../utils",
+ "namespace-emitter": "^2.0.1",
+ "qs-stringify": "^1.1.0"
+ }
+}
- _this9.removeUpload(uploadID);
- });
- return lastStep.then(function () {
- // Set result data.
- var _this9$getState2 = _this9.getState(),
- currentUploads = _this9$getState2.currentUploads;
+},{}],23:[function(require,module,exports){
+"use strict";
- var currentUpload = currentUploads[uploadID];
+/**
+ * Little AbortController proxy module so we can swap out the implementation easily later.
+ */
+exports.AbortController = AbortController;
+exports.AbortSignal = AbortSignal;
- if (!currentUpload) {
- return;
- } // Mark postprocessing step as complete if necessary; this addresses a case where we might get
- // stuck in the postprocessing UI while the upload is fully complete.
- // If the postprocessing steps do not do any work, they may not emit postprocessing events at
- // all, and never mark the postprocessing as complete. This is fine on its own but we
- // introduced code in the @uppy/core upload-success handler to prepare postprocessing progress
- // state if any postprocessors are registered. That is to avoid a "flash of completed state"
- // before the postprocessing plugins can emit events.
- //
- // So, just in case an upload with postprocessing plugins *has* completed *without* emitting
- // postprocessing completion, we do it instead.
-
-
- currentUpload.fileIDs.forEach(function (fileID) {
- var file = _this9.getFile(fileID);
-
- if (file && file.progress.postprocess) {
- _this9.emit('postprocess-complete', file);
- }
- });
- var files = currentUpload.fileIDs.map(function (fileID) {
- return _this9.getFile(fileID);
- });
- var successful = files.filter(function (file) {
- return !file.error;
- });
- var failed = files.filter(function (file) {
- return file.error;
- });
+exports.createAbortError = (message = 'Aborted') => new DOMException(message, 'AbortError');
+},{}],24:[function(require,module,exports){
+"use strict";
- _this9.addResultData(uploadID, {
- successful: successful,
- failed: failed,
- uploadID: uploadID
- });
- }).then(function () {
- // Emit completion events.
- // This is in a separate function so that the `currentUploads` variable
- // always refers to the latest state. In the handler right above it refers
- // to an outdated object without the `.result` property.
- var _this9$getState3 = _this9.getState(),
- currentUploads = _this9$getState3.currentUploads;
-
- if (!currentUploads[uploadID]) {
- return;
- }
+/**
+ * Create a wrapper around an event emitter with a `remove` method to remove
+ * all events that were added using the wrapped emitter.
+ */
+module.exports = class EventTracker {
+ constructor(emitter) {
+ this._events = [];
+ this._emitter = emitter;
+ }
+
+ on(event, fn) {
+ this._events.push([event, fn]);
+
+ return this._emitter.on(event, fn);
+ }
+
+ remove() {
+ this._events.forEach(([event, fn]) => {
+ this._emitter.off(event, fn);
+ });
+ }
+
+};
+},{}],25:[function(require,module,exports){
+"use strict";
- var currentUpload = currentUploads[uploadID];
- var result = currentUpload.result;
+class NetworkError extends Error {
+ constructor(error, xhr = null) {
+ super(`This looks like a network error, the endpoint might be blocked by an internet provider or a firewall.\n\nSource error: [${error}]`);
+ this.isNetworkError = true;
+ this.request = xhr;
+ }
- _this9.emit('complete', result);
+}
- _this9.removeUpload(uploadID); // eslint-disable-next-line consistent-return
+module.exports = NetworkError;
+},{}],26:[function(require,module,exports){
+"use strict";
+const findIndex = require('./findIndex');
- return result;
- }).then(function (result) {
- if (result == null) {
- _this9.log("Not setting result for an upload that has been removed: " + uploadID);
- }
+function createCancelError() {
+ return new Error('Cancelled');
+}
- return result;
- });
+class RateLimitedQueue {
+ constructor(limit) {
+ if (typeof limit !== 'number' || limit === 0) {
+ this.limit = Infinity;
+ } else {
+ this.limit = limit;
+ }
+
+ this.activeRequests = 0;
+ this.queuedHandlers = [];
}
- /**
- * Start an upload for all the files that are not currently being uploaded.
- *
- * @returns {Promise}
- */
- ;
- _proto.upload = function upload() {
- var _this10 = this;
+ _call(fn) {
+ this.activeRequests += 1;
+ let done = false;
+ let cancelActive;
- if (!this.plugins.uploader) {
- this.log('No uploader type plugins are used', 'warning');
+ try {
+ cancelActive = fn();
+ } catch (err) {
+ this.activeRequests -= 1;
+ throw err;
}
- var _this$getState9 = this.getState(),
- files = _this$getState9.files;
+ return {
+ abort: () => {
+ if (done) return;
+ done = true;
+ this.activeRequests -= 1;
+ cancelActive();
+
+ this._queueNext();
+ },
+ done: () => {
+ if (done) return;
+ done = true;
+ this.activeRequests -= 1;
+
+ this._queueNext();
+ }
+ };
+ }
- var onBeforeUploadResult = this.opts.onBeforeUpload(files);
+ _queueNext() {
+ // Do it soon but not immediately, this allows clearing out the entire queue synchronously
+ // one by one without continuously _advancing_ it (and starting new tasks before immediately
+ // aborting them)
+ Promise.resolve().then(() => {
+ this._next();
+ });
+ }
- if (onBeforeUploadResult === false) {
- return Promise.reject(new Error('Not starting the upload because onBeforeUpload returned false'));
+ _next() {
+ if (this.activeRequests >= this.limit) {
+ return;
}
- if (onBeforeUploadResult && typeof onBeforeUploadResult === 'object') {
- files = onBeforeUploadResult; // Updating files in state, because uploader plugins receive file IDs,
- // and then fetch the actual file object from state
+ if (this.queuedHandlers.length === 0) {
+ return;
+ } // Dispatch the next request, and update the abort/done handlers
+ // so that cancelling it does the Right Thing (and doesn't just try
+ // to dequeue an already-running request).
- this.setState({
- files: files
- });
- }
- return Promise.resolve().then(function () {
- return _this10.checkMinNumberOfFiles(files);
- }).catch(function (err) {
- _this10.showOrLogErrorAndThrow(err);
- }).then(function () {
- var _this10$getState = _this10.getState(),
- currentUploads = _this10$getState.currentUploads; // get a list of files that are currently assigned to uploads
+ const next = this.queuedHandlers.shift();
+ const handler = this._call(next.fn);
- var currentlyUploadingFiles = Object.keys(currentUploads).reduce(function (prev, curr) {
- return prev.concat(currentUploads[curr].fileIDs);
- }, []);
- var waitingFileIDs = [];
- Object.keys(files).forEach(function (fileID) {
- var file = _this10.getFile(fileID); // if the file hasn't started uploading and hasn't already been assigned to an upload..
+ next.abort = handler.abort;
+ next.done = handler.done;
+ }
+ _queue(fn, options = {}) {
+ const handler = {
+ fn,
+ priority: options.priority || 0,
+ abort: () => {
+ this._dequeue(handler);
+ },
+ done: () => {
+ throw new Error('Cannot mark a queued request as done: this indicates a bug');
+ }
+ };
+ const index = findIndex(this.queuedHandlers, other => {
+ return handler.priority > other.priority;
+ });
- if (!file.progress.uploadStarted && currentlyUploadingFiles.indexOf(fileID) === -1) {
- waitingFileIDs.push(file.id);
- }
- });
+ if (index === -1) {
+ this.queuedHandlers.push(handler);
+ } else {
+ this.queuedHandlers.splice(index, 0, handler);
+ }
- var uploadID = _this10.createUpload(waitingFileIDs);
+ return handler;
+ }
- return _this10.runUpload(uploadID);
- }).catch(function (err) {
- _this10.showOrLogErrorAndThrow(err, {
- showInformer: false
- });
- });
- };
+ _dequeue(handler) {
+ const index = this.queuedHandlers.indexOf(handler);
- _createClass(Uppy, [{
- key: "state",
- get: function get() {
- return this.getState();
+ if (index !== -1) {
+ this.queuedHandlers.splice(index, 1);
}
- }]);
+ }
- return Uppy;
-}();
+ run(fn, queueOptions) {
+ if (this.activeRequests < this.limit) {
+ return this._call(fn);
+ }
-Uppy.VERSION = version;
+ return this._queue(fn, queueOptions);
+ }
-module.exports = function core(opts) {
- return new Uppy(opts);
-}; // Expose class constructor.
+ wrapPromiseFunction(fn, queueOptions) {
+ return (...args) => {
+ let queuedRequest;
+ const outerPromise = new Promise((resolve, reject) => {
+ queuedRequest = this.run(() => {
+ let cancelError;
+ let innerPromise;
+ try {
+ innerPromise = Promise.resolve(fn(...args));
+ } catch (err) {
+ innerPromise = Promise.reject(err);
+ }
-module.exports.Uppy = Uppy;
-module.exports.Plugin = Plugin;
-module.exports.debugLogger = debugLogger;
-},{"../package.json":18,"./Plugin":14,"./loggers":16,"./supportsUploadProgress":17,"@transloadit/prettier-bytes":1,"@uppy/store-default":20,"@uppy/utils/lib/Translator":26,"@uppy/utils/lib/findIndex":31,"@uppy/utils/lib/generateFileID":32,"@uppy/utils/lib/getFileNameAndExtension":38,"@uppy/utils/lib/getFileType":39,"cuid":50,"lodash.throttle":54,"mime-match":55,"namespace-emitter":56}],16:[function(require,module,exports){
-var getTimeStamp = require('@uppy/utils/lib/getTimeStamp'); // Swallow all logs, except errors.
-// default if logger is not set or debug: false
+ innerPromise.then(result => {
+ if (cancelError) {
+ reject(cancelError);
+ } else {
+ queuedRequest.done();
+ resolve(result);
+ }
+ }, err => {
+ if (cancelError) {
+ reject(cancelError);
+ } else {
+ queuedRequest.done();
+ reject(err);
+ }
+ });
+ return () => {
+ cancelError = createCancelError();
+ };
+ }, queueOptions);
+ });
+ outerPromise.abort = () => {
+ queuedRequest.abort();
+ };
-var justErrorsLogger = {
- debug: function debug() {},
- warn: function warn() {},
- error: function error() {
- var _console;
+ return outerPromise;
+ };
+ }
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
+}
- return (_console = console).error.apply(_console, ["[Uppy] [" + getTimeStamp() + "]"].concat(args));
- }
-}; // Print logs to console with namespace + timestamp,
-// set by logger: Uppy.debugLogger or debug: true
+module.exports = {
+ RateLimitedQueue,
+ internalRateLimitedQueue: Symbol('__queue')
+};
+},{"./findIndex":30}],27:[function(require,module,exports){
+"use strict";
-var debugLogger = {
- debug: function debug() {
- // IE 10 doesn’t support console.debug
- var debug = console.debug || console.log;
+const {
+ createAbortError
+} = require('./AbortController');
+/**
+ * Return a Promise that resolves after `ms` milliseconds.
+ *
+ * @param {number} ms - Number of milliseconds to wait.
+ * @param {{ signal?: AbortSignal }} [opts] - An abort signal that can be used to cancel the delay early.
+ * @returns {Promise<void>} A Promise that resolves after the given amount of `ms`.
+ */
- for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- args[_key2] = arguments[_key2];
- }
- debug.call.apply(debug, [console, "[Uppy] [" + getTimeStamp() + "]"].concat(args));
- },
- warn: function warn() {
- var _console2;
+module.exports = function delay(ms, opts) {
+ return new Promise((resolve, reject) => {
+ if (opts && opts.signal && opts.signal.aborted) {
+ return reject(createAbortError());
+ }
- for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
- args[_key3] = arguments[_key3];
+ function onabort() {
+ clearTimeout(timeout);
+ cleanup();
+ reject(createAbortError());
}
- return (_console2 = console).warn.apply(_console2, ["[Uppy] [" + getTimeStamp() + "]"].concat(args));
- },
- error: function error() {
- var _console3;
+ const timeout = setTimeout(() => {
+ cleanup();
+ resolve();
+ }, ms);
- for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
- args[_key4] = arguments[_key4];
+ if (opts && opts.signal) {
+ opts.signal.addEventListener('abort', onabort);
}
- return (_console3 = console).error.apply(_console3, ["[Uppy] [" + getTimeStamp() + "]"].concat(args));
- }
-};
-module.exports = {
- justErrorsLogger: justErrorsLogger,
- debugLogger: debugLogger
+ function cleanup() {
+ if (opts && opts.signal) {
+ opts.signal.removeEventListener('abort', onabort);
+ }
+ }
+ });
};
-},{"@uppy/utils/lib/getTimeStamp":41}],17:[function(require,module,exports){
-// Edge 15.x does not fire 'progress' events on uploads.
-// See https://github.com/transloadit/uppy/issues/945
-// And https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12224510/
-module.exports = function supportsUploadProgress(userAgent) {
- // Allow passing in userAgent for tests
- if (userAgent == null) {
- userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : null;
- } // Assume it works because basically everything supports progress events.
+},{"./AbortController":23}],28:[function(require,module,exports){
+"use strict";
+const throttle = require('lodash.throttle');
- if (!userAgent) return true;
- var m = /Edge\/(\d+\.\d+)/.exec(userAgent);
- if (!m) return true;
- var edgeVersion = m[1];
+function _emitSocketProgress(uploader, progressData, file) {
+ const {
+ progress,
+ bytesUploaded,
+ bytesTotal
+ } = progressData;
- var _edgeVersion$split = edgeVersion.split('.'),
- major = _edgeVersion$split[0],
- minor = _edgeVersion$split[1];
+ if (progress) {
+ uploader.uppy.log(`Upload progress: ${progress}`);
+ uploader.uppy.emit('upload-progress', file, {
+ uploader,
+ bytesUploaded,
+ bytesTotal
+ });
+ }
+}
- major = parseInt(major, 10);
- minor = parseInt(minor, 10); // Worked before:
- // Edge 40.15063.0.0
- // Microsoft EdgeHTML 15.15063
+module.exports = throttle(_emitSocketProgress, 300, {
+ leading: true,
+ trailing: true
+});
+},{"lodash.throttle":7}],29:[function(require,module,exports){
+"use strict";
- if (major < 15 || major === 15 && minor < 15063) {
- return true;
- } // Fixed in:
- // Microsoft EdgeHTML 18.18218
+const NetworkError = require('./NetworkError');
+/**
+ * Wrapper around window.fetch that throws a NetworkError when appropriate
+ */
- if (major > 18 || major === 18 && minor >= 18218) {
- return true;
- } // other versions don't work.
+module.exports = function fetchWithNetworkError(...options) {
+ return fetch(...options).catch(err => {
+ if (err.name === 'AbortError') {
+ throw err;
+ } else {
+ throw new NetworkError(err);
+ }
+ });
+};
+},{"./NetworkError":25}],30:[function(require,module,exports){
+"use strict";
+
+/**
+ * Array.prototype.findIndex ponyfill for old browsers.
+ *
+ * @param {Array} array
+ * @param {Function} predicate
+ * @returns {number}
+ */
+module.exports = function findIndex(array, predicate) {
+ for (let i = 0; i < array.length; i++) {
+ if (predicate(array[i])) return i;
+ }
+ return -1;
+};
+},{}],31:[function(require,module,exports){
+"use strict";
- return false;
+module.exports = function getSocketHost(url) {
+ // get the host domain
+ const regex = /^(?:https?:\/\/|\/\/)?(?:[^@\n]+@)?(?:www\.)?([^\n]+)/i;
+ const host = regex.exec(url)[1];
+ const socketProtocol = /^http:\/\//i.test(url) ? 'ws' : 'wss';
+ return `${socketProtocol}://${host}`;
};
-},{}],18:[function(require,module,exports){
+},{}],32:[function(require,module,exports){
module.exports={
- "name": "@uppy/core",
- "description": "Core module for the extensible JavaScript file upload widget with support for drag&drop, resumable uploads, previews, restrictions, file processing/encoding, remote providers like Instagram, Dropbox, Google Drive, S3 and more :dog:",
- "version": "1.19.2",
+ "name": "@uppy/aws-s3-multipart",
+ "description": "Upload to Amazon S3 with Uppy and S3's Multipart upload strategy",
+ "version": "2.0.0-alpha.0",
"license": "MIT",
"main": "lib/index.js",
- "style": "dist/style.min.css",
"types": "types/index.d.ts",
"keywords": [
"file uploader",
+ "aws s3",
+ "amazon s3",
+ "s3",
"uppy",
- "uppy-plugin"
+ "uppy-plugin",
+ "multipart"
],
"homepage": "https://uppy.io",
"bugs": {
@@ -4707,561 +2894,825 @@ module.exports={
"url": "git+https://github.com/transloadit/uppy.git"
},
"dependencies": {
- "@transloadit/prettier-bytes": "0.0.7",
- "@uppy/store-default": "^1.2.7",
- "@uppy/utils": "^3.6.2",
- "cuid": "^2.1.1",
- "lodash.throttle": "^4.1.1",
- "mime-match": "^1.0.2",
- "namespace-emitter": "^2.0.1",
- "preact": "8.2.9"
+ "@uppy/companion-client": "file:../companion-client",
+ "@uppy/utils": "file:../utils"
},
- "gitHead": "4b782ffbbb443672843d7b4096956bed3b11d612"
+ "devDependencies": {
+ "whatwg-fetch": "3.6.2",
+ "nock": "^13.1.0"
+ },
+ "peerDependencies": {
+ "@uppy/core": "^1.0.0"
+ }
+}
+
+},{}],33:[function(require,module,exports){
+"use strict";
+
+const cuid = require('cuid');
+
+const {
+ Provider,
+ RequestClient,
+ Socket
+} = require('@uppy/companion-client');
+
+const emitSocketProgress = require('@uppy/utils/lib/emitSocketProgress');
+
+const getSocketHost = require('@uppy/utils/lib/getSocketHost');
+
+const EventTracker = require('@uppy/utils/lib/EventTracker');
+
+const ProgressTimeout = require('@uppy/utils/lib/ProgressTimeout');
+
+const NetworkError = require('@uppy/utils/lib/NetworkError');
+
+const isNetworkError = require('@uppy/utils/lib/isNetworkError');
+
+const {
+ internalRateLimitedQueue
+} = require('@uppy/utils/lib/RateLimitedQueue'); // 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 = Object.assign(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) {
+ const dataWithUpdatedType = file.data.slice(0, file.data.size, file.meta.type);
+ return dataWithUpdatedType;
}
-},{}],19:[function(require,module,exports){
-var _class, _temp;
+module.exports = class MiniXHRUpload {
+ constructor(uppy, opts) {
+ this.uppy = uppy;
+ this.opts = {
+ validateStatus(status, responseText, response) {
+ return status >= 200 && status < 300;
+ },
+
+ ...opts
+ };
+ this.requests = opts[internalRateLimitedQueue];
+ this.uploaderEvents = Object.create(null);
+ this.i18n = opts.i18n;
+ }
+
+ _getOptions(file) {
+ const {
+ uppy
+ } = this;
+ const overrides = uppy.getState().xhrUpload;
+ const opts = { ...this.opts,
+ ...(overrides || {}),
+ ...(file.xhrUpload || {}),
+ headers: {}
+ };
+ Object.assign(opts.headers, this.opts.headers);
+
+ if (overrides) {
+ Object.assign(opts.headers, overrides.headers);
+ }
+
+ if (file.xhrUpload) {
+ Object.assign(opts.headers, file.xhrUpload.headers);
+ }
+
+ return opts;
+ }
+
+ uploadFile(id, current, total) {
+ const 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);
+ }
+
+ _addMetadata(formData, meta, opts) {
+ const metaFields = Array.isArray(opts.metaFields) ? opts.metaFields // Send along all fields by default.
+ : Object.keys(meta);
+ metaFields.forEach(item => {
+ formData.append(item, meta[item]);
+ });
+ }
+
+ _createFormDataUpload(file, opts) {
+ const formPost = new FormData();
-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._addMetadata(formPost, file.meta, opts);
-function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
+ const dataWithUpdatedType = setTypeInBlob(file);
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
+ if (file.name) {
+ formPost.append(opts.fieldName, dataWithUpdatedType, file.meta.name);
+ } else {
+ formPost.append(opts.fieldName, dataWithUpdatedType);
+ }
-var _require = require('@uppy/core'),
- Plugin = _require.Plugin;
+ return formPost;
+ }
-var getDroppedFiles = require('@uppy/utils/lib/getDroppedFiles');
+ _createBareUpload(file, opts) {
+ return file.data;
+ }
-var toArray = require('@uppy/utils/lib/toArray');
-/**
- * Drop Target plugin
- *
- */
+ _onFileRemoved(fileID, cb) {
+ this.uploaderEvents[fileID].on('file-removed', file => {
+ if (fileID === file.id) cb(file.id);
+ });
+ }
+ _onRetry(fileID, cb) {
+ this.uploaderEvents[fileID].on('upload-retry', targetFileID => {
+ if (fileID === targetFileID) {
+ cb();
+ }
+ });
+ }
-module.exports = (_temp = _class = /*#__PURE__*/function (_Plugin) {
- _inheritsLoose(DropTarget, _Plugin);
+ _onRetryAll(fileID, cb) {
+ this.uploaderEvents[fileID].on('retry-all', filesToRetry => {
+ if (!this.uppy.getFile(fileID)) return;
+ cb();
+ });
+ }
- function DropTarget(uppy, opts) {
- var _this;
+ _onCancelAll(fileID, cb) {
+ this.uploaderEvents[fileID].on('cancel-all', () => {
+ if (!this.uppy.getFile(fileID)) return;
+ cb();
+ });
+ }
- _this = _Plugin.call(this, uppy, opts) || this;
+ _uploadLocalFile(file, current, total) {
+ const opts = this._getOptions(file);
- _this.addFiles = function (files) {
- var descriptors = files.map(function (file) {
- return {
- source: _this.id,
- name: file.name,
- type: file.type,
- data: file,
- meta: {
- // path of the file relative to the ancestor directory the user selected.
- // e.g. 'docs/Old Prague/airbnb.pdf'
- relativePath: file.relativePath || null
- }
- };
+ this.uppy.log(`uploading ${current} of ${total}`);
+ return new Promise((resolve, reject) => {
+ // This is done in index.js in the S3 plugin.
+ // this.uppy.emit('upload-started', file)
+ const data = opts.formData ? this._createFormDataUpload(file, opts) : this._createBareUpload(file, opts);
+ const xhr = new XMLHttpRequest();
+ this.uploaderEvents[file.id] = new EventTracker(this.uppy);
+ const timer = new ProgressTimeout(opts.timeout, () => {
+ xhr.abort();
+ queuedRequest.done();
+ const error = new Error(this.i18n('timedOut', {
+ seconds: Math.ceil(opts.timeout / 1000)
+ }));
+ this.uppy.emit('upload-error', file, error);
+ reject(error);
});
+ const id = cuid();
+ xhr.upload.addEventListener('loadstart', ev => {
+ this.uppy.log(`[AwsS3/XHRUpload] ${id} started`);
+ });
+ xhr.upload.addEventListener('progress', ev => {
+ this.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
- try {
- _this.uppy.addFiles(descriptors);
- } catch (err) {
- _this.uppy.log(err);
- }
- };
-
- _this.handleDrop = function (event) {
- event.preventDefault();
- event.stopPropagation();
- clearTimeout(_this.removeDragOverClassTimeout); // 2. Remove dragover class
+ timer.progress();
- event.currentTarget.classList.remove('uppy-is-drag-over');
+ if (ev.lengthComputable) {
+ this.uppy.emit('upload-progress', file, {
+ uploader: this,
+ bytesUploaded: ev.loaded,
+ bytesTotal: ev.total
+ });
+ }
+ });
+ xhr.addEventListener('load', ev => {
+ this.uppy.log(`[AwsS3/XHRUpload] ${id} finished`);
+ timer.done();
+ queuedRequest.done();
- _this.setPluginState({
- isDraggingOver: false
- }); // 3. Add all dropped files
+ if (this.uploaderEvents[file.id]) {
+ this.uploaderEvents[file.id].remove();
+ this.uploaderEvents[file.id] = null;
+ }
+ if (opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {
+ const body = opts.getResponseData(xhr.responseText, xhr);
+ const uploadURL = body[opts.responseUrlFieldName];
+ const uploadResp = {
+ status: ev.target.status,
+ body,
+ uploadURL
+ };
+ this.uppy.emit('upload-success', file, uploadResp);
- _this.uppy.log('[DropTarget] Files were dropped');
+ if (uploadURL) {
+ this.uppy.log(`Download ${file.name} from ${uploadURL}`);
+ }
- var logDropError = function logDropError(error) {
- _this.uppy.log(error, 'error');
- };
+ return resolve(file);
+ }
- getDroppedFiles(event.dataTransfer, {
- logDropError: logDropError
- }).then(function (files) {
- return _this.addFiles(files);
+ const body = opts.getResponseData(xhr.responseText, xhr);
+ const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));
+ const response = {
+ status: ev.target.status,
+ body
+ };
+ this.uppy.emit('upload-error', file, error, response);
+ return reject(error);
});
- };
-
- _this.handleDragOver = function (event) {
- event.preventDefault();
- event.stopPropagation(); // 1. Add a small (+) icon on drop
- // (and prevent browsers from interpreting this as files being _moved_ into the browser,
- // https://github.com/transloadit/uppy/issues/1978)
+ xhr.addEventListener('error', ev => {
+ this.uppy.log(`[AwsS3/XHRUpload] ${id} errored`);
+ timer.done();
+ queuedRequest.done();
- event.dataTransfer.dropEffect = 'copy';
- clearTimeout(_this.removeDragOverClassTimeout);
- event.currentTarget.classList.add('uppy-is-drag-over');
+ if (this.uploaderEvents[file.id]) {
+ this.uploaderEvents[file.id].remove();
+ this.uploaderEvents[file.id] = null;
+ }
- _this.setPluginState({
- isDraggingOver: true
+ const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));
+ this.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.
- _this.handleDragLeave = function (event) {
- event.preventDefault();
- event.stopPropagation();
- var currentTarget = event.currentTarget;
- clearTimeout(_this.removeDragOverClassTimeout); // Timeout against flickering, this solution is taken from drag-drop library.
- // Solution with 'pointer-events: none' didn't work across browsers.
+ xhr.withCredentials = opts.withCredentials;
- _this.removeDragOverClassTimeout = setTimeout(function () {
- currentTarget.classList.remove('uppy-is-drag-over');
+ if (opts.responseType !== '') {
+ xhr.responseType = opts.responseType;
+ }
- _this.setPluginState({
- isDraggingOver: false
- });
- }, 50);
- };
+ Object.keys(opts.headers).forEach(header => {
+ xhr.setRequestHeader(header, opts.headers[header]);
+ });
+ const queuedRequest = this.requests.run(() => {
+ xhr.send(data);
+ return () => {
+ timer.done();
+ xhr.abort();
+ };
+ }, {
+ priority: 1
+ });
- _this.addListeners = function () {
- var target = _this.opts.target;
+ this._onFileRemoved(file.id, () => {
+ queuedRequest.abort();
+ reject(new Error('File removed'));
+ });
- if (target instanceof Element) {
- _this.nodes = [target];
- } else if (typeof target === 'string') {
- _this.nodes = toArray(document.querySelectorAll(target));
- }
+ this._onCancelAll(file.id, () => {
+ queuedRequest.abort();
+ reject(new Error('Upload cancelled'));
+ });
+ });
+ }
- if (!_this.nodes && !_this.nodes.length > 0) {
- throw new Error("\"" + target + "\" does not match any HTML elements");
- }
+ _uploadRemoteFile(file, current, total) {
+ const opts = this._getOptions(file);
- _this.nodes.forEach(function (node) {
- node.addEventListener('dragover', _this.handleDragOver, false);
- node.addEventListener('dragleave', _this.handleDragLeave, false);
- node.addEventListener('drop', _this.handleDrop, false);
+ return new Promise((resolve, reject) => {
+ // This is done in index.js in the S3 plugin.
+ // this.uppy.emit('upload-started', file)
+ const fields = {};
+ const metaFields = Array.isArray(opts.metaFields) ? opts.metaFields // Send along all fields by default.
+ : Object.keys(file.meta);
+ metaFields.forEach(name => {
+ fields[name] = file.meta[name];
});
- };
-
- _this.removeListeners = function () {
- if (_this.nodes) {
- _this.nodes.forEach(function (node) {
- node.removeEventListener('dragover', _this.handleDragOver, false);
- node.removeEventListener('dragleave', _this.handleDragLeave, false);
- node.removeEventListener('drop', _this.handleDrop, false);
+ const Client = file.remote.providerOptions.provider ? Provider : RequestClient;
+ const client = new Client(this.uppy, file.remote.providerOptions);
+ client.post(file.remote.url, { ...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(res => {
+ const {
+ token
+ } = res;
+ const host = getSocketHost(file.remote.companionUrl);
+ const socket = new Socket({
+ target: `${host}/api/${token}`,
+ autoOpen: false
});
- }
- };
+ this.uploaderEvents[file.id] = new EventTracker(this.uppy);
- _this.type = 'acquirer';
- _this.id = _this.opts.id || 'DropTarget';
- _this.title = 'Drop Target'; // Default options
+ this._onFileRemoved(file.id, () => {
+ socket.send('pause', {});
+ queuedRequest.abort();
+ resolve(`upload ${file.id} was removed`);
+ });
- var defaultOpts = {
- target: null
- }; // Merge default options with the ones set by user
+ this._onCancelAll(file.id, () => {
+ socket.send('pause', {});
+ queuedRequest.abort();
+ resolve(`upload ${file.id} was canceled`);
+ });
- _this.opts = _extends({}, defaultOpts, opts);
- _this.removeDragOverClassTimeout = null;
- return _this;
- }
+ this._onRetry(file.id, () => {
+ socket.send('pause', {});
+ socket.send('resume', {});
+ });
- var _proto = DropTarget.prototype;
+ this._onRetryAll(file.id, () => {
+ socket.send('pause', {});
+ socket.send('resume', {});
+ });
- _proto.install = function install() {
- this.setPluginState({
- isDraggingOver: false
- });
- this.addListeners();
- };
+ socket.on('progress', progressData => emitSocketProgress(this, progressData, file));
+ socket.on('success', data => {
+ const body = opts.getResponseData(data.response.responseText, data.response);
+ const uploadURL = body[opts.responseUrlFieldName];
+ const uploadResp = {
+ status: data.response.status,
+ body,
+ uploadURL,
+ bytesUploaded: data.bytesUploaded
+ };
+ this.uppy.emit('upload-success', file, uploadResp);
+ queuedRequest.done();
- _proto.uninstall = function uninstall() {
- this.removeListeners();
- };
+ if (this.uploaderEvents[file.id]) {
+ this.uploaderEvents[file.id].remove();
+ this.uploaderEvents[file.id] = null;
+ }
- return DropTarget;
-}(Plugin), _class.VERSION = "0.2.4", _temp);
-},{"@uppy/core":15,"@uppy/utils/lib/getDroppedFiles":33,"@uppy/utils/lib/toArray":47}],20:[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); }
+ return resolve();
+ });
+ socket.on('error', errData => {
+ const resp = errData.response;
+ const error = resp ? opts.getResponseError(resp.responseText, resp) : Object.assign(new Error(errData.error.message), {
+ cause: errData.error
+ });
+ this.uppy.emit('upload-error', file, error);
+ queuedRequest.done();
-/**
- * Default store that keeps state in a simple object.
- */
-var DefaultStore = /*#__PURE__*/function () {
- function DefaultStore() {
- this.state = {};
- this.callbacks = [];
- }
+ if (this.uploaderEvents[file.id]) {
+ this.uploaderEvents[file.id].remove();
+ this.uploaderEvents[file.id] = null;
+ }
- var _proto = DefaultStore.prototype;
+ reject(error);
+ });
+ const queuedRequest = this.requests.run(() => {
+ socket.open();
- _proto.getState = function getState() {
- return this.state;
- };
+ if (file.isPaused) {
+ socket.send('pause', {});
+ }
- _proto.setState = function setState(patch) {
- var prevState = _extends({}, this.state);
+ return () => socket.close();
+ });
+ }).catch(err => {
+ this.uppy.emit('upload-error', file, err);
+ reject(err);
+ });
+ });
+ }
- var nextState = _extends({}, this.state, patch);
+};
+},{"@uppy/companion-client":41,"@uppy/utils/lib/EventTracker":44,"@uppy/utils/lib/NetworkError":45,"@uppy/utils/lib/ProgressTimeout":46,"@uppy/utils/lib/RateLimitedQueue":47,"@uppy/utils/lib/emitSocketProgress":49,"@uppy/utils/lib/getSocketHost":52,"@uppy/utils/lib/isNetworkError":54,"cuid":3}],34:[function(require,module,exports){
+"use strict";
- this.state = nextState;
+var _class, _temp;
- this._publish(prevState, nextState, patch);
- };
+/**
+ * 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 breaking change, so it is
+ * planned for some future Uppy version.
+ *
+ * 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 :)
+ */
+const {
+ BasePlugin
+} = require('@uppy/core');
- _proto.subscribe = function subscribe(listener) {
- var _this = this;
+const Translator = require('@uppy/utils/lib/Translator');
- this.callbacks.push(listener);
- return function () {
- // Remove the listener.
- _this.callbacks.splice(_this.callbacks.indexOf(listener), 1);
- };
- };
+const {
+ RateLimitedQueue,
+ internalRateLimitedQueue
+} = require('@uppy/utils/lib/RateLimitedQueue');
- _proto._publish = function _publish() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
+const settle = require('@uppy/utils/lib/settle');
- this.callbacks.forEach(function (listener) {
- listener.apply(void 0, args);
- });
- };
+const hasProperty = require('@uppy/utils/lib/hasProperty');
- return DefaultStore;
-}();
+const {
+ RequestClient
+} = require('@uppy/companion-client');
-DefaultStore.VERSION = "1.2.7";
+const qsStringify = require('qs-stringify');
-module.exports = function defaultStore() {
- return new DefaultStore();
-};
-},{}],21:[function(require,module,exports){
-/**
- * Little AbortController proxy module so we can swap out the implementation easily later.
- */
-var _require = require('abortcontroller-polyfill/dist/abortcontroller'),
- AbortController = _require.AbortController,
- AbortSignal = _require.AbortSignal;
+const MiniXHRUpload = require('./MiniXHRUpload');
-function createAbortError(message) {
- if (message === void 0) {
- message = 'Aborted';
- }
+const isXml = require('./isXml');
- try {
- return new DOMException(message, 'AbortError');
- } catch (_unused) {
- // For Internet Explorer
- var error = new Error(message);
- error.name = 'AbortError';
- return error;
- }
+function resolveUrl(origin, link) {
+ return new URL(link, origin || undefined).toString();
}
-
-exports.AbortController = AbortController;
-exports.AbortSignal = AbortSignal;
-exports.createAbortError = createAbortError;
-},{"abortcontroller-polyfill/dist/abortcontroller":49}],22:[function(require,module,exports){
/**
- * Create a wrapper around an event emitter with a `remove` method to remove
- * all events that were added using the wrapped emitter.
+ * 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.
*/
-module.exports = /*#__PURE__*/function () {
- function EventTracker(emitter) {
- this._events = [];
- this._emitter = emitter;
- }
- var _proto = EventTracker.prototype;
-
- _proto.on = function on(event, fn) {
- this._events.push([event, fn]);
- return this._emitter.on(event, fn);
- };
+function getXmlValue(source, tagName) {
+ const start = source.indexOf(`<${tagName}>`);
+ const end = source.indexOf(`</${tagName}>`, start);
+ return start !== -1 && end !== -1 ? source.slice(start + tagName.length + 2, end) : '';
+}
- _proto.remove = function remove() {
- var _this = this;
+function assertServerError(res) {
+ if (res && res.error) {
+ const error = new Error(res.message);
+ Object.assign(error, res.error);
+ throw error;
+ }
- this._events.forEach(function (_ref) {
- var event = _ref[0],
- fn = _ref[1];
+ return res;
+} // warning deduplication flag: see `getResponseData()` XHRUpload option definition
- _this._emitter.off(event, fn);
- });
- };
- return EventTracker;
-}();
-},{}],23:[function(require,module,exports){
-function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
+let warnedSuccessActionStatus = false;
+module.exports = (_temp = _class = class AwsS3 extends BasePlugin {
+ constructor(uppy, opts) {
+ super(uppy, opts);
+ this.type = 'uploader';
+ this.id = this.opts.id || 'AwsS3';
+ this.title = 'AWS S3';
+ this.defaultLocale = {
+ strings: {
+ timedOut: 'Upload stalled for %{seconds} seconds, aborting.'
+ }
+ };
+ const defaultOptions = {
+ timeout: 30 * 1000,
+ limit: 0,
+ metaFields: [],
+ // have to opt in
+ getUploadParameters: this.getUploadParameters.bind(this)
+ };
+ this.opts = { ...defaultOptions,
+ ...opts
+ };
+ this.client = new RequestClient(uppy, opts);
+ this.handleUpload = this.handleUpload.bind(this);
+ this.requests = new RateLimitedQueue(this.opts.limit);
+ }
-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); }
+ getUploadParameters(file) {
+ if (!this.opts.companionUrl) {
+ throw new Error('Expected a `companionUrl` option containing a Companion address.');
+ }
-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); }
+ const filename = file.meta.name;
+ const {
+ type
+ } = file.meta;
+ const metadata = {};
+ this.opts.metaFields.forEach(key => {
+ if (file.meta[key] != null) {
+ metadata[key] = file.meta[key].toString();
+ }
+ });
+ const query = qsStringify({
+ filename,
+ type,
+ metadata
+ });
+ return this.client.get(`s3/params?${query}`).then(assertServerError);
+ }
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
+ validateParameters(file, params) {
+ const valid = typeof params === 'object' && params && typeof params.url === 'string' && (typeof params.fields === 'object' || params.fields == null);
-function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
+ if (!valid) {
+ const 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;
+ }
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
+ const methodIsValid = params.method == null || /^(put|post)$/i.test(params.method);
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
+ if (!methodIsValid) {
+ const 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;
+ }
+ }
-var NetworkError = /*#__PURE__*/function (_Error) {
- _inheritsLoose(NetworkError, _Error);
+ handleUpload(fileIDs) {
+ /**
+ * keep track of `getUploadParameters()` responses
+ * so we can cancel the calls individually using just a file ID
+ *
+ * @type {object.<string, Promise>}
+ */
+ const paramsPromises = Object.create(null);
- function NetworkError(error, xhr) {
- var _this;
+ function onremove(file) {
+ const {
+ id
+ } = file;
- if (xhr === void 0) {
- xhr = null;
+ if (hasProperty(paramsPromises, id)) {
+ paramsPromises[id].abort();
+ }
}
- _this = _Error.call(this, "This looks like a network error, the endpoint might be blocked by an internet provider or a firewall.\n\nSource error: [" + error + "]") || this;
- _this.isNetworkError = true;
- _this.request = xhr;
- return _this;
- }
+ this.uppy.on('file-removed', onremove);
+ fileIDs.forEach(id => {
+ const file = this.uppy.getFile(id);
+ this.uppy.emit('upload-started', file);
+ });
+ const getUploadParameters = this.requests.wrapPromiseFunction(file => {
+ return this.opts.getUploadParameters(file);
+ });
+ const numberOfFiles = fileIDs.length;
+ return settle(fileIDs.map((id, index) => {
+ paramsPromises[id] = getUploadParameters(this.uppy.getFile(id));
+ return paramsPromises[id].then(params => {
+ delete paramsPromises[id];
+ const file = this.uppy.getFile(id);
+ this.validateParameters(file, params);
+ const {
+ method = 'post',
+ url,
+ fields,
+ headers
+ } = params;
+ const xhrOpts = {
+ method,
+ formData: method.toLowerCase() === 'post',
+ endpoint: url,
+ metaFields: fields ? Object.keys(fields) : []
+ };
- return NetworkError;
-}( /*#__PURE__*/_wrapNativeSuper(Error));
+ if (headers) {
+ xhrOpts.headers = headers;
+ }
-module.exports = NetworkError;
-},{}],24:[function(require,module,exports){
-/**
- * Helper to abort upload requests if there has not been any progress for `timeout` ms.
- * Create an instance using `timer = new ProgressTimeout(10000, onTimeout)`
- * Call `timer.progress()` to signal that there has been progress of any kind.
- * Call `timer.done()` when the upload has completed.
- */
-var ProgressTimeout = /*#__PURE__*/function () {
- function ProgressTimeout(timeout, timeoutHandler) {
- this._timeout = timeout;
- this._onTimedOut = timeoutHandler;
- this._isDone = false;
- this._aliveTimer = null;
- this._onTimedOut = this._onTimedOut.bind(this);
+ this.uppy.setFileState(file.id, {
+ meta: { ...file.meta,
+ ...fields
+ },
+ xhrUpload: xhrOpts
+ });
+ return this._uploader.uploadFile(file.id, index, numberOfFiles);
+ }).catch(error => {
+ delete paramsPromises[id];
+ const file = this.uppy.getFile(id);
+ this.uppy.emit('upload-error', file, error);
+ });
+ })).then(settled => {
+ // cleanup.
+ this.uppy.off('file-removed', onremove);
+ return settled;
+ });
}
- var _proto = ProgressTimeout.prototype;
-
- _proto.progress = function progress() {
- // Some browsers fire another progress event when the upload is
- // cancelled, so we have to ignore progress after the timer was
- // told to stop.
- if (this._isDone) return;
+ install() {
+ const {
+ uppy
+ } = this;
+ 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.
- if (this._timeout > 0) {
- if (this._aliveTimer) clearTimeout(this._aliveTimer);
- this._aliveTimer = setTimeout(this._onTimedOut, this._timeout);
- }
- };
+ function defaultGetResponseData(content, xhr) {
+ const opts = this; // If no response, we've hopefully done a PUT request to the file
+ // in the bucket on its full URL.
- _proto.done = function done() {
- if (this._aliveTimer) {
- clearTimeout(this._aliveTimer);
- this._aliveTimer = null;
- }
+ 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.
- this._isDone = true;
- };
- return ProgressTimeout;
-}();
+ return {
+ location: null
+ };
+ } // responseURL is not available in older browsers.
-module.exports = ProgressTimeout;
-},{}],25:[function(require,module,exports){
-var findIndex = require('./findIndex');
-function createCancelError() {
- return new Error('Cancelled');
-}
+ 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
-module.exports = /*#__PURE__*/function () {
- function RateLimitedQueue(limit) {
- if (typeof limit !== 'number' || limit === 0) {
- this.limit = Infinity;
- } else {
- this.limit = limit;
- }
- this.activeRequests = 0;
- this.queuedHandlers = [];
- }
+ return {
+ location: xhr.responseURL.replace(/\?.*$/, '')
+ };
+ }
- var _proto = RateLimitedQueue.prototype;
+ 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.
- _proto._call = function _call(fn) {
- var _this = this;
- this.activeRequests += 1;
- var _done = false;
- var cancelActive;
+ function defaultGetResponseError(content, xhr) {
+ // If no response, we don't have a specific error message, use the default.
+ if (!isXml(content, xhr)) {
+ return;
+ }
- try {
- cancelActive = fn();
- } catch (err) {
- this.activeRequests -= 1;
- throw err;
+ const error = getXmlValue(content, 'Message');
+ return new Error(error);
}
- return {
- abort: function abort() {
- if (_done) return;
- _done = true;
- _this.activeRequests -= 1;
- cancelActive();
-
- _this._queueNext();
- },
- done: function done() {
- if (_done) return;
- _done = true;
- _this.activeRequests -= 1;
+ const xhrOptions = {
+ fieldName: 'file',
+ responseUrlFieldName: 'location',
+ timeout: this.opts.timeout,
+ // Share the rate limiting queue with XHRUpload.
+ [internalRateLimitedQueue]: this.requests,
+ responseType: 'text',
+ getResponseData: this.opts.getResponseData || defaultGetResponseData,
+ getResponseError: defaultGetResponseError
+ }; // Only for MiniXHRUpload, remove once we can depend on XHRUpload directly again
- _this._queueNext();
- }
- };
- };
+ xhrOptions.i18n = this.i18n; // Revert to `this.uppy.use(XHRUpload)` once the big comment block at the top of
+ // this file is solved
- _proto._queueNext = function _queueNext() {
- var _this2 = this;
+ this._uploader = new MiniXHRUpload(this.uppy, xhrOptions);
+ }
- // Do it soon but not immediately, this allows clearing out the entire queue synchronously
- // one by one without continuously _advancing_ it (and starting new tasks before immediately
- // aborting them)
- Promise.resolve().then(function () {
- _this2._next();
- });
- };
+ uninstall() {
+ this.uppy.removeUploader(this.handleUpload);
+ }
- _proto._next = function _next() {
- if (this.activeRequests >= this.limit) {
- return;
- }
+}, _class.VERSION = require('../package.json').version, _temp);
+},{"../package.json":56,"./MiniXHRUpload":33,"./isXml":35,"@uppy/companion-client":41,"@uppy/core":60,"@uppy/utils/lib/RateLimitedQueue":47,"@uppy/utils/lib/Translator":48,"@uppy/utils/lib/hasProperty":53,"@uppy/utils/lib/settle":55,"qs-stringify":11}],35:[function(require,module,exports){
+"use strict";
- if (this.queuedHandlers.length === 0) {
- return;
- } // Dispatch the next request, and update the abort/done handlers
- // so that cancelling it does the Right Thing (and doesn't just try
- // to dequeue an already-running request).
+/**
+ * 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.
+ */
- var next = this.queuedHandlers.shift();
+function isXml(content, xhr) {
+ const rawContentType = xhr.headers ? xhr.headers['content-type'] : xhr.getResponseHeader('Content-Type');
- var handler = this._call(next.fn);
+ if (typeof rawContentType === 'string') {
+ const contentType = removeMimeParameters(rawContentType).toLowerCase();
- next.abort = handler.abort;
- next.done = handler.done;
- };
+ if (contentType === 'application/xml' || contentType === 'text/xml') {
+ return true;
+ } // GCS uses text/html for some reason
+ // https://github.com/transloadit/uppy/issues/896
- _proto._queue = function _queue(fn, options) {
- var _this3 = this;
- if (options === void 0) {
- options = {};
+ if (contentType === 'text/html' && /^<\?xml /.test(content)) {
+ return true;
}
+ }
- var handler = {
- fn: fn,
- priority: options.priority || 0,
- abort: function abort() {
- _this3._dequeue(handler);
- },
- done: function done() {
- throw new Error('Cannot mark a queued request as done: this indicates a bug');
- }
- };
- var index = findIndex(this.queuedHandlers, function (other) {
- return handler.priority > other.priority;
- });
+ return false;
+}
- if (index === -1) {
- this.queuedHandlers.push(handler);
- } else {
- this.queuedHandlers.splice(index, 0, handler);
- }
+module.exports = isXml;
+},{}],36:[function(require,module,exports){
+arguments[4][15][0].apply(exports,arguments)
+},{"dup":15}],37:[function(require,module,exports){
+arguments[4][16][0].apply(exports,arguments)
+},{"./RequestClient":38,"./tokenStorage":42,"dup":16,"qs-stringify":11}],38:[function(require,module,exports){
+arguments[4][17][0].apply(exports,arguments)
+},{"../package.json":43,"./AuthError":36,"@uppy/utils/lib/fetchWithNetworkError":50,"dup":17}],39:[function(require,module,exports){
+arguments[4][18][0].apply(exports,arguments)
+},{"./RequestClient":38,"dup":18}],40:[function(require,module,exports){
+arguments[4][19][0].apply(exports,arguments)
+},{"dup":19,"namespace-emitter":9}],41:[function(require,module,exports){
+arguments[4][20][0].apply(exports,arguments)
+},{"./Provider":37,"./RequestClient":38,"./SearchProvider":39,"./Socket":40,"dup":20}],42:[function(require,module,exports){
+arguments[4][21][0].apply(exports,arguments)
+},{"dup":21}],43:[function(require,module,exports){
+arguments[4][22][0].apply(exports,arguments)
+},{"dup":22}],44:[function(require,module,exports){
+arguments[4][24][0].apply(exports,arguments)
+},{"dup":24}],45:[function(require,module,exports){
+arguments[4][25][0].apply(exports,arguments)
+},{"dup":25}],46:[function(require,module,exports){
+"use strict";
- return handler;
- };
+/**
+ * Helper to abort upload requests if there has not been any progress for `timeout` ms.
+ * Create an instance using `timer = new ProgressTimeout(10000, onTimeout)`
+ * Call `timer.progress()` to signal that there has been progress of any kind.
+ * Call `timer.done()` when the upload has completed.
+ */
+class ProgressTimeout {
+ constructor(timeout, timeoutHandler) {
+ this._timeout = timeout;
+ this._onTimedOut = timeoutHandler;
+ this._isDone = false;
+ this._aliveTimer = null;
+ this._onTimedOut = this._onTimedOut.bind(this);
+ }
- _proto._dequeue = function _dequeue(handler) {
- var index = this.queuedHandlers.indexOf(handler);
+ progress() {
+ // Some browsers fire another progress event when the upload is
+ // cancelled, so we have to ignore progress after the timer was
+ // told to stop.
+ if (this._isDone) return;
- if (index !== -1) {
- this.queuedHandlers.splice(index, 1);
+ if (this._timeout > 0) {
+ if (this._aliveTimer) clearTimeout(this._aliveTimer);
+ this._aliveTimer = setTimeout(this._onTimedOut, this._timeout);
}
- };
+ }
- _proto.run = function run(fn, queueOptions) {
- if (this.activeRequests < this.limit) {
- return this._call(fn);
+ done() {
+ if (this._aliveTimer) {
+ clearTimeout(this._aliveTimer);
+ this._aliveTimer = null;
}
- return this._queue(fn, queueOptions);
- };
-
- _proto.wrapPromiseFunction = function wrapPromiseFunction(fn, queueOptions) {
- var _this4 = this;
-
- return function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- var queuedRequest;
- var outerPromise = new Promise(function (resolve, reject) {
- queuedRequest = _this4.run(function () {
- var cancelError;
- var innerPromise;
-
- try {
- innerPromise = Promise.resolve(fn.apply(void 0, args));
- } catch (err) {
- innerPromise = Promise.reject(err);
- }
-
- innerPromise.then(function (result) {
- if (cancelError) {
- reject(cancelError);
- } else {
- queuedRequest.done();
- resolve(result);
- }
- }, function (err) {
- if (cancelError) {
- reject(cancelError);
- } else {
- queuedRequest.done();
- reject(err);
- }
- });
- return function () {
- cancelError = createCancelError();
- };
- }, queueOptions);
- });
-
- outerPromise.abort = function () {
- queuedRequest.abort();
- };
+ this._isDone = true;
+ }
- return outerPromise;
- };
- };
+}
- return RateLimitedQueue;
-}();
-},{"./findIndex":31}],26:[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); }
+module.exports = ProgressTimeout;
+},{}],47:[function(require,module,exports){
+arguments[4][26][0].apply(exports,arguments)
+},{"./findIndex":51,"dup":26}],48:[function(require,module,exports){
+"use strict";
-var has = require('./hasProperty');
+const has = require('./hasProperty');
/**
* Translates strings with interpolation & pluralization support.
* Extensible with custom dictionaries and pluralization functions.
@@ -5275,44 +3726,42 @@ var has = require('./hasProperty');
*/
-module.exports = /*#__PURE__*/function () {
+module.exports = class Translator {
/**
* @param {object|Array<object>} locales - locale or list of locales.
*/
- function Translator(locales) {
- var _this = this;
-
+ constructor(locales) {
this.locale = {
strings: {},
- pluralize: function pluralize(n) {
+
+ pluralize(n) {
if (n === 1) {
return 0;
}
return 1;
}
+
};
if (Array.isArray(locales)) {
- locales.forEach(function (locale) {
- return _this._apply(locale);
- });
+ locales.forEach(locale => this._apply(locale));
} else {
this._apply(locales);
}
}
- var _proto = Translator.prototype;
-
- _proto._apply = function _apply(locale) {
+ _apply(locale) {
if (!locale || !locale.strings) {
return;
}
- var prevLocale = this.locale;
- this.locale = _extends({}, prevLocale, {
- strings: _extends({}, prevLocale.strings, locale.strings)
- });
+ const prevLocale = this.locale;
+ this.locale = { ...prevLocale,
+ strings: { ...prevLocale.strings,
+ ...locale.strings
+ }
+ };
this.locale.pluralize = locale.pluralize || prevLocale.pluralize;
}
/**
@@ -5326,39 +3775,36 @@ module.exports = /*#__PURE__*/function () {
* @param {object} options with values that will be used to replace placeholders
* @returns {any[]} interpolated
*/
- ;
- _proto.interpolate = function interpolate(phrase, options) {
- var _String$prototype = String.prototype,
- split = _String$prototype.split,
- replace = _String$prototype.replace;
- var dollarRegex = /\$/g;
- var dollarBillsYall = '$$$$';
- var interpolated = [phrase];
- for (var arg in options) {
+ interpolate(phrase, options) {
+ const dollarRegex = /\$/g;
+ const dollarBillsYall = '$$$$';
+ let interpolated = [phrase];
+
+ for (const arg in options) {
if (arg !== '_' && has(options, arg)) {
// Ensure replacement value is escaped to prevent special $-prefixed
// regex replace tokens. the "$$$$" is needed because each "$" needs to
// be escaped with "$" itself, and we need two in the resulting output.
- var replacement = options[arg];
+ let replacement = options[arg];
if (typeof replacement === 'string') {
- replacement = replace.call(options[arg], dollarRegex, dollarBillsYall);
+ replacement = dollarRegex[Symbol.replace](replacement, dollarBillsYall);
} // We create a new `RegExp` each time instead of using a more-efficient
// string replace so that the same argument can be replaced multiple times
// in the same phrase.
- interpolated = insertReplacement(interpolated, new RegExp("%\\{" + arg + "\\}", 'g'), replacement);
+ interpolated = insertReplacement(interpolated, new RegExp(`%\\{${arg}\\}`, 'g'), replacement);
}
}
return interpolated;
function insertReplacement(source, rx, replacement) {
- var newParts = [];
- source.forEach(function (chunk) {
+ const newParts = [];
+ source.forEach(chunk => {
// When the source contains multiple placeholders for interpolation,
// we should ignore chunks that are not strings, because those
// can be JSX objects and will be otherwise incorrectly turned into strings.
@@ -5367,3523 +3813,4012 @@ module.exports = /*#__PURE__*/function () {
return newParts.push(chunk);
}
- split.call(chunk, rx).forEach(function (raw, i, list) {
- if (raw !== '') {
- newParts.push(raw);
- } // Interlace with the `replacement` value
+ rx[Symbol.split](chunk).forEach((raw, i, list) => {
+ if (raw !== '') {
+ newParts.push(raw);
+ } // Interlace with the `replacement` value
+
+
+ if (i < list.length - 1) {
+ newParts.push(replacement);
+ }
+ });
+ });
+ return newParts;
+ }
+ }
+ /**
+ * Public translate method
+ *
+ * @param {string} key
+ * @param {object} options with values that will be used later to replace placeholders in string
+ * @returns {string} translated (and interpolated)
+ */
+
+
+ translate(key, options) {
+ return this.translateArray(key, options).join('');
+ }
+ /**
+ * Get a translation and return the translated and interpolated parts as an array.
+ *
+ * @param {string} key
+ * @param {object} options with values that will be used to replace placeholders
+ * @returns {Array} The translated and interpolated parts, in order.
+ */
+
+
+ translateArray(key, options) {
+ if (!has(this.locale.strings, key)) {
+ throw new Error(`missing string: ${key}`);
+ }
+
+ const string = this.locale.strings[key];
+ const hasPluralForms = typeof string === 'object';
+
+ if (hasPluralForms) {
+ if (options && typeof options.smart_count !== 'undefined') {
+ const plural = this.locale.pluralize(options.smart_count);
+ return this.interpolate(string[plural], options);
+ }
+
+ throw new Error('Attempted to use a string with plural forms, but no value was given for %{smart_count}');
+ }
+
+ return this.interpolate(string, options);
+ }
+
+};
+},{"./hasProperty":53}],49:[function(require,module,exports){
+arguments[4][28][0].apply(exports,arguments)
+},{"dup":28,"lodash.throttle":7}],50:[function(require,module,exports){
+arguments[4][29][0].apply(exports,arguments)
+},{"./NetworkError":45,"dup":29}],51:[function(require,module,exports){
+arguments[4][30][0].apply(exports,arguments)
+},{"dup":30}],52:[function(require,module,exports){
+arguments[4][31][0].apply(exports,arguments)
+},{"dup":31}],53:[function(require,module,exports){
+"use strict";
+
+module.exports = function has(object, key) {
+ return Object.prototype.hasOwnProperty.call(object, key);
+};
+},{}],54:[function(require,module,exports){
+"use strict";
+
+function isNetworkError(xhr) {
+ if (!xhr) {
+ return false;
+ }
+
+ return xhr.readyState !== 0 && xhr.readyState !== 4 || xhr.status === 0;
+}
+
+module.exports = isNetworkError;
+},{}],55:[function(require,module,exports){
+"use strict";
+
+module.exports = function settle(promises) {
+ const resolutions = [];
+ const rejections = [];
+
+ function resolved(value) {
+ resolutions.push(value);
+ }
+
+ function rejected(error) {
+ rejections.push(error);
+ }
+
+ const wait = Promise.all(promises.map(promise => promise.then(resolved, rejected)));
+ return wait.then(() => {
+ return {
+ successful: resolutions,
+ failed: rejections
+ };
+ });
+};
+},{}],56:[function(require,module,exports){
+module.exports={
+ "name": "@uppy/aws-s3",
+ "description": "Upload to Amazon S3 with Uppy",
+ "version": "2.0.0-alpha.0",
+ "license": "MIT",
+ "main": "lib/index.js",
+ "types": "types/index.d.ts",
+ "keywords": [
+ "file uploader",
+ "aws s3",
+ "amazon s3",
+ "s3",
+ "uppy",
+ "uppy-plugin"
+ ],
+ "homepage": "https://uppy.io",
+ "bugs": {
+ "url": "https://github.com/transloadit/uppy/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/transloadit/uppy.git"
+ },
+ "dependencies": {
+ "@uppy/companion-client": "file:../companion-client",
+ "@uppy/utils": "file:../utils",
+ "@uppy/xhr-upload": "file:../xhr-upload",
+ "cuid": "^2.1.1",
+ "qs-stringify": "^1.1.0"
+ },
+ "devDependencies": {
+ "whatwg-fetch": "3.6.2"
+ },
+ "peerDependencies": {
+ "@uppy/core": "^1.0.0"
+ }
+}
+
+},{}],57:[function(require,module,exports){
+"use strict";
+
+/**
+ * Core plugin logic that all plugins share.
+ *
+ * BasePlugin does not contain DOM rendering so it can be used for plugins
+ * without a user interface.
+ *
+ * See `Plugin` for the extended version with Preact rendering for interfaces.
+ */
+const Translator = require('@uppy/utils/lib/Translator');
+
+module.exports = class BasePlugin {
+ constructor(uppy, opts = {}) {
+ this.uppy = uppy;
+ this.opts = opts;
+ }
+
+ getPluginState() {
+ const {
+ plugins
+ } = this.uppy.getState();
+ return plugins[this.id] || {};
+ }
+
+ setPluginState(update) {
+ const {
+ plugins
+ } = this.uppy.getState();
+ this.uppy.setState({
+ plugins: { ...plugins,
+ [this.id]: { ...plugins[this.id],
+ ...update
+ }
+ }
+ });
+ }
+
+ setOptions(newOpts) {
+ this.opts = { ...this.opts,
+ ...newOpts
+ };
+ this.setPluginState(); // so that UI re-renders with new options
+
+ this.i18nInit();
+ }
+
+ i18nInit() {
+ const translator = new Translator([this.defaultLocale, this.uppy.locale, this.opts.locale]);
+ this.i18n = translator.translate.bind(translator);
+ this.i18nArray = translator.translateArray.bind(translator);
+ this.setPluginState(); // so that UI re-renders and we see the updated locale
+ }
+ /**
+ * Extendable methods
+ * ==================
+ * These methods are here to serve as an overview of the extendable methods as well as
+ * making them not conditional in use, such as `if (this.afterUpdate)`.
+ */
+ // eslint-disable-next-line class-methods-use-this
+
+
+ addTarget() {
+ throw new Error('Extend the addTarget method to add your plugin to another plugin\'s target');
+ } // eslint-disable-next-line class-methods-use-this
+
+
+ install() {} // eslint-disable-next-line class-methods-use-this
+
+
+ uninstall() {}
+ /**
+ * 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.
+ */
+
+
+ render() {
+ throw new Error('Extend the render method to add your plugin to a DOM element');
+ } // eslint-disable-next-line class-methods-use-this
+
+
+ onMount() {} // eslint-disable-next-line class-methods-use-this
+
+
+ update() {} // Called after every state update, after everything's mounted. Debounced.
+ // eslint-disable-next-line class-methods-use-this
+
+
+ afterUpdate() {}
+
+};
+},{"@uppy/utils/lib/Translator":65}],58:[function(require,module,exports){
+"use strict";
+
+function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }
+
+var id = 0;
+
+function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; }
+
+const {
+ render,
+ h,
+ createRef,
+ cloneElement
+} = require('preact');
+
+const findDOMElement = require('@uppy/utils/lib/findDOMElement');
+
+const BasePlugin = require('./BasePlugin');
+/**
+ * Defer a frequent call to the microtask queue.
+ *
+ * @param {() => T} fn
+ * @returns {Promise<T>}
+ */
+
+
+function debounce(fn) {
+ let calling = null;
+ let latestArgs = null;
+ return (...args) => {
+ latestArgs = args;
+
+ if (!calling) {
+ calling = Promise.resolve().then(() => {
+ 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(...latestArgs);
+ });
+ }
+
+ return calling;
+ };
+}
+/**
+ * UIPlugin is the extended version of BasePlugin to incorporate rendering with Preact.
+ * Use this for plugins that need a user interface.
+ *
+ * For plugins without an user interface, see BasePlugin.
+ */
+
+var _updateUI = /*#__PURE__*/_classPrivateFieldLooseKey("updateUI");
- if (i < list.length - 1) {
- newParts.push(replacement);
- }
- });
- });
- return newParts;
- }
+class UIPlugin extends BasePlugin {
+ constructor(...args) {
+ super(...args);
+ Object.defineProperty(this, _updateUI, {
+ writable: true,
+ value: void 0
+ });
}
- /**
- * Public translate method
- *
- * @param {string} key
- * @param {object} options with values that will be used later to replace placeholders in string
- * @returns {string} translated (and interpolated)
- */
- ;
- _proto.translate = function translate(key, options) {
- return this.translateArray(key, options).join('');
- }
/**
- * Get a translation and return the translated and interpolated parts as an array.
- *
- * @param {string} key
- * @param {object} options with values that will be used to replace placeholders
- * @returns {Array} The translated and interpolated parts, in order.
+ * 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.
*/
- ;
+ mount(target, plugin) {
+ const callerPluginName = plugin.id;
+ const targetElement = findDOMElement(target);
- _proto.translateArray = function translateArray(key, options) {
- if (!has(this.locale.strings, key)) {
- throw new Error("missing string: " + key);
- }
+ if (targetElement) {
+ this.isTargetDOMEl = true; // API for plugins that require a synchronous rerender.
- var string = this.locale.strings[key];
- var hasPluralForms = typeof string === 'object';
+ _classPrivateFieldLooseBase(this, _updateUI)[_updateUI] = debounce(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;
+ render(this.render(state), targetElement);
+ this.afterUpdate();
+ });
+ this.uppy.log(`Installing ${callerPluginName} to a DOM element '${target}'`);
- if (hasPluralForms) {
- if (options && typeof options.smart_count !== 'undefined') {
- var plural = this.locale.pluralize(options.smart_count);
- return this.interpolate(string[plural], options);
+ if (this.opts.replaceTargetContent) {
+ // Although you could remove the child nodes using DOM APIs (container.innerHTML = ''),
+ // this isn't recommended because the component might need to do additional cleanup when it is removed.
+ // To remove the rendered content and run any cleanup processes, render an empty element into the container:
+ render(h(null), targetElement);
}
- throw new Error('Attempted to use a string with plural forms, but no value was given for %{smart_count}');
+ render(this.render(this.uppy.getState()), targetElement);
+ this.el = targetElement.firstElementChild;
+ this.onMount();
+ return this.el;
}
- return this.interpolate(string, options);
- };
-
- return Translator;
-}();
-},{"./hasProperty":42}],27:[function(require,module,exports){
-var _require = require('./AbortController'),
- createAbortError = _require.createAbortError;
-/**
- * Return a Promise that resolves after `ms` milliseconds.
- *
- * @param {number} ms - Number of milliseconds to wait.
- * @param {{ signal?: AbortSignal }} [opts] - An abort signal that can be used to cancel the delay early.
- * @returns {Promise<void>} A Promise that resolves after the given amount of `ms`.
- */
+ let targetPlugin;
+ if (typeof target === 'object' && target instanceof UIPlugin) {
+ // Targeting a plugin *instance*
+ targetPlugin = target;
+ } else if (typeof target === 'function') {
+ // Targeting a plugin type
+ const Target = target; // Find the target plugin instance.
-module.exports = function delay(ms, opts) {
- return new Promise(function (resolve, reject) {
- if (opts && opts.signal && opts.signal.aborted) {
- return reject(createAbortError());
+ this.uppy.iteratePlugins(p => {
+ if (p instanceof Target) {
+ targetPlugin = p;
+ return false;
+ }
+ });
}
- function onabort() {
- clearTimeout(timeout);
- cleanup();
- reject(createAbortError());
+ if (targetPlugin) {
+ this.uppy.log(`Installing ${callerPluginName} to ${targetPlugin.id}`);
+ this.parent = targetPlugin;
+ this.el = targetPlugin.addTarget(plugin);
+ this.onMount();
+ return this.el;
}
- var timeout = setTimeout(function () {
- cleanup();
- resolve();
- }, ms);
+ this.uppy.log(`Not installing ${callerPluginName}`);
+ let message = `Invalid target option given to ${callerPluginName}.`;
- if (opts && opts.signal) {
- opts.signal.addEventListener('abort', onabort);
+ 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 <script> tag initializing Uppy is right before the closing </body> tag at the end of the page. ' + '(see https://github.com/transloadit/uppy/issues/1042)\n\n' + 'If you meant to target a plugin, please confirm that your `import` statements or `require` calls are correct.';
}
- function cleanup() {
- if (opts && opts.signal) {
- opts.signal.removeEventListener('abort', onabort);
- }
- }
- });
-};
-},{"./AbortController":21}],28:[function(require,module,exports){
-var throttle = require('lodash.throttle');
+ throw new Error(message);
+ }
-function _emitSocketProgress(uploader, progressData, file) {
- var progress = progressData.progress,
- bytesUploaded = progressData.bytesUploaded,
- bytesTotal = progressData.bytesTotal;
+ update(state) {
+ if (this.el != null) {
+ var _classPrivateFieldLoo, _classPrivateFieldLoo2;
- if (progress) {
- uploader.uppy.log("Upload progress: " + progress);
- uploader.uppy.emit('upload-progress', file, {
- uploader: uploader,
- bytesUploaded: bytesUploaded,
- bytesTotal: bytesTotal
- });
+ (_classPrivateFieldLoo = (_classPrivateFieldLoo2 = _classPrivateFieldLooseBase(this, _updateUI))[_updateUI]) == null ? void 0 : _classPrivateFieldLoo.call(_classPrivateFieldLoo2, state);
+ }
}
-}
-
-module.exports = throttle(_emitSocketProgress, 300, {
- leading: true,
- trailing: true
-});
-},{"lodash.throttle":54}],29:[function(require,module,exports){
-var NetworkError = require('./NetworkError');
-/**
- * Wrapper around window.fetch that throws a NetworkError when appropriate
- */
+ unmount() {
+ if (this.isTargetDOMEl) {
+ var _this$el;
-module.exports = function fetchWithNetworkError() {
- return fetch.apply(void 0, arguments).catch(function (err) {
- if (err.name === 'AbortError') {
- throw err;
- } else {
- throw new NetworkError(err);
+ (_this$el = this.el) == null ? void 0 : _this$el.remove();
}
- });
-};
-},{"./NetworkError":23}],30:[function(require,module,exports){
-var isDOMElement = require('./isDOMElement');
-/**
- * Find a DOM element.
- *
- * @param {Node|string} element
- * @returns {Node|null}
- */
+ }
+}
-module.exports = function findDOMElement(element, context) {
- if (context === void 0) {
- context = document;
- }
+module.exports = UIPlugin;
+},{"./BasePlugin":57,"@uppy/utils/lib/findDOMElement":66,"preact":10}],59:[function(require,module,exports){
+"use strict";
- if (typeof element === 'string') {
- return context.querySelector(element);
+module.exports = function getFileName(fileType, fileDescriptor) {
+ if (fileDescriptor.name) {
+ return fileDescriptor.name;
}
- if (isDOMElement(element)) {
- return element;
- }
-};
-},{"./isDOMElement":43}],31:[function(require,module,exports){
-/**
- * Array.prototype.findIndex ponyfill for old browsers.
- *
- * @param {Array} array
- * @param {Function} predicate
- * @returns {number}
- */
-module.exports = function findIndex(array, predicate) {
- for (var i = 0; i < array.length; i++) {
- if (predicate(array[i])) return i;
+ if (fileType.split('/')[0] === 'image') {
+ return `${fileType.split('/')[0]}.${fileType.split('/')[1]}`;
}
- return -1;
+ return 'noname';
};
-},{}],32:[function(require,module,exports){
-/**
- * Takes a file object and turns it into fileID, by converting file.name to lowercase,
- * removing extra characters and adding type, size and lastModified
- *
- * @param {object} file
- * @returns {string} the fileID
- */
-module.exports = function generateFileID(file) {
- // It's tempting to do `[items].filter(Boolean).join('-')` here, but that
- // is slower! simple string concatenation is fast
- var id = 'uppy';
+},{}],60:[function(require,module,exports){
+"use strict";
- if (typeof file.name === 'string') {
- id += "-" + encodeFilename(file.name.toLowerCase());
- }
+let _Symbol$for, _Symbol$for2;
- if (file.type !== undefined) {
- id += "-" + file.type;
- }
+function _classPrivateFieldLooseBase(receiver, privateKey) { if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) { throw new TypeError("attempted to use private field on non-instance"); } return receiver; }
- if (file.meta && typeof file.meta.relativePath === 'string') {
- id += "-" + encodeFilename(file.meta.relativePath.toLowerCase());
- }
+var id = 0;
- if (file.data.size !== undefined) {
- id += "-" + file.data.size;
- }
+function _classPrivateFieldLooseKey(name) { return "__private_" + id++ + "_" + name; }
- if (file.data.lastModified !== undefined) {
- id += "-" + file.data.lastModified;
- }
+/* global AggregateError */
+const Translator = require('@uppy/utils/lib/Translator');
- return id;
-};
+const ee = require('namespace-emitter');
+
+const cuid = require('cuid');
+
+const throttle = require('lodash.throttle');
+
+const prettierBytes = require('@transloadit/prettier-bytes');
+
+const match = require('mime-match');
+
+const DefaultStore = require('@uppy/store-default');
+
+const getFileType = require('@uppy/utils/lib/getFileType');
+
+const getFileNameAndExtension = require('@uppy/utils/lib/getFileNameAndExtension');
+
+const generateFileID = require('@uppy/utils/lib/generateFileID');
+
+const supportsUploadProgress = require('./supportsUploadProgress');
+
+const getFileName = require('./getFileName');
+
+const {
+ justErrorsLogger,
+ debugLogger
+} = require('./loggers');
+
+const UIPlugin = require('./UIPlugin');
+
+const BasePlugin = require('./BasePlugin'); // Exported from here.
+
+
+class RestrictionError extends Error {
+ constructor(...args) {
+ super(...args);
+ this.isRestriction = true;
+ }
-function encodeFilename(name) {
- var suffix = '';
- return name.replace(/[^A-Z0-9]/ig, function (character) {
- suffix += "-" + encodeCharacter(character);
- return '/';
- }) + suffix;
}
-function encodeCharacter(character) {
- return character.charCodeAt(0).toString(32);
+if (typeof AggregateError === 'undefined') {
+ // eslint-disable-next-line no-global-assign
+ globalThis.AggregateError = class AggregateError extends Error {
+ constructor(message, errors) {
+ super(message);
+ this.errors = errors;
+ }
+
+ };
}
-},{}],33:[function(require,module,exports){
-var webkitGetAsEntryApi = require('./utils/webkitGetAsEntryApi/index');
-var fallbackApi = require('./utils/fallbackApi');
+class AggregateRestrictionError extends AggregateError {
+ constructor(...args) {
+ super(...args);
+ this.isRestriction = true;
+ }
+
+}
/**
- * Returns a promise that resolves to the array of dropped files (if a folder is dropped, and browser supports folder parsing - promise resolves to the flat array of all files in all directories).
- * Each file has .relativePath prop appended to it (e.g. "/docs/Prague/ticket_from_prague_to_ufa.pdf") if browser supports it. Otherwise it's undefined.
- *
- * @param {DataTransfer} dataTransfer
- * @param {Function} logDropError - a function that's called every time some folder or some file error out (e.g. because of the folder name being too long on Windows). Notice that resulting promise will always be resolved anyway.
- *
- * @returns {Promise} - Array<File>
+ * Uppy Core module.
+ * Manages plugins, state updates, acts as an event bus,
+ * adds/removes files and metadata.
*/
-module.exports = function getDroppedFiles(dataTransfer, _temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- _ref$logDropError = _ref.logDropError,
- logDropError = _ref$logDropError === void 0 ? function () {} : _ref$logDropError;
+var _plugins = /*#__PURE__*/_classPrivateFieldLooseKey("plugins");
- // Get all files from all subdirs. Works (at least) in Chrome, Mozilla, and Safari
- if (dataTransfer.items && dataTransfer.items[0] && 'webkitGetAsEntry' in dataTransfer.items[0]) {
- return webkitGetAsEntryApi(dataTransfer, logDropError); // Otherwise just return all first-order files
- }
+var _storeUnsubscribe = /*#__PURE__*/_classPrivateFieldLooseKey("storeUnsubscribe");
- return fallbackApi(dataTransfer);
-};
-},{"./utils/fallbackApi":34,"./utils/webkitGetAsEntryApi/index":37}],34:[function(require,module,exports){
-var toArray = require('../../toArray'); // .files fallback, should be implemented in any browser
+var _emitter = /*#__PURE__*/_classPrivateFieldLooseKey("emitter");
+var _preProcessors = /*#__PURE__*/_classPrivateFieldLooseKey("preProcessors");
-module.exports = function fallbackApi(dataTransfer) {
- var files = toArray(dataTransfer.files);
- return Promise.resolve(files);
-};
-},{"../../toArray":47}],35:[function(require,module,exports){
-/**
- * Recursive function, calls the original callback() when the directory is entirely parsed.
- *
- * @param {FileSystemDirectoryReader} directoryReader
- * @param {Array} oldEntries
- * @param {Function} logDropError
- * @param {Function} callback - called with ([ all files and directories in that directoryReader ])
- */
-module.exports = function getFilesAndDirectoriesFromDirectory(directoryReader, oldEntries, logDropError, _ref) {
- var onSuccess = _ref.onSuccess;
- directoryReader.readEntries(function (entries) {
- var newEntries = [].concat(oldEntries, entries); // According to the FileSystem API spec, getFilesAndDirectoriesFromDirectory() must be called until it calls the onSuccess with an empty array.
+var _uploaders = /*#__PURE__*/_classPrivateFieldLooseKey("uploaders");
- if (entries.length) {
- setTimeout(function () {
- getFilesAndDirectoriesFromDirectory(directoryReader, newEntries, logDropError, {
- onSuccess: onSuccess
- });
- }, 0); // Done iterating this particular directory
- } else {
- onSuccess(newEntries);
- }
- }, // Make sure we resolve on error anyway, it's fine if only one directory couldn't be parsed!
- function (error) {
- logDropError(error);
- onSuccess(oldEntries);
- });
-};
-},{}],36:[function(require,module,exports){
-/**
- * Get the relative path from the FileEntry#fullPath, because File#webkitRelativePath is always '', at least onDrop.
- *
- * @param {FileEntry} fileEntry
- *
- * @returns {string|null} - if file is not in a folder - return null (this is to be consistent with .relativePath-s of files selected from My Device). If file is in a folder - return its fullPath, e.g. '/simpsons/hi.jpeg'.
- */
-module.exports = function getRelativePath(fileEntry) {
- // fileEntry.fullPath - "/simpsons/hi.jpeg" or undefined (for browsers that don't support it)
- // fileEntry.name - "hi.jpeg"
- if (!fileEntry.fullPath || fileEntry.fullPath === "/" + fileEntry.name) {
- return null;
- }
+var _postProcessors = /*#__PURE__*/_classPrivateFieldLooseKey("postProcessors");
- return fileEntry.fullPath;
-};
-},{}],37:[function(require,module,exports){
-var toArray = require('../../../toArray');
+var _checkRestrictions = /*#__PURE__*/_classPrivateFieldLooseKey("checkRestrictions");
-var getRelativePath = require('./getRelativePath');
+var _checkMinNumberOfFiles = /*#__PURE__*/_classPrivateFieldLooseKey("checkMinNumberOfFiles");
-var getFilesAndDirectoriesFromDirectory = require('./getFilesAndDirectoriesFromDirectory');
+var _checkRequiredMetaFields = /*#__PURE__*/_classPrivateFieldLooseKey("checkRequiredMetaFields");
-module.exports = function webkitGetAsEntryApi(dataTransfer, logDropError) {
- var files = [];
- var rootPromises = [];
- /**
- * Returns a resolved promise, when :files array is enhanced
- *
- * @param {(FileSystemFileEntry|FileSystemDirectoryEntry)} entry
- * @returns {Promise} - empty promise that resolves when :files is enhanced with a file
- */
+var _showOrLogErrorAndThrow = /*#__PURE__*/_classPrivateFieldLooseKey("showOrLogErrorAndThrow");
- var createPromiseToAddFileOrParseDirectory = function createPromiseToAddFileOrParseDirectory(entry) {
- return new Promise(function (resolve) {
- // This is a base call
- if (entry.isFile) {
- // Creates a new File object which can be used to read the file.
- entry.file(function (file) {
- file.relativePath = getRelativePath(entry);
- files.push(file);
- resolve();
- }, // Make sure we resolve on error anyway, it's fine if only one file couldn't be read!
- function (error) {
- logDropError(error);
- resolve();
- }); // This is a recursive call
- } else if (entry.isDirectory) {
- var directoryReader = entry.createReader();
- getFilesAndDirectoriesFromDirectory(directoryReader, [], logDropError, {
- onSuccess: function onSuccess(entries) {
- var promises = entries.map(function (entry) {
- return createPromiseToAddFileOrParseDirectory(entry);
- });
- Promise.all(promises).then(function () {
- return resolve();
- });
- }
- });
- }
- });
- }; // For each dropped item, - make sure it's a file/directory, and start deepening in!
+var _assertNewUploadAllowed = /*#__PURE__*/_classPrivateFieldLooseKey("assertNewUploadAllowed");
+
+var _checkAndCreateFileStateObject = /*#__PURE__*/_classPrivateFieldLooseKey("checkAndCreateFileStateObject");
+var _startIfAutoProceed = /*#__PURE__*/_classPrivateFieldLooseKey("startIfAutoProceed");
- toArray(dataTransfer.items).forEach(function (item) {
- var entry = item.webkitGetAsEntry(); // :entry can be null when we drop the url e.g.
+var _addListeners = /*#__PURE__*/_classPrivateFieldLooseKey("addListeners");
- if (entry) {
- rootPromises.push(createPromiseToAddFileOrParseDirectory(entry));
- }
- });
- return Promise.all(rootPromises).then(function () {
- return files;
- });
-};
-},{"../../../toArray":47,"./getFilesAndDirectoriesFromDirectory":35,"./getRelativePath":36}],38:[function(require,module,exports){
-/**
- * Takes a full filename string and returns an object {name, extension}
- *
- * @param {string} fullFileName
- * @returns {object} {name, extension}
- */
-module.exports = function getFileNameAndExtension(fullFileName) {
- var lastDot = fullFileName.lastIndexOf('.'); // these count as no extension: "no-dot", "trailing-dot."
+var _updateOnlineStatus = /*#__PURE__*/_classPrivateFieldLooseKey("updateOnlineStatus");
- if (lastDot === -1 || lastDot === fullFileName.length - 1) {
- return {
- name: fullFileName,
- extension: undefined
- };
- }
+var _createUpload = /*#__PURE__*/_classPrivateFieldLooseKey("createUpload");
- return {
- name: fullFileName.slice(0, lastDot),
- extension: fullFileName.slice(lastDot + 1)
- };
-};
-},{}],39:[function(require,module,exports){
-var getFileNameAndExtension = require('./getFileNameAndExtension');
+var _getUpload = /*#__PURE__*/_classPrivateFieldLooseKey("getUpload");
-var mimeTypes = require('./mimeTypes');
+var _removeUpload = /*#__PURE__*/_classPrivateFieldLooseKey("removeUpload");
-module.exports = function getFileType(file) {
- var fileExtension = file.name ? getFileNameAndExtension(file.name).extension : null;
- fileExtension = fileExtension ? fileExtension.toLowerCase() : null;
+var _runUpload = /*#__PURE__*/_classPrivateFieldLooseKey("runUpload");
- if (file.type) {
- // if mime type is set in the file object already, use that
- return file.type;
- }
+_Symbol$for = Symbol.for('uppy test: getPlugins');
+_Symbol$for2 = Symbol.for('uppy test: createUpload');
- if (fileExtension && mimeTypes[fileExtension]) {
- // else, see if we can map extension to a mime type
- return mimeTypes[fileExtension];
- } // if all fails, fall back to a generic byte stream type
+class Uppy {
+ // eslint-disable-next-line global-require
+ /** @type {Record<string, BasePlugin[]>} */
- return 'application/octet-stream';
-};
-},{"./getFileNameAndExtension":38,"./mimeTypes":45}],40:[function(require,module,exports){
-module.exports = function getSocketHost(url) {
- // get the host domain
- var regex = /^(?:https?:\/\/|\/\/)?(?:[^@\n]+@)?(?:www\.)?([^\n]+)/i;
- var host = regex.exec(url)[1];
- var socketProtocol = /^http:\/\//i.test(url) ? 'ws' : 'wss';
- return socketProtocol + "://" + host;
-};
-},{}],41:[function(require,module,exports){
-/**
- * Returns a timestamp in the format of `hours:minutes:seconds`
- */
-module.exports = function getTimeStamp() {
- var date = new Date();
- var hours = pad(date.getHours().toString());
- var minutes = pad(date.getMinutes().toString());
- var seconds = pad(date.getSeconds().toString());
- return hours + ":" + minutes + ":" + seconds;
-};
-/**
- * Adds zero to strings shorter than two characters
- */
+ /**
+ * Instantiate Uppy
+ *
+ * @param {object} opts — Uppy options
+ */
+ constructor(_opts) {
+ Object.defineProperty(this, _runUpload, {
+ value: _runUpload2
+ });
+ Object.defineProperty(this, _removeUpload, {
+ value: _removeUpload2
+ });
+ Object.defineProperty(this, _getUpload, {
+ value: _getUpload2
+ });
+ Object.defineProperty(this, _createUpload, {
+ value: _createUpload2
+ });
+ Object.defineProperty(this, _addListeners, {
+ value: _addListeners2
+ });
+ Object.defineProperty(this, _startIfAutoProceed, {
+ value: _startIfAutoProceed2
+ });
+ Object.defineProperty(this, _checkAndCreateFileStateObject, {
+ value: _checkAndCreateFileStateObject2
+ });
+ Object.defineProperty(this, _assertNewUploadAllowed, {
+ value: _assertNewUploadAllowed2
+ });
+ Object.defineProperty(this, _showOrLogErrorAndThrow, {
+ value: _showOrLogErrorAndThrow2
+ });
+ Object.defineProperty(this, _checkRequiredMetaFields, {
+ value: _checkRequiredMetaFields2
+ });
+ Object.defineProperty(this, _checkMinNumberOfFiles, {
+ value: _checkMinNumberOfFiles2
+ });
+ Object.defineProperty(this, _checkRestrictions, {
+ value: _checkRestrictions2
+ });
+ Object.defineProperty(this, _plugins, {
+ writable: true,
+ value: Object.create(null)
+ });
+ Object.defineProperty(this, _storeUnsubscribe, {
+ writable: true,
+ value: void 0
+ });
+ Object.defineProperty(this, _emitter, {
+ writable: true,
+ value: ee()
+ });
+ Object.defineProperty(this, _preProcessors, {
+ writable: true,
+ value: new Set()
+ });
+ Object.defineProperty(this, _uploaders, {
+ writable: true,
+ value: new Set()
+ });
+ Object.defineProperty(this, _postProcessors, {
+ writable: true,
+ value: new Set()
+ });
+ Object.defineProperty(this, _updateOnlineStatus, {
+ writable: true,
+ value: this.updateOnlineStatus.bind(this)
+ });
+ this.defaultLocale = {
+ strings: {
+ addBulkFilesFailed: {
+ 0: 'Failed to add %{smart_count} file due to an internal error',
+ 1: 'Failed to add %{smart_count} files due to internal errors'
+ },
+ youCanOnlyUploadX: {
+ 0: 'You can only upload %{smart_count} file',
+ 1: 'You can only upload %{smart_count} files'
+ },
+ youHaveToAtLeastSelectX: {
+ 0: 'You have to select at least %{smart_count} file',
+ 1: 'You have to select at least %{smart_count} files'
+ },
+ exceedsSize: '%{file} exceeds maximum allowed size of %{size}',
+ missingRequiredMetaField: 'Missing required meta fields',
+ missingRequiredMetaFieldOnFile: 'Missing required meta fields in %{fileName}',
+ inferiorSize: 'This file is smaller than the allowed size of %{size}',
+ youCanOnlyUploadFileTypes: 'You can only upload: %{types}',
+ noNewAlreadyUploading: 'Cannot add new files: already uploading',
+ noDuplicates: 'Cannot add the duplicate file \'%{fileName}\', it already exists',
+ companionError: 'Connection with Companion failed',
+ companionUnauthorizeHint: 'To unauthorize to your %{provider} account, please go to %{url}',
+ failedToUpload: 'Failed to upload %{file}',
+ noInternetConnection: 'No Internet connection',
+ connectedToInternet: 'Connected to the Internet',
+ // Strings for remote providers
+ noFilesFound: 'You have no files or folders here',
+ selectX: {
+ 0: 'Select %{smart_count}',
+ 1: 'Select %{smart_count}'
+ },
+ allFilesFromFolderNamed: 'All files from folder %{name}',
+ openFolderNamed: 'Open folder %{name}',
+ cancel: 'Cancel',
+ logOut: 'Log out',
+ filter: 'Filter',
+ resetFilter: 'Reset filter',
+ loading: 'Loading...',
+ authenticateWithTitle: 'Please authenticate with %{pluginName} to select files',
+ authenticateWith: 'Connect to %{pluginName}',
+ searchImages: 'Search for images',
+ enterTextToSearch: 'Enter text to search for images',
+ backToSearch: 'Back to Search',
+ emptyFolderAdded: 'No files were added from empty folder',
+ folderAlreadyAdded: 'The folder "%{folder}" was already added',
+ folderAdded: {
+ 0: 'Added %{smart_count} file from %{folder}',
+ 1: 'Added %{smart_count} files from %{folder}'
+ }
+ }
+ };
+ const defaultOptions = {
+ id: 'uppy',
+ autoProceed: false,
+ allowMultipleUploads: true,
+ debug: false,
+ restrictions: {
+ maxFileSize: null,
+ minFileSize: null,
+ maxTotalFileSize: null,
+ maxNumberOfFiles: null,
+ minNumberOfFiles: null,
+ allowedFileTypes: null,
+ requiredMetaFields: []
+ },
+ meta: {},
+ onBeforeFileAdded: currentFile => currentFile,
+ onBeforeUpload: files => files,
+ store: DefaultStore(),
+ logger: justErrorsLogger,
+ infoTimeout: 5000
+ }; // Merge default options with the ones set by user,
+ // making sure to merge restrictions too
+ this.opts = { ...defaultOptions,
+ ..._opts,
+ restrictions: { ...defaultOptions.restrictions,
+ ...(_opts && _opts.restrictions)
+ }
+ }; // Support debug: true for backwards-compatability, unless logger is set in opts
+ // opts instead of this.opts to avoid comparing objects — we set logger: justErrorsLogger in defaultOptions
-function pad(str) {
- return str.length !== 2 ? 0 + str : str;
-}
-},{}],42:[function(require,module,exports){
-module.exports = function has(object, key) {
- return Object.prototype.hasOwnProperty.call(object, key);
-};
-},{}],43:[function(require,module,exports){
-/**
- * Check if an object is a DOM element. Duck-typing based on `nodeType`.
- *
- * @param {*} obj
- */
-module.exports = function isDOMElement(obj) {
- return obj && typeof obj === 'object' && obj.nodeType === Node.ELEMENT_NODE;
-};
-},{}],44:[function(require,module,exports){
-function isNetworkError(xhr) {
- if (!xhr) {
- return false;
- }
+ if (_opts && _opts.logger && _opts.debug) {
+ this.log('You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.', 'warning');
+ } else if (_opts && _opts.debug) {
+ this.opts.logger = debugLogger;
+ }
- return xhr.readyState !== 0 && xhr.readyState !== 4 || xhr.status === 0;
-}
+ this.log(`Using Core v${this.constructor.VERSION}`);
-module.exports = isNetworkError;
-},{}],45:[function(require,module,exports){
-// ___Why not add the mime-types package?
-// It's 19.7kB gzipped, and we only need mime types for well-known extensions (for file previews).
-// ___Where to take new extensions from?
-// https://github.com/jshttp/mime-db/blob/master/db.json
-module.exports = {
- md: 'text/markdown',
- markdown: 'text/markdown',
- mp4: 'video/mp4',
- mp3: 'audio/mp3',
- svg: 'image/svg+xml',
- jpg: 'image/jpeg',
- png: 'image/png',
- gif: 'image/gif',
- heic: 'image/heic',
- heif: 'image/heif',
- yaml: 'text/yaml',
- yml: 'text/yaml',
- csv: 'text/csv',
- tsv: 'text/tab-separated-values',
- tab: 'text/tab-separated-values',
- avi: 'video/x-msvideo',
- mks: 'video/x-matroska',
- mkv: 'video/x-matroska',
- mov: 'video/quicktime',
- doc: 'application/msword',
- docm: 'application/vnd.ms-word.document.macroenabled.12',
- docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- dot: 'application/msword',
- dotm: 'application/vnd.ms-word.template.macroenabled.12',
- dotx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
- xla: 'application/vnd.ms-excel',
- xlam: 'application/vnd.ms-excel.addin.macroenabled.12',
- xlc: 'application/vnd.ms-excel',
- xlf: 'application/x-xliff+xml',
- xlm: 'application/vnd.ms-excel',
- xls: 'application/vnd.ms-excel',
- xlsb: 'application/vnd.ms-excel.sheet.binary.macroenabled.12',
- xlsm: 'application/vnd.ms-excel.sheet.macroenabled.12',
- xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
- xlt: 'application/vnd.ms-excel',
- xltm: 'application/vnd.ms-excel.template.macroenabled.12',
- xltx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
- xlw: 'application/vnd.ms-excel',
- txt: 'text/plain',
- text: 'text/plain',
- conf: 'text/plain',
- log: 'text/plain',
- pdf: 'application/pdf',
- zip: 'application/zip',
- '7z': 'application/x-7z-compressed',
- rar: 'application/x-rar-compressed',
- tar: 'application/x-tar',
- gz: 'application/gzip',
- dmg: 'application/x-apple-diskimage'
-};
-},{}],46:[function(require,module,exports){
-module.exports = function settle(promises) {
- var resolutions = [];
- var rejections = [];
+ if (this.opts.restrictions.allowedFileTypes && this.opts.restrictions.allowedFileTypes !== null && !Array.isArray(this.opts.restrictions.allowedFileTypes)) {
+ throw new TypeError('`restrictions.allowedFileTypes` must be an array');
+ }
+
+ this.i18nInit(); // ___Why throttle at 500ms?
+ // - We must throttle at >250ms for superfocus in Dashboard to work well
+ // (because animation takes 0.25s, and we want to wait for all animations to be over before refocusing).
+ // [Practical Check]: if thottle is at 100ms, then if you are uploading a file,
+ // and click 'ADD MORE FILES', - focus won't activate in Firefox.
+ // - We must throttle at around >500ms to avoid performance lags.
+ // [Practical Check] Firefox, try to upload a big file for a prolonged period of time. Laptop will start to heat up.
+
+ this.calculateProgress = throttle(this.calculateProgress.bind(this), 500, {
+ leading: true,
+ trailing: true
+ });
+ this.store = this.opts.store;
+ this.setState({
+ plugins: {},
+ files: {},
+ currentUploads: {},
+ allowNewUpload: true,
+ capabilities: {
+ uploadProgress: supportsUploadProgress(),
+ individualCancellation: true,
+ resumableUploads: false
+ },
+ totalProgress: 0,
+ meta: { ...this.opts.meta
+ },
+ info: [],
+ recoveredState: null
+ });
+ _classPrivateFieldLooseBase(this, _storeUnsubscribe)[_storeUnsubscribe] = this.store.subscribe((prevState, nextState, patch) => {
+ this.emit('state-update', prevState, nextState, patch);
+ this.updateAll(nextState);
+ }); // Exposing uppy object on window for debugging and testing
+
+ if (this.opts.debug && typeof window !== 'undefined') {
+ window[this.opts.id] = this;
+ }
- function resolved(value) {
- resolutions.push(value);
+ _classPrivateFieldLooseBase(this, _addListeners)[_addListeners]();
}
- function rejected(error) {
- rejections.push(error);
+ emit(event, ...args) {
+ _classPrivateFieldLooseBase(this, _emitter)[_emitter].emit(event, ...args);
}
- var wait = Promise.all(promises.map(function (promise) {
- return promise.then(resolved, rejected);
- }));
- return wait.then(function () {
- return {
- successful: resolutions,
- failed: rejections
- };
- });
-};
-},{}],47:[function(require,module,exports){
-/**
- * Converts list into array
- */
-module.exports = function toArray(list) {
- return Array.prototype.slice.call(list || [], 0);
-};
-},{}],48:[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; _setPrototypeOf(subClass, superClass); }
+ on(event, callback) {
+ _classPrivateFieldLooseBase(this, _emitter)[_emitter].on(event, callback);
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-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); }
+ return this;
+ }
-var _require = require('@uppy/core'),
- Plugin = _require.Plugin;
+ once(event, callback) {
+ _classPrivateFieldLooseBase(this, _emitter)[_emitter].once(event, callback);
-var cuid = require('cuid');
+ return this;
+ }
-var Translator = require('@uppy/utils/lib/Translator');
+ off(event, callback) {
+ _classPrivateFieldLooseBase(this, _emitter)[_emitter].off(event, callback);
-var _require2 = require('@uppy/companion-client'),
- Provider = _require2.Provider,
- RequestClient = _require2.RequestClient,
- Socket = _require2.Socket;
+ return this;
+ }
+ /**
+ * Iterate on all plugins and run `update` on them.
+ * Called each time state changes.
+ *
+ */
-var emitSocketProgress = require('@uppy/utils/lib/emitSocketProgress');
-var getSocketHost = require('@uppy/utils/lib/getSocketHost');
+ updateAll(state) {
+ this.iteratePlugins(plugin => {
+ plugin.update(state);
+ });
+ }
+ /**
+ * Updates state with a patch
+ *
+ * @param {object} patch {foo: 'bar'}
+ */
-var settle = require('@uppy/utils/lib/settle');
-var EventTracker = require('@uppy/utils/lib/EventTracker');
+ setState(patch) {
+ this.store.setState(patch);
+ }
+ /**
+ * Returns current state.
+ *
+ * @returns {object}
+ */
-var ProgressTimeout = require('@uppy/utils/lib/ProgressTimeout');
-var RateLimitedQueue = require('@uppy/utils/lib/RateLimitedQueue');
+ getState() {
+ return this.store.getState();
+ }
+ /**
+ * Back compat for when uppy.state is used instead of uppy.getState().
+ *
+ * @deprecated
+ */
-var NetworkError = require('@uppy/utils/lib/NetworkError');
-var isNetworkError = require('@uppy/utils/lib/isNetworkError');
+ get state() {
+ // Here, state is a non-enumerable property.
+ return this.getState();
+ }
+ /**
+ * Shorthand to set state for a specific file.
+ */
-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
+ setFileState(fileID, state) {
+ if (!this.getState().files[fileID]) {
+ throw new Error(`Can’t set state for ${fileID} (the file could have been removed)`);
+ }
- if (!(error instanceof Error)) {
- error = _extends(new Error('Upload error'), {
- data: error
+ this.setState({
+ files: { ...this.getState().files,
+ [fileID]: { ...this.getState().files[fileID],
+ ...state
+ }
+ }
});
}
- if (isNetworkError(xhr)) {
- error = new NetworkError(error, xhr);
- return error;
+ i18nInit() {
+ const translator = new Translator([this.defaultLocale, this.opts.locale]);
+ this.i18n = translator.translate.bind(translator);
+ this.i18nArray = translator.translateArray.bind(translator);
+ this.locale = translator.locale;
}
- error.request = xhr;
- return error;
-}
-/**
- * Set `data.type` in the blob to `file.meta.type`,
- * because we might have detected a more accurate file type in Uppy
- * https://stackoverflow.com/a/50875615
- *
- * @param {object} file File object with `data`, `size` and `meta` properties
- * @returns {object} blob updated with the new `type` set from `file.meta.type`
- */
+ setOptions(newOpts) {
+ this.opts = { ...this.opts,
+ ...newOpts,
+ restrictions: { ...this.opts.restrictions,
+ ...(newOpts && newOpts.restrictions)
+ }
+ };
+ if (newOpts.meta) {
+ this.setMeta(newOpts.meta);
+ }
-function setTypeInBlob(file) {
- var dataWithUpdatedType = file.data.slice(0, file.data.size, file.meta.type);
- return dataWithUpdatedType;
-}
+ this.i18nInit();
-module.exports = (_temp = _class = /*#__PURE__*/function (_Plugin) {
- _inheritsLoose(XHRUpload, _Plugin);
+ if (newOpts.locale) {
+ this.iteratePlugins(plugin => {
+ plugin.setOptions();
+ });
+ } // Note: this is not the preact `setState`, it's an internal function that has the same name.
- function XHRUpload(uppy, opts) {
- var _this;
- _this = _Plugin.call(this, uppy, opts) || this;
- _this.type = 'uploader';
- _this.id = _this.opts.id || 'XHRUpload';
- _this.title = 'XHRUpload';
- _this.defaultLocale = {
- strings: {
- timedOut: 'Upload stalled for %{seconds} seconds, aborting.'
- }
- }; // Default options
+ this.setState(); // so that UI re-renders with new options
+ }
- var defaultOptions = {
- formData: true,
- fieldName: 'files[]',
- method: 'post',
- metaFields: null,
- responseUrlFieldName: 'url',
- bundle: false,
- headers: {},
- timeout: 30 * 1000,
- limit: 0,
- withCredentials: false,
- responseType: '',
+ resetProgress() {
+ const defaultProgress = {
+ percentage: 0,
+ bytesUploaded: 0,
+ uploadComplete: false,
+ uploadStarted: null
+ };
+ const files = { ...this.getState().files
+ };
+ const updatedFiles = {};
+ Object.keys(files).forEach(fileID => {
+ const updatedFile = { ...files[fileID]
+ };
+ updatedFile.progress = { ...updatedFile.progress,
+ ...defaultProgress
+ };
+ updatedFiles[fileID] = updatedFile;
+ });
+ this.setState({
+ files: updatedFiles,
+ totalProgress: 0
+ });
+ this.emit('reset-progress');
+ }
- /**
- * @typedef respObj
- * @property {string} responseText
- * @property {number} status
- * @property {string} statusText
- * @property {object.<string, string>} headers
- *
- * @param {string} responseText the response body string
- * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
- */
- getResponseData: function getResponseData(responseText, response) {
- var parsedResponse = {};
+ addPreProcessor(fn) {
+ _classPrivateFieldLooseBase(this, _preProcessors)[_preProcessors].add(fn);
+ }
- try {
- parsedResponse = JSON.parse(responseText);
- } catch (err) {
- console.log(err);
- }
+ removePreProcessor(fn) {
+ return _classPrivateFieldLooseBase(this, _preProcessors)[_preProcessors].delete(fn);
+ }
- return parsedResponse;
- },
+ addPostProcessor(fn) {
+ _classPrivateFieldLooseBase(this, _postProcessors)[_postProcessors].add(fn);
+ }
- /**
- *
- * @param {string} responseText the response body string
- * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
- */
- getResponseError: function getResponseError(responseText, response) {
- var error = new Error('Upload error');
+ removePostProcessor(fn) {
+ return _classPrivateFieldLooseBase(this, _postProcessors)[_postProcessors].delete(fn);
+ }
- if (isNetworkError(response)) {
- error = new NetworkError(error, response);
- }
+ addUploader(fn) {
+ _classPrivateFieldLooseBase(this, _uploaders)[_uploaders].add(fn);
+ }
- return error;
- },
+ removeUploader(fn) {
+ return _classPrivateFieldLooseBase(this, _uploaders)[_uploaders].delete(fn);
+ }
- /**
- * Check if the response from the upload endpoint indicates that the upload was successful.
- *
- * @param {number} status the response status code
- * @param {string} responseText the response body string
- * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
- */
- validateStatus: function validateStatus(status, responseText, response) {
- return status >= 200 && status < 300;
- }
+ setMeta(data) {
+ const updatedMeta = { ...this.getState().meta,
+ ...data
};
- _this.opts = _extends({}, defaultOptions, opts);
-
- _this.i18nInit();
-
- _this.handleUpload = _this.handleUpload.bind(_assertThisInitialized(_this)); // Simultaneous upload limiting is shared across all uploads with this plugin.
- // __queue is for internal Uppy use only!
+ const updatedFiles = { ...this.getState().files
+ };
+ Object.keys(updatedFiles).forEach(fileID => {
+ updatedFiles[fileID] = { ...updatedFiles[fileID],
+ meta: { ...updatedFiles[fileID].meta,
+ ...data
+ }
+ };
+ });
+ this.log('Adding metadata:');
+ this.log(data);
+ this.setState({
+ meta: updatedMeta,
+ files: updatedFiles
+ });
+ }
- if (_this.opts.__queue instanceof RateLimitedQueue) {
- _this.requests = _this.opts.__queue;
- } else {
- _this.requests = new RateLimitedQueue(_this.opts.limit);
- }
+ setFileMeta(fileID, data) {
+ const updatedFiles = { ...this.getState().files
+ };
- if (_this.opts.bundle && !_this.opts.formData) {
- throw new Error('`opts.formData` must be true when `opts.bundle` is enabled.');
+ if (!updatedFiles[fileID]) {
+ this.log('Was trying to set metadata for a file that has been removed: ', fileID);
+ return;
}
- _this.uploaderEvents = Object.create(null);
- return _this;
+ const newMeta = { ...updatedFiles[fileID].meta,
+ ...data
+ };
+ updatedFiles[fileID] = { ...updatedFiles[fileID],
+ meta: newMeta
+ };
+ this.setState({
+ files: updatedFiles
+ });
}
+ /**
+ * Get a file object.
+ *
+ * @param {string} fileID The ID of the file object to return.
+ */
- var _proto = XHRUpload.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.getOptions = function getOptions(file) {
- var overrides = this.uppy.getState().xhrUpload;
- var headers = this.opts.headers;
+ getFile(fileID) {
+ return this.getState().files[fileID];
+ }
+ /**
+ * Get all files in an array.
+ */
- var opts = _extends({}, this.opts, overrides || {}, file.xhrUpload || {}, {
- headers: {}
- }); // Support for `headers` as a function, only in the XHRUpload settings.
- // Options set by other plugins in Uppy state or on the files themselves are still merged in afterward.
- //
- // ```js
- // headers: (file) => ({ expires: file.meta.expires })
- // ```
+ getFiles() {
+ const {
+ files
+ } = this.getState();
+ return Object.values(files);
+ }
+
+ getObjectOfFilesPerState() {
+ const {
+ files: filesObject,
+ totalProgress,
+ error
+ } = this.getState();
+ const files = Object.values(filesObject);
+ const inProgressFiles = files.filter(({
+ progress
+ }) => !progress.uploadComplete && progress.uploadStarted);
+ const newFiles = files.filter(file => !file.progress.uploadStarted);
+ const startedFiles = files.filter(file => file.progress.uploadStarted || file.progress.preprocess || file.progress.postprocess);
+ const uploadStartedFiles = files.filter(file => file.progress.uploadStarted);
+ const pausedFiles = files.filter(file => file.isPaused);
+ const completeFiles = files.filter(file => file.progress.uploadComplete);
+ const erroredFiles = files.filter(file => file.error);
+ const inProgressNotPausedFiles = inProgressFiles.filter(file => !file.isPaused);
+ const processingFiles = files.filter(file => file.progress.preprocess || file.progress.postprocess);
+ return {
+ newFiles,
+ startedFiles,
+ uploadStartedFiles,
+ pausedFiles,
+ completeFiles,
+ erroredFiles,
+ inProgressFiles,
+ inProgressNotPausedFiles,
+ processingFiles,
+ isUploadStarted: uploadStartedFiles.length > 0,
+ isAllComplete: totalProgress === 100 && completeFiles.length === files.length && processingFiles.length === 0,
+ isAllErrored: !!error && erroredFiles.length === files.length,
+ isAllPaused: inProgressFiles.length !== 0 && pausedFiles.length === inProgressFiles.length,
+ isUploadInProgress: inProgressFiles.length > 0,
+ isSomeGhost: files.some(file => file.isGhost)
+ };
+ }
+ /**
+ * A public wrapper for _checkRestrictions — checks if a file passes a set of restrictions.
+ * For use in UI pluigins (like Providers), to disallow selecting files that won’t pass restrictions.
+ *
+ * @param {object} file object to check
+ * @param {Array} [files] array to check maxNumberOfFiles and maxTotalFileSize
+ * @returns {object} { result: true/false, reason: why file didn’t pass restrictions }
+ */
- if (typeof headers === 'function') {
- opts.headers = headers(file);
- } else {
- _extends(opts.headers, this.opts.headers);
- }
- if (overrides) {
- _extends(opts.headers, overrides.headers);
- }
+ validateRestrictions(file, files) {
+ try {
+ _classPrivateFieldLooseBase(this, _checkRestrictions)[_checkRestrictions](file, files);
- if (file.xhrUpload) {
- _extends(opts.headers, file.xhrUpload.headers);
+ return {
+ result: true
+ };
+ } catch (err) {
+ return {
+ result: false,
+ reason: err.message
+ };
}
+ }
+ /**
+ * Check if file passes a set of restrictions set in options: maxFileSize, minFileSize,
+ * maxNumberOfFiles and allowedFileTypes.
+ *
+ * @param {object} file object to check
+ * @param {Array} [files] array to check maxNumberOfFiles and maxTotalFileSize
+ * @private
+ */
- return opts;
- };
-
- _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);
+ checkIfFileAlreadyExists(fileID) {
+ const {
+ files
+ } = this.getState();
- if (file.name) {
- formPost.append(opts.fieldName, dataWithUpdatedType, file.meta.name);
- } else {
- formPost.append(opts.fieldName, dataWithUpdatedType);
+ if (files[fileID] && !files[fileID].isGhost) {
+ return true;
}
- return formPost;
- };
+ return false;
+ }
+ /**
+ * Create a file state object based on user-provided `addFile()` options.
+ *
+ * Note this is extremely side-effectful and should only be done when a file state object
+ * will be added to state immediately afterward!
+ *
+ * The `files` value is passed in because it may be updated by the caller without updating the store.
+ */
+
- _proto.createBundledUpload = function createBundledUpload(files, opts) {
- var _this2 = this;
+ /**
+ * Add a new file to `state.files`. This will run `onBeforeFileAdded`,
+ * try to guess file type in a clever way, check file against restrictions,
+ * and start an upload if `autoProceed === true`.
+ *
+ * @param {object} file object to add
+ * @returns {string} id for the added file
+ */
+ addFile(file) {
+ _classPrivateFieldLooseBase(this, _assertNewUploadAllowed)[_assertNewUploadAllowed](file);
- var formPost = new FormData();
+ const {
+ files
+ } = this.getState();
- var _this$uppy$getState = this.uppy.getState(),
- meta = _this$uppy$getState.meta;
+ let newFile = _classPrivateFieldLooseBase(this, _checkAndCreateFileStateObject)[_checkAndCreateFileStateObject](files, file); // Users are asked to re-select recovered files without data,
+ // and to keep the progress, meta and everthing else, we only replace said data
- this.addMetadata(formPost, meta, opts);
- files.forEach(function (file) {
- var opts = _this2.getOptions(file);
- var dataWithUpdatedType = setTypeInBlob(file);
+ if (files[newFile.id] && files[newFile.id].isGhost) {
+ newFile = { ...files[newFile.id],
+ data: file.data,
+ isGhost: false
+ };
+ this.log(`Replaced the blob in the restored ghost file: ${newFile.name}, ${newFile.id}`);
+ }
- if (file.name) {
- formPost.append(opts.fieldName, dataWithUpdatedType, file.name);
- } else {
- formPost.append(opts.fieldName, dataWithUpdatedType);
+ this.setState({
+ files: { ...files,
+ [newFile.id]: newFile
}
});
- return formPost;
- };
-
- _proto.createBareUpload = function createBareUpload(file, opts) {
- return file.data;
- };
-
- _proto.upload = function upload(file, current, total) {
- var _this3 = this;
-
- var opts = this.getOptions(file);
- this.uppy.log("uploading " + current + " of " + total);
- return new Promise(function (resolve, reject) {
- _this3.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);
+ this.emit('file-added', newFile);
+ this.emit('files-added', [newFile]);
+ this.log(`Added file: ${newFile.name}, ${newFile.id}, mime type: ${newFile.type}`);
- reject(error);
- });
- var id = cuid();
- xhr.upload.addEventListener('loadstart', function (ev) {
- _this3.uppy.log("[XHRUpload] " + id + " started");
- });
- xhr.upload.addEventListener('progress', function (ev) {
- _this3.uppy.log("[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
+ _classPrivateFieldLooseBase(this, _startIfAutoProceed)[_startIfAutoProceed]();
+ return newFile.id;
+ }
+ /**
+ * Add multiple files to `state.files`. See the `addFile()` documentation.
+ *
+ * If an error occurs while adding a file, it is logged and the user is notified.
+ * This is good for UI plugins, but not for programmatic use.
+ * Programmatic users should usually still use `addFile()` on individual files.
+ */
- 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("[XHRUpload] " + id + " finished");
+ addFiles(fileDescriptors) {
+ _classPrivateFieldLooseBase(this, _assertNewUploadAllowed)[_assertNewUploadAllowed](); // create a copy of the files object only once
- timer.done();
- queuedRequest.done();
- if (_this3.uploaderEvents[file.id]) {
- _this3.uploaderEvents[file.id].remove();
+ const files = { ...this.getState().files
+ };
+ const newFiles = [];
+ const errors = [];
- _this3.uploaderEvents[file.id] = null;
- }
+ for (let i = 0; i < fileDescriptors.length; i++) {
+ try {
+ let newFile = _classPrivateFieldLooseBase(this, _checkAndCreateFileStateObject)[_checkAndCreateFileStateObject](files, fileDescriptors[i]); // Users are asked to re-select recovered files without data,
+ // and to keep the progress, meta and everthing else, we only replace said data
- 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
+ if (files[newFile.id] && files[newFile.id].isGhost) {
+ newFile = { ...files[newFile.id],
+ data: fileDescriptors[i].data,
+ isGhost: false
};
-
- _this3.uppy.emit('upload-success', file, uploadResp);
-
- if (uploadURL) {
- _this3.uppy.log("Download " + file.name + " from " + uploadURL);
- }
-
- return resolve(file);
+ this.log(`Replaced blob in a ghost file: ${newFile.name}, ${newFile.id}`);
}
- var body = opts.getResponseData(xhr.responseText, xhr);
- var error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));
- var response = {
- status: ev.target.status,
- body: body
- };
+ files[newFile.id] = newFile;
+ newFiles.push(newFile);
+ } catch (err) {
+ if (!err.isRestriction) {
+ errors.push(err);
+ }
+ }
+ }
- _this3.uppy.emit('upload-error', file, error, response);
+ this.setState({
+ files
+ });
+ newFiles.forEach(newFile => {
+ this.emit('file-added', newFile);
+ });
+ this.emit('files-added', newFiles);
- return reject(error);
+ if (newFiles.length > 5) {
+ this.log(`Added batch of ${newFiles.length} files`);
+ } else {
+ Object.keys(newFiles).forEach(fileID => {
+ this.log(`Added file: ${newFiles[fileID].name}\n id: ${newFiles[fileID].id}\n type: ${newFiles[fileID].type}`);
});
- xhr.addEventListener('error', function (ev) {
- _this3.uppy.log("[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);
+ if (newFiles.length > 0) {
+ _classPrivateFieldLooseBase(this, _startIfAutoProceed)[_startIfAutoProceed]();
+ }
- return reject(error);
+ if (errors.length > 0) {
+ let message = 'Multiple errors occurred while adding files:\n';
+ errors.forEach(subError => {
+ message += `\n * ${subError.message}`;
});
- xhr.open(opts.method.toUpperCase(), opts.endpoint, true); // IE10 does not allow setting `withCredentials` and `responseType`
- // before `open()` is called.
+ this.info({
+ message: this.i18n('addBulkFilesFailed', {
+ smart_count: errors.length
+ }),
+ details: message
+ }, 'error', this.opts.infoTimeout);
- xhr.withCredentials = opts.withCredentials;
+ if (typeof AggregateError === 'function') {
+ throw new AggregateError(errors, message);
+ } else {
+ const err = new Error(message);
+ err.errors = errors;
+ throw err;
+ }
+ }
+ }
- if (opts.responseType !== '') {
- xhr.responseType = opts.responseType;
+ removeFiles(fileIDs, reason) {
+ const {
+ files,
+ currentUploads
+ } = this.getState();
+ const updatedFiles = { ...files
+ };
+ const updatedUploads = { ...currentUploads
+ };
+ const removedFiles = Object.create(null);
+ fileIDs.forEach(fileID => {
+ if (files[fileID]) {
+ removedFiles[fileID] = files[fileID];
+ delete updatedFiles[fileID];
}
+ }); // Remove files from the `fileIDs` list in each upload.
- var queuedRequest = _this3.requests.run(function () {
- // When using an authentication system like JWT, the bearer token goes as a header. This
- // header needs to be fresh each time the token is refreshed so computing and setting the
- // headers just before the upload starts enables this kind of authentication to work properly.
- // Otherwise, half-way through the list of uploads the token could be stale and the upload would fail.
- var currentOpts = _this3.getOptions(file);
+ function fileIsNotRemoved(uploadFileID) {
+ return removedFiles[uploadFileID] === undefined;
+ }
- Object.keys(currentOpts.headers).forEach(function (header) {
- xhr.setRequestHeader(header, currentOpts.headers[header]);
- });
- xhr.send(data);
- return function () {
- timer.done();
- xhr.abort();
- };
- });
+ Object.keys(updatedUploads).forEach(uploadID => {
+ const newFileIDs = currentUploads[uploadID].fileIDs.filter(fileIsNotRemoved); // Remove the upload if no files are associated with it anymore.
- _this3.onFileRemove(file.id, function () {
- queuedRequest.abort();
- reject(new Error('File removed'));
- });
+ if (newFileIDs.length === 0) {
+ delete updatedUploads[uploadID];
+ return;
+ }
- _this3.onCancelAll(file.id, function () {
- queuedRequest.abort();
- reject(new Error('Upload cancelled'));
- });
+ updatedUploads[uploadID] = { ...currentUploads[uploadID],
+ fileIDs: newFileIDs
+ };
});
- };
-
- _proto.uploadRemote = function uploadRemote(file, current, total) {
- var _this4 = this;
-
- var opts = this.getOptions(file);
- return new Promise(function (resolve, reject) {
- _this4.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);
+ const stateUpdate = {
+ currentUploads: updatedUploads,
+ files: updatedFiles
+ }; // If all files were removed - allow new uploads,
+ // and clear recoveredState
- _this4.onFileRemove(file.id, function () {
- socket.send('pause', {});
- queuedRequest.abort();
- resolve("upload " + file.id + " was removed");
- });
+ if (Object.keys(updatedFiles).length === 0) {
+ stateUpdate.allowNewUpload = true;
+ stateUpdate.error = null;
+ stateUpdate.recoveredState = null;
+ }
- _this4.onCancelAll(file.id, function () {
- socket.send('pause', {});
- queuedRequest.abort();
- resolve("upload " + file.id + " was canceled");
- });
+ this.setState(stateUpdate);
+ this.calculateTotalProgress();
+ const removedFileIDs = Object.keys(removedFiles);
+ removedFileIDs.forEach(fileID => {
+ this.emit('file-removed', removedFiles[fileID], reason);
+ });
- _this4.onRetry(file.id, function () {
- socket.send('pause', {});
- socket.send('resume', {});
- });
+ if (removedFileIDs.length > 5) {
+ this.log(`Removed ${removedFileIDs.length} files`);
+ } else {
+ this.log(`Removed files: ${removedFileIDs.join(', ')}`);
+ }
+ }
- _this4.onRetryAll(file.id, function () {
- socket.send('pause', {});
- socket.send('resume', {});
- });
+ removeFile(fileID, reason = null) {
+ this.removeFiles([fileID], reason);
+ }
- 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
- };
+ pauseResume(fileID) {
+ if (!this.getState().capabilities.resumableUploads || this.getFile(fileID).uploadComplete) {
+ return undefined;
+ }
- _this4.uppy.emit('upload-success', file, uploadResp);
+ const wasPaused = this.getFile(fileID).isPaused || false;
+ const isPaused = !wasPaused;
+ this.setFileState(fileID, {
+ isPaused
+ });
+ this.emit('upload-pause', fileID, isPaused);
+ return isPaused;
+ }
- queuedRequest.done();
+ pauseAll() {
+ const updatedFiles = { ...this.getState().files
+ };
+ const inProgressUpdatedFiles = Object.keys(updatedFiles).filter(file => {
+ return !updatedFiles[file].progress.uploadComplete && updatedFiles[file].progress.uploadStarted;
+ });
+ inProgressUpdatedFiles.forEach(file => {
+ const updatedFile = { ...updatedFiles[file],
+ isPaused: true
+ };
+ updatedFiles[file] = updatedFile;
+ });
+ this.setState({
+ files: updatedFiles
+ });
+ this.emit('pause-all');
+ }
- if (_this4.uploaderEvents[file.id]) {
- _this4.uploaderEvents[file.id].remove();
+ resumeAll() {
+ const updatedFiles = { ...this.getState().files
+ };
+ const inProgressUpdatedFiles = Object.keys(updatedFiles).filter(file => {
+ return !updatedFiles[file].progress.uploadComplete && updatedFiles[file].progress.uploadStarted;
+ });
+ inProgressUpdatedFiles.forEach(file => {
+ const updatedFile = { ...updatedFiles[file],
+ isPaused: false,
+ error: null
+ };
+ updatedFiles[file] = updatedFile;
+ });
+ this.setState({
+ files: updatedFiles
+ });
+ this.emit('resume-all');
+ }
- _this4.uploaderEvents[file.id] = null;
- }
+ retryAll() {
+ const updatedFiles = { ...this.getState().files
+ };
+ const filesToRetry = Object.keys(updatedFiles).filter(file => {
+ return updatedFiles[file].error;
+ });
+ filesToRetry.forEach(file => {
+ const updatedFile = { ...updatedFiles[file],
+ isPaused: false,
+ error: null
+ };
+ updatedFiles[file] = updatedFile;
+ });
+ this.setState({
+ files: updatedFiles,
+ error: null
+ });
+ this.emit('retry-all', filesToRetry);
- 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
- });
+ if (filesToRetry.length === 0) {
+ return Promise.resolve({
+ successful: [],
+ failed: []
+ });
+ }
- _this4.uppy.emit('upload-error', file, error);
+ const uploadID = _classPrivateFieldLooseBase(this, _createUpload)[_createUpload](filesToRetry, {
+ forceAllowNewUpload: true // create new upload even if allowNewUpload: false
- queuedRequest.done();
+ });
- if (_this4.uploaderEvents[file.id]) {
- _this4.uploaderEvents[file.id].remove();
+ return _classPrivateFieldLooseBase(this, _runUpload)[_runUpload](uploadID);
+ }
- _this4.uploaderEvents[file.id] = null;
- }
+ cancelAll() {
+ this.emit('cancel-all');
+ const {
+ files
+ } = this.getState();
+ const fileIDs = Object.keys(files);
- reject(error);
- });
+ if (fileIDs.length) {
+ this.removeFiles(fileIDs, 'cancel-all');
+ }
- var queuedRequest = _this4.requests.run(function () {
- socket.open();
+ this.setState({
+ totalProgress: 0,
+ error: null,
+ recoveredState: null
+ });
+ }
- if (file.isPaused) {
- socket.send('pause', {});
- }
+ retryUpload(fileID) {
+ this.setFileState(fileID, {
+ error: null,
+ isPaused: false
+ });
+ this.emit('upload-retry', fileID);
- return function () {
- return socket.close();
- };
- });
- }).catch(function (err) {
- _this4.uppy.emit('upload-error', file, err);
+ const uploadID = _classPrivateFieldLooseBase(this, _createUpload)[_createUpload]([fileID], {
+ forceAllowNewUpload: true // create new upload even if allowNewUpload: false
- reject(err);
- });
});
- };
- _proto.uploadBundle = function uploadBundle(files) {
- var _this5 = this;
+ return _classPrivateFieldLooseBase(this, _runUpload)[_runUpload](uploadID);
+ }
- return new Promise(function (resolve, reject) {
- var endpoint = _this5.opts.endpoint;
- var method = _this5.opts.method;
+ reset() {
+ this.cancelAll();
+ }
- var optsFromState = _this5.uppy.getState().xhrUpload;
+ logout() {
+ this.iteratePlugins(plugin => {
+ if (plugin.provider && plugin.provider.logout) {
+ plugin.provider.logout();
+ }
+ });
+ }
- var formData = _this5.createBundledUpload(files, _extends({}, _this5.opts, optsFromState || {}));
+ calculateProgress(file, data) {
+ if (!this.getFile(file.id)) {
+ this.log(`Not setting progress for a file that has been removed: ${file.id}`);
+ return;
+ } // bytesTotal may be null or zero; in that case we can't divide by it
- var xhr = new XMLHttpRequest();
- var timer = new ProgressTimeout(_this5.opts.timeout, function () {
- xhr.abort();
- var error = new Error(_this5.i18n('timedOut', {
- seconds: Math.ceil(_this5.opts.timeout / 1000)
- }));
- emitError(error);
- reject(error);
- });
- var emitError = function emitError(error) {
- files.forEach(function (file) {
- _this5.uppy.emit('upload-error', file, error);
- });
- };
+ const canHavePercentage = Number.isFinite(data.bytesTotal) && data.bytesTotal > 0;
+ this.setFileState(file.id, {
+ progress: { ...this.getFile(file.id).progress,
+ bytesUploaded: data.bytesUploaded,
+ bytesTotal: data.bytesTotal,
+ percentage: canHavePercentage ? Math.round(data.bytesUploaded / data.bytesTotal * 100) : 0
+ }
+ });
+ this.calculateTotalProgress();
+ }
- xhr.upload.addEventListener('loadstart', function (ev) {
- _this5.uppy.log('[XHRUpload] started uploading bundle');
+ calculateTotalProgress() {
+ // calculate total progress, using the number of files currently uploading,
+ // multiplied by 100 and the summ of individual progress of each file
+ const files = this.getFiles();
+ const inProgress = files.filter(file => {
+ return file.progress.uploadStarted || file.progress.preprocess || file.progress.postprocess;
+ });
- timer.progress();
- });
- xhr.upload.addEventListener('progress', function (ev) {
- timer.progress();
- if (!ev.lengthComputable) return;
- files.forEach(function (file) {
- _this5.uppy.emit('upload-progress', file, {
- uploader: _this5,
- bytesUploaded: ev.loaded / ev.total * file.size,
- bytesTotal: file.size
- });
- });
+ if (inProgress.length === 0) {
+ this.emit('progress', 0);
+ this.setState({
+ totalProgress: 0
});
- xhr.addEventListener('load', function (ev) {
- timer.done();
-
- if (_this5.opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {
- var body = _this5.opts.getResponseData(xhr.responseText, xhr);
-
- var uploadResp = {
- status: ev.target.status,
- body: body
- };
- files.forEach(function (file) {
- _this5.uppy.emit('upload-success', file, uploadResp);
- });
- return resolve();
- }
+ return;
+ }
- var error = _this5.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error');
- error.request = xhr;
- emitError(error);
- return reject(error);
- });
- xhr.addEventListener('error', function (ev) {
- timer.done();
- var error = _this5.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error');
- emitError(error);
- return reject(error);
- });
+ const sizedFiles = inProgress.filter(file => file.progress.bytesTotal != null);
+ const unsizedFiles = inProgress.filter(file => file.progress.bytesTotal == null);
- _this5.uppy.on('cancel-all', function () {
- timer.done();
- xhr.abort();
+ if (sizedFiles.length === 0) {
+ const progressMax = inProgress.length * 100;
+ const currentProgress = unsizedFiles.reduce((acc, file) => {
+ return acc + file.progress.percentage;
+ }, 0);
+ const totalProgress = Math.round(currentProgress / progressMax * 100);
+ this.setState({
+ totalProgress
});
+ return;
+ }
- xhr.open(method.toUpperCase(), endpoint, true); // IE10 does not allow setting `withCredentials` and `responseType`
- // before `open()` is called.
-
- xhr.withCredentials = _this5.opts.withCredentials;
-
- if (_this5.opts.responseType !== '') {
- xhr.responseType = _this5.opts.responseType;
- }
-
- Object.keys(_this5.opts.headers).forEach(function (header) {
- xhr.setRequestHeader(header, _this5.opts.headers[header]);
- });
- xhr.send(formData);
- files.forEach(function (file) {
- _this5.uppy.emit('upload-started', file);
- });
+ let totalSize = sizedFiles.reduce((acc, file) => {
+ return acc + file.progress.bytesTotal;
+ }, 0);
+ const averageSize = totalSize / sizedFiles.length;
+ totalSize += averageSize * unsizedFiles.length;
+ let uploadedSize = 0;
+ sizedFiles.forEach(file => {
+ uploadedSize += file.progress.bytesUploaded;
});
- };
-
- _proto.uploadFiles = function uploadFiles(files) {
- var _this6 = this;
-
- var promises = files.map(function (file, i) {
- var current = parseInt(i, 10) + 1;
- var total = files.length;
-
- if (file.error) {
- return Promise.reject(new Error(file.error));
- }
+ unsizedFiles.forEach(file => {
+ uploadedSize += averageSize * (file.progress.percentage || 0) / 100;
+ });
+ let totalProgress = totalSize === 0 ? 0 : Math.round(uploadedSize / totalSize * 100); // hot fix, because:
+ // uploadedSize ended up larger than totalSize, resulting in 1325% total
- if (file.isRemote) {
- return _this6.uploadRemote(file, current, total);
- }
+ if (totalProgress > 100) {
+ totalProgress = 100;
+ }
- return _this6.upload(file, current, total);
+ this.setState({
+ totalProgress
});
- return settle(promises);
- };
+ this.emit('progress', totalProgress);
+ }
+ /**
+ * Registers listeners for all global actions, like:
+ * `error`, `file-removed`, `upload-progress`
+ */
- _proto.onFileRemove = function onFileRemove(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();
- }
- });
- };
+ updateOnlineStatus() {
+ const online = typeof window.navigator.onLine !== 'undefined' ? window.navigator.onLine : true;
- _proto.onRetryAll = function onRetryAll(fileID, cb) {
- var _this7 = this;
+ if (!online) {
+ this.emit('is-offline');
+ this.info(this.i18n('noInternetConnection'), 'error', 0);
+ this.wasOffline = true;
+ } else {
+ this.emit('is-online');
- this.uploaderEvents[fileID].on('retry-all', function (filesToRetry) {
- if (!_this7.uppy.getFile(fileID)) return;
- cb();
- });
- };
+ if (this.wasOffline) {
+ this.emit('back-online');
+ this.info(this.i18n('connectedToInternet'), 'success', 3000);
+ this.wasOffline = false;
+ }
+ }
+ }
- _proto.onCancelAll = function onCancelAll(fileID, cb) {
- var _this8 = this;
+ getID() {
+ return this.opts.id;
+ }
+ /**
+ * Registers a plugin with Core.
+ *
+ * @param {object} Plugin object
+ * @param {object} [opts] object with options to be passed to Plugin
+ * @returns {object} self for chaining
+ */
+ // eslint-disable-next-line no-shadow
- this.uploaderEvents[fileID].on('cancel-all', function () {
- if (!_this8.uppy.getFile(fileID)) return;
- cb();
- });
- };
- _proto.handleUpload = function handleUpload(fileIDs) {
- var _this9 = this;
+ use(Plugin, opts) {
+ if (typeof Plugin !== 'function') {
+ const msg = `Expected a plugin class, but got ${Plugin === null ? 'null' : typeof Plugin}.` + ' Please verify that the plugin was imported and spelled correctly.';
+ throw new TypeError(msg);
+ } // Instantiate
- if (fileIDs.length === 0) {
- this.uppy.log('[XHRUpload] No files to upload!');
- return Promise.resolve();
- } // no limit configured by the user, and no RateLimitedQueue passed in by a "parent" plugin (basically just AwsS3) using the top secret `__queue` option
+ const plugin = new Plugin(this, opts);
+ const pluginId = plugin.id;
- if (this.opts.limit === 0 && !this.opts.__queue) {
- this.uppy.log('[XHRUpload] When uploading multiple files at once, consider setting the `limit` option (to `10` for example), to limit the number of concurrent uploads, which helps prevent memory and network issues: https://uppy.io/docs/xhr-upload/#limit-0', 'warning');
+ if (!pluginId) {
+ throw new Error('Your plugin must have an id');
}
- this.uppy.log('[XHRUpload] Uploading...');
- var files = fileIDs.map(function (fileID) {
- return _this9.uppy.getFile(fileID);
- });
+ if (!plugin.type) {
+ throw new Error('Your plugin must have a type');
+ }
- if (this.opts.bundle) {
- // if bundle: true, we don’t support remote uploads
- var isSomeFileRemote = files.some(function (file) {
- return file.isRemote;
- });
+ const existsPluginAlready = this.getPlugin(pluginId);
- if (isSomeFileRemote) {
- throw new Error('Can’t upload remote files when the `bundle: true` option is set');
- }
+ if (existsPluginAlready) {
+ const msg = `Already found a plugin named '${existsPluginAlready.id}'. ` + `Tried to use: '${pluginId}'.\n` + 'Uppy plugins must have unique `id` options. See https://uppy.io/docs/plugins/#id.';
+ throw new Error(msg);
+ }
- if (typeof this.opts.headers === 'function') {
- throw new TypeError('`headers` may not be a function when the `bundle: true` option is set');
- }
+ if (Plugin.VERSION) {
+ this.log(`Using ${pluginId} v${Plugin.VERSION}`);
+ }
- return this.uploadBundle(files);
+ if (plugin.type in _classPrivateFieldLooseBase(this, _plugins)[_plugins]) {
+ _classPrivateFieldLooseBase(this, _plugins)[_plugins][plugin.type].push(plugin);
+ } else {
+ _classPrivateFieldLooseBase(this, _plugins)[_plugins][plugin.type] = [plugin];
}
- return this.uploadFiles(files).then(function () {
- return null;
- });
- };
+ plugin.install();
+ return this;
+ }
+ /**
+ * Find one Plugin by name.
+ *
+ * @param {string} id plugin id
+ * @returns {BasePlugin|undefined}
+ */
- _proto.install = function install() {
- if (this.opts.bundle) {
- var _this$uppy$getState2 = this.uppy.getState(),
- capabilities = _this$uppy$getState2.capabilities;
- this.uppy.setState({
- capabilities: _extends({}, capabilities, {
- individualCancellation: false
- })
- });
+ getPlugin(id) {
+ for (const plugins of Object.values(_classPrivateFieldLooseBase(this, _plugins)[_plugins])) {
+ const foundPlugin = plugins.find(plugin => plugin.id === id);
+ if (foundPlugin != null) return foundPlugin;
}
- this.uppy.addUploader(this.handleUpload);
- };
+ return undefined;
+ }
- _proto.uninstall = function uninstall() {
- if (this.opts.bundle) {
- var _this$uppy$getState3 = this.uppy.getState(),
- capabilities = _this$uppy$getState3.capabilities;
+ [_Symbol$for](type) {
+ return _classPrivateFieldLooseBase(this, _plugins)[_plugins][type];
+ }
+ /**
+ * Iterate through all `use`d plugins.
+ *
+ * @param {Function} method that will be run on each plugin
+ */
- this.uppy.setState({
- capabilities: _extends({}, capabilities, {
- individualCancellation: true
- })
- });
- }
- this.uppy.removeUploader(this.handleUpload);
- };
+ iteratePlugins(method) {
+ Object.values(_classPrivateFieldLooseBase(this, _plugins)[_plugins]).flat(1).forEach(method);
+ }
+ /**
+ * Uninstall and remove a plugin.
+ *
+ * @param {object} instance The plugin instance to remove.
+ */
- return XHRUpload;
-}(Plugin), _class.VERSION = "1.7.5", _temp);
-},{"@uppy/companion-client":12,"@uppy/core":15,"@uppy/utils/lib/EventTracker":22,"@uppy/utils/lib/NetworkError":23,"@uppy/utils/lib/ProgressTimeout":24,"@uppy/utils/lib/RateLimitedQueue":25,"@uppy/utils/lib/Translator":26,"@uppy/utils/lib/emitSocketProgress":28,"@uppy/utils/lib/getSocketHost":40,"@uppy/utils/lib/isNetworkError":44,"@uppy/utils/lib/settle":46,"cuid":50}],49:[function(require,module,exports){
-'use strict';
-Object.defineProperty(exports, '__esModule', { value: true });
+ removePlugin(instance) {
+ this.log(`Removing plugin ${instance.id}`);
+ this.emit('plugin-remove', instance);
-function _classCallCheck(instance, Constructor) {
- if (!(instance instanceof Constructor)) {
- throw new TypeError("Cannot call a class as a function");
- }
-}
+ if (instance.uninstall) {
+ instance.uninstall();
+ }
-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);
- }
-}
+ const list = _classPrivateFieldLooseBase(this, _plugins)[_plugins][instance.type]; // list.indexOf failed here, because Vue3 converted the plugin instance
+ // to a Proxy object, which failed the strict comparison test:
+ // obj !== objProxy
-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");
- }
+ const index = list.findIndex(item => item.id === instance.id);
- subClass.prototype = Object.create(superClass && superClass.prototype, {
- constructor: {
- value: subClass,
- writable: true,
- configurable: true
+ if (index !== -1) {
+ list.splice(index, 1);
}
- });
- 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);
-}
+ const state = this.getState();
+ const updatedState = {
+ plugins: { ...state.plugins,
+ [instance.id]: undefined
+ }
+ };
+ this.setState(updatedState);
+ }
+ /**
+ * Uninstall all plugins and close down this Uppy instance.
+ */
-function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
-}
+ close() {
+ this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`);
+ this.reset();
-function _isNativeReflectConstruct() {
- if (typeof Reflect === "undefined" || !Reflect.construct) return false;
- if (Reflect.construct.sham) return false;
- if (typeof Proxy === "function") return true;
+ _classPrivateFieldLooseBase(this, _storeUnsubscribe)[_storeUnsubscribe]();
- try {
- Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
- return true;
- } catch (e) {
- return false;
+ this.iteratePlugins(plugin => {
+ this.removePlugin(plugin);
+ });
+
+ if (typeof window !== 'undefined' && window.removeEventListener) {
+ window.removeEventListener('online', _classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus]);
+ window.removeEventListener('offline', _classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus]);
+ }
}
-}
-function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
+ hideInfo() {
+ const {
+ info
+ } = this.getState();
+ this.setState({
+ info: info.slice(1)
+ });
+ this.emit('info-hidden');
}
+ /**
+ * Set info message in `state.info`, so that UI plugins like `Informer`
+ * can display the message.
+ *
+ * @param {string | object} message Message to be displayed by the informer
+ * @param {string} [type]
+ * @param {number} [duration]
+ */
- return self;
-}
-function _possibleConstructorReturn(self, call) {
- if (call && (typeof call === "object" || typeof call === "function")) {
- return call;
+ info(message, type = 'info', duration = 3000) {
+ const isComplexMessage = typeof message === 'object';
+ this.setState({
+ info: [...this.getState().info, {
+ type,
+ message: isComplexMessage ? message.message : message,
+ details: isComplexMessage ? message.details : null
+ }]
+ });
+ setTimeout(() => this.hideInfo(), duration);
+ this.emit('info-visible');
}
+ /**
+ * Passes messages to a function, provided in `opts.logger`.
+ * If `opts.logger: Uppy.debugLogger` or `opts.debug: true`, logs to the browser console.
+ *
+ * @param {string|object} message to log
+ * @param {string} [type] optional `error` or `warning`
+ */
- return _assertThisInitialized(self);
-}
-function _createSuper(Derived) {
- var hasNativeReflectConstruct = _isNativeReflectConstruct();
+ log(message, type) {
+ const {
+ logger
+ } = this.opts;
- return function _createSuperInternal() {
- var Super = _getPrototypeOf(Derived),
- result;
+ switch (type) {
+ case 'error':
+ logger.error(message);
+ break;
- if (hasNativeReflectConstruct) {
- var NewTarget = _getPrototypeOf(this).constructor;
+ case 'warning':
+ logger.warn(message);
+ break;
- result = Reflect.construct(Super, arguments, NewTarget);
- } else {
- result = Super.apply(this, arguments);
+ default:
+ logger.debug(message);
+ break;
}
-
- return _possibleConstructorReturn(this, result);
- };
-}
-
-function _superPropBase(object, property) {
- while (!Object.prototype.hasOwnProperty.call(object, property)) {
- object = _getPrototypeOf(object);
- if (object === null) break;
}
+ /**
+ * Restore an upload by its ID.
+ */
- 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);
+ restore(uploadID) {
+ this.log(`Core: attempting to restore upload "${uploadID}"`);
- if (!base) return;
- var desc = Object.getOwnPropertyDescriptor(base, property);
+ if (!this.getState().currentUploads[uploadID]) {
+ _classPrivateFieldLooseBase(this, _removeUpload)[_removeUpload](uploadID);
- if (desc.get) {
- return desc.get.call(receiver);
- }
+ return Promise.reject(new Error('Nonexistent upload'));
+ }
- return desc.value;
- };
+ return _classPrivateFieldLooseBase(this, _runUpload)[_runUpload](uploadID);
}
+ /**
+ * Create an upload for a bunch of files.
+ *
+ * @param {Array<string>} fileIDs File IDs to include in this upload.
+ * @returns {string} ID of this upload.
+ */
- return _get(target, property, receiver || target);
-}
-
-var Emitter = /*#__PURE__*/function () {
- function Emitter() {
- _classCallCheck(this, Emitter);
- Object.defineProperty(this, 'listeners', {
- value: {},
- writable: true,
- configurable: true
- });
+ [_Symbol$for2](...args) {
+ return _classPrivateFieldLooseBase(this, _createUpload)[_createUpload](...args);
}
- _createClass(Emitter, [{
- key: "addEventListener",
- value: function addEventListener(type, callback, options) {
- if (!(type in this.listeners)) {
- this.listeners[type] = [];
- }
-
- this.listeners[type].push({
- callback: callback,
- options: options
- });
+ /**
+ * Add data to an upload's result object.
+ *
+ * @param {string} uploadID The ID of the upload.
+ * @param {object} data Data properties to add to the result object.
+ */
+ addResultData(uploadID, data) {
+ if (!_classPrivateFieldLooseBase(this, _getUpload)[_getUpload](uploadID)) {
+ this.log(`Not setting result for an upload that has been removed: ${uploadID}`);
+ return;
}
- }, {
- 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 === callback) {
- stack.splice(i, 1);
- return;
- }
+ const {
+ currentUploads
+ } = this.getState();
+ const currentUpload = { ...currentUploads[uploadID],
+ result: { ...currentUploads[uploadID].result,
+ ...data
}
- }
- }, {
- key: "dispatchEvent",
- value: function dispatchEvent(event) {
- if (!(event.type in this.listeners)) {
- return;
+ };
+ this.setState({
+ currentUploads: { ...currentUploads,
+ [uploadID]: currentUpload
}
+ });
+ }
+ /**
+ * Remove an upload, eg. if it has been canceled or completed.
+ *
+ * @param {string} uploadID The ID of the upload.
+ */
- var stack = this.listeners[event.type];
- var stackToCall = stack.slice();
- for (var i = 0, l = stackToCall.length; i < l; i++) {
- var listener = stackToCall[i];
+ /**
+ * Start an upload for all the files that are not currently being uploaded.
+ *
+ * @returns {Promise}
+ */
+ upload() {
+ var _classPrivateFieldLoo;
- try {
- listener.callback.call(this, event);
- } catch (e) {
- Promise.resolve().then(function () {
- throw e;
- });
- }
+ if (!((_classPrivateFieldLoo = _classPrivateFieldLooseBase(this, _plugins)[_plugins].uploader) != null && _classPrivateFieldLoo.length)) {
+ this.log('No uploader type plugins are used', 'warning');
+ }
- if (listener.options && listener.options.once) {
- this.removeEventListener(event.type, listener.callback);
- }
- }
+ let {
+ files
+ } = this.getState();
+ const onBeforeUploadResult = this.opts.onBeforeUpload(files);
- return !event.defaultPrevented;
+ if (onBeforeUploadResult === false) {
+ return Promise.reject(new Error('Not starting the upload because onBeforeUpload returned false'));
}
- }]);
-
- return Emitter;
-}();
-var AbortSignal = /*#__PURE__*/function (_Emitter) {
- _inherits(AbortSignal, _Emitter);
+ if (onBeforeUploadResult && typeof onBeforeUploadResult === 'object') {
+ files = onBeforeUploadResult; // Updating files in state, because uploader plugins receive file IDs,
+ // and then fetch the actual file object from state
- var _super = _createSuper(AbortSignal);
+ this.setState({
+ files
+ });
+ }
- function AbortSignal() {
- var _this;
+ return Promise.resolve().then(() => {
+ _classPrivateFieldLooseBase(this, _checkMinNumberOfFiles)[_checkMinNumberOfFiles](files);
- _classCallCheck(this, AbortSignal);
+ _classPrivateFieldLooseBase(this, _checkRequiredMetaFields)[_checkRequiredMetaFields](files);
+ }).catch(err => {
+ _classPrivateFieldLooseBase(this, _showOrLogErrorAndThrow)[_showOrLogErrorAndThrow](err);
+ }).then(() => {
+ const {
+ currentUploads
+ } = this.getState(); // get a list of files that are currently assigned to uploads
- _this = _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
+ const currentlyUploadingFiles = Object.values(currentUploads).flatMap(curr => curr.fileIDs);
+ const waitingFileIDs = [];
+ Object.keys(files).forEach(fileID => {
+ const file = this.getFile(fileID); // if the file hasn't started uploading and hasn't already been assigned to an upload..
- if (!_this.listeners) {
- Emitter.call(_assertThisInitialized(_this));
- } // 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
+ if (!file.progress.uploadStarted && currentlyUploadingFiles.indexOf(fileID) === -1) {
+ waitingFileIDs.push(file.id);
+ }
+ });
+ const uploadID = _classPrivateFieldLooseBase(this, _createUpload)[_createUpload](waitingFileIDs);
- Object.defineProperty(_assertThisInitialized(_this), 'aborted', {
- value: false,
- writable: true,
- configurable: true
- });
- Object.defineProperty(_assertThisInitialized(_this), 'onabort', {
- value: null,
- writable: true,
- configurable: true
+ return _classPrivateFieldLooseBase(this, _runUpload)[_runUpload](uploadID);
+ }).catch(err => {
+ _classPrivateFieldLooseBase(this, _showOrLogErrorAndThrow)[_showOrLogErrorAndThrow](err, {
+ showInformer: false
+ });
});
- return _this;
}
- _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);
- }
- }
+} // Expose class constructor.
- _get(_getPrototypeOf(AbortSignal.prototype), "dispatchEvent", this).call(this, event);
- }
- }]);
- return AbortSignal;
-}(Emitter);
-var AbortController = /*#__PURE__*/function () {
- function AbortController() {
- _classCallCheck(this, AbortController);
+function _checkRestrictions2(file, files = this.getFiles()) {
+ const {
+ maxFileSize,
+ minFileSize,
+ maxTotalFileSize,
+ maxNumberOfFiles,
+ allowedFileTypes
+ } = this.opts.restrictions;
- // 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
- });
+ if (maxNumberOfFiles) {
+ if (files.length + 1 > maxNumberOfFiles) {
+ throw new RestrictionError(`${this.i18n('youCanOnlyUploadX', {
+ smart_count: maxNumberOfFiles
+ })}`);
+ }
}
- _createClass(AbortController, [{
- key: "abort",
- value: function abort() {
- var event;
+ if (allowedFileTypes) {
+ const isCorrectFileType = allowedFileTypes.some(type => {
+ // check if this is a mime-type
+ if (type.indexOf('/') > -1) {
+ if (!file.type) return false;
+ return match(file.type.replace(/;.*?$/, ''), type);
+ } // otherwise this is likely an extension
- 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
- };
- }
+
+ if (type[0] === '.' && file.extension) {
+ return file.extension.toLowerCase() === type.substr(1).toLowerCase();
}
- this.signal.dispatchEvent(event);
- }
- }, {
- key: "toString",
- value: function toString() {
- return '[object AbortController]';
- }
- }]);
+ return false;
+ });
- return AbortController;
-}();
+ if (!isCorrectFileType) {
+ const allowedFileTypesString = allowedFileTypes.join(', ');
+ throw new RestrictionError(this.i18n('youCanOnlyUploadFileTypes', {
+ types: allowedFileTypesString
+ }));
+ }
+ } // We can't check maxTotalFileSize if the size is unknown.
-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;
+ if (maxTotalFileSize && file.size != null) {
+ let totalFilesSize = 0;
+ totalFilesSize += file.size;
+ files.forEach(f => {
+ totalFilesSize += f.size;
+ });
-},{}],50:[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
- */
+ if (totalFilesSize > maxTotalFileSize) {
+ throw new RestrictionError(this.i18n('exceedsSize', {
+ size: prettierBytes(maxTotalFileSize),
+ file: file.name
+ }));
+ }
+ } // We can't check maxFileSize if the size is unknown.
-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);
+ if (maxFileSize && file.size != null) {
+ if (file.size > maxFileSize) {
+ throw new RestrictionError(this.i18n('exceedsSize', {
+ size: prettierBytes(maxFileSize),
+ file: file.name
+ }));
+ }
+ } // We can't check minFileSize if the size is unknown.
-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;
+ if (minFileSize && file.size != null) {
+ if (file.size < minFileSize) {
+ throw new RestrictionError(this.i18n('inferiorSize', {
+ size: prettierBytes(minFileSize)
+ }));
+ }
+ }
}
-function cuid () {
- // Starting with a lowercase letter makes
- // it HTML element ID friendly.
- var letter = 'c', // hard-coded allows for sequential access
+function _checkMinNumberOfFiles2(files) {
+ const {
+ minNumberOfFiles
+ } = this.opts.restrictions;
- // timestamp
- // warning: this exposes the exact date and time
- // that the uid was created.
- timestamp = (new Date().getTime()).toString(base),
+ if (Object.keys(files).length < minNumberOfFiles) {
+ throw new RestrictionError(`${this.i18n('youHaveToAtLeastSelectX', {
+ smart_count: minNumberOfFiles
+ })}`);
+ }
+}
- // Prevent same-machine collisions.
- counter = pad(safeCounter().toString(base), blockSize),
+function _checkRequiredMetaFields2(files) {
+ const {
+ requiredMetaFields
+ } = this.opts.restrictions;
+ const {
+ hasOwnProperty
+ } = Object.prototype.hasOwnProperty;
+ const errors = [];
+ const fileIDs = Object.keys(files);
+
+ for (let i = 0; i < fileIDs.length; i++) {
+ const file = this.getFile(fileIDs[i]);
+
+ for (let i = 0; i < requiredMetaFields.length; i++) {
+ if (!hasOwnProperty.call(file.meta, requiredMetaFields[i])) {
+ const err = new RestrictionError(`${this.i18n('missingRequiredMetaFieldOnFile', {
+ fileName: file.name
+ })}`);
+ errors.push(err);
+
+ _classPrivateFieldLooseBase(this, _showOrLogErrorAndThrow)[_showOrLogErrorAndThrow](err, {
+ file,
+ showInformer: false,
+ throwErr: false
+ });
+ }
+ }
+ }
- // A few chars to generate distinct ids for different
- // clients (so different computers are far less
- // likely to generate the same id)
- print = fingerprint(),
+ if (errors.length) {
+ throw new AggregateRestrictionError(`${this.i18n('missingRequiredMetaField')}`, errors);
+ }
+}
- // Grab some more chars from Math.random()
- random = randomBlock() + randomBlock();
+function _showOrLogErrorAndThrow2(err, {
+ showInformer = true,
+ file = null,
+ throwErr = true
+} = {}) {
+ const message = typeof err === 'object' ? err.message : err;
+ const details = typeof err === 'object' && err.details ? err.details : ''; // Restriction errors should be logged, but not as errors,
+ // as they are expected and shown in the UI.
- return letter + timestamp + counter + print + random;
-}
+ let logMessageWithDetails = message;
-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);
+ if (details) {
+ logMessageWithDetails += ` ${details}`;
+ }
- return date.slice(-2) +
- counter + print + random;
-};
+ if (err.isRestriction) {
+ this.log(logMessageWithDetails);
+ this.emit('restriction-failed', file, err);
+ } else {
+ this.log(logMessageWithDetails, 'error');
+ } // Sometimes informer has to be shown manually by the developer,
+ // for example, in `onBeforeFileAdded`.
-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;
-};
+ if (showInformer) {
+ this.info({
+ message,
+ details
+ }, 'error', this.opts.infoTimeout);
+ }
-cuid.fingerprint = fingerprint;
+ if (throwErr) {
+ throw typeof err === 'object' ? err : new Error(err);
+ }
+}
-module.exports = cuid;
+function _assertNewUploadAllowed2(file) {
+ const {
+ allowNewUpload
+ } = this.getState();
-},{"./lib/fingerprint.js":51,"./lib/getRandomValue.js":52,"./lib/pad.js":53}],51:[function(require,module,exports){
-var pad = require('./pad.js');
+ if (allowNewUpload === false) {
+ _classPrivateFieldLooseBase(this, _showOrLogErrorAndThrow)[_showOrLogErrorAndThrow](new RestrictionError(this.i18n('noNewAlreadyUploading')), {
+ file
+ });
+ }
+}
-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);
+function _checkAndCreateFileStateObject2(files, fileDescriptor) {
+ const fileType = getFileType(fileDescriptor);
+ const fileName = getFileName(fileType, fileDescriptor);
+ const fileExtension = getFileNameAndExtension(fileName).extension;
+ const isRemote = Boolean(fileDescriptor.isRemote);
+ const fileID = generateFileID({ ...fileDescriptor,
+ type: fileType
+ });
-module.exports = function fingerprint () {
- return clientId;
-};
+ if (this.checkIfFileAlreadyExists(fileID)) {
+ const error = new RestrictionError(this.i18n('noDuplicates', {
+ fileName
+ }));
-},{"./pad.js":53}],52:[function(require,module,exports){
+ _classPrivateFieldLooseBase(this, _showOrLogErrorAndThrow)[_showOrLogErrorAndThrow](error, {
+ file: fileDescriptor
+ });
+ }
-var getRandomValue;
+ const meta = fileDescriptor.meta || {};
+ meta.name = fileName;
+ meta.type = fileType; // `null` means the size is unknown.
-var crypto = typeof window !== 'undefined' &&
- (window.crypto || window.msCrypto) ||
- typeof self !== 'undefined' &&
- self.crypto;
+ const size = Number.isFinite(fileDescriptor.data.size) ? fileDescriptor.data.size : null;
+ let newFile = {
+ source: fileDescriptor.source || '',
+ id: fileID,
+ name: fileName,
+ extension: fileExtension || '',
+ meta: { ...this.getState().meta,
+ ...meta
+ },
+ type: fileType,
+ data: fileDescriptor.data,
+ progress: {
+ percentage: 0,
+ bytesUploaded: 0,
+ bytesTotal: size,
+ uploadComplete: false,
+ uploadStarted: null
+ },
+ size,
+ isRemote,
+ remote: fileDescriptor.remote || '',
+ preview: fileDescriptor.preview
+ };
+ const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(newFile, files);
-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;
-}
+ if (onBeforeFileAddedResult === false) {
+ // Don’t show UI info for this error, as it should be done by the developer
+ _classPrivateFieldLooseBase(this, _showOrLogErrorAndThrow)[_showOrLogErrorAndThrow](new RestrictionError('Cannot add the file because onBeforeFileAdded returned false.'), {
+ showInformer: false,
+ fileDescriptor
+ });
+ } else if (typeof onBeforeFileAddedResult === 'object' && onBeforeFileAddedResult !== null) {
+ newFile = onBeforeFileAddedResult;
+ }
-module.exports = getRandomValue;
+ try {
+ const filesArray = Object.keys(files).map(i => files[i]);
-},{}],53:[function(require,module,exports){
-module.exports = function pad (num, size) {
- var s = '000000000' + num;
- return s.substr(s.length - size);
-};
+ _classPrivateFieldLooseBase(this, _checkRestrictions)[_checkRestrictions](newFile, filesArray);
+ } catch (err) {
+ _classPrivateFieldLooseBase(this, _showOrLogErrorAndThrow)[_showOrLogErrorAndThrow](err, {
+ file: newFile
+ });
+ }
-},{}],54:[function(require,module,exports){
-(function (global){(function (){
-/**
- * lodash (Custom Build) <https://lodash.com/>
- * Build: `lodash modularize exports="npm" -o ./`
- * Copyright jQuery Foundation and other contributors <https://jquery.org/>
- * Released under MIT license <https://lodash.com/license>
- * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
- * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
- */
+ return newFile;
+}
-/** Used as the `TypeError` message for "Functions" methods. */
-var FUNC_ERROR_TEXT = 'Expected a function';
+function _startIfAutoProceed2() {
+ if (this.opts.autoProceed && !this.scheduledAutoProceed) {
+ this.scheduledAutoProceed = setTimeout(() => {
+ this.scheduledAutoProceed = null;
+ this.upload().catch(err => {
+ if (!err.isRestriction) {
+ this.log(err.stack || err.message || err);
+ }
+ });
+ }, 4);
+ }
+}
-/** Used as references for various `Number` constants. */
-var NAN = 0 / 0;
+function _addListeners2() {
+ /**
+ * @param {Error} error
+ * @param {object} [file]
+ * @param {object} [response]
+ */
+ const errorHandler = (error, file, response) => {
+ let errorMsg = error.message || 'Unknown error';
-/** `Object#toString` result references. */
-var symbolTag = '[object Symbol]';
+ if (error.details) {
+ errorMsg += ` ${error.details}`;
+ }
-/** Used to match leading and trailing whitespace. */
-var reTrim = /^\s+|\s+$/g;
+ this.setState({
+ error: errorMsg
+ });
-/** Used to detect bad signed hexadecimal string values. */
-var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
+ if (file != null && file.id in this.getState().files) {
+ this.setFileState(file.id, {
+ error: errorMsg,
+ response
+ });
+ }
+ };
-/** Used to detect binary string values. */
-var reIsBinary = /^0b[01]+$/i;
+ this.on('error', errorHandler);
+ this.on('upload-error', (file, error, response) => {
+ errorHandler(error, file, response);
-/** Used to detect octal string values. */
-var reIsOctal = /^0o[0-7]+$/i;
+ if (typeof error === 'object' && error.message) {
+ const newError = new Error(error.message);
+ newError.details = error.message;
-/** Built-in method references without a dependency on `root`. */
-var freeParseInt = parseInt;
+ if (error.details) {
+ newError.details += ` ${error.details}`;
+ }
-/** Detect free variable `global` from Node.js. */
-var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
+ newError.message = this.i18n('failedToUpload', {
+ file: file.name
+ });
-/** Detect free variable `self`. */
-var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
+ _classPrivateFieldLooseBase(this, _showOrLogErrorAndThrow)[_showOrLogErrorAndThrow](newError, {
+ throwErr: false
+ });
+ } else {
+ _classPrivateFieldLooseBase(this, _showOrLogErrorAndThrow)[_showOrLogErrorAndThrow](error, {
+ throwErr: false
+ });
+ }
+ });
+ this.on('upload', () => {
+ this.setState({
+ error: null
+ });
+ });
+ this.on('upload-started', file => {
+ if (!this.getFile(file.id)) {
+ this.log(`Not setting progress for a file that has been removed: ${file.id}`);
+ return;
+ }
-/** Used as a reference to the global object. */
-var root = freeGlobal || freeSelf || Function('return this')();
+ this.setFileState(file.id, {
+ progress: {
+ uploadStarted: Date.now(),
+ uploadComplete: false,
+ percentage: 0,
+ bytesUploaded: 0,
+ bytesTotal: file.size
+ }
+ });
+ });
+ this.on('upload-progress', this.calculateProgress);
+ this.on('upload-success', (file, uploadResp) => {
+ if (!this.getFile(file.id)) {
+ this.log(`Not setting progress for a file that has been removed: ${file.id}`);
+ return;
+ }
-/** Used for built-in method references. */
-var objectProto = Object.prototype;
+ const currentProgress = this.getFile(file.id).progress;
+ this.setFileState(file.id, {
+ progress: { ...currentProgress,
+ postprocess: _classPrivateFieldLooseBase(this, _postProcessors)[_postProcessors].size > 0 ? {
+ mode: 'indeterminate'
+ } : null,
+ uploadComplete: true,
+ percentage: 100,
+ bytesUploaded: currentProgress.bytesTotal
+ },
+ response: uploadResp,
+ uploadURL: uploadResp.uploadURL,
+ isPaused: false
+ }); // Remote providers sometimes don't tell us the file size,
+ // but we can know how many bytes we uploaded once the upload is complete.
-/**
- * Used to resolve the
- * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
- * of values.
- */
-var objectToString = objectProto.toString;
+ if (file.size == null) {
+ this.setFileState(file.id, {
+ size: uploadResp.bytesUploaded || currentProgress.bytesTotal
+ });
+ }
-/* Built-in method references for those with the same name as other `lodash` methods. */
-var nativeMax = Math.max,
- nativeMin = Math.min;
+ this.calculateTotalProgress();
+ });
+ this.on('preprocess-progress', (file, progress) => {
+ if (!this.getFile(file.id)) {
+ this.log(`Not setting progress for a file that has been removed: ${file.id}`);
+ return;
+ }
-/**
- * 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();
-};
+ this.setFileState(file.id, {
+ progress: { ...this.getFile(file.id).progress,
+ preprocess: progress
+ }
+ });
+ });
+ this.on('preprocess-complete', file => {
+ if (!this.getFile(file.id)) {
+ this.log(`Not setting progress for a file that has been removed: ${file.id}`);
+ return;
+ }
-/**
- * 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;
+ const files = { ...this.getState().files
+ };
+ files[file.id] = { ...files[file.id],
+ progress: { ...files[file.id].progress
+ }
+ };
+ delete files[file.id].progress.preprocess;
+ this.setState({
+ files
+ });
+ });
+ this.on('postprocess-progress', (file, progress) => {
+ if (!this.getFile(file.id)) {
+ this.log(`Not setting progress for a file that has been removed: ${file.id}`);
+ return;
+ }
+
+ this.setFileState(file.id, {
+ progress: { ...this.getState().files[file.id].progress,
+ postprocess: progress
+ }
+ });
+ });
+ this.on('postprocess-complete', file => {
+ if (!this.getFile(file.id)) {
+ this.log(`Not setting progress for a file that has been removed: ${file.id}`);
+ return;
+ }
- 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;
+ const files = { ...this.getState().files
+ };
+ files[file.id] = { ...files[file.id],
+ progress: { ...files[file.id].progress
+ }
+ };
+ delete files[file.id].progress.postprocess;
+ this.setState({
+ files
+ });
+ });
+ this.on('restored', () => {
+ // Files may have changed--ensure progress is still accurate.
+ this.calculateTotalProgress();
+ }); // show informer if offline
+
+ if (typeof window !== 'undefined' && window.addEventListener) {
+ window.addEventListener('online', _classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus]);
+ window.addEventListener('offline', _classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus]);
+ setTimeout(_classPrivateFieldLooseBase(this, _updateOnlineStatus)[_updateOnlineStatus], 3000);
}
+}
- function invokeFunc(time) {
- var args = lastArgs,
- thisArg = lastThis;
+function _createUpload2(fileIDs, opts = {}) {
+ // uppy.retryAll sets this to true — when retrying we want to ignore `allowNewUpload: false`
+ const {
+ forceAllowNewUpload = false
+ } = opts;
+ const {
+ allowNewUpload,
+ currentUploads
+ } = this.getState();
- lastArgs = lastThis = undefined;
- lastInvokeTime = time;
- result = func.apply(thisArg, args);
- return result;
+ if (!allowNewUpload && !forceAllowNewUpload) {
+ throw new Error('Cannot create a new upload: already uploading.');
}
- 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;
- }
+ const uploadID = cuid();
+ this.emit('upload', {
+ id: uploadID,
+ fileIDs
+ });
+ this.setState({
+ allowNewUpload: this.opts.allowMultipleUploads !== false,
+ currentUploads: { ...currentUploads,
+ [uploadID]: {
+ fileIDs,
+ step: 0,
+ result: {}
+ }
+ }
+ });
+ return uploadID;
+}
- function remainingWait(time) {
- var timeSinceLastCall = time - lastCallTime,
- timeSinceLastInvoke = time - lastInvokeTime,
- result = wait - timeSinceLastCall;
+function _getUpload2(uploadID) {
+ const {
+ currentUploads
+ } = this.getState();
+ return currentUploads[uploadID];
+}
- return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result;
- }
+function _removeUpload2(uploadID) {
+ const currentUploads = { ...this.getState().currentUploads
+ };
+ delete currentUploads[uploadID];
+ this.setState({
+ currentUploads
+ });
+}
- function shouldInvoke(time) {
- var timeSinceLastCall = time - lastCallTime,
- timeSinceLastInvoke = time - lastInvokeTime;
+function _runUpload2(uploadID) {
+ const uploadData = this.getState().currentUploads[uploadID];
+ const restoreStep = uploadData.step;
+ const steps = [..._classPrivateFieldLooseBase(this, _preProcessors)[_preProcessors], ..._classPrivateFieldLooseBase(this, _uploaders)[_uploaders], ..._classPrivateFieldLooseBase(this, _postProcessors)[_postProcessors]];
+ let lastStep = Promise.resolve();
+ steps.forEach((fn, step) => {
+ // Skip this step if we are restoring and have already completed this step before.
+ if (step < restoreStep) {
+ return;
+ }
- // 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));
- }
+ lastStep = lastStep.then(() => {
+ const {
+ currentUploads
+ } = this.getState();
+ const currentUpload = currentUploads[uploadID];
- function timerExpired() {
- var time = now();
- if (shouldInvoke(time)) {
- return trailingEdge(time);
+ if (!currentUpload) {
+ return;
+ }
+
+ const updatedUpload = { ...currentUpload,
+ step
+ };
+ this.setState({
+ currentUploads: { ...currentUploads,
+ [uploadID]: updatedUpload
+ }
+ }); // TODO give this the `updatedUpload` object as its only parameter maybe?
+ // Otherwise when more metadata may be added to the upload this would keep getting more parameters
+
+ return fn(updatedUpload.fileIDs, uploadID); // eslint-disable-line consistent-return
+ }).then(() => null);
+ }); // Not returning the `catch`ed promise, because we still want to return a rejected
+ // promise from this method if the upload failed.
+
+ lastStep.catch(err => {
+ this.emit('error', err);
+
+ _classPrivateFieldLooseBase(this, _removeUpload)[_removeUpload](uploadID);
+ });
+ return lastStep.then(() => {
+ // Set result data.
+ const {
+ currentUploads
+ } = this.getState();
+ const currentUpload = currentUploads[uploadID];
+
+ if (!currentUpload) {
+ return;
+ } // Mark postprocessing step as complete if necessary; this addresses a case where we might get
+ // stuck in the postprocessing UI while the upload is fully complete.
+ // If the postprocessing steps do not do any work, they may not emit postprocessing events at
+ // all, and never mark the postprocessing as complete. This is fine on its own but we
+ // introduced code in the @uppy/core upload-success handler to prepare postprocessing progress
+ // state if any postprocessors are registered. That is to avoid a "flash of completed state"
+ // before the postprocessing plugins can emit events.
+ //
+ // So, just in case an upload with postprocessing plugins *has* completed *without* emitting
+ // postprocessing completion, we do it instead.
+
+
+ currentUpload.fileIDs.forEach(fileID => {
+ const file = this.getFile(fileID);
+
+ if (file && file.progress.postprocess) {
+ this.emit('postprocess-complete', file);
+ }
+ });
+ const files = currentUpload.fileIDs.map(fileID => this.getFile(fileID));
+ const successful = files.filter(file => !file.error);
+ const failed = files.filter(file => file.error);
+ this.addResultData(uploadID, {
+ successful,
+ failed,
+ uploadID
+ });
+ }).then(() => {
+ // Emit completion events.
+ // This is in a separate function so that the `currentUploads` variable
+ // always refers to the latest state. In the handler right above it refers
+ // to an outdated object without the `.result` property.
+ const {
+ currentUploads
+ } = this.getState();
+
+ if (!currentUploads[uploadID]) {
+ return;
}
- // Restart the timer.
- timerId = setTimeout(timerExpired, remainingWait(time));
- }
- function trailingEdge(time) {
- timerId = undefined;
+ const currentUpload = currentUploads[uploadID];
+ const {
+ result
+ } = currentUpload;
+ this.emit('complete', result);
- // Only invoke if we have `lastArgs` which means `func` has been
- // debounced at least once.
- if (trailing && lastArgs) {
- return invokeFunc(time);
+ _classPrivateFieldLooseBase(this, _removeUpload)[_removeUpload](uploadID); // eslint-disable-next-line consistent-return
+
+
+ return result;
+ }).then(result => {
+ if (result == null) {
+ this.log(`Not setting result for an upload that has been removed: ${uploadID}`);
}
- lastArgs = lastThis = undefined;
+
return result;
- }
+ });
+}
- function cancel() {
- if (timerId !== undefined) {
- clearTimeout(timerId);
- }
- lastInvokeTime = 0;
- lastArgs = lastCallTime = lastThis = timerId = undefined;
+Uppy.VERSION = require('../package.json').version;
+module.exports = Uppy;
+module.exports.Uppy = Uppy;
+module.exports.UIPlugin = UIPlugin;
+module.exports.BasePlugin = BasePlugin;
+module.exports.debugLogger = debugLogger;
+},{"../package.json":74,"./BasePlugin":57,"./UIPlugin":58,"./getFileName":59,"./loggers":61,"./supportsUploadProgress":62,"@transloadit/prettier-bytes":2,"@uppy/store-default":63,"@uppy/utils/lib/Translator":65,"@uppy/utils/lib/generateFileID":67,"@uppy/utils/lib/getFileNameAndExtension":68,"@uppy/utils/lib/getFileType":69,"cuid":3,"lodash.throttle":7,"mime-match":8,"namespace-emitter":9}],61:[function(require,module,exports){
+"use strict";
+
+const getTimeStamp = require('@uppy/utils/lib/getTimeStamp'); // Swallow all logs, except errors.
+// default if logger is not set or debug: false
+
+
+const justErrorsLogger = {
+ debug: (...args) => {},
+ warn: (...args) => {},
+ error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args)
+}; // Print logs to console with namespace + timestamp,
+// set by logger: Uppy.debugLogger or debug: true
+
+const debugLogger = {
+ debug: (...args) => console.debug(`[Uppy] [${getTimeStamp()}]`, ...args),
+ warn: (...args) => console.warn(`[Uppy] [${getTimeStamp()}]`, ...args),
+ error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args)
+};
+module.exports = {
+ justErrorsLogger,
+ debugLogger
+};
+},{"@uppy/utils/lib/getTimeStamp":70}],62:[function(require,module,exports){
+"use strict";
+
+// Edge 15.x does not fire 'progress' events on uploads.
+// See https://github.com/transloadit/uppy/issues/945
+// And https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12224510/
+module.exports = function supportsUploadProgress(userAgent) {
+ // Allow passing in userAgent for tests
+ if (userAgent == null) {
+ userAgent = typeof navigator !== 'undefined' ? navigator.userAgent : null;
+ } // Assume it works because basically everything supports progress events.
+
+
+ if (!userAgent) return true;
+ const m = /Edge\/(\d+\.\d+)/.exec(userAgent);
+ if (!m) return true;
+ const edgeVersion = m[1];
+ let [major, minor] = edgeVersion.split('.');
+ major = parseInt(major, 10);
+ minor = parseInt(minor, 10); // Worked before:
+ // Edge 40.15063.0.0
+ // Microsoft EdgeHTML 15.15063
+
+ if (major < 15 || major === 15 && minor < 15063) {
+ return true;
+ } // Fixed in:
+ // Microsoft EdgeHTML 18.18218
+
+
+ if (major > 18 || major === 18 && minor >= 18218) {
+ return true;
+ } // other versions don't work.
+
+
+ return false;
+};
+},{}],63:[function(require,module,exports){
+"use strict";
+
+/**
+ * Default store that keeps state in a simple object.
+ */
+class DefaultStore {
+ constructor() {
+ this.state = {};
+ this.callbacks = [];
}
- function flush() {
- return timerId === undefined ? result : trailingEdge(now());
+ getState() {
+ return this.state;
}
- function debounced() {
- var time = now(),
- isInvoking = shouldInvoke(time);
+ setState(patch) {
+ const prevState = { ...this.state
+ };
+ const nextState = { ...this.state,
+ ...patch
+ };
+ this.state = nextState;
- lastArgs = arguments;
- lastThis = this;
- lastCallTime = time;
+ this._publish(prevState, nextState, patch);
+ }
- 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;
+ subscribe(listener) {
+ this.callbacks.push(listener);
+ return () => {
+ // Remove the listener.
+ this.callbacks.splice(this.callbacks.indexOf(listener), 1);
+ };
}
- debounced.cancel = cancel;
- debounced.flush = flush;
- return debounced;
+
+ _publish(...args) {
+ this.callbacks.forEach(listener => {
+ listener(...args);
+ });
+ }
+
}
-/**
- * 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);
+DefaultStore.VERSION = require('../package.json').version;
+
+module.exports = function defaultStore() {
+ return new DefaultStore();
+};
+},{"../package.json":64}],64:[function(require,module,exports){
+module.exports={
+ "name": "@uppy/store-default",
+ "description": "The default simple object-based store for Uppy.",
+ "version": "2.0.0-alpha.0",
+ "license": "MIT",
+ "main": "lib/index.js",
+ "types": "types/index.d.ts",
+ "keywords": [
+ "file uploader",
+ "uppy",
+ "uppy-store"
+ ],
+ "homepage": "https://uppy.io",
+ "bugs": {
+ "url": "https://github.com/transloadit/uppy/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/transloadit/uppy.git"
+ }
+}
+
+},{}],65:[function(require,module,exports){
+arguments[4][48][0].apply(exports,arguments)
+},{"./hasProperty":71,"dup":48}],66:[function(require,module,exports){
+"use strict";
+
+const isDOMElement = require('./isDOMElement');
+/**
+ * Find a DOM element.
*
- * // Cancel the trailing throttled invocation.
- * jQuery(window).on('popstate', throttled.cancel);
+ * @param {Node|string} element
+ * @returns {Node|null}
*/
-function throttle(func, wait, options) {
- var leading = true,
- trailing = true;
- if (typeof func != 'function') {
- throw new TypeError(FUNC_ERROR_TEXT);
+
+module.exports = function findDOMElement(element, context = document) {
+ if (typeof element === 'string') {
+ return context.querySelector(element);
}
- if (isObject(options)) {
- leading = 'leading' in options ? !!options.leading : leading;
- trailing = 'trailing' in options ? !!options.trailing : trailing;
+
+ if (isDOMElement(element)) {
+ return element;
}
- return debounce(func, wait, {
- 'leading': leading,
- 'maxWait': wait,
- 'trailing': trailing
- });
-}
+};
+},{"./isDOMElement":72}],67:[function(require,module,exports){
+"use strict";
/**
- * 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
+ * Takes a file object and turns it into fileID, by converting file.name to lowercase,
+ * removing extra characters and adding type, size and lastModified
*
- * _.isObject(null);
- * // => false
+ * @param {object} file
+ * @returns {string} the fileID
*/
-function isObject(value) {
- var type = typeof value;
- return !!value && (type == 'object' || type == 'function');
+module.exports = function generateFileID(file) {
+ // It's tempting to do `[items].filter(Boolean).join('-')` here, but that
+ // is slower! simple string concatenation is fast
+ let id = 'uppy';
+
+ if (typeof file.name === 'string') {
+ id += `-${encodeFilename(file.name.toLowerCase())}`;
+ }
+
+ if (file.type !== undefined) {
+ id += `-${file.type}`;
+ }
+
+ if (file.meta && typeof file.meta.relativePath === 'string') {
+ id += `-${encodeFilename(file.meta.relativePath.toLowerCase())}`;
+ }
+
+ if (file.data.size !== undefined) {
+ id += `-${file.data.size}`;
+ }
+
+ if (file.data.lastModified !== undefined) {
+ id += `-${file.data.lastModified}`;
+ }
+
+ return id;
+};
+
+function encodeFilename(name) {
+ let suffix = '';
+ return name.replace(/[^A-Z0-9]/ig, character => {
+ suffix += `-${encodeCharacter(character)}`;
+ return '/';
+ }) + suffix;
+}
+
+function encodeCharacter(character) {
+ return character.charCodeAt(0).toString(32);
}
+},{}],68:[function(require,module,exports){
+"use strict";
/**
- * 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
+ * Takes a full filename string and returns an object {name, extension}
*
- * _.isObjectLike(null);
- * // => false
+ * @param {string} fullFileName
+ * @returns {object} {name, extension}
*/
-function isObjectLike(value) {
- return !!value && typeof value == 'object';
+module.exports = function getFileNameAndExtension(fullFileName) {
+ const lastDot = fullFileName.lastIndexOf('.'); // these count as no extension: "no-dot", "trailing-dot."
+
+ if (lastDot === -1 || lastDot === fullFileName.length - 1) {
+ return {
+ name: fullFileName,
+ extension: undefined
+ };
+ }
+
+ return {
+ name: fullFileName.slice(0, lastDot),
+ extension: fullFileName.slice(lastDot + 1)
+ };
+};
+},{}],69:[function(require,module,exports){
+"use strict";
+
+const getFileNameAndExtension = require('./getFileNameAndExtension');
+
+const mimeTypes = require('./mimeTypes');
+
+module.exports = function getFileType(file) {
+ let fileExtension = file.name ? getFileNameAndExtension(file.name).extension : null;
+ fileExtension = fileExtension ? fileExtension.toLowerCase() : null;
+
+ if (file.type) {
+ // if mime type is set in the file object already, use that
+ return file.type;
+ }
+
+ if (fileExtension && mimeTypes[fileExtension]) {
+ // else, see if we can map extension to a mime type
+ return mimeTypes[fileExtension];
+ } // if all fails, fall back to a generic byte stream type
+
+
+ return 'application/octet-stream';
+};
+},{"./getFileNameAndExtension":68,"./mimeTypes":73}],70:[function(require,module,exports){
+"use strict";
+
+/**
+ * Returns a timestamp in the format of `hours:minutes:seconds`
+ */
+module.exports = function getTimeStamp() {
+ const date = new Date();
+ const hours = pad(date.getHours().toString());
+ const minutes = pad(date.getMinutes().toString());
+ const seconds = pad(date.getSeconds().toString());
+ return `${hours}:${minutes}:${seconds}`;
+};
+/**
+ * Adds zero to strings shorter than two characters
+ */
+
+
+function pad(str) {
+ return str.length !== 2 ? 0 + str : str;
}
+},{}],71:[function(require,module,exports){
+arguments[4][53][0].apply(exports,arguments)
+},{"dup":53}],72:[function(require,module,exports){
+"use strict";
/**
- * 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
+ * Check if an object is a DOM element. Duck-typing based on `nodeType`.
*
- * _.isSymbol('abc');
- * // => false
+ * @param {*} obj
*/
-function isSymbol(value) {
- return typeof value == 'symbol' ||
- (isObjectLike(value) && objectToString.call(value) == symbolTag);
+module.exports = function isDOMElement(obj) {
+ return obj && typeof obj === 'object' && obj.nodeType === Node.ELEMENT_NODE;
+};
+},{}],73:[function(require,module,exports){
+"use strict";
+
+// ___Why not add the mime-types package?
+// It's 19.7kB gzipped, and we only need mime types for well-known extensions (for file previews).
+// ___Where to take new extensions from?
+// https://github.com/jshttp/mime-db/blob/master/db.json
+module.exports = {
+ md: 'text/markdown',
+ markdown: 'text/markdown',
+ mp4: 'video/mp4',
+ mp3: 'audio/mp3',
+ svg: 'image/svg+xml',
+ jpg: 'image/jpeg',
+ png: 'image/png',
+ gif: 'image/gif',
+ heic: 'image/heic',
+ heif: 'image/heif',
+ yaml: 'text/yaml',
+ yml: 'text/yaml',
+ csv: 'text/csv',
+ tsv: 'text/tab-separated-values',
+ tab: 'text/tab-separated-values',
+ avi: 'video/x-msvideo',
+ mks: 'video/x-matroska',
+ mkv: 'video/x-matroska',
+ mov: 'video/quicktime',
+ doc: 'application/msword',
+ docm: 'application/vnd.ms-word.document.macroenabled.12',
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ dot: 'application/msword',
+ dotm: 'application/vnd.ms-word.template.macroenabled.12',
+ dotx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
+ xla: 'application/vnd.ms-excel',
+ xlam: 'application/vnd.ms-excel.addin.macroenabled.12',
+ xlc: 'application/vnd.ms-excel',
+ xlf: 'application/x-xliff+xml',
+ xlm: 'application/vnd.ms-excel',
+ xls: 'application/vnd.ms-excel',
+ xlsb: 'application/vnd.ms-excel.sheet.binary.macroenabled.12',
+ xlsm: 'application/vnd.ms-excel.sheet.macroenabled.12',
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ xlt: 'application/vnd.ms-excel',
+ xltm: 'application/vnd.ms-excel.template.macroenabled.12',
+ xltx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
+ xlw: 'application/vnd.ms-excel',
+ txt: 'text/plain',
+ text: 'text/plain',
+ conf: 'text/plain',
+ log: 'text/plain',
+ pdf: 'application/pdf',
+ zip: 'application/zip',
+ '7z': 'application/x-7z-compressed',
+ rar: 'application/x-rar-compressed',
+ tar: 'application/x-tar',
+ gz: 'application/gzip',
+ dmg: 'application/x-apple-diskimage'
+};
+},{}],74:[function(require,module,exports){
+module.exports={
+ "name": "@uppy/core",
+ "description": "Core module for the extensible JavaScript file upload widget with support for drag&drop, resumable uploads, previews, restrictions, file processing/encoding, remote providers like Instagram, Dropbox, Google Drive, S3 and more :dog:",
+ "version": "2.0.0-alpha.0",
+ "license": "MIT",
+ "main": "lib/index.js",
+ "style": "dist/style.min.css",
+ "types": "types/index.d.ts",
+ "keywords": [
+ "file uploader",
+ "uppy",
+ "uppy-plugin"
+ ],
+ "homepage": "https://uppy.io",
+ "bugs": {
+ "url": "https://github.com/transloadit/uppy/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/transloadit/uppy.git"
+ },
+ "dependencies": {
+ "@transloadit/prettier-bytes": "0.0.7",
+ "@uppy/store-default": "file:../store-default",
+ "@uppy/utils": "file:../utils",
+ "exorcist": "^2.0.0",
+ "lodash.throttle": "^4.1.1",
+ "mime-match": "^1.0.2",
+ "namespace-emitter": "^2.0.1",
+ "cuid": "^2.1.1",
+ "preact": "^10.5.13"
+ }
}
+},{}],75:[function(require,module,exports){
+"use strict";
+
+var _class, _temp;
+
+const {
+ BasePlugin
+} = require('@uppy/core');
+
+const getDroppedFiles = require('@uppy/utils/lib/getDroppedFiles');
+
+const toArray = require('@uppy/utils/lib/toArray');
/**
- * 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
+ * Drop Target plugin
*
- * _.toNumber('3.2');
- * // => 3.2
*/
-function toNumber(value) {
- if (typeof value == 'number') {
- return value;
- }
- if (isSymbol(value)) {
- return NAN;
+
+
+module.exports = (_temp = _class = class DropTarget extends BasePlugin {
+ constructor(uppy, opts) {
+ super(uppy, opts);
+
+ this.addFiles = files => {
+ const descriptors = files.map(file => ({
+ source: this.id,
+ name: file.name,
+ type: file.type,
+ data: file,
+ meta: {
+ // path of the file relative to the ancestor directory the user selected.
+ // e.g. 'docs/Old Prague/airbnb.pdf'
+ relativePath: file.relativePath || null
+ }
+ }));
+
+ try {
+ this.uppy.addFiles(descriptors);
+ } catch (err) {
+ this.uppy.log(err);
+ }
+ };
+
+ this.handleDrop = event => {
+ event.preventDefault();
+ event.stopPropagation();
+ clearTimeout(this.removeDragOverClassTimeout); // 2. Remove dragover class
+
+ event.currentTarget.classList.remove('uppy-is-drag-over');
+ this.setPluginState({
+ isDraggingOver: false
+ }); // 3. Add all dropped files
+
+ this.uppy.log('[DropTarget] Files were dropped');
+
+ const logDropError = error => {
+ this.uppy.log(error, 'error');
+ };
+
+ getDroppedFiles(event.dataTransfer, {
+ logDropError
+ }).then(files => this.addFiles(files));
+ };
+
+ this.handleDragOver = event => {
+ event.preventDefault();
+ event.stopPropagation(); // 1. Add a small (+) icon on drop
+ // (and prevent browsers from interpreting this as files being _moved_ into the browser,
+ // https://github.com/transloadit/uppy/issues/1978)
+
+ event.dataTransfer.dropEffect = 'copy';
+ clearTimeout(this.removeDragOverClassTimeout);
+ event.currentTarget.classList.add('uppy-is-drag-over');
+ this.setPluginState({
+ isDraggingOver: true
+ });
+ };
+
+ this.handleDragLeave = event => {
+ event.preventDefault();
+ event.stopPropagation();
+ const {
+ currentTarget
+ } = event;
+ clearTimeout(this.removeDragOverClassTimeout); // Timeout against flickering, this solution is taken from drag-drop library.
+ // Solution with 'pointer-events: none' didn't work across browsers.
+
+ this.removeDragOverClassTimeout = setTimeout(() => {
+ currentTarget.classList.remove('uppy-is-drag-over');
+ this.setPluginState({
+ isDraggingOver: false
+ });
+ }, 50);
+ };
+
+ this.addListeners = () => {
+ const {
+ target
+ } = this.opts;
+
+ if (target instanceof Element) {
+ this.nodes = [target];
+ } else if (typeof target === 'string') {
+ this.nodes = toArray(document.querySelectorAll(target));
+ }
+
+ if (!this.nodes && !this.nodes.length > 0) {
+ throw new Error(`"${target}" does not match any HTML elements`);
+ }
+
+ this.nodes.forEach(node => {
+ node.addEventListener('dragover', this.handleDragOver, false);
+ node.addEventListener('dragleave', this.handleDragLeave, false);
+ node.addEventListener('drop', this.handleDrop, false);
+ });
+ };
+
+ this.removeListeners = () => {
+ if (this.nodes) {
+ this.nodes.forEach(node => {
+ node.removeEventListener('dragover', this.handleDragOver, false);
+ node.removeEventListener('dragleave', this.handleDragLeave, false);
+ node.removeEventListener('drop', this.handleDrop, false);
+ });
+ }
+ };
+
+ this.type = 'acquirer';
+ this.id = this.opts.id || 'DropTarget';
+ this.title = 'Drop Target'; // Default options
+
+ const defaultOpts = {
+ target: null
+ }; // Merge default options with the ones set by user
+
+ this.opts = { ...defaultOpts,
+ ...opts
+ };
+ this.removeDragOverClassTimeout = null;
}
- if (isObject(value)) {
- var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
- value = isObject(other) ? (other + '') : other;
+
+ install() {
+ this.setPluginState({
+ isDraggingOver: false
+ });
+ this.addListeners();
}
- if (typeof value != 'string') {
- return value === 0 ? value : +value;
+
+ uninstall() {
+ this.removeListeners();
}
- 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;
+}, _class.VERSION = require('../package.json').version, _temp);
+},{"../package.json":82,"@uppy/core":60,"@uppy/utils/lib/getDroppedFiles":76,"@uppy/utils/lib/toArray":81}],76:[function(require,module,exports){
+"use strict";
-}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],55:[function(require,module,exports){
-var wildcard = require('wildcard');
-var reMimePartSplit = /[\/\+\.]/;
+const webkitGetAsEntryApi = require('./utils/webkitGetAsEntryApi/index');
+const fallbackApi = require('./utils/fallbackApi');
/**
- # mime-match
+ * Returns a promise that resolves to the array of dropped files (if a folder is dropped, and browser supports folder parsing - promise resolves to the flat array of all files in all directories).
+ * Each file has .relativePath prop appended to it (e.g. "/docs/Prague/ticket_from_prague_to_ufa.pdf") if browser supports it. Otherwise it's undefined.
+ *
+ * @param {DataTransfer} dataTransfer
+ * @param {Function} logDropError - a function that's called every time some folder or some file error out (e.g. because of the folder name being too long on Windows). Notice that resulting promise will always be resolved anyway.
+ *
+ * @returns {Promise} - Array<File>
+ */
- 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
+module.exports = function getDroppedFiles(dataTransfer, {
+ logDropError = () => {}
+} = {}) {
+ // Get all files from all subdirs. Works (at least) in Chrome, Mozilla, and Safari
+ if (dataTransfer.items && dataTransfer.items[0] && 'webkitGetAsEntry' in dataTransfer.items[0]) {
+ return webkitGetAsEntryApi(dataTransfer, logDropError); // Otherwise just return all first-order files
+ }
- <<< example.js
+ return fallbackApi(dataTransfer);
+};
+},{"./utils/fallbackApi":77,"./utils/webkitGetAsEntryApi/index":80}],77:[function(require,module,exports){
+"use strict";
-**/
-module.exports = function(target, pattern) {
- function test(pattern) {
- var result = wildcard(pattern, target, reMimePartSplit);
+const toArray = require('../../toArray'); // .files fallback, should be implemented in any browser
- // ensure that we have a valid mime type (should have two parts)
- return result && result.length >= 2;
- }
- return pattern ? test(pattern.split(';')[0]) : test;
+module.exports = function fallbackApi(dataTransfer) {
+ const files = toArray(dataTransfer.files);
+ return Promise.resolve(files);
};
+},{"../../toArray":81}],78:[function(require,module,exports){
+"use strict";
-},{"wildcard":62}],56:[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)
+ * Recursive function, calls the original callback() when the directory is entirely parsed.
+ *
+ * @param {FileSystemDirectoryReader} directoryReader
+ * @param {Array} oldEntries
+ * @param {Function} logDropError
+ * @param {Function} callback - called with ([ all files and directories in that directoryReader ])
+ */
+module.exports = function getFilesAndDirectoriesFromDirectory(directoryReader, oldEntries, logDropError, {
+ onSuccess
+}) {
+ directoryReader.readEntries(entries => {
+ const newEntries = [...oldEntries, ...entries]; // According to the FileSystem API spec, getFilesAndDirectoriesFromDirectory() must be called until it calls the onSuccess with an empty array.
- if (toEmit.length) {
- emitAll(event, toEmit, [arg1, arg2, arg3, arg4, arg5, arg6])
+ if (entries.length) {
+ setTimeout(() => {
+ getFilesAndDirectoriesFromDirectory(directoryReader, newEntries, logDropError, {
+ onSuccess
+ });
+ }, 0); // Done iterating this particular directory
+ } else {
+ onSuccess(newEntries);
}
+ }, // Make sure we resolve on error anyway, it's fine if only one directory couldn't be parsed!
+ error => {
+ logDropError(error);
+ onSuccess(oldEntries);
+ });
+};
+},{}],79:[function(require,module,exports){
+"use strict";
+
+/**
+ * Get the relative path from the FileEntry#fullPath, because File#webkitRelativePath is always '', at least onDrop.
+ *
+ * @param {FileEntry} fileEntry
+ *
+ * @returns {string|null} - if file is not in a folder - return null (this is to be consistent with .relativePath-s of files selected from My Device). If file is in a folder - return its fullPath, e.g. '/simpsons/hi.jpeg'.
+ */
+module.exports = function getRelativePath(fileEntry) {
+ // fileEntry.fullPath - "/simpsons/hi.jpeg" or undefined (for browsers that don't support it)
+ // fileEntry.name - "hi.jpeg"
+ if (!fileEntry.fullPath || fileEntry.fullPath === `/${fileEntry.name}`) {
+ return null;
}
- /**
- * 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] = []
- }
+ return fileEntry.fullPath;
+};
+},{}],80:[function(require,module,exports){
+"use strict";
- _fns[event].push(fn)
- }
+const toArray = require('../../../toArray');
+const getRelativePath = require('./getRelativePath');
+
+const getFilesAndDirectoriesFromDirectory = require('./getFilesAndDirectoriesFromDirectory');
+
+module.exports = function webkitGetAsEntryApi(dataTransfer, logDropError) {
+ const files = [];
+ const rootPromises = [];
/**
- * 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)
+ * Returns a resolved promise, when :files array is enhanced
+ *
+ * @param {(FileSystemFileEntry|FileSystemDirectoryEntry)} entry
+ * @returns {Promise} - empty promise that resolves when :files is enhanced with a file
+ */
+
+ const createPromiseToAddFileOrParseDirectory = entry => new Promise(resolve => {
+ // This is a base call
+ if (entry.isFile) {
+ // Creates a new File object which can be used to read the file.
+ entry.file(file => {
+ file.relativePath = getRelativePath(entry);
+ files.push(file);
+ resolve();
+ }, // Make sure we resolve on error anyway, it's fine if only one file couldn't be read!
+ error => {
+ logDropError(error);
+ resolve();
+ }); // This is a recursive call
+ } else if (entry.isDirectory) {
+ const directoryReader = entry.createReader();
+ getFilesAndDirectoriesFromDirectory(directoryReader, [], logDropError, {
+ onSuccess: entries => {
+ const promises = entries.map(entry => createPromiseToAddFileOrParseDirectory(entry));
+ Promise.all(promises).then(() => resolve());
+ }
+ });
}
- this.on(event, one)
- }
+ }); // For each dropped item, - make sure it's a file/directory, and start deepening in!
- /**
- * 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
+ toArray(dataTransfer.items).forEach(item => {
+ const entry = item.webkitGetAsEntry(); // :entry can be null when we drop the url e.g.
- for (i; i < l; i++) {
- if (fns[i] !== fn) {
- keep.push(fns[i])
- }
- }
+ if (entry) {
+ rootPromises.push(createPromiseToAddFileOrParseDirectory(entry));
}
+ });
+ return Promise.all(rootPromises).then(() => files);
+};
+},{"../../../toArray":81,"./getFilesAndDirectoriesFromDirectory":78,"./getRelativePath":79}],81:[function(require,module,exports){
+"use strict";
- keep.length ? this._fns[event] = keep : delete this._fns[event]
+/**
+ * Converts list into array
+ */
+module.exports = function toArray(list) {
+ return Array.prototype.slice.call(list || [], 0);
+};
+},{}],82:[function(require,module,exports){
+module.exports={
+ "name": "@uppy/drop-target",
+ "description": "Lets your users drag and drop files on a DOM element",
+ "version": "1.0.0-alpha.0",
+ "license": "MIT",
+ "main": "lib/index.js",
+ "types": "types/index.d.ts",
+ "keywords": [
+ "file uploader",
+ "uppy",
+ "uppy-plugin",
+ "drag-drop",
+ "drag",
+ "drop",
+ "dropzone",
+ "upload"
+ ],
+ "homepage": "https://uppy.io",
+ "bugs": {
+ "url": "https://github.com/transloadit/uppy/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/transloadit/uppy.git"
+ },
+ "dependencies": {
+ "@uppy/utils": "file:../utils"
+ },
+ "peerDependencies": {
+ "@uppy/core": "^1.0.0"
+ },
+ "publishConfig": {
+ "access": "public"
}
+}
- 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)]
+},{}],83:[function(require,module,exports){
+"use strict";
- var keys = Object.keys(_fns)
- var i = 0
- var l = keys.length
+var _class, _temp;
- for (i; i < l; i++) {
- var key = keys[i]
- if (key === '*') {
- out = out.concat(_fns[key])
- }
+const {
+ BasePlugin
+} = require('@uppy/core');
- if (args.length === 2 && args[0] === key) {
- out = out.concat(_fns[key])
- break
- }
- }
+const cuid = require('cuid');
- return out
- }
+const Translator = require('@uppy/utils/lib/Translator');
- function emitAll (e, fns, args) {
- var i = 0
- var l = fns.length
+const {
+ Provider,
+ RequestClient,
+ Socket
+} = require('@uppy/companion-client');
- for (i; i < l; i++) {
- if (!fns[i]) break
- fns[i].event = e
- fns[i].apply(fns[i], args)
- }
- }
+const emitSocketProgress = require('@uppy/utils/lib/emitSocketProgress');
- return emitter
-}
+const getSocketHost = require('@uppy/utils/lib/getSocketHost');
-},{}],57:[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;
-}();
+const settle = require('@uppy/utils/lib/settle');
-},{}],58:[function(require,module,exports){
-var has = Object.prototype.hasOwnProperty
+const EventTracker = require('@uppy/utils/lib/EventTracker');
-/**
- * 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}
- */
+const ProgressTimeout = require('@uppy/utils/lib/ProgressTimeout');
-module.exports = function queryStringify (obj, prefix) {
- var pairs = []
- for (var key in obj) {
- if (!has.call(obj, key)) {
- continue
- }
+const {
+ RateLimitedQueue,
+ internalRateLimitedQueue
+} = require('@uppy/utils/src/RateLimitedQueue');
- 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('&')
-}
+const NetworkError = require('@uppy/utils/lib/NetworkError');
-},{}],59:[function(require,module,exports){
-'use strict';
+const isNetworkError = require('@uppy/utils/lib/isNetworkError');
-var has = Object.prototype.hasOwnProperty
- , undef;
+function buildResponseError(xhr, err) {
+ let error = err; // No error message
-/**
- * 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;
+ 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 = Object.assign(new Error('Upload error'), {
+ data: error
+ });
}
-}
-/**
- * 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;
+ if (isNetworkError(xhr)) {
+ error = new NetworkError(error, xhr);
+ return error;
}
-}
+ error.request = xhr;
+ return error;
+}
/**
- * Simple query string parser.
+ * Set `data.type` in the blob to `file.meta.type`,
+ * because we might have detected a more accurate file type in Uppy
+ * https://stackoverflow.com/a/50875615
*
- * @param {String} query The query string that needs to be parsed.
- * @returns {Object}
- * @api public
+ * @param {object} file File object with `data`, `size` and `meta` properties
+ * @returns {object} blob updated with the new `type` set from `file.meta.type`
*/
-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;
+function setTypeInBlob(file) {
+ const dataWithUpdatedType = file.data.slice(0, file.data.size, file.meta.type);
+ return dataWithUpdatedType;
}
-/**
- * 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 || '';
+module.exports = (_temp = _class = class XHRUpload extends BasePlugin {
+ // eslint-disable-next-line global-require
+ constructor(uppy, opts) {
+ super(uppy, opts);
+ this.type = 'uploader';
+ this.id = this.opts.id || 'XHRUpload';
+ this.title = 'XHRUpload';
+ this.defaultLocale = {
+ strings: {
+ timedOut: 'Upload stalled for %{seconds} seconds, aborting.'
+ }
+ }; // Default options
+
+ const defaultOptions = {
+ formData: true,
+ fieldName: opts.bundle ? 'files[]' : 'file',
+ method: 'post',
+ metaFields: null,
+ responseUrlFieldName: 'url',
+ bundle: false,
+ headers: {},
+ timeout: 30 * 1000,
+ limit: 5,
+ withCredentials: false,
+ responseType: '',
+
+ /**
+ * @typedef respObj
+ * @property {string} responseText
+ * @property {number} status
+ * @property {string} statusText
+ * @property {object.<string, string>} headers
+ *
+ * @param {string} responseText the response body string
+ * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
+ */
+ getResponseData(responseText) {
+ let parsedResponse = {};
+
+ try {
+ parsedResponse = JSON.parse(responseText);
+ } catch (err) {
+ this.uppy.log(err);
+ }
+
+ return parsedResponse;
+ },
+
+ /**
+ *
+ * @param {string} responseText the response body string
+ * @param {XMLHttpRequest | respObj} response the response object (XHR or similar)
+ */
+ getResponseError(_, response) {
+ let error = new Error('Upload error');
+
+ if (isNetworkError(response)) {
+ error = new NetworkError(error, response);
+ }
- var pairs = []
- , value
- , key;
+ return error;
+ },
- //
- // 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 = '';
+ /**
+ * Check if the response from the upload endpoint indicates that the upload was successful.
+ *
+ * @param {number} status the response status code
+ */
+ validateStatus(status) {
+ return status >= 200 && status < 300;
}
- key = encode(key);
- value = encode(value);
+ };
+ this.opts = { ...defaultOptions,
+ ...opts
+ };
+ this.handleUpload = this.handleUpload.bind(this); // Simultaneous upload limiting is shared across all uploads with this plugin.
- //
- // 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);
+ if (internalRateLimitedQueue in this.opts) {
+ this.requests = this.opts[internalRateLimitedQueue];
+ } else {
+ this.requests = new RateLimitedQueue(this.opts.limit);
}
- }
- return pairs.length ? prefix + pairs.join('&') : '';
-}
+ if (this.opts.bundle && !this.opts.formData) {
+ throw new Error('`opts.formData` must be true when `opts.bundle` is enabled.');
+ }
-//
-// Expose the module.
-//
-exports.stringify = querystringify;
-exports.parse = querystring;
+ this.uploaderEvents = Object.create(null);
+ }
-},{}],60:[function(require,module,exports){
-'use strict';
+ getOptions(file) {
+ const overrides = this.uppy.getState().xhrUpload;
+ const {
+ headers
+ } = this.opts;
+ const opts = { ...this.opts,
+ ...(overrides || {}),
+ ...(file.xhrUpload || {}),
+ headers: {}
+ }; // Support for `headers` as a function, only in the XHRUpload settings.
+ // Options set by other plugins in Uppy state or on the files themselves are still merged in afterward.
+ //
+ // ```js
+ // headers: (file) => ({ expires: file.meta.expires })
+ // ```
-/**
- * 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 (typeof headers === 'function') {
+ opts.headers = headers(file);
+ } else {
+ Object.assign(opts.headers, this.opts.headers);
+ }
- if (!port) return false;
+ if (overrides) {
+ Object.assign(opts.headers, overrides.headers);
+ }
- switch (protocol) {
- case 'http':
- case 'ws':
- return port !== 80;
+ if (file.xhrUpload) {
+ Object.assign(opts.headers, file.xhrUpload.headers);
+ }
- case 'https':
- case 'wss':
- return port !== 443;
+ return opts;
+ } // eslint-disable-next-line class-methods-use-this
- case 'ftp':
- return port !== 21;
- case 'gopher':
- return port !== 70;
+ addMetadata(formData, meta, opts) {
+ const metaFields = Array.isArray(opts.metaFields) ? opts.metaFields : Object.keys(meta); // Send along all fields by default.
- case 'file':
- return false;
+ metaFields.forEach(item => {
+ formData.append(item, meta[item]);
+ });
}
- return port !== 0;
-};
-
-},{}],61:[function(require,module,exports){
-(function (global){(function (){
-'use strict';
+ createFormDataUpload(file, opts) {
+ const formPost = new FormData();
+ this.addMetadata(formPost, file.meta, opts);
+ const dataWithUpdatedType = setTypeInBlob(file);
-var required = require('requires-port')
- , qs = require('querystringify')
- , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:[\\/]+/
- , protocolre = /^([a-z][a-z0-9.+-]*:)?([\\/]{1,})?([\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 +'+');
+ if (file.name) {
+ formPost.append(opts.fieldName, dataWithUpdatedType, file.meta.name);
+ } else {
+ formPost.append(opts.fieldName, dataWithUpdatedType);
+ }
-/**
- * Trim a given string.
- *
- * @param {String} str String to trim.
- * @public
- */
-function trimLeft(str) {
- return (str ? str : '').toString().replace(left, '');
-}
+ return formPost;
+ }
-/**
- * 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.
-];
+ createBundledUpload(files, opts) {
+ const formPost = new FormData();
+ const {
+ meta
+ } = this.uppy.getState();
+ this.addMetadata(formPost, meta, opts);
+ files.forEach(file => {
+ const options = this.getOptions(file);
+ const dataWithUpdatedType = setTypeInBlob(file);
-/**
- * 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 };
+ if (file.name) {
+ formPost.append(options.fieldName, dataWithUpdatedType, file.name);
+ } else {
+ formPost.append(options.fieldName, dataWithUpdatedType);
+ }
+ });
+ return formPost;
+ }
-/**
- * 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;
+ upload(file, current, total) {
+ const opts = this.getOptions(file);
+ this.uppy.log(`uploading ${current} of ${total}`);
+ return new Promise((resolve, reject) => {
+ this.uppy.emit('upload-started', file);
+ const data = opts.formData ? this.createFormDataUpload(file, opts) : file.data;
+ const xhr = new XMLHttpRequest();
+ this.uploaderEvents[file.id] = new EventTracker(this.uppy);
+ const timer = new ProgressTimeout(opts.timeout, () => {
+ xhr.abort();
+ queuedRequest.done();
+ const error = new Error(this.i18n('timedOut', {
+ seconds: Math.ceil(opts.timeout / 1000)
+ }));
+ this.uppy.emit('upload-error', file, error);
+ reject(error);
+ });
+ const id = cuid();
+ xhr.upload.addEventListener('loadstart', () => {
+ this.uppy.log(`[XHRUpload] ${id} started`);
+ });
+ xhr.upload.addEventListener('progress', ev => {
+ this.uppy.log(`[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
- if (typeof window !== 'undefined') globalVar = window;
- else if (typeof global !== 'undefined') globalVar = global;
- else if (typeof self !== 'undefined') globalVar = self;
- else globalVar = {};
+ timer.progress();
- var location = globalVar.location || {};
- loc = loc || location;
+ if (ev.lengthComputable) {
+ this.uppy.emit('upload-progress', file, {
+ uploader: this,
+ bytesUploaded: ev.loaded,
+ bytesTotal: ev.total
+ });
+ }
+ });
+ xhr.addEventListener('load', ev => {
+ this.uppy.log(`[XHRUpload] ${id} finished`);
+ timer.done();
+ queuedRequest.done();
- var finaldestination = {}
- , type = typeof loc
- , key;
+ if (this.uploaderEvents[file.id]) {
+ this.uploaderEvents[file.id].remove();
+ this.uploaderEvents[file.id] = null;
+ }
- 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 (opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {
+ const body = opts.getResponseData(xhr.responseText, xhr);
+ const uploadURL = body[opts.responseUrlFieldName];
+ const uploadResp = {
+ status: ev.target.status,
+ body,
+ uploadURL
+ };
+ this.uppy.emit('upload-success', file, uploadResp);
- if (finaldestination.slashes === undefined) {
- finaldestination.slashes = slashes.test(loc.href);
- }
- }
+ if (uploadURL) {
+ this.uppy.log(`Download ${file.name} from ${uploadURL}`);
+ }
- return finaldestination;
-}
+ return resolve(file);
+ }
-/**
- * @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.
- */
+ const body = opts.getResponseData(xhr.responseText, xhr);
+ const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));
+ const response = {
+ status: ev.target.status,
+ body
+ };
+ this.uppy.emit('upload-error', file, error, response);
+ return reject(error);
+ });
+ xhr.addEventListener('error', () => {
+ this.uppy.log(`[XHRUpload] ${id} errored`);
+ timer.done();
+ queuedRequest.done();
-/**
- * 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);
+ if (this.uploaderEvents[file.id]) {
+ this.uploaderEvents[file.id].remove();
+ this.uploaderEvents[file.id] = null;
+ }
- var match = protocolre.exec(address)
- , protocol = match[1] ? match[1].toLowerCase() : ''
- , slashes = !!(match[2] && match[2].length >= 2)
- , rest = match[2] && match[2].length === 1 ? '/' + match[3] : match[3];
+ const error = buildResponseError(xhr, opts.getResponseError(xhr.responseText, xhr));
+ this.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.
- return {
- protocol: protocol,
- slashes: slashes,
- rest: rest
- };
-}
+ xhr.withCredentials = opts.withCredentials;
-/**
- * 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;
+ if (opts.responseType !== '') {
+ xhr.responseType = opts.responseType;
+ }
- var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/'))
- , i = path.length
- , last = path[i - 1]
- , unshift = false
- , up = 0;
+ const queuedRequest = this.requests.run(() => {
+ this.uppy.emit('upload-started', file); // When using an authentication system like JWT, the bearer token goes as a header. This
+ // header needs to be fresh each time the token is refreshed so computing and setting the
+ // headers just before the upload starts enables this kind of authentication to work properly.
+ // Otherwise, half-way through the list of uploads the token could be stale and the upload would fail.
- 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--;
- }
+ const currentOpts = this.getOptions(file);
+ Object.keys(currentOpts.headers).forEach(header => {
+ xhr.setRequestHeader(header, currentOpts.headers[header]);
+ });
+ xhr.send(data);
+ return () => {
+ timer.done();
+ xhr.abort();
+ };
+ });
+ this.onFileRemove(file.id, () => {
+ queuedRequest.abort();
+ reject(new Error('File removed'));
+ });
+ this.onCancelAll(file.id, () => {
+ queuedRequest.abort();
+ reject(new Error('Upload cancelled'));
+ });
+ });
}
- if (unshift) path.unshift('');
- if (last === '.' || last === '..') path.push('');
+ uploadRemote(file) {
+ const opts = this.getOptions(file);
+ return new Promise((resolve, reject) => {
+ const fields = {};
+ const metaFields = Array.isArray(opts.metaFields) ? opts.metaFields // Send along all fields by default.
+ : Object.keys(file.meta);
+ metaFields.forEach(name => {
+ fields[name] = file.meta[name];
+ });
+ const Client = file.remote.providerOptions.provider ? Provider : RequestClient;
+ const client = new Client(this.uppy, file.remote.providerOptions);
+ client.post(file.remote.url, { ...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(res => {
+ const {
+ token
+ } = res;
+ const host = getSocketHost(file.remote.companionUrl);
+ const socket = new Socket({
+ target: `${host}/api/${token}`,
+ autoOpen: false
+ });
+ this.uploaderEvents[file.id] = new EventTracker(this.uppy);
+ this.onFileRemove(file.id, () => {
+ socket.send('pause', {});
+ queuedRequest.abort();
+ resolve(`upload ${file.id} was removed`);
+ });
+ this.onCancelAll(file.id, () => {
+ socket.send('pause', {});
+ queuedRequest.abort();
+ resolve(`upload ${file.id} was canceled`);
+ });
+ this.onRetry(file.id, () => {
+ socket.send('pause', {});
+ socket.send('resume', {});
+ });
+ this.onRetryAll(file.id, () => {
+ socket.send('pause', {});
+ socket.send('resume', {});
+ });
+ socket.on('progress', progressData => emitSocketProgress(this, progressData, file));
+ socket.on('success', data => {
+ const body = opts.getResponseData(data.response.responseText, data.response);
+ const uploadURL = body[opts.responseUrlFieldName];
+ const uploadResp = {
+ status: data.response.status,
+ body,
+ uploadURL
+ };
+ this.uppy.emit('upload-success', file, uploadResp);
+ queuedRequest.done();
- return path.join('/');
-}
+ if (this.uploaderEvents[file.id]) {
+ this.uploaderEvents[file.id].remove();
+ this.uploaderEvents[file.id] = null;
+ }
-/**
- * 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);
+ return resolve();
+ });
+ socket.on('error', errData => {
+ const resp = errData.response;
+ const error = resp ? opts.getResponseError(resp.responseText, resp) : Object.assign(new Error(errData.error.message), {
+ cause: errData.error
+ });
+ this.uppy.emit('upload-error', file, error);
+ queuedRequest.done();
- if (!(this instanceof Url)) {
- return new Url(address, location, parser);
- }
+ if (this.uploaderEvents[file.id]) {
+ this.uploaderEvents[file.id].remove();
+ this.uploaderEvents[file.id] = null;
+ }
- var relative, extracted, parse, instruction, index, key
- , instructions = rules.slice()
- , type = typeof location
- , url = this
- , i = 0;
+ reject(error);
+ });
+ const queuedRequest = this.requests.run(() => {
+ socket.open();
- //
- // 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 (file.isPaused) {
+ socket.send('pause', {});
+ }
+
+ return () => socket.close();
+ });
+ }).catch(err => {
+ this.uppy.emit('upload-error', file, err);
+ reject(err);
+ });
+ });
}
- if (parser && 'function' !== typeof parser) parser = qs.parse;
+ uploadBundle(files) {
+ return new Promise((resolve, reject) => {
+ const {
+ endpoint
+ } = this.opts;
+ const {
+ method
+ } = this.opts;
+ const optsFromState = this.uppy.getState().xhrUpload;
+ const formData = this.createBundledUpload(files, { ...this.opts,
+ ...(optsFromState || {})
+ });
+ const xhr = new XMLHttpRequest();
+ const timer = new ProgressTimeout(this.opts.timeout, () => {
+ xhr.abort();
+ const error = new Error(this.i18n('timedOut', {
+ seconds: Math.ceil(this.opts.timeout / 1000)
+ }));
+ emitError(error);
+ reject(error);
+ });
- location = lolcation(location);
+ const emitError = error => {
+ files.forEach(file => {
+ this.uppy.emit('upload-error', file, error);
+ });
+ };
- //
- // 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;
+ xhr.upload.addEventListener('loadstart', () => {
+ this.uppy.log('[XHRUpload] started uploading bundle');
+ timer.progress();
+ });
+ xhr.upload.addEventListener('progress', ev => {
+ timer.progress();
+ if (!ev.lengthComputable) return;
+ files.forEach(file => {
+ this.uppy.emit('upload-progress', file, {
+ uploader: this,
+ bytesUploaded: ev.loaded / ev.total * file.size,
+ bytesTotal: file.size
+ });
+ });
+ });
+ xhr.addEventListener('load', ev => {
+ timer.done();
- //
- // When the authority component is absent the URL starts with a path
- // component.
- //
- if (!extracted.slashes) instructions[3] = [/(.*)/, 'pathname'];
+ if (this.opts.validateStatus(ev.target.status, xhr.responseText, xhr)) {
+ const body = this.opts.getResponseData(xhr.responseText, xhr);
+ const uploadResp = {
+ status: ev.target.status,
+ body
+ };
+ files.forEach(file => {
+ this.uppy.emit('upload-success', file, uploadResp);
+ });
+ return resolve();
+ }
+
+ const error = this.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error');
+ error.request = xhr;
+ emitError(error);
+ return reject(error);
+ });
+ xhr.addEventListener('error', () => {
+ timer.done();
+ const error = this.opts.getResponseError(xhr.responseText, xhr) || new Error('Upload error');
+ emitError(error);
+ return reject(error);
+ });
+ this.uppy.on('cancel-all', () => {
+ timer.done();
+ xhr.abort();
+ });
+ xhr.open(method.toUpperCase(), endpoint, true); // IE10 does not allow setting `withCredentials` and `responseType`
+ // before `open()` is called.
- for (; i < instructions.length; i++) {
- instruction = instructions[i];
+ xhr.withCredentials = this.opts.withCredentials;
- if (typeof instruction === 'function') {
- address = instruction(address);
- continue;
- }
+ if (this.opts.responseType !== '') {
+ xhr.responseType = this.opts.responseType;
+ }
+
+ Object.keys(this.opts.headers).forEach(header => {
+ xhr.setRequestHeader(header, this.opts.headers[header]);
+ });
+ xhr.send(formData);
+ files.forEach(file => {
+ this.uppy.emit('upload-started', file);
+ });
+ });
+ }
- parse = instruction[0];
- key = instruction[1];
+ uploadFiles(files) {
+ const promises = files.map((file, i) => {
+ const current = parseInt(i, 10) + 1;
+ const total = files.length;
- 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);
- }
+ if (file.error) {
+ return Promise.reject(new Error(file.error));
}
- } 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] || '' : ''
- );
+ if (file.isRemote) {
+ return this.uploadRemote(file, current, total);
+ }
- //
- // 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();
+ return this.upload(file, current, total);
+ });
+ return settle(promises);
}
- //
- // 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);
+ onFileRemove(fileID, cb) {
+ this.uploaderEvents[fileID].on('file-removed', file => {
+ if (fileID === file.id) cb(file.id);
+ });
}
- //
- // Default to a / for pathname if none exists. This normalizes the URL
- // to always have a /
- //
- if (url.pathname.charAt(0) !== '/' && url.hostname) {
- url.pathname = '/' + url.pathname;
+ onRetry(fileID, cb) {
+ this.uploaderEvents[fileID].on('upload-retry', targetFileID => {
+ if (fileID === targetFileID) {
+ cb();
+ }
+ });
}
- //
- // 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 = '';
+ onRetryAll(fileID, cb) {
+ this.uploaderEvents[fileID].on('retry-all', () => {
+ if (!this.uppy.getFile(fileID)) return;
+ cb();
+ });
}
- //
- // 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] || '';
+ onCancelAll(fileID, cb) {
+ this.uploaderEvents[fileID].on('cancel-all', () => {
+ if (!this.uppy.getFile(fileID)) return;
+ cb();
+ });
}
- 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();
-}
+ handleUpload(fileIDs) {
+ if (fileIDs.length === 0) {
+ this.uppy.log('[XHRUpload] No files to upload!');
+ return Promise.resolve();
+ } // No limit configured by the user, and no RateLimitedQueue passed in by a "parent" plugin
+ // (basically just AwsS3) using the internal symbol
-/**
- * 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);
- }
+ if (this.opts.limit === 0 && !this.opts[internalRateLimitedQueue]) {
+ this.uppy.log('[XHRUpload] When uploading multiple files at once, consider setting the `limit` option (to `10` for example), to limit the number of concurrent uploads, which helps prevent memory and network issues: https://uppy.io/docs/xhr-upload/#limit-0', 'warning');
+ }
- url[part] = value;
- break;
+ this.uppy.log('[XHRUpload] Uploading...');
+ const files = fileIDs.map(fileID => this.uppy.getFile(fileID));
- case 'port':
- url[part] = value;
+ if (this.opts.bundle) {
+ // if bundle: true, we don’t support remote uploads
+ const isSomeFileRemote = files.some(file => file.isRemote);
- if (!required(value, url.protocol)) {
- url.host = url.hostname;
- url[part] = '';
- } else if (value) {
- url.host = url.hostname +':'+ value;
+ if (isSomeFileRemote) {
+ throw new Error('Can’t upload remote files when the `bundle: true` option is set');
}
- 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 = '';
+ if (typeof this.opts.headers === 'function') {
+ throw new TypeError('`headers` may not be a function when the `bundle: true` option is set');
}
- 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;
+ return this.uploadBundle(files);
+ }
- default:
- url[part] = value;
+ return this.uploadFiles(files).then(() => null);
}
- for (var i = 0; i < rules.length; i++) {
- var ins = rules[i];
+ install() {
+ if (this.opts.bundle) {
+ const {
+ capabilities
+ } = this.uppy.getState();
+ this.uppy.setState({
+ capabilities: { ...capabilities,
+ individualCancellation: false
+ }
+ });
+ }
- if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase();
+ this.uppy.addUploader(this.handleUpload);
}
- 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 ? '//' : '');
+ uninstall() {
+ if (this.opts.bundle) {
+ const {
+ capabilities
+ } = this.uppy.getState();
+ this.uppy.setState({
+ capabilities: { ...capabilities,
+ individualCancellation: true
+ }
+ });
+ }
- if (url.username) {
- result += url.username;
- if (url.password) result += ':'+ url.password;
- result += '@';
+ this.uppy.removeUploader(this.handleUpload);
}
- 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;
+}, _class.VERSION = require('../package.json').version, _temp);
+},{"../package.json":104,"@uppy/companion-client":89,"@uppy/core":60,"@uppy/utils/lib/EventTracker":92,"@uppy/utils/lib/NetworkError":93,"@uppy/utils/lib/ProgressTimeout":94,"@uppy/utils/lib/Translator":95,"@uppy/utils/lib/emitSocketProgress":96,"@uppy/utils/lib/getSocketHost":98,"@uppy/utils/lib/isNetworkError":100,"@uppy/utils/lib/settle":101,"@uppy/utils/src/RateLimitedQueue":102,"cuid":3}],84:[function(require,module,exports){
+arguments[4][15][0].apply(exports,arguments)
+},{"dup":15}],85:[function(require,module,exports){
+arguments[4][16][0].apply(exports,arguments)
+},{"./RequestClient":86,"./tokenStorage":90,"dup":16,"qs-stringify":11}],86:[function(require,module,exports){
+arguments[4][17][0].apply(exports,arguments)
+},{"../package.json":91,"./AuthError":84,"@uppy/utils/lib/fetchWithNetworkError":97,"dup":17}],87:[function(require,module,exports){
+arguments[4][18][0].apply(exports,arguments)
+},{"./RequestClient":86,"dup":18}],88:[function(require,module,exports){
+arguments[4][19][0].apply(exports,arguments)
+},{"dup":19,"namespace-emitter":9}],89:[function(require,module,exports){
+arguments[4][20][0].apply(exports,arguments)
+},{"./Provider":85,"./RequestClient":86,"./SearchProvider":87,"./Socket":88,"dup":20}],90:[function(require,module,exports){
+arguments[4][21][0].apply(exports,arguments)
+},{"dup":21}],91:[function(require,module,exports){
+arguments[4][22][0].apply(exports,arguments)
+},{"dup":22}],92:[function(require,module,exports){
+arguments[4][24][0].apply(exports,arguments)
+},{"dup":24}],93:[function(require,module,exports){
+arguments[4][25][0].apply(exports,arguments)
+},{"dup":25}],94:[function(require,module,exports){
+arguments[4][46][0].apply(exports,arguments)
+},{"dup":46}],95:[function(require,module,exports){
+arguments[4][48][0].apply(exports,arguments)
+},{"./hasProperty":99,"dup":48}],96:[function(require,module,exports){
+arguments[4][28][0].apply(exports,arguments)
+},{"dup":28,"lodash.throttle":7}],97:[function(require,module,exports){
+arguments[4][29][0].apply(exports,arguments)
+},{"./NetworkError":93,"dup":29}],98:[function(require,module,exports){
+arguments[4][31][0].apply(exports,arguments)
+},{"dup":31}],99:[function(require,module,exports){
+arguments[4][53][0].apply(exports,arguments)
+},{"dup":53}],100:[function(require,module,exports){
+arguments[4][54][0].apply(exports,arguments)
+},{"dup":54}],101:[function(require,module,exports){
+arguments[4][55][0].apply(exports,arguments)
+},{"dup":55}],102:[function(require,module,exports){
+const findIndex = require('./findIndex')
+
+function createCancelError () {
+ return new Error('Cancelled')
}
-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":59,"requires-port":60}],62:[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
+class RateLimitedQueue {
+ constructor (limit) {
+ if (typeof limit !== 'number' || limit === 0) {
+ this.limit = Infinity
+ } else {
+ this.limit = limit
+ }
- It works with strings:
+ this.activeRequests = 0
+ this.queuedHandlers = []
+ }
- <<< examples/strings.js
+ _call (fn) {
+ this.activeRequests += 1
- Arrays:
+ let done = false
- <<< examples/arrays.js
+ let cancelActive
+ try {
+ cancelActive = fn()
+ } catch (err) {
+ this.activeRequests -= 1
+ throw err
+ }
- Objects (matching against keys):
+ return {
+ abort: () => {
+ if (done) return
+ done = true
+ this.activeRequests -= 1
+ cancelActive()
+ this._queueNext()
+ },
- <<< examples/objects.js
+ done: () => {
+ if (done) return
+ done = true
+ this.activeRequests -= 1
+ this._queueNext()
+ },
+ }
+ }
- While the library works in Node, if you are are looking for file-based
- wildcard matching then you should have a look at:
+ _queueNext () {
+ // Do it soon but not immediately, this allows clearing out the entire queue synchronously
+ // one by one without continuously _advancing_ it (and starting new tasks before immediately
+ // aborting them)
+ Promise.resolve().then(() => {
+ this._next()
+ })
+ }
- <https://github.com/isaacs/node-glob>
-**/
+ _next () {
+ if (this.activeRequests >= this.limit) {
+ return
+ }
+ if (this.queuedHandlers.length === 0) {
+ return
+ }
-function WildcardMatcher(text, separator) {
- this.text = text = text || '';
- this.hasWild = ~text.indexOf('*');
- this.separator = separator;
- this.parts = text.split(separator);
-}
+ // Dispatch the next request, and update the abort/done handlers
+ // so that cancelling it does the Right Thing (and doesn't just try
+ // to dequeue an already-running request).
+ const next = this.queuedHandlers.shift()
+ const handler = this._call(next.fn)
+ next.abort = handler.abort
+ next.done = handler.done
+ }
-WildcardMatcher.prototype.match = function(input) {
- var matches = true;
- var parts = this.parts;
- var ii;
- var partsCount = parts.length;
- var testParts;
+ _queue (fn, options = {}) {
+ const handler = {
+ fn,
+ priority: options.priority || 0,
+ abort: () => {
+ this._dequeue(handler)
+ },
+ done: () => {
+ throw new Error('Cannot mark a queued request as done: this indicates a bug')
+ },
+ }
- if (typeof input == 'string' || input instanceof String) {
- if (!this.hasWild && this.text != input) {
- matches = false;
+ const index = findIndex(this.queuedHandlers, (other) => {
+ return handler.priority > other.priority
+ })
+ if (index === -1) {
+ this.queuedHandlers.push(handler)
} 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;
- }
- }
+ this.queuedHandlers.splice(index, 0, handler)
+ }
+ return handler
+ }
- // If matches, then return the component parts
- matches = matches && testParts;
+ _dequeue (handler) {
+ const index = this.queuedHandlers.indexOf(handler)
+ if (index !== -1) {
+ this.queuedHandlers.splice(index, 1)
}
}
- else if (typeof input.splice == 'function') {
- matches = [];
- for (ii = input.length; ii--; ) {
- if (this.match(input[ii])) {
- matches[matches.length] = input[ii];
- }
+ run (fn, queueOptions) {
+ if (this.activeRequests < this.limit) {
+ return this._call(fn)
}
+ return this._queue(fn, queueOptions)
}
- else if (typeof input == 'object') {
- matches = {};
- for (var key in input) {
- if (this.match(key)) {
- matches[key] = input[key];
+ wrapPromiseFunction (fn, queueOptions) {
+ return (...args) => {
+ let queuedRequest
+ const outerPromise = new Promise((resolve, reject) => {
+ queuedRequest = this.run(() => {
+ let cancelError
+ let innerPromise
+ try {
+ innerPromise = Promise.resolve(fn(...args))
+ } catch (err) {
+ innerPromise = Promise.reject(err)
+ }
+
+ innerPromise.then((result) => {
+ if (cancelError) {
+ reject(cancelError)
+ } else {
+ queuedRequest.done()
+ resolve(result)
+ }
+ }, (err) => {
+ if (cancelError) {
+ reject(cancelError)
+ } else {
+ queuedRequest.done()
+ reject(err)
+ }
+ })
+
+ return () => {
+ cancelError = createCancelError()
+ }
+ }, queueOptions)
+ })
+
+ outerPromise.abort = () => {
+ queuedRequest.abort()
}
+
+ return outerPromise
}
}
+}
- return matches;
-};
+module.exports = {
+ RateLimitedQueue,
+ internalRateLimitedQueue: Symbol('__queue'),
+}
-module.exports = function(text, test, separator) {
- var matcher = new WildcardMatcher(text, separator || /[\/\.]/);
- if (typeof test != 'undefined') {
- return matcher.match(test);
+},{"./findIndex":103}],103:[function(require,module,exports){
+/**
+ * Array.prototype.findIndex ponyfill for old browsers.
+ *
+ * @param {Array} array
+ * @param {Function} predicate
+ * @returns {number}
+ */
+module.exports = function findIndex (array, predicate) {
+ for (let i = 0; i < array.length; i++) {
+ if (predicate(array[i])) return i
}
+ return -1
+}
- return matcher;
-};
+},{}],104:[function(require,module,exports){
+module.exports={
+ "name": "@uppy/xhr-upload",
+ "description": "Plain and simple classic HTML multipart form uploads with Uppy, as well as uploads using the HTTP PUT method.",
+ "version": "2.0.0-alpha.0",
+ "license": "MIT",
+ "main": "lib/index.js",
+ "types": "types/index.d.ts",
+ "keywords": [
+ "file uploader",
+ "xhr",
+ "xhr upload",
+ "XMLHttpRequest",
+ "ajax",
+ "fetch",
+ "uppy",
+ "uppy-plugin"
+ ],
+ "homepage": "https://uppy.io",
+ "bugs": {
+ "url": "https://github.com/transloadit/uppy/issues"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/transloadit/uppy.git"
+ },
+ "dependencies": {
+ "@uppy/companion-client": "file:../companion-client",
+ "@uppy/utils": "file:../utils",
+ "cuid": "^2.1.1"
+ },
+ "devDependencies": {
+ "nock": "^13.1.0"
+ },
+ "peerDependencies": {
+ "@uppy/core": "^1.0.0"
+ }
+}
-},{}],63:[function(require,module,exports){
-// We need a custom build of Uppy because we do not use webpack for
-// our JS modules/build. The only way to get what you want from Uppy
-// is to use the webpack modules or to include the entire Uppy project
-// including all plugins in a single JS file. This way we can just
-// use the plugins we actually want.
-window.Uppy = {}
-Uppy.Core = require('@uppy/core')
-Uppy.Plugin = Uppy.Core.Plugin
-Uppy.XHRUpload = require('@uppy/xhr-upload')
-Uppy.AwsS3 = require('@uppy/aws-s3')
-Uppy.AwsS3Multipart = require('@uppy/aws-s3-multipart')
-Uppy.DropTarget = require('@uppy/drop-target')
-
-},{"@uppy/aws-s3":5,"@uppy/aws-s3-multipart":3,"@uppy/core":15,"@uppy/drop-target":19,"@uppy/xhr-upload":48}]},{},[63]);
+},{}]},{},[1]);