wp/wp-includes/js/dist/media-utils.js
changeset 22 8c2e4d02f4ef
parent 21 48c4eec2b7e6
equal deleted inserted replaced
21:48c4eec2b7e6 22:8c2e4d02f4ef
    50 __webpack_require__.r(__webpack_exports__);
    50 __webpack_require__.r(__webpack_exports__);
    51 
    51 
    52 // EXPORTS
    52 // EXPORTS
    53 __webpack_require__.d(__webpack_exports__, {
    53 __webpack_require__.d(__webpack_exports__, {
    54   MediaUpload: () => (/* reexport */ media_upload),
    54   MediaUpload: () => (/* reexport */ media_upload),
    55   uploadMedia: () => (/* reexport */ uploadMedia)
    55   privateApis: () => (/* reexport */ privateApis),
       
    56   transformAttachment: () => (/* reexport */ transformAttachment),
       
    57   uploadMedia: () => (/* reexport */ uploadMedia),
       
    58   validateFileSize: () => (/* reexport */ validateFileSize),
       
    59   validateMimeType: () => (/* reexport */ validateMimeType),
       
    60   validateMimeTypeForUser: () => (/* reexport */ validateMimeTypeForUser)
    56 });
    61 });
    57 
    62 
    58 ;// CONCATENATED MODULE: external ["wp","element"]
    63 ;// external ["wp","element"]
    59 const external_wp_element_namespaceObject = window["wp"]["element"];
    64 const external_wp_element_namespaceObject = window["wp"]["element"];
    60 ;// CONCATENATED MODULE: external ["wp","i18n"]
    65 ;// external ["wp","i18n"]
    61 const external_wp_i18n_namespaceObject = window["wp"]["i18n"];
    66 const external_wp_i18n_namespaceObject = window["wp"]["i18n"];
    62 ;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/components/media-upload/index.js
    67 ;// ./node_modules/@wordpress/media-utils/build-module/components/media-upload/index.js
    63 /**
    68 /**
    64  * WordPress dependencies
    69  * WordPress dependencies
    65  */
    70  */
    66 
    71 
    67 
    72 
   115     createStates: function createStates() {
   120     createStates: function createStates() {
   116       this.on('toolbar:create:featured-image', this.featuredImageToolbar, this);
   121       this.on('toolbar:create:featured-image', this.featuredImageToolbar, this);
   117       this.on('content:render:edit-image', this.editState, this);
   122       this.on('content:render:edit-image', this.editState, this);
   118       this.states.add([new wp.media.controller.FeaturedImage(), new wp.media.controller.EditImage({
   123       this.states.add([new wp.media.controller.FeaturedImage(), new wp.media.controller.EditImage({
   119         model: this.options.editImage
   124         model: this.options.editImage
       
   125       })]);
       
   126     }
       
   127   });
       
   128 };
       
   129 
       
   130 /**
       
   131  * Prepares the default frame for selecting a single media item.
       
   132  *
       
   133  * @return {window.wp.media.view.MediaFrame.Select} The default media workflow.
       
   134  */
       
   135 const getSingleMediaFrame = () => {
       
   136   const {
       
   137     wp
       
   138   } = window;
       
   139 
       
   140   // Extend the default Select frame, and use the same `createStates` method as in core,
       
   141   // but with the addition of `filterable: 'uploaded'` to the Library state, so that
       
   142   // the user can filter the media library by uploaded media.
       
   143   return wp.media.view.MediaFrame.Select.extend({
       
   144     /**
       
   145      * Create the default states on the frame.
       
   146      */
       
   147     createStates() {
       
   148       const options = this.options;
       
   149       if (this.options.states) {
       
   150         return;
       
   151       }
       
   152 
       
   153       // Add the default states.
       
   154       this.states.add([
       
   155       // Main states.
       
   156       new wp.media.controller.Library({
       
   157         library: wp.media.query(options.library),
       
   158         multiple: options.multiple,
       
   159         title: options.title,
       
   160         priority: 20,
       
   161         filterable: 'uploaded' // Allow filtering by uploaded images.
       
   162       }), new wp.media.controller.EditImage({
       
   163         model: options.editImage
   120       })]);
   164       })]);
   121     }
   165     }
   122   });
   166   });
   123 };
   167 };
   124 
   168 
   309     this.frame = new this.GalleryDetailsMediaFrame({
   353     this.frame = new this.GalleryDetailsMediaFrame({
   310       mimeType: allowedTypes,
   354       mimeType: allowedTypes,
   311       state: currentState,
   355       state: currentState,
   312       multiple,
   356       multiple,
   313       selection,
   357       selection,
   314       editing: value && value.length ? true : false
   358       editing: !!value?.length
   315     });
   359     });
   316     wp.media.frame = this.frame;
   360     wp.media.frame = this.frame;
   317     this.initializeListeners();
   361     this.initializeListeners();
   318   }
   362   }
   319 
   363 
   351     wp.media.view.settings.post = {
   395     wp.media.view.settings.post = {
   352       ...wp.media.view.settings.post,
   396       ...wp.media.view.settings.post,
   353       featuredImageId: featuredImageId || -1
   397       featuredImageId: featuredImageId || -1
   354     };
   398     };
   355   }
   399   }
       
   400 
       
   401   /**
       
   402    * Initializes the Media Library requirements for the single image flow.
       
   403    *
       
   404    * @return {void}
       
   405    */
       
   406   buildAndSetSingleMediaFrame() {
       
   407     const {
       
   408       wp
       
   409     } = window;
       
   410     const {
       
   411       allowedTypes,
       
   412       multiple = false,
       
   413       title = (0,external_wp_i18n_namespaceObject.__)('Select or Upload Media'),
       
   414       value
       
   415     } = this.props;
       
   416     const frameConfig = {
       
   417       title,
       
   418       multiple
       
   419     };
       
   420     if (!!allowedTypes) {
       
   421       frameConfig.library = {
       
   422         type: allowedTypes
       
   423       };
       
   424     }
       
   425 
       
   426     // If a frame already exists, remove it.
       
   427     if (this.frame) {
       
   428       this.frame.remove();
       
   429     }
       
   430     const singleImageFrame = getSingleMediaFrame();
       
   431     const attachments = getAttachmentsCollection(value);
       
   432     const selection = new wp.media.model.Selection(attachments.models, {
       
   433       props: attachments.props.toJSON()
       
   434     });
       
   435     this.frame = new singleImageFrame({
       
   436       mimeType: allowedTypes,
       
   437       multiple,
       
   438       selection,
       
   439       ...frameConfig
       
   440     });
       
   441     wp.media.frame = this.frame;
       
   442   }
   356   componentWillUnmount() {
   443   componentWillUnmount() {
   357     this.frame?.remove();
   444     this.frame?.remove();
   358   }
   445   }
   359   onUpdate(selections) {
   446   onUpdate(selections) {
   360     const {
   447     const {
   425       onClose
   512       onClose
   426     } = this.props;
   513     } = this.props;
   427     if (onClose) {
   514     if (onClose) {
   428       onClose();
   515       onClose();
   429     }
   516     }
       
   517     this.frame.detach();
   430   }
   518   }
   431   updateCollection() {
   519   updateCollection() {
   432     const frameContent = this.frame.content.get();
   520     const frameContent = this.frame.content.get();
   433     if (frameContent && frameContent.collection) {
   521     if (frameContent && frameContent.collection) {
   434       const collection = frameContent.collection;
   522       const collection = frameContent.collection;
   443       collection.more();
   531       collection.more();
   444     }
   532     }
   445   }
   533   }
   446   openModal() {
   534   openModal() {
   447     const {
   535     const {
   448       allowedTypes,
       
   449       gallery = false,
   536       gallery = false,
   450       unstableFeaturedImageFlow = false,
   537       unstableFeaturedImageFlow = false,
   451       modalClass,
   538       modalClass
   452       multiple = false,
       
   453       title = (0,external_wp_i18n_namespaceObject.__)('Select or Upload Media')
       
   454     } = this.props;
   539     } = this.props;
   455     const {
       
   456       wp
       
   457     } = window;
       
   458     if (gallery) {
   540     if (gallery) {
   459       this.buildAndSetGalleryFrame();
   541       this.buildAndSetGalleryFrame();
   460     } else {
   542     } else {
   461       const frameConfig = {
   543       this.buildAndSetSingleMediaFrame();
   462         title,
       
   463         multiple
       
   464       };
       
   465       if (!!allowedTypes) {
       
   466         frameConfig.library = {
       
   467           type: allowedTypes
       
   468         };
       
   469       }
       
   470       this.frame = wp.media(frameConfig);
       
   471     }
   544     }
   472     if (modalClass) {
   545     if (modalClass) {
   473       this.frame.$el.addClass(modalClass);
   546       this.frame.$el.addClass(modalClass);
   474     }
   547     }
   475     if (unstableFeaturedImageFlow) {
   548     if (unstableFeaturedImageFlow) {
   484     });
   557     });
   485   }
   558   }
   486 }
   559 }
   487 /* harmony default export */ const media_upload = (MediaUpload);
   560 /* harmony default export */ const media_upload = (MediaUpload);
   488 
   561 
   489 ;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/components/index.js
   562 ;// ./node_modules/@wordpress/media-utils/build-module/components/index.js
   490 
   563 
   491 
   564 
   492 ;// CONCATENATED MODULE: external ["wp","apiFetch"]
   565 ;// external ["wp","blob"]
       
   566 const external_wp_blob_namespaceObject = window["wp"]["blob"];
       
   567 ;// external ["wp","apiFetch"]
   493 const external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
   568 const external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
   494 var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
   569 var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
   495 ;// CONCATENATED MODULE: external ["wp","blob"]
   570 ;// ./node_modules/@wordpress/media-utils/build-module/utils/flatten-form-data.js
   496 const external_wp_blob_namespaceObject = window["wp"]["blob"];
   571 /**
   497 ;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/upload-media.js
   572  * Determines whether the passed argument appears to be a plain object.
       
   573  *
       
   574  * @param data The object to inspect.
       
   575  */
       
   576 function isPlainObject(data) {
       
   577   return data !== null && typeof data === 'object' && Object.getPrototypeOf(data) === Object.prototype;
       
   578 }
       
   579 
       
   580 /**
       
   581  * Recursively flatten data passed to form data, to allow using multi-level objects.
       
   582  *
       
   583  * @param {FormData}      formData Form data object.
       
   584  * @param {string}        key      Key to amend to form data object
       
   585  * @param {string|Object} data     Data to be amended to form data.
       
   586  */
       
   587 function flattenFormData(formData, key, data) {
       
   588   if (isPlainObject(data)) {
       
   589     for (const [name, value] of Object.entries(data)) {
       
   590       flattenFormData(formData, `${key}[${name}]`, value);
       
   591     }
       
   592   } else if (data !== undefined) {
       
   593     formData.append(key, String(data));
       
   594   }
       
   595 }
       
   596 
       
   597 ;// ./node_modules/@wordpress/media-utils/build-module/utils/transform-attachment.js
       
   598 /**
       
   599  * Internal dependencies
       
   600  */
       
   601 
       
   602 /**
       
   603  * Transforms an attachment object from the REST API shape into the shape expected by the block editor and other consumers.
       
   604  *
       
   605  * @param attachment REST API attachment object.
       
   606  */
       
   607 function transformAttachment(attachment) {
       
   608   var _attachment$caption$r;
       
   609   // eslint-disable-next-line camelcase
       
   610   const {
       
   611     alt_text,
       
   612     source_url,
       
   613     ...savedMediaProps
       
   614   } = attachment;
       
   615   return {
       
   616     ...savedMediaProps,
       
   617     alt: attachment.alt_text,
       
   618     caption: (_attachment$caption$r = attachment.caption?.raw) !== null && _attachment$caption$r !== void 0 ? _attachment$caption$r : '',
       
   619     title: attachment.title.raw,
       
   620     url: attachment.source_url,
       
   621     poster: attachment._embedded?.['wp:featuredmedia']?.[0]?.source_url || undefined
       
   622   };
       
   623 }
       
   624 
       
   625 ;// ./node_modules/@wordpress/media-utils/build-module/utils/upload-to-server.js
   498 /**
   626 /**
   499  * WordPress dependencies
   627  * WordPress dependencies
   500  */
   628  */
   501 
   629 
   502 
   630 
   503 
   631 /**
   504 const noop = () => {};
   632  * Internal dependencies
   505 
   633  */
       
   634 
       
   635 
       
   636 async function uploadToServer(file, additionalData = {}, signal) {
       
   637   // Create upload payload.
       
   638   const data = new FormData();
       
   639   data.append('file', file, file.name || file.type.replace('/', '.'));
       
   640   for (const [key, value] of Object.entries(additionalData)) {
       
   641     flattenFormData(data, key, value);
       
   642   }
       
   643   return transformAttachment(await external_wp_apiFetch_default()({
       
   644     // This allows the video block to directly get a video's poster image.
       
   645     path: '/wp/v2/media?_embed=wp:featuredmedia',
       
   646     body: data,
       
   647     method: 'POST',
       
   648     signal
       
   649   }));
       
   650 }
       
   651 
       
   652 ;// ./node_modules/@wordpress/media-utils/build-module/utils/upload-error.js
       
   653 /**
       
   654  * MediaError class.
       
   655  *
       
   656  * Small wrapper around the `Error` class
       
   657  * to hold an error code and a reference to a file object.
       
   658  */
       
   659 class UploadError extends Error {
       
   660   constructor({
       
   661     code,
       
   662     message,
       
   663     file,
       
   664     cause
       
   665   }) {
       
   666     super(message, {
       
   667       cause
       
   668     });
       
   669     Object.setPrototypeOf(this, new.target.prototype);
       
   670     this.code = code;
       
   671     this.file = file;
       
   672   }
       
   673 }
       
   674 
       
   675 ;// ./node_modules/@wordpress/media-utils/build-module/utils/validate-mime-type.js
       
   676 /**
       
   677  * WordPress dependencies
       
   678  */
       
   679 
       
   680 
       
   681 /**
       
   682  * Internal dependencies
       
   683  */
       
   684 
       
   685 
       
   686 /**
       
   687  * Verifies if the caller (e.g. a block) supports this mime type.
       
   688  *
       
   689  * @param file         File object.
       
   690  * @param allowedTypes List of allowed mime types.
       
   691  */
       
   692 function validateMimeType(file, allowedTypes) {
       
   693   if (!allowedTypes) {
       
   694     return;
       
   695   }
       
   696 
       
   697   // Allowed type specified by consumer.
       
   698   const isAllowedType = allowedTypes.some(allowedType => {
       
   699     // If a complete mimetype is specified verify if it matches exactly the mime type of the file.
       
   700     if (allowedType.includes('/')) {
       
   701       return allowedType === file.type;
       
   702     }
       
   703     // Otherwise a general mime type is used, and we should verify if the file mimetype starts with it.
       
   704     return file.type.startsWith(`${allowedType}/`);
       
   705   });
       
   706   if (file.type && !isAllowedType) {
       
   707     throw new UploadError({
       
   708       code: 'MIME_TYPE_NOT_SUPPORTED',
       
   709       message: (0,external_wp_i18n_namespaceObject.sprintf)(
       
   710       // translators: %s: file name.
       
   711       (0,external_wp_i18n_namespaceObject.__)('%s: Sorry, this file type is not supported here.'), file.name),
       
   712       file
       
   713     });
       
   714   }
       
   715 }
       
   716 
       
   717 ;// ./node_modules/@wordpress/media-utils/build-module/utils/get-mime-types-array.js
   506 /**
   718 /**
   507  * Browsers may use unexpected mime types, and they differ from browser to browser.
   719  * Browsers may use unexpected mime types, and they differ from browser to browser.
   508  * This function computes a flexible array of mime types from the mime type structured provided by the server.
   720  * This function computes a flexible array of mime types from the mime type structured provided by the server.
   509  * Converts { jpg|jpeg|jpe: "image/jpeg" } into [ "image/jpeg", "image/jpg", "image/jpeg", "image/jpe" ]
   721  * Converts { jpg|jpeg|jpe: "image/jpeg" } into [ "image/jpeg", "image/jpg", "image/jpeg", "image/jpe" ]
   510  * The computation of this array instead of directly using the object,
       
   511  * solves the problem in chrome where mp3 files have audio/mp3 as mime type instead of audio/mpeg.
       
   512  * https://bugs.chromium.org/p/chromium/issues/detail?id=227004
       
   513  *
   722  *
   514  * @param {?Object} wpMimeTypesObject Mime type object received from the server.
   723  * @param {?Object} wpMimeTypesObject Mime type object received from the server.
   515  *                                    Extensions are keys separated by '|' and values are mime types associated with an extension.
   724  *                                    Extensions are keys separated by '|' and values are mime types associated with an extension.
   516  *
   725  *
   517  * @return {?Array} An array of mime types or the parameter passed if it was "falsy".
   726  * @return An array of mime types or null
   518  */
   727  */
   519 function getMimeTypesArray(wpMimeTypesObject) {
   728 function getMimeTypesArray(wpMimeTypesObject) {
   520   if (!wpMimeTypesObject) {
   729   if (!wpMimeTypesObject) {
   521     return wpMimeTypesObject;
   730     return null;
   522   }
   731   }
   523   return Object.entries(wpMimeTypesObject).map(([extensionsString, mime]) => {
   732   return Object.entries(wpMimeTypesObject).flatMap(([extensionsString, mime]) => {
   524     const [type] = mime.split('/');
   733     const [type] = mime.split('/');
   525     const extensions = extensionsString.split('|');
   734     const extensions = extensionsString.split('|');
   526     return [mime, ...extensions.map(extension => `${type}/${extension}`)];
   735     return [mime, ...extensions.map(extension => `${type}/${extension}`)];
   527   }).flat();
   736   });
   528 }
   737 }
   529 
   738 
   530 /**
   739 ;// ./node_modules/@wordpress/media-utils/build-module/utils/validate-mime-type-for-user.js
   531  *	Media Upload is used by audio, image, gallery, video, and file blocks to
   740 /**
   532  *	handle uploading a media file when a file upload button is activated.
   741  * WordPress dependencies
   533  *
   742  */
   534  *	TODO: future enhancement to add an upload indicator.
   743 
   535  *
   744 
   536  * @param {Object}   $0                    Parameters object passed to the function.
   745 /**
   537  * @param {?Array}   $0.allowedTypes       Array with the types of media that can be uploaded, if unset all types are allowed.
   746  * Internal dependencies
   538  * @param {?Object}  $0.additionalData     Additional data to include in the request.
   747  */
   539  * @param {Array}    $0.filesList          List of files.
   748 
   540  * @param {?number}  $0.maxUploadFileSize  Maximum upload size in bytes allowed for the site.
   749 
   541  * @param {Function} $0.onError            Function called when an error happens.
   750 
   542  * @param {Function} $0.onFileChange       Function called each time a file or a temporary representation of the file is available.
   751 /**
   543  * @param {?Object}  $0.wpAllowedMimeTypes List of allowed mime types and file extensions.
   752  * Verifies if the user is allowed to upload this mime type.
   544  */
   753  *
   545 async function uploadMedia({
   754  * @param file               File object.
       
   755  * @param wpAllowedMimeTypes List of allowed mime types and file extensions.
       
   756  */
       
   757 function validateMimeTypeForUser(file, wpAllowedMimeTypes) {
       
   758   // Allowed types for the current WP_User.
       
   759   const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes);
       
   760   if (!allowedMimeTypesForUser) {
       
   761     return;
       
   762   }
       
   763   const isAllowedMimeTypeForUser = allowedMimeTypesForUser.includes(file.type);
       
   764   if (file.type && !isAllowedMimeTypeForUser) {
       
   765     throw new UploadError({
       
   766       code: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',
       
   767       message: (0,external_wp_i18n_namespaceObject.sprintf)(
       
   768       // translators: %s: file name.
       
   769       (0,external_wp_i18n_namespaceObject.__)('%s: Sorry, you are not allowed to upload this file type.'), file.name),
       
   770       file
       
   771     });
       
   772   }
       
   773 }
       
   774 
       
   775 ;// ./node_modules/@wordpress/media-utils/build-module/utils/validate-file-size.js
       
   776 /**
       
   777  * WordPress dependencies
       
   778  */
       
   779 
       
   780 
       
   781 /**
       
   782  * Internal dependencies
       
   783  */
       
   784 
       
   785 
       
   786 /**
       
   787  * Verifies whether the file is within the file upload size limits for the site.
       
   788  *
       
   789  * @param file              File object.
       
   790  * @param maxUploadFileSize Maximum upload size in bytes allowed for the site.
       
   791  */
       
   792 function validateFileSize(file, maxUploadFileSize) {
       
   793   // Don't allow empty files to be uploaded.
       
   794   if (file.size <= 0) {
       
   795     throw new UploadError({
       
   796       code: 'EMPTY_FILE',
       
   797       message: (0,external_wp_i18n_namespaceObject.sprintf)(
       
   798       // translators: %s: file name.
       
   799       (0,external_wp_i18n_namespaceObject.__)('%s: This file is empty.'), file.name),
       
   800       file
       
   801     });
       
   802   }
       
   803   if (maxUploadFileSize && file.size > maxUploadFileSize) {
       
   804     throw new UploadError({
       
   805       code: 'SIZE_ABOVE_LIMIT',
       
   806       message: (0,external_wp_i18n_namespaceObject.sprintf)(
       
   807       // translators: %s: file name.
       
   808       (0,external_wp_i18n_namespaceObject.__)('%s: This file exceeds the maximum upload size for this site.'), file.name),
       
   809       file
       
   810     });
       
   811   }
       
   812 }
       
   813 
       
   814 ;// ./node_modules/@wordpress/media-utils/build-module/utils/upload-media.js
       
   815 /**
       
   816  * WordPress dependencies
       
   817  */
       
   818 
       
   819 
       
   820 
       
   821 /**
       
   822  * Internal dependencies
       
   823  */
       
   824 
       
   825 
       
   826 
       
   827 
       
   828 
       
   829 
       
   830 /**
       
   831  * Upload a media file when the file upload button is activated
       
   832  * or when adding a file to the editor via drag & drop.
       
   833  *
       
   834  * @param $0                    Parameters object passed to the function.
       
   835  * @param $0.allowedTypes       Array with the types of media that can be uploaded, if unset all types are allowed.
       
   836  * @param $0.additionalData     Additional data to include in the request.
       
   837  * @param $0.filesList          List of files.
       
   838  * @param $0.maxUploadFileSize  Maximum upload size in bytes allowed for the site.
       
   839  * @param $0.onError            Function called when an error happens.
       
   840  * @param $0.onFileChange       Function called each time a file or a temporary representation of the file is available.
       
   841  * @param $0.wpAllowedMimeTypes List of allowed mime types and file extensions.
       
   842  * @param $0.signal             Abort signal.
       
   843  * @param $0.multiple           Whether to allow multiple files to be uploaded.
       
   844  */
       
   845 function uploadMedia({
       
   846   wpAllowedMimeTypes,
   546   allowedTypes,
   847   allowedTypes,
   547   additionalData = {},
   848   additionalData = {},
   548   filesList,
   849   filesList,
   549   maxUploadFileSize,
   850   maxUploadFileSize,
   550   onError = noop,
   851   onError,
   551   onFileChange,
   852   onFileChange,
   552   wpAllowedMimeTypes = null
   853   signal,
       
   854   multiple = true
   553 }) {
   855 }) {
   554   // Cast filesList to array.
   856   if (!multiple && filesList.length > 1) {
   555   const files = [...filesList];
   857     onError?.(new Error((0,external_wp_i18n_namespaceObject.__)('Only one file can be used here.')));
       
   858     return;
       
   859   }
       
   860   const validFiles = [];
   556   const filesSet = [];
   861   const filesSet = [];
   557   const setAndUpdateFiles = (idx, value) => {
   862   const setAndUpdateFiles = (index, value) => {
   558     (0,external_wp_blob_namespaceObject.revokeBlobURL)(filesSet[idx]?.url);
   863     // For client-side media processing, this is handled by the upload-media package.
   559     filesSet[idx] = value;
   864     if (!window.__experimentalMediaProcessing) {
   560     onFileChange(filesSet.filter(Boolean));
   865       if (filesSet[index]?.url) {
       
   866         (0,external_wp_blob_namespaceObject.revokeBlobURL)(filesSet[index].url);
       
   867       }
       
   868     }
       
   869     filesSet[index] = value;
       
   870     onFileChange?.(filesSet.filter(attachment => attachment !== null));
   561   };
   871   };
   562 
   872   for (const mediaFile of filesList) {
   563   // Allowed type specified by consumer.
       
   564   const isAllowedType = fileType => {
       
   565     if (!allowedTypes) {
       
   566       return true;
       
   567     }
       
   568     return allowedTypes.some(allowedType => {
       
   569       // If a complete mimetype is specified verify if it matches exactly the mime type of the file.
       
   570       if (allowedType.includes('/')) {
       
   571         return allowedType === fileType;
       
   572       }
       
   573       // Otherwise a general mime type is used and we should verify if the file mimetype starts with it.
       
   574       return fileType.startsWith(`${allowedType}/`);
       
   575     });
       
   576   };
       
   577 
       
   578   // Allowed types for the current WP_User.
       
   579   const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes);
       
   580   const isAllowedMimeTypeForUser = fileType => {
       
   581     return allowedMimeTypesForUser.includes(fileType);
       
   582   };
       
   583   const validFiles = [];
       
   584   for (const mediaFile of files) {
       
   585     // Verify if user is allowed to upload this mime type.
   873     // Verify if user is allowed to upload this mime type.
   586     // Defer to the server when type not detected.
   874     // Defer to the server when type not detected.
   587     if (allowedMimeTypesForUser && mediaFile.type && !isAllowedMimeTypeForUser(mediaFile.type)) {
   875     try {
   588       onError({
   876       validateMimeTypeForUser(mediaFile, wpAllowedMimeTypes);
   589         code: 'MIME_TYPE_NOT_ALLOWED_FOR_USER',
   877     } catch (error) {
   590         message: (0,external_wp_i18n_namespaceObject.sprintf)(
   878       onError?.(error);
   591         // translators: %s: file name.
   879       continue;
   592         (0,external_wp_i18n_namespaceObject.__)('%s: Sorry, you are not allowed to upload this file type.'), mediaFile.name),
   880     }
   593         file: mediaFile
   881 
       
   882     // Check if the caller (e.g. a block) supports this mime type.
       
   883     // Defer to the server when type not detected.
       
   884     try {
       
   885       validateMimeType(mediaFile, allowedTypes);
       
   886     } catch (error) {
       
   887       onError?.(error);
       
   888       continue;
       
   889     }
       
   890 
       
   891     // Verify if file is greater than the maximum file upload size allowed for the site.
       
   892     try {
       
   893       validateFileSize(mediaFile, maxUploadFileSize);
       
   894     } catch (error) {
       
   895       onError?.(error);
       
   896       continue;
       
   897     }
       
   898     validFiles.push(mediaFile);
       
   899 
       
   900     // For client-side media processing, this is handled by the upload-media package.
       
   901     if (!window.__experimentalMediaProcessing) {
       
   902       // Set temporary URL to create placeholder media file, this is replaced
       
   903       // with final file from media gallery when upload is `done` below.
       
   904       filesSet.push({
       
   905         url: (0,external_wp_blob_namespaceObject.createBlobURL)(mediaFile)
   594       });
   906       });
   595       continue;
   907       onFileChange?.(filesSet);
   596     }
   908     }
   597 
   909   }
   598     // Check if the block supports this mime type.
   910   validFiles.map(async (file, index) => {
   599     // Defer to the server when type not detected.
       
   600     if (mediaFile.type && !isAllowedType(mediaFile.type)) {
       
   601       onError({
       
   602         code: 'MIME_TYPE_NOT_SUPPORTED',
       
   603         message: (0,external_wp_i18n_namespaceObject.sprintf)(
       
   604         // translators: %s: file name.
       
   605         (0,external_wp_i18n_namespaceObject.__)('%s: Sorry, this file type is not supported here.'), mediaFile.name),
       
   606         file: mediaFile
       
   607       });
       
   608       continue;
       
   609     }
       
   610 
       
   611     // Verify if file is greater than the maximum file upload size allowed for the site.
       
   612     if (maxUploadFileSize && mediaFile.size > maxUploadFileSize) {
       
   613       onError({
       
   614         code: 'SIZE_ABOVE_LIMIT',
       
   615         message: (0,external_wp_i18n_namespaceObject.sprintf)(
       
   616         // translators: %s: file name.
       
   617         (0,external_wp_i18n_namespaceObject.__)('%s: This file exceeds the maximum upload size for this site.'), mediaFile.name),
       
   618         file: mediaFile
       
   619       });
       
   620       continue;
       
   621     }
       
   622 
       
   623     // Don't allow empty files to be uploaded.
       
   624     if (mediaFile.size <= 0) {
       
   625       onError({
       
   626         code: 'EMPTY_FILE',
       
   627         message: (0,external_wp_i18n_namespaceObject.sprintf)(
       
   628         // translators: %s: file name.
       
   629         (0,external_wp_i18n_namespaceObject.__)('%s: This file is empty.'), mediaFile.name),
       
   630         file: mediaFile
       
   631       });
       
   632       continue;
       
   633     }
       
   634     validFiles.push(mediaFile);
       
   635 
       
   636     // Set temporary URL to create placeholder media file, this is replaced
       
   637     // with final file from media gallery when upload is `done` below.
       
   638     filesSet.push({
       
   639       url: (0,external_wp_blob_namespaceObject.createBlobURL)(mediaFile)
       
   640     });
       
   641     onFileChange(filesSet);
       
   642   }
       
   643   for (let idx = 0; idx < validFiles.length; ++idx) {
       
   644     const mediaFile = validFiles[idx];
       
   645     try {
   911     try {
   646       var _savedMedia$caption$r;
   912       const attachment = await uploadToServer(file, additionalData, signal);
   647       const savedMedia = await createMediaFromFile(mediaFile, additionalData);
   913       setAndUpdateFiles(index, attachment);
   648       // eslint-disable-next-line camelcase
       
   649       const {
       
   650         alt_text,
       
   651         source_url,
       
   652         ...savedMediaProps
       
   653       } = savedMedia;
       
   654       const mediaObject = {
       
   655         ...savedMediaProps,
       
   656         alt: savedMedia.alt_text,
       
   657         caption: (_savedMedia$caption$r = savedMedia.caption?.raw) !== null && _savedMedia$caption$r !== void 0 ? _savedMedia$caption$r : '',
       
   658         title: savedMedia.title.raw,
       
   659         url: savedMedia.source_url
       
   660       };
       
   661       setAndUpdateFiles(idx, mediaObject);
       
   662     } catch (error) {
   914     } catch (error) {
   663       // Reset to empty on failure.
   915       // Reset to empty on failure.
   664       setAndUpdateFiles(idx, null);
   916       setAndUpdateFiles(index, null);
       
   917 
       
   918       // @wordpress/api-fetch throws any response that isn't in the 200 range as-is.
   665       let message;
   919       let message;
   666       if (error.message) {
   920       if (typeof error === 'object' && error !== null && 'message' in error) {
   667         message = error.message;
   921         message = typeof error.message === 'string' ? error.message : String(error.message);
   668       } else {
   922       } else {
   669         message = (0,external_wp_i18n_namespaceObject.sprintf)(
   923         message = (0,external_wp_i18n_namespaceObject.sprintf)(
   670         // translators: %s: file name
   924         // translators: %s: file name
   671         (0,external_wp_i18n_namespaceObject.__)('Error while uploading file %s to the media library.'), mediaFile.name);
   925         (0,external_wp_i18n_namespaceObject.__)('Error while uploading file %s to the media library.'), file.name);
   672       }
   926       }
   673       onError({
   927       onError?.(new UploadError({
   674         code: 'GENERAL',
   928         code: 'GENERAL',
   675         message,
   929         message,
   676         file: mediaFile
   930         file,
   677       });
   931         cause: error instanceof Error ? error : undefined
   678     }
   932       }));
   679   }
   933     }
   680 }
   934   });
   681 
   935 }
   682 /**
   936 
   683  * @param {File}    file           Media File to Save.
   937 ;// ./node_modules/@wordpress/media-utils/build-module/utils/sideload-to-server.js
   684  * @param {?Object} additionalData Additional data to include in the request.
   938 /**
   685  *
   939  * WordPress dependencies
   686  * @return {Promise} Media Object Promise.
   940  */
   687  */
   941 
   688 function createMediaFromFile(file, additionalData) {
   942 
       
   943 /**
       
   944  * Internal dependencies
       
   945  */
       
   946 
       
   947 
       
   948 
       
   949 
       
   950 /**
       
   951  * Uploads a file to the server without creating an attachment.
       
   952  *
       
   953  * @param file           Media File to Save.
       
   954  * @param attachmentId   Parent attachment ID.
       
   955  * @param additionalData Additional data to include in the request.
       
   956  * @param signal         Abort signal.
       
   957  *
       
   958  * @return The saved attachment.
       
   959  */
       
   960 async function sideloadToServer(file, attachmentId, additionalData = {}, signal) {
   689   // Create upload payload.
   961   // Create upload payload.
   690   const data = new window.FormData();
   962   const data = new FormData();
   691   data.append('file', file, file.name || file.type.replace('/', '.'));
   963   data.append('file', file, file.name || file.type.replace('/', '.'));
   692   if (additionalData) {
   964   for (const [key, value] of Object.entries(additionalData)) {
   693     Object.entries(additionalData).forEach(([key, value]) => data.append(key, value));
   965     flattenFormData(data, key, value);
   694   }
   966   }
   695   return external_wp_apiFetch_default()({
   967   return transformAttachment(await external_wp_apiFetch_default()({
   696     path: '/wp/v2/media',
   968     path: `/wp/v2/media/${attachmentId}/sideload`,
   697     body: data,
   969     body: data,
   698     method: 'POST'
   970     method: 'POST',
   699   });
   971     signal
   700 }
   972   }));
   701 
   973 }
   702 ;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/utils/index.js
   974 
   703 
   975 ;// ./node_modules/@wordpress/media-utils/build-module/utils/sideload-media.js
   704 
   976 /**
   705 ;// CONCATENATED MODULE: ./node_modules/@wordpress/media-utils/build-module/index.js
   977  * WordPress dependencies
       
   978  */
       
   979 
       
   980 
       
   981 /**
       
   982  * Internal dependencies
       
   983  */
       
   984 
       
   985 
       
   986 
       
   987 const noop = () => {};
       
   988 /**
       
   989  * Uploads a file to the server without creating an attachment.
       
   990  *
       
   991  * @param $0                Parameters object passed to the function.
       
   992  * @param $0.file           Media File to Save.
       
   993  * @param $0.attachmentId   Parent attachment ID.
       
   994  * @param $0.additionalData Additional data to include in the request.
       
   995  * @param $0.signal         Abort signal.
       
   996  * @param $0.onFileChange   Function called each time a file or a temporary representation of the file is available.
       
   997  * @param $0.onError        Function called when an error happens.
       
   998  */
       
   999 async function sideloadMedia({
       
  1000   file,
       
  1001   attachmentId,
       
  1002   additionalData = {},
       
  1003   signal,
       
  1004   onFileChange,
       
  1005   onError = noop
       
  1006 }) {
       
  1007   try {
       
  1008     const attachment = await sideloadToServer(file, attachmentId, additionalData, signal);
       
  1009     onFileChange?.([attachment]);
       
  1010   } catch (error) {
       
  1011     let message;
       
  1012     if (error instanceof Error) {
       
  1013       message = error.message;
       
  1014     } else {
       
  1015       message = (0,external_wp_i18n_namespaceObject.sprintf)(
       
  1016       // translators: %s: file name
       
  1017       (0,external_wp_i18n_namespaceObject.__)('Error while sideloading file %s to the server.'), file.name);
       
  1018     }
       
  1019     onError(new UploadError({
       
  1020       code: 'GENERAL',
       
  1021       message,
       
  1022       file,
       
  1023       cause: error instanceof Error ? error : undefined
       
  1024     }));
       
  1025   }
       
  1026 }
       
  1027 
       
  1028 ;// external ["wp","privateApis"]
       
  1029 const external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
       
  1030 ;// ./node_modules/@wordpress/media-utils/build-module/lock-unlock.js
       
  1031 /**
       
  1032  * WordPress dependencies
       
  1033  */
       
  1034 
       
  1035 const {
       
  1036   lock,
       
  1037   unlock
       
  1038 } = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.', '@wordpress/media-utils');
       
  1039 
       
  1040 ;// ./node_modules/@wordpress/media-utils/build-module/private-apis.js
       
  1041 /**
       
  1042  * Internal dependencies
       
  1043  */
       
  1044 
       
  1045 
       
  1046 
       
  1047 /**
       
  1048  * Private @wordpress/media-utils APIs.
       
  1049  */
       
  1050 const privateApis = {};
       
  1051 lock(privateApis, {
       
  1052   sideloadMedia: sideloadMedia
       
  1053 });
       
  1054 
       
  1055 ;// ./node_modules/@wordpress/media-utils/build-module/index.js
       
  1056 
       
  1057 
       
  1058 
       
  1059 
       
  1060 
   706 
  1061 
   707 
  1062 
   708 
  1063 
   709 (window.wp = window.wp || {}).mediaUtils = __webpack_exports__;
  1064 (window.wp = window.wp || {}).mediaUtils = __webpack_exports__;
   710 /******/ })()
  1065 /******/ })()