[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/js/dist/ -> upload-media.js (source)

   1  "use strict";
   2  var wp;
   3  (wp ||= {}).uploadMedia = (() => {
   4    var __create = Object.create;
   5    var __defProp = Object.defineProperty;
   6    var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
   7    var __getOwnPropNames = Object.getOwnPropertyNames;
   8    var __getProtoOf = Object.getPrototypeOf;
   9    var __hasOwnProp = Object.prototype.hasOwnProperty;
  10    var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
  11      get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
  12    }) : x)(function(x) {
  13      if (typeof require !== "undefined") return require.apply(this, arguments);
  14      throw Error('Dynamic require of "' + x + '" is not supported');
  15    });
  16    var __commonJS = (cb, mod) => function __require2() {
  17      return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  18    };
  19    var __export = (target, all) => {
  20      for (var name in all)
  21        __defProp(target, name, { get: all[name], enumerable: true });
  22    };
  23    var __copyProps = (to, from, except, desc) => {
  24      if (from && typeof from === "object" || typeof from === "function") {
  25        for (let key of __getOwnPropNames(from))
  26          if (!__hasOwnProp.call(to, key) && key !== except)
  27            __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  28      }
  29      return to;
  30    };
  31    var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  32      // If the importer is in node compatibility mode or this is not an ESM
  33      // file that has been converted to a CommonJS file using a Babel-
  34      // compatible transform (i.e. "__esModule" has not been set), then set
  35      // "default" to the CommonJS "module.exports" for node compatibility.
  36      isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  37      mod
  38    ));
  39    var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  40  
  41    // package-external:@wordpress/data
  42    var require_data = __commonJS({
  43      "package-external:@wordpress/data"(exports, module) {
  44        module.exports = window.wp.data;
  45      }
  46    });
  47  
  48    // package-external:@wordpress/url
  49    var require_url = __commonJS({
  50      "package-external:@wordpress/url"(exports, module) {
  51        module.exports = window.wp.url;
  52      }
  53    });
  54  
  55    // package-external:@wordpress/i18n
  56    var require_i18n = __commonJS({
  57      "package-external:@wordpress/i18n"(exports, module) {
  58        module.exports = window.wp.i18n;
  59      }
  60    });
  61  
  62    // package-external:@wordpress/blob
  63    var require_blob = __commonJS({
  64      "package-external:@wordpress/blob"(exports, module) {
  65        module.exports = window.wp.blob;
  66      }
  67    });
  68  
  69    // package-external:@wordpress/private-apis
  70    var require_private_apis = __commonJS({
  71      "package-external:@wordpress/private-apis"(exports, module) {
  72        module.exports = window.wp.privateApis;
  73      }
  74    });
  75  
  76    // package-external:@wordpress/element
  77    var require_element = __commonJS({
  78      "package-external:@wordpress/element"(exports, module) {
  79        module.exports = window.wp.element;
  80      }
  81    });
  82  
  83    // package-external:@wordpress/compose
  84    var require_compose = __commonJS({
  85      "package-external:@wordpress/compose"(exports, module) {
  86        module.exports = window.wp.compose;
  87      }
  88    });
  89  
  90    // vendor-external:react/jsx-runtime
  91    var require_jsx_runtime = __commonJS({
  92      "vendor-external:react/jsx-runtime"(exports, module) {
  93        module.exports = window.ReactJSXRuntime;
  94      }
  95    });
  96  
  97    // packages/upload-media/build-module/index.mjs
  98    var index_exports = {};
  99    __export(index_exports, {
 100      MediaUploadProvider: () => provider_default,
 101      UploadError: () => UploadError,
 102      clearFeatureDetectionCache: () => clearFeatureDetectionCache,
 103      detectClientSideMediaSupport: () => detectClientSideMediaSupport,
 104      isClientSideMediaSupported: () => isClientSideMediaSupported,
 105      store: () => store
 106    });
 107  
 108    // packages/upload-media/build-module/store/index.mjs
 109    var import_data = __toESM(require_data(), 1);
 110  
 111    // packages/upload-media/build-module/store/types.mjs
 112    var Type = /* @__PURE__ */ ((Type2) => {
 113      Type2["Unknown"] = "REDUX_UNKNOWN";
 114      Type2["Add"] = "ADD_ITEM";
 115      Type2["Prepare"] = "PREPARE_ITEM";
 116      Type2["Cancel"] = "CANCEL_ITEM";
 117      Type2["Remove"] = "REMOVE_ITEM";
 118      Type2["RetryItem"] = "RETRY_ITEM";
 119      Type2["PauseItem"] = "PAUSE_ITEM";
 120      Type2["ResumeItem"] = "RESUME_ITEM";
 121      Type2["PauseQueue"] = "PAUSE_QUEUE";
 122      Type2["ResumeQueue"] = "RESUME_QUEUE";
 123      Type2["OperationStart"] = "OPERATION_START";
 124      Type2["OperationFinish"] = "OPERATION_FINISH";
 125      Type2["AddOperations"] = "ADD_OPERATIONS";
 126      Type2["CacheBlobUrl"] = "CACHE_BLOB_URL";
 127      Type2["RevokeBlobUrls"] = "REVOKE_BLOB_URLS";
 128      Type2["UpdateProgress"] = "UPDATE_PROGRESS";
 129      Type2["UpdateSettings"] = "UPDATE_SETTINGS";
 130      return Type2;
 131    })(Type || {});
 132    var ItemStatus = /* @__PURE__ */ ((ItemStatus2) => {
 133      ItemStatus2["Queued"] = "QUEUED";
 134      ItemStatus2["Processing"] = "PROCESSING";
 135      ItemStatus2["Paused"] = "PAUSED";
 136      ItemStatus2["Uploaded"] = "UPLOADED";
 137      ItemStatus2["Error"] = "ERROR";
 138      return ItemStatus2;
 139    })(ItemStatus || {});
 140    var OperationType = /* @__PURE__ */ ((OperationType2) => {
 141      OperationType2["Prepare"] = "PREPARE";
 142      OperationType2["Upload"] = "UPLOAD";
 143      OperationType2["ResizeCrop"] = "RESIZE_CROP";
 144      OperationType2["Rotate"] = "ROTATE";
 145      OperationType2["TranscodeImage"] = "TRANSCODE_IMAGE";
 146      OperationType2["ThumbnailGeneration"] = "THUMBNAIL_GENERATION";
 147      OperationType2["Finalize"] = "FINALIZE";
 148      return OperationType2;
 149    })(OperationType || {});
 150  
 151    // packages/upload-media/build-module/store/constants.mjs
 152    var STORE_NAME = "core/upload-media";
 153    var DEFAULT_MAX_CONCURRENT_UPLOADS = 5;
 154    var DEFAULT_MAX_CONCURRENT_IMAGE_PROCESSING = 2;
 155    var CLIENT_SIDE_SUPPORTED_MIME_TYPES = [
 156      "image/jpeg",
 157      "image/png",
 158      "image/gif",
 159      "image/webp",
 160      "image/avif"
 161    ];
 162  
 163    // packages/upload-media/build-module/store/reducer.mjs
 164    var noop = () => {
 165    };
 166    var DEFAULT_STATE = {
 167      queue: [],
 168      queueStatus: "active",
 169      blobUrls: {},
 170      settings: {
 171        mediaUpload: noop,
 172        maxConcurrentUploads: DEFAULT_MAX_CONCURRENT_UPLOADS,
 173        maxConcurrentImageProcessing: DEFAULT_MAX_CONCURRENT_IMAGE_PROCESSING
 174      }
 175    };
 176    function reducer(state = DEFAULT_STATE, action = { type: Type.Unknown }) {
 177      switch (action.type) {
 178        case Type.PauseQueue: {
 179          return {
 180            ...state,
 181            queueStatus: "paused"
 182          };
 183        }
 184        case Type.ResumeQueue: {
 185          return {
 186            ...state,
 187            queueStatus: "active"
 188          };
 189        }
 190        case Type.PauseItem:
 191          return {
 192            ...state,
 193            queue: state.queue.map(
 194              (item) => item.id === action.id ? {
 195                ...item,
 196                status: ItemStatus.Paused
 197              } : item
 198            )
 199          };
 200        case Type.ResumeItem:
 201          return {
 202            ...state,
 203            queue: state.queue.map(
 204              (item) => item.id === action.id ? {
 205                ...item,
 206                status: ItemStatus.Processing
 207              } : item
 208            )
 209          };
 210        case Type.Add:
 211          return {
 212            ...state,
 213            queue: [...state.queue, action.item]
 214          };
 215        case Type.Cancel:
 216          return {
 217            ...state,
 218            queue: state.queue.map(
 219              (item) => item.id === action.id ? {
 220                ...item,
 221                error: action.error
 222              } : item
 223            )
 224          };
 225        case Type.RetryItem:
 226          return {
 227            ...state,
 228            queue: state.queue.map(
 229              (item) => item.id === action.id ? {
 230                ...item,
 231                status: ItemStatus.Processing,
 232                error: void 0,
 233                retryCount: (item.retryCount ?? 0) + 1
 234              } : item
 235            )
 236          };
 237        case Type.Remove:
 238          return {
 239            ...state,
 240            queue: state.queue.filter((item) => item.id !== action.id)
 241          };
 242        case Type.OperationStart: {
 243          return {
 244            ...state,
 245            queue: state.queue.map(
 246              (item) => item.id === action.id ? {
 247                ...item,
 248                currentOperation: action.operation
 249              } : item
 250            )
 251          };
 252        }
 253        case Type.AddOperations:
 254          return {
 255            ...state,
 256            queue: state.queue.map((item) => {
 257              if (item.id !== action.id) {
 258                return item;
 259              }
 260              return {
 261                ...item,
 262                operations: [
 263                  ...item.operations || [],
 264                  ...action.operations
 265                ]
 266              };
 267            })
 268          };
 269        case Type.OperationFinish:
 270          return {
 271            ...state,
 272            queue: state.queue.map((item) => {
 273              if (item.id !== action.id) {
 274                return item;
 275              }
 276              const operations = item.operations ? item.operations.slice(1) : [];
 277              const attachment = item.attachment || action.item.attachment ? {
 278                ...item.attachment,
 279                ...action.item.attachment
 280              } : void 0;
 281              return {
 282                ...item,
 283                currentOperation: void 0,
 284                operations,
 285                ...action.item,
 286                attachment,
 287                additionalData: {
 288                  ...item.additionalData,
 289                  ...action.item.additionalData
 290                }
 291              };
 292            })
 293          };
 294        case Type.CacheBlobUrl: {
 295          const blobUrls = state.blobUrls[action.id] || [];
 296          return {
 297            ...state,
 298            blobUrls: {
 299              ...state.blobUrls,
 300              [action.id]: [...blobUrls, action.blobUrl]
 301            }
 302          };
 303        }
 304        case Type.RevokeBlobUrls: {
 305          const newBlobUrls = { ...state.blobUrls };
 306          delete newBlobUrls[action.id];
 307          return {
 308            ...state,
 309            blobUrls: newBlobUrls
 310          };
 311        }
 312        case Type.UpdateProgress:
 313          return {
 314            ...state,
 315            queue: state.queue.map(
 316              (item) => item.id === action.id ? {
 317                ...item,
 318                progress: action.progress
 319              } : item
 320            )
 321          };
 322        case Type.UpdateSettings: {
 323          return {
 324            ...state,
 325            settings: {
 326              ...state.settings,
 327              ...action.settings
 328            }
 329          };
 330        }
 331      }
 332      return state;
 333    }
 334    var reducer_default = reducer;
 335  
 336    // packages/upload-media/build-module/store/selectors.mjs
 337    var selectors_exports = {};
 338    __export(selectors_exports, {
 339      getItems: () => getItems,
 340      getSettings: () => getSettings,
 341      isUploading: () => isUploading,
 342      isUploadingById: () => isUploadingById,
 343      isUploadingByUrl: () => isUploadingByUrl
 344    });
 345    function getItems(state) {
 346      return state.queue;
 347    }
 348    function isUploading(state) {
 349      return state.queue.length >= 1;
 350    }
 351    function isUploadingByUrl(state, url) {
 352      return state.queue.some(
 353        (item) => item.attachment?.url === url || item.sourceUrl === url
 354      );
 355    }
 356    function isUploadingById(state, attachmentId) {
 357      return state.queue.some(
 358        (item) => item.attachment?.id === attachmentId || item.sourceAttachmentId === attachmentId
 359      );
 360    }
 361    function getSettings(state) {
 362      return state.settings;
 363    }
 364  
 365    // packages/upload-media/build-module/store/private-selectors.mjs
 366    var private_selectors_exports = {};
 367    __export(private_selectors_exports, {
 368      getActiveImageProcessingCount: () => getActiveImageProcessingCount,
 369      getActiveUploadCount: () => getActiveUploadCount,
 370      getAllItems: () => getAllItems,
 371      getBlobUrls: () => getBlobUrls,
 372      getFailedItems: () => getFailedItems,
 373      getItem: () => getItem,
 374      getItemProgress: () => getItemProgress,
 375      getPausedUploadForPost: () => getPausedUploadForPost,
 376      getPendingImageProcessing: () => getPendingImageProcessing,
 377      getPendingUploads: () => getPendingUploads,
 378      hasPendingItemsByParentId: () => hasPendingItemsByParentId,
 379      isBatchUploaded: () => isBatchUploaded,
 380      isPaused: () => isPaused,
 381      isUploadingToPost: () => isUploadingToPost
 382    });
 383    function getAllItems(state) {
 384      return state.queue;
 385    }
 386    function getItem(state, id) {
 387      return state.queue.find((item) => item.id === id);
 388    }
 389    function isBatchUploaded(state, batchId) {
 390      const batchItems = state.queue.filter(
 391        (item) => batchId === item.batchId
 392      );
 393      return batchItems.length === 0;
 394    }
 395    function isUploadingToPost(state, postOrAttachmentId) {
 396      return state.queue.some(
 397        (item) => item.currentOperation === OperationType.Upload && item.additionalData.post === postOrAttachmentId
 398      );
 399    }
 400    function getPausedUploadForPost(state, postOrAttachmentId) {
 401      return state.queue.find(
 402        (item) => item.status === ItemStatus.Paused && item.additionalData.post === postOrAttachmentId
 403      );
 404    }
 405    function isPaused(state) {
 406      return state.queueStatus === "paused";
 407    }
 408    function getBlobUrls(state, id) {
 409      return state.blobUrls[id] || [];
 410    }
 411    function getActiveUploadCount(state) {
 412      return state.queue.filter(
 413        (item) => item.currentOperation === OperationType.Upload
 414      ).length;
 415    }
 416    function getPendingUploads(state) {
 417      return state.queue.filter((item) => {
 418        const nextOperation = Array.isArray(item.operations?.[0]) ? item.operations[0][0] : item.operations?.[0];
 419        return nextOperation === OperationType.Upload && item.currentOperation !== OperationType.Upload;
 420      });
 421    }
 422    function getActiveImageProcessingCount(state) {
 423      return state.queue.filter(
 424        (item) => item.currentOperation === OperationType.ResizeCrop || item.currentOperation === OperationType.Rotate
 425      ).length;
 426    }
 427    function getPendingImageProcessing(state) {
 428      return state.queue.filter((item) => {
 429        const nextOperation = Array.isArray(item.operations?.[0]) ? item.operations[0][0] : item.operations?.[0];
 430        return (nextOperation === OperationType.ResizeCrop || nextOperation === OperationType.Rotate) && item.currentOperation !== OperationType.ResizeCrop && item.currentOperation !== OperationType.Rotate;
 431      });
 432    }
 433    function getFailedItems(state) {
 434      return state.queue.filter((item) => item.error !== void 0);
 435    }
 436    function hasPendingItemsByParentId(state, parentId) {
 437      return state.queue.some((item) => item.parentId === parentId);
 438    }
 439    function getItemProgress(state, id) {
 440      const item = state.queue.find((i) => i.id === id);
 441      return item?.progress;
 442    }
 443  
 444    // packages/upload-media/build-module/store/actions.mjs
 445    var actions_exports = {};
 446    __export(actions_exports, {
 447      addItems: () => addItems,
 448      cancelItem: () => cancelItem,
 449      retryItem: () => retryItem
 450    });
 451  
 452    // node_modules/uuid/dist/esm-browser/rng.js
 453    var getRandomValues;
 454    var rnds8 = new Uint8Array(16);
 455    function rng() {
 456      if (!getRandomValues) {
 457        getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
 458        if (!getRandomValues) {
 459          throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
 460        }
 461      }
 462      return getRandomValues(rnds8);
 463    }
 464  
 465    // node_modules/uuid/dist/esm-browser/stringify.js
 466    var byteToHex = [];
 467    for (let i = 0; i < 256; ++i) {
 468      byteToHex.push((i + 256).toString(16).slice(1));
 469    }
 470    function unsafeStringify(arr, offset = 0) {
 471      return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];
 472    }
 473  
 474    // node_modules/uuid/dist/esm-browser/native.js
 475    var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
 476    var native_default = {
 477      randomUUID
 478    };
 479  
 480    // node_modules/uuid/dist/esm-browser/v4.js
 481    function v4(options, buf, offset) {
 482      if (native_default.randomUUID && !buf && !options) {
 483        return native_default.randomUUID();
 484      }
 485      options = options || {};
 486      const rnds = options.random || (options.rng || rng)();
 487      rnds[6] = rnds[6] & 15 | 64;
 488      rnds[8] = rnds[8] & 63 | 128;
 489      if (buf) {
 490        offset = offset || 0;
 491        for (let i = 0; i < 16; ++i) {
 492          buf[offset + i] = rnds[i];
 493        }
 494        return buf;
 495      }
 496      return unsafeStringify(rnds);
 497    }
 498    var v4_default = v4;
 499  
 500    // packages/upload-media/build-module/image-file.mjs
 501    var ImageFile = class extends File {
 502      width = 0;
 503      height = 0;
 504      originalWidth = 0;
 505      originalHeight = 0;
 506      get wasResized() {
 507        return (this.originalWidth || 0) > this.width || (this.originalHeight || 0) > this.height;
 508      }
 509      constructor(file, width, height, originalWidth, originalHeight) {
 510        super([file], file.name, {
 511          type: file.type,
 512          lastModified: file.lastModified
 513        });
 514        this.width = width;
 515        this.height = height;
 516        this.originalWidth = originalWidth;
 517        this.originalHeight = originalHeight;
 518      }
 519    };
 520  
 521    // packages/upload-media/build-module/utils.mjs
 522    var import_url = __toESM(require_url(), 1);
 523    var import_i18n = __toESM(require_i18n(), 1);
 524    function convertBlobToFile(fileOrBlob) {
 525      if (fileOrBlob instanceof File) {
 526        return fileOrBlob;
 527      }
 528      if ("name" in fileOrBlob && typeof fileOrBlob.name === "string") {
 529        return new File([fileOrBlob], fileOrBlob.name, {
 530          type: fileOrBlob.type,
 531          lastModified: fileOrBlob.lastModified
 532        });
 533      }
 534      const ext = fileOrBlob.type.split("/")[1];
 535      const mediaType = "application/pdf" === fileOrBlob.type ? "document" : fileOrBlob.type.split("/")[0];
 536      return new File([fileOrBlob], `$mediaType}.$ext}`, {
 537        type: fileOrBlob.type
 538      });
 539    }
 540    function renameFile(file, name) {
 541      return new File([file], name, {
 542        type: file.type,
 543        lastModified: file.lastModified
 544      });
 545    }
 546    function cloneFile(file) {
 547      return renameFile(file, file.name);
 548    }
 549    function getFileBasename(name) {
 550      return name.includes(".") ? name.split(".").slice(0, -1).join(".") : name;
 551    }
 552  
 553    // packages/upload-media/build-module/store/utils/index.mjs
 554    var vipsModulePromise;
 555    var vipsModule;
 556    function loadVipsModule() {
 557      if (!vipsModulePromise) {
 558        vipsModulePromise = import("@wordpress/vips/worker").then(
 559          (mod) => {
 560            vipsModule = mod;
 561            return mod;
 562          }
 563        );
 564      }
 565      return vipsModulePromise;
 566    }
 567    async function vipsConvertImageFormat(id, file, type, quality, interlaced) {
 568      const { vipsConvertImageFormat: convertImageFormat } = await loadVipsModule();
 569      const buffer = await convertImageFormat(
 570        id,
 571        await file.arrayBuffer(),
 572        file.type,
 573        type,
 574        quality,
 575        interlaced
 576      );
 577      const ext = type.split("/")[1];
 578      const fileName = `$getFileBasename(file.name)}.$ext}`;
 579      return new File([new Blob([buffer])], fileName, {
 580        type
 581      });
 582    }
 583    async function vipsHasTransparency(url) {
 584      const { vipsHasTransparency: hasTransparency } = await loadVipsModule();
 585      const response = await fetch(url);
 586      if (!response.ok) {
 587        throw new Error(`Failed to fetch image: $response.status}`);
 588      }
 589      return hasTransparency(await response.arrayBuffer());
 590    }
 591    async function vipsResizeImage(id, file, resize, smartCrop, addSuffix, signal, scaledSuffix, quality) {
 592      if (signal?.aborted) {
 593        throw new Error("Operation aborted");
 594      }
 595      const { vipsResizeImage: resizeImage } = await loadVipsModule();
 596      const { buffer, width, height, originalWidth, originalHeight } = await resizeImage(
 597        id,
 598        await file.arrayBuffer(),
 599        file.type,
 600        resize,
 601        smartCrop,
 602        quality
 603      );
 604      let fileName = file.name;
 605      const wasResized = originalWidth > width || originalHeight > height;
 606      if (wasResized) {
 607        const basename = getFileBasename(file.name);
 608        if (scaledSuffix) {
 609          fileName = file.name.replace(basename, `$basename}-scaled`);
 610        } else if (addSuffix) {
 611          fileName = file.name.replace(
 612            basename,
 613            `$basename}-$width}x$height}`
 614          );
 615        }
 616      }
 617      const resultFile = new ImageFile(
 618        new File(
 619          [new Blob([buffer], { type: file.type })],
 620          fileName,
 621          {
 622            type: file.type
 623          }
 624        ),
 625        width,
 626        height,
 627        originalWidth,
 628        originalHeight
 629      );
 630      return resultFile;
 631    }
 632    async function vipsRotateImage(id, file, orientation, signal) {
 633      if (signal?.aborted) {
 634        throw new Error("Operation aborted");
 635      }
 636      if (orientation === 1) {
 637        return file;
 638      }
 639      const { vipsRotateImage: rotateImage } = await loadVipsModule();
 640      const { buffer, width, height } = await rotateImage(
 641        id,
 642        await file.arrayBuffer(),
 643        file.type,
 644        orientation
 645      );
 646      const basename = getFileBasename(file.name);
 647      const fileName = file.name.replace(basename, `$basename}-rotated`);
 648      const resultFile = new ImageFile(
 649        new File(
 650          [new Blob([buffer], { type: file.type })],
 651          fileName,
 652          {
 653            type: file.type
 654          }
 655        ),
 656        width,
 657        height
 658      );
 659      return resultFile;
 660    }
 661    async function vipsCancelOperations(id) {
 662      if (!vipsModule) {
 663        return false;
 664      }
 665      return vipsModule.vipsCancelOperations(id);
 666    }
 667    function terminateVipsWorker() {
 668      if (vipsModule) {
 669        vipsModule.terminateVipsWorker();
 670      }
 671    }
 672  
 673    // packages/upload-media/build-module/validate-mime-type.mjs
 674    var import_i18n2 = __toESM(require_i18n(), 1);
 675  
 676    // packages/upload-media/build-module/upload-error.mjs
 677    var UploadError = class extends Error {
 678      code;
 679      file;
 680      constructor({ code, message, file, cause }) {
 681        super(message, { cause });
 682        Object.setPrototypeOf(this, new.target.prototype);
 683        this.code = code;
 684        this.file = file;
 685      }
 686    };
 687  
 688    // packages/upload-media/build-module/validate-mime-type.mjs
 689    function validateMimeType(file, allowedTypes) {
 690      if (!allowedTypes) {
 691        return;
 692      }
 693      const isAllowedType = allowedTypes.some((allowedType) => {
 694        if (allowedType.includes("/")) {
 695          return allowedType === file.type;
 696        }
 697        return file.type.startsWith(`$allowedType}/`);
 698      });
 699      if (file.type && !isAllowedType) {
 700        throw new UploadError({
 701          code: "MIME_TYPE_NOT_SUPPORTED",
 702          message: (0, import_i18n2.sprintf)(
 703            // translators: %s: file name.
 704            (0, import_i18n2.__)("%s: Sorry, this file type is not supported here."),
 705            file.name
 706          ),
 707          file
 708        });
 709      }
 710    }
 711  
 712    // packages/upload-media/build-module/validate-mime-type-for-user.mjs
 713    var import_i18n3 = __toESM(require_i18n(), 1);
 714  
 715    // packages/upload-media/build-module/get-mime-types-array.mjs
 716    function getMimeTypesArray(wpMimeTypesObject) {
 717      if (!wpMimeTypesObject) {
 718        return null;
 719      }
 720      return Object.entries(wpMimeTypesObject).flatMap(
 721        ([extensionsString, mime]) => {
 722          const [type] = mime.split("/");
 723          const extensions = extensionsString.split("|");
 724          return [
 725            mime,
 726            ...extensions.map(
 727              (extension) => `$type}/$extension}`
 728            )
 729          ];
 730        }
 731      );
 732    }
 733  
 734    // packages/upload-media/build-module/validate-mime-type-for-user.mjs
 735    function validateMimeTypeForUser(file, wpAllowedMimeTypes) {
 736      const allowedMimeTypesForUser = getMimeTypesArray(wpAllowedMimeTypes);
 737      if (!allowedMimeTypesForUser) {
 738        return;
 739      }
 740      const isAllowedMimeTypeForUser = allowedMimeTypesForUser.includes(
 741        file.type
 742      );
 743      if (file.type && !isAllowedMimeTypeForUser) {
 744        throw new UploadError({
 745          code: "MIME_TYPE_NOT_ALLOWED_FOR_USER",
 746          message: (0, import_i18n3.sprintf)(
 747            // translators: %s: file name.
 748            (0, import_i18n3.__)(
 749              "%s: Sorry, you are not allowed to upload this file type."
 750            ),
 751            file.name
 752          ),
 753          file
 754        });
 755      }
 756    }
 757  
 758    // packages/upload-media/build-module/validate-file-size.mjs
 759    var import_i18n4 = __toESM(require_i18n(), 1);
 760    function validateFileSize(file, maxUploadFileSize) {
 761      if (file.size <= 0) {
 762        throw new UploadError({
 763          code: "EMPTY_FILE",
 764          message: (0, import_i18n4.sprintf)(
 765            // translators: %s: file name.
 766            (0, import_i18n4.__)("%s: This file is empty."),
 767            file.name
 768          ),
 769          file
 770        });
 771      }
 772      if (maxUploadFileSize && file.size > maxUploadFileSize) {
 773        throw new UploadError({
 774          code: "SIZE_ABOVE_LIMIT",
 775          message: (0, import_i18n4.sprintf)(
 776            // translators: %s: file name.
 777            (0, import_i18n4.__)(
 778              "%s: This file exceeds the maximum upload size for this site."
 779            ),
 780            file.name
 781          ),
 782          file
 783        });
 784      }
 785    }
 786  
 787    // packages/upload-media/build-module/store/actions.mjs
 788    function addItems({
 789      files,
 790      onChange,
 791      onSuccess,
 792      onError,
 793      onBatchSuccess,
 794      additionalData,
 795      allowedTypes
 796    }) {
 797      return async ({ select: select2, dispatch }) => {
 798        const batchId = v4_default();
 799        for (const file of files) {
 800          try {
 801            validateMimeType(file, allowedTypes);
 802            validateMimeTypeForUser(
 803              file,
 804              select2.getSettings().allowedMimeTypes
 805            );
 806          } catch (error) {
 807            onError?.(error);
 808            continue;
 809          }
 810          try {
 811            validateFileSize(
 812              file,
 813              select2.getSettings().maxUploadFileSize
 814            );
 815          } catch (error) {
 816            onError?.(error);
 817            continue;
 818          }
 819          dispatch.addItem({
 820            file,
 821            batchId,
 822            onChange,
 823            onSuccess,
 824            onBatchSuccess,
 825            onError,
 826            additionalData
 827          });
 828        }
 829      };
 830    }
 831    function cancelItem(id, error, silent = false) {
 832      return async ({ select: select2, dispatch }) => {
 833        const item = select2.getItem(id);
 834        if (!item) {
 835          return;
 836        }
 837        item.abortController?.abort();
 838        await vipsCancelOperations(id);
 839        if (!silent) {
 840          const { onError } = item;
 841          onError?.(error ?? new Error("Upload cancelled"));
 842          if (!onError && error) {
 843            console.error("Upload cancelled", error);
 844          }
 845        }
 846        dispatch({
 847          type: Type.Cancel,
 848          id,
 849          error
 850        });
 851        dispatch.removeItem(id);
 852        dispatch.revokeBlobUrls(id);
 853        if (item.batchId && select2.isBatchUploaded(item.batchId)) {
 854          item.onBatchSuccess?.();
 855        }
 856      };
 857    }
 858    function retryItem(id) {
 859      return async ({ select: select2, dispatch }) => {
 860        const item = select2.getItem(id);
 861        if (!item) {
 862          return;
 863        }
 864        if (!item.error) {
 865          return;
 866        }
 867        dispatch({
 868          type: Type.RetryItem,
 869          id
 870        });
 871        dispatch.processItem(id);
 872      };
 873    }
 874  
 875    // packages/upload-media/build-module/store/private-actions.mjs
 876    var private_actions_exports = {};
 877    __export(private_actions_exports, {
 878      addItem: () => addItem,
 879      addSideloadItem: () => addSideloadItem,
 880      finalizeItem: () => finalizeItem,
 881      finishOperation: () => finishOperation,
 882      generateThumbnails: () => generateThumbnails,
 883      getTranscodeImageOperation: () => getTranscodeImageOperation,
 884      pauseItem: () => pauseItem,
 885      pauseQueue: () => pauseQueue,
 886      prepareItem: () => prepareItem,
 887      processItem: () => processItem,
 888      removeItem: () => removeItem,
 889      resizeCropItem: () => resizeCropItem,
 890      resumeItemByPostId: () => resumeItemByPostId,
 891      resumeQueue: () => resumeQueue,
 892      revokeBlobUrls: () => revokeBlobUrls,
 893      rotateItem: () => rotateItem,
 894      sideloadItem: () => sideloadItem,
 895      transcodeImageItem: () => transcodeImageItem,
 896      updateItemProgress: () => updateItemProgress,
 897      updateSettings: () => updateSettings,
 898      uploadItem: () => uploadItem
 899    });
 900    var import_blob = __toESM(require_blob(), 1);
 901  
 902    // packages/upload-media/build-module/stub-file.mjs
 903    var StubFile = class extends File {
 904      constructor(fileName = "stub-file") {
 905        super([], fileName);
 906      }
 907    };
 908  
 909    // packages/upload-media/build-module/store/private-actions.mjs
 910    var DEFAULT_OUTPUT_QUALITY = 0.82;
 911    function shouldPauseForSideload(item, operation, select2) {
 912      if (operation !== OperationType.Upload || !item.parentId || !item.additionalData.post) {
 913        return false;
 914      }
 915      return select2.isUploadingToPost(item.additionalData.post);
 916    }
 917    function addItem({
 918      file: fileOrBlob,
 919      batchId,
 920      onChange,
 921      onSuccess,
 922      onBatchSuccess,
 923      onError,
 924      additionalData = {},
 925      sourceUrl,
 926      sourceAttachmentId,
 927      abortController,
 928      operations
 929    }) {
 930      return async ({ dispatch }) => {
 931        const itemId = v4_default();
 932        const file = convertBlobToFile(fileOrBlob);
 933        let blobUrl;
 934        if (!(file instanceof StubFile)) {
 935          blobUrl = (0, import_blob.createBlobURL)(file);
 936          dispatch({
 937            type: Type.CacheBlobUrl,
 938            id: itemId,
 939            blobUrl
 940          });
 941        }
 942        dispatch({
 943          type: Type.Add,
 944          item: {
 945            id: itemId,
 946            batchId,
 947            status: ItemStatus.Processing,
 948            sourceFile: cloneFile(file),
 949            file,
 950            attachment: {
 951              url: blobUrl
 952            },
 953            additionalData: {
 954              convert_format: false,
 955              generate_sub_sizes: false,
 956              ...additionalData
 957            },
 958            onChange,
 959            onSuccess,
 960            onBatchSuccess,
 961            onError,
 962            sourceUrl,
 963            sourceAttachmentId,
 964            abortController: abortController || new AbortController(),
 965            operations: Array.isArray(operations) ? operations : [OperationType.Prepare]
 966          }
 967        });
 968        dispatch.processItem(itemId);
 969      };
 970    }
 971    function addSideloadItem({
 972      file,
 973      onChange,
 974      additionalData,
 975      operations,
 976      batchId,
 977      parentId
 978    }) {
 979      return ({ dispatch }) => {
 980        const itemId = v4_default();
 981        dispatch({
 982          type: Type.Add,
 983          item: {
 984            id: itemId,
 985            batchId,
 986            status: ItemStatus.Processing,
 987            sourceFile: cloneFile(file),
 988            file,
 989            onChange,
 990            additionalData: {
 991              ...additionalData
 992            },
 993            parentId,
 994            operations: Array.isArray(operations) ? operations : [OperationType.Prepare],
 995            abortController: new AbortController()
 996          }
 997        });
 998        dispatch.processItem(itemId);
 999      };
1000    }
1001    function processItem(id) {
1002      return async ({ select: select2, dispatch }) => {
1003        if (select2.isPaused()) {
1004          return;
1005        }
1006        const item = select2.getItem(id);
1007        if (!item) {
1008          return;
1009        }
1010        const {
1011          attachment,
1012          onChange,
1013          onSuccess,
1014          onBatchSuccess,
1015          batchId,
1016          parentId
1017        } = item;
1018        const operation = Array.isArray(item.operations?.[0]) ? item.operations[0][0] : item.operations?.[0];
1019        const operationArgs = Array.isArray(item.operations?.[0]) ? item.operations[0][1] : void 0;
1020        if (shouldPauseForSideload(item, operation, select2)) {
1021          dispatch({
1022            type: Type.PauseItem,
1023            id
1024          });
1025          return;
1026        }
1027        if (operation === OperationType.Upload) {
1028          const settings = select2.getSettings();
1029          const activeCount = select2.getActiveUploadCount();
1030          if (activeCount >= settings.maxConcurrentUploads) {
1031            return;
1032          }
1033        }
1034        if (operation === OperationType.ResizeCrop || operation === OperationType.Rotate) {
1035          const settings = select2.getSettings();
1036          const activeCount = select2.getActiveImageProcessingCount();
1037          if (activeCount >= settings.maxConcurrentImageProcessing) {
1038            return;
1039          }
1040        }
1041        if (attachment) {
1042          onChange?.([attachment]);
1043        }
1044        if (!operation) {
1045          if (parentId || !parentId && !select2.hasPendingItemsByParentId(id)) {
1046            if (attachment) {
1047              onSuccess?.([attachment]);
1048            }
1049            dispatch.removeItem(id);
1050            dispatch.revokeBlobUrls(id);
1051            if (batchId && select2.isBatchUploaded(batchId)) {
1052              onBatchSuccess?.();
1053            }
1054          }
1055          if (parentId && batchId && select2.isBatchUploaded(batchId)) {
1056            const parentItem = select2.getItem(parentId);
1057            if (!parentItem) {
1058              return;
1059            }
1060            if (parentItem.operations && parentItem.operations.length > 0) {
1061              dispatch.processItem(parentId);
1062              return;
1063            }
1064            if (attachment) {
1065              parentItem.onSuccess?.([attachment]);
1066            }
1067            dispatch.removeItem(parentId);
1068            dispatch.revokeBlobUrls(parentId);
1069            if (parentItem.batchId && select2.isBatchUploaded(parentItem.batchId)) {
1070              parentItem.onBatchSuccess?.();
1071            }
1072          }
1073          return;
1074        }
1075        if (operation === OperationType.Finalize && select2.hasPendingItemsByParentId(id)) {
1076          return;
1077        }
1078        dispatch({
1079          type: Type.OperationStart,
1080          id,
1081          operation
1082        });
1083        switch (operation) {
1084          case OperationType.Prepare:
1085            dispatch.prepareItem(item.id);
1086            break;
1087          case OperationType.ResizeCrop:
1088            dispatch.resizeCropItem(
1089              item.id,
1090              operationArgs
1091            );
1092            break;
1093          case OperationType.Rotate:
1094            dispatch.rotateItem(
1095              item.id,
1096              operationArgs
1097            );
1098            break;
1099          case OperationType.TranscodeImage:
1100            dispatch.transcodeImageItem(
1101              item.id,
1102              operationArgs
1103            );
1104            break;
1105          case OperationType.Upload:
1106            if (item.parentId) {
1107              dispatch.sideloadItem(id);
1108            } else {
1109              dispatch.uploadItem(id);
1110            }
1111            break;
1112          case OperationType.ThumbnailGeneration:
1113            dispatch.generateThumbnails(id);
1114            break;
1115          case OperationType.Finalize:
1116            dispatch.finalizeItem(id);
1117            break;
1118        }
1119      };
1120    }
1121    function pauseQueue() {
1122      return {
1123        type: Type.PauseQueue
1124      };
1125    }
1126    function resumeQueue() {
1127      return async ({ select: select2, dispatch }) => {
1128        dispatch({
1129          type: Type.ResumeQueue
1130        });
1131        for (const item of select2.getAllItems()) {
1132          dispatch.processItem(item.id);
1133        }
1134      };
1135    }
1136    function pauseItem(id) {
1137      return async ({ dispatch }) => {
1138        dispatch({
1139          type: Type.PauseItem,
1140          id
1141        });
1142      };
1143    }
1144    function resumeItemByPostId(postOrAttachmentId) {
1145      return async ({ select: select2, dispatch }) => {
1146        const item = select2.getPausedUploadForPost(postOrAttachmentId);
1147        if (item) {
1148          dispatch({
1149            type: Type.ResumeItem,
1150            id: item.id
1151          });
1152          dispatch.processItem(item.id);
1153        }
1154      };
1155    }
1156    function removeItem(id) {
1157      return async ({ select: select2, dispatch }) => {
1158        const item = select2.getItem(id);
1159        if (!item) {
1160          return;
1161        }
1162        dispatch({
1163          type: Type.Remove,
1164          id
1165        });
1166        if (select2.getAllItems().length === 0) {
1167          terminateVipsWorker();
1168        }
1169      };
1170    }
1171    function finishOperation(id, updates) {
1172      return async ({ select: select2, dispatch }) => {
1173        const item = select2.getItem(id);
1174        const previousOperation = item?.currentOperation;
1175        dispatch({
1176          type: Type.OperationFinish,
1177          id,
1178          item: updates
1179        });
1180        dispatch.processItem(id);
1181        if (previousOperation === OperationType.Upload) {
1182          const pendingUploads = select2.getPendingUploads();
1183          for (const pendingItem of pendingUploads) {
1184            dispatch.processItem(pendingItem.id);
1185          }
1186        }
1187        if (previousOperation === OperationType.ResizeCrop || previousOperation === OperationType.Rotate) {
1188          const pendingItems = select2.getPendingImageProcessing();
1189          for (const pendingItem of pendingItems) {
1190            dispatch.processItem(pendingItem.id);
1191          }
1192        }
1193      };
1194    }
1195    var VALID_IMAGE_FORMATS = ["jpeg", "webp", "avif", "png", "gif"];
1196    function isValidImageFormat(format) {
1197      return VALID_IMAGE_FORMATS.includes(format);
1198    }
1199    function getInterlacedSetting(outputMimeType, settings) {
1200      switch (outputMimeType) {
1201        case "image/jpeg":
1202          return settings.jpegInterlaced ?? false;
1203        case "image/png":
1204          return settings.pngInterlaced ?? false;
1205        case "image/gif":
1206          return settings.gifInterlaced ?? false;
1207        default:
1208          return false;
1209      }
1210    }
1211    async function getTranscodeImageOperation(file, outputMimeType, settings) {
1212      if (file.type === "image/png" && outputMimeType === "image/jpeg") {
1213        const blobUrl = (0, import_blob.createBlobURL)(file);
1214        try {
1215          const hasAlpha = await vipsHasTransparency(blobUrl);
1216          if (hasAlpha) {
1217            return null;
1218          }
1219        } catch {
1220          return null;
1221        } finally {
1222          (0, import_blob.revokeBlobURL)(blobUrl);
1223        }
1224      }
1225      const formatPart = outputMimeType.split("/")[1];
1226      if (!isValidImageFormat(formatPart)) {
1227        return null;
1228      }
1229      return [
1230        OperationType.TranscodeImage,
1231        {
1232          outputFormat: formatPart,
1233          outputQuality: DEFAULT_OUTPUT_QUALITY,
1234          interlaced: getInterlacedSetting(outputMimeType, settings)
1235        }
1236      ];
1237    }
1238    function prepareItem(id) {
1239      return async ({ select: select2, dispatch }) => {
1240        const item = select2.getItem(id);
1241        if (!item) {
1242          return;
1243        }
1244        const { file } = item;
1245        const operations = [];
1246        const settings = select2.getSettings();
1247        const isImage = file.type.startsWith("image/");
1248        const isVipsSupported = CLIENT_SIDE_SUPPORTED_MIME_TYPES.includes(
1249          file.type
1250        );
1251        if (isImage && isVipsSupported) {
1252          const { imageOutputFormats } = settings;
1253          const outputMimeType = imageOutputFormats?.[file.type];
1254          if (outputMimeType && outputMimeType !== file.type) {
1255            const transcodeOperation = await getTranscodeImageOperation(
1256              file,
1257              outputMimeType,
1258              settings
1259            );
1260            if (transcodeOperation) {
1261              operations.push(transcodeOperation);
1262            }
1263          }
1264          operations.push(
1265            OperationType.Upload,
1266            OperationType.ThumbnailGeneration,
1267            OperationType.Finalize
1268          );
1269        } else {
1270          operations.push(OperationType.Upload);
1271        }
1272        dispatch({
1273          type: Type.AddOperations,
1274          id,
1275          operations
1276        });
1277        const updates = !isVipsSupported || !isImage ? {
1278          additionalData: {
1279            ...item.additionalData,
1280            generate_sub_sizes: true,
1281            convert_format: true
1282          }
1283        } : {};
1284        dispatch.finishOperation(id, updates);
1285      };
1286    }
1287    function uploadItem(id) {
1288      return async ({ select: select2, dispatch }) => {
1289        const item = select2.getItem(id);
1290        if (!item) {
1291          return;
1292        }
1293        select2.getSettings().mediaUpload({
1294          filesList: [item.file],
1295          additionalData: item.additionalData,
1296          signal: item.abortController?.signal,
1297          onFileChange: ([attachment]) => {
1298            if (attachment && !(0, import_blob.isBlobURL)(attachment.url)) {
1299              dispatch.finishOperation(id, {
1300                attachment
1301              });
1302            }
1303          },
1304          onSuccess: ([attachment]) => {
1305            dispatch.finishOperation(id, {
1306              attachment
1307            });
1308          },
1309          onError: (error) => {
1310            dispatch.cancelItem(id, error);
1311          }
1312        });
1313      };
1314    }
1315    function sideloadItem(id) {
1316      return async ({ select: select2, dispatch }) => {
1317        const item = select2.getItem(id);
1318        if (!item) {
1319          return;
1320        }
1321        const { post, ...additionalData } = item.additionalData;
1322        const mediaSideload = select2.getSettings().mediaSideload;
1323        if (!mediaSideload) {
1324          dispatch.finishOperation(id, {});
1325          return;
1326        }
1327        mediaSideload({
1328          file: item.file,
1329          attachmentId: post,
1330          additionalData,
1331          signal: item.abortController?.signal,
1332          onFileChange: ([attachment]) => {
1333            dispatch.finishOperation(id, { attachment });
1334            dispatch.resumeItemByPostId(post);
1335          },
1336          onError: (error) => {
1337            dispatch.cancelItem(id, error);
1338            dispatch.resumeItemByPostId(post);
1339          }
1340        });
1341      };
1342    }
1343    function resizeCropItem(id, args) {
1344      return async ({ select: select2, dispatch }) => {
1345        const item = select2.getItem(id);
1346        if (!item) {
1347          return;
1348        }
1349        if (!args?.resize) {
1350          dispatch.finishOperation(id, {
1351            file: item.file
1352          });
1353          return;
1354        }
1355        const addSuffix = Boolean(item.parentId);
1356        const scaledSuffix = Boolean(args.isThresholdResize);
1357        try {
1358          const file = await vipsResizeImage(
1359            item.id,
1360            item.file,
1361            args.resize,
1362            false,
1363            // smartCrop
1364            addSuffix,
1365            item.abortController?.signal,
1366            scaledSuffix
1367          );
1368          const blobUrl = (0, import_blob.createBlobURL)(file);
1369          dispatch({
1370            type: Type.CacheBlobUrl,
1371            id,
1372            blobUrl
1373          });
1374          dispatch.finishOperation(id, {
1375            file,
1376            attachment: {
1377              url: blobUrl
1378            }
1379          });
1380        } catch (error) {
1381          dispatch.cancelItem(
1382            id,
1383            new UploadError({
1384              code: "IMAGE_TRANSCODING_ERROR",
1385              message: "File could not be uploaded",
1386              file: item.file,
1387              cause: error instanceof Error ? error : void 0
1388            })
1389          );
1390        }
1391      };
1392    }
1393    function rotateItem(id, args) {
1394      return async ({ select: select2, dispatch }) => {
1395        const item = select2.getItem(id);
1396        if (!item) {
1397          return;
1398        }
1399        if (!args?.orientation || args.orientation === 1) {
1400          dispatch.finishOperation(id, {
1401            file: item.file
1402          });
1403          return;
1404        }
1405        try {
1406          const file = await vipsRotateImage(
1407            item.id,
1408            item.file,
1409            args.orientation,
1410            item.abortController?.signal
1411          );
1412          const blobUrl = (0, import_blob.createBlobURL)(file);
1413          dispatch({
1414            type: Type.CacheBlobUrl,
1415            id,
1416            blobUrl
1417          });
1418          dispatch.finishOperation(id, {
1419            file,
1420            attachment: {
1421              url: blobUrl
1422            }
1423          });
1424        } catch (error) {
1425          dispatch.cancelItem(
1426            id,
1427            new UploadError({
1428              code: "IMAGE_ROTATION_ERROR",
1429              message: "Image could not be rotated",
1430              file: item.file,
1431              cause: error instanceof Error ? error : void 0
1432            })
1433          );
1434        }
1435      };
1436    }
1437    function transcodeImageItem(id, args) {
1438      return async ({ select: select2, dispatch }) => {
1439        const item = select2.getItem(id);
1440        if (!item) {
1441          return;
1442        }
1443        if (!args?.outputFormat) {
1444          dispatch.finishOperation(id, {
1445            file: item.file
1446          });
1447          return;
1448        }
1449        const outputMimeType = `image/$args.outputFormat}`;
1450        const quality = args.outputQuality ?? DEFAULT_OUTPUT_QUALITY;
1451        const interlaced = args.interlaced ?? false;
1452        try {
1453          const file = await vipsConvertImageFormat(
1454            item.id,
1455            item.file,
1456            outputMimeType,
1457            quality,
1458            interlaced
1459          );
1460          const blobUrl = (0, import_blob.createBlobURL)(file);
1461          dispatch({
1462            type: Type.CacheBlobUrl,
1463            id,
1464            blobUrl
1465          });
1466          dispatch.finishOperation(id, {
1467            file,
1468            attachment: {
1469              url: blobUrl
1470            }
1471          });
1472        } catch (error) {
1473          dispatch.cancelItem(
1474            id,
1475            new UploadError({
1476              code: "MEDIA_TRANSCODING_ERROR",
1477              message: "Image could not be transcoded to the target format",
1478              file: item.file,
1479              cause: error instanceof Error ? error : void 0
1480            })
1481          );
1482        }
1483      };
1484    }
1485    function generateThumbnails(id) {
1486      return async ({ select: select2, dispatch }) => {
1487        const item = select2.getItem(id);
1488        if (!item) {
1489          return;
1490        }
1491        if (!item.attachment) {
1492          dispatch.finishOperation(id, {});
1493          return;
1494        }
1495        const attachment = item.attachment;
1496        const needsRotation = attachment.exif_orientation && attachment.exif_orientation !== 1 && !item.file.name.includes("-scaled");
1497        if (needsRotation && attachment.id) {
1498          try {
1499            const rotatedFile = await vipsRotateImage(
1500              item.id,
1501              item.sourceFile,
1502              attachment.exif_orientation,
1503              item.abortController?.signal
1504            );
1505            dispatch.addSideloadItem({
1506              file: rotatedFile,
1507              batchId: v4_default(),
1508              parentId: item.id,
1509              additionalData: {
1510                post: attachment.id,
1511                image_size: "original",
1512                convert_format: false
1513              },
1514              operations: [OperationType.Upload]
1515            });
1516          } catch {
1517            console.warn(
1518              "Failed to rotate image, continuing with thumbnails"
1519            );
1520          }
1521        }
1522        if (!item.parentId && attachment.missing_image_sizes && attachment.missing_image_sizes.length > 0) {
1523          const settings = select2.getSettings();
1524          const allImageSizes = settings.allImageSizes || {};
1525          const sizesToGenerate = attachment.missing_image_sizes;
1526          const file = attachment.filename ? renameFile(item.sourceFile, attachment.filename) : item.sourceFile;
1527          const batchId = v4_default();
1528          const { imageOutputFormats } = settings;
1529          const sourceType = item.sourceFile.type;
1530          const outputMimeType = imageOutputFormats?.[sourceType];
1531          let thumbnailTranscodeOperation = null;
1532          if (outputMimeType && outputMimeType !== sourceType) {
1533            thumbnailTranscodeOperation = await getTranscodeImageOperation(
1534              item.sourceFile,
1535              outputMimeType,
1536              settings
1537            );
1538          }
1539          for (const name of sizesToGenerate) {
1540            const imageSize = allImageSizes[name];
1541            if (!imageSize) {
1542              console.warn(
1543                `Image size "$name}" not found in configuration`
1544              );
1545              continue;
1546            }
1547            const thumbnailOperations = [
1548              [OperationType.ResizeCrop, { resize: imageSize }]
1549            ];
1550            if (thumbnailTranscodeOperation) {
1551              thumbnailOperations.push(thumbnailTranscodeOperation);
1552            }
1553            thumbnailOperations.push(OperationType.Upload);
1554            dispatch.addSideloadItem({
1555              file,
1556              onChange: ([updatedAttachment]) => {
1557                if ((0, import_blob.isBlobURL)(updatedAttachment.url)) {
1558                  return;
1559                }
1560                item.onChange?.([updatedAttachment]);
1561              },
1562              batchId,
1563              parentId: item.id,
1564              additionalData: {
1565                // Sideloading does not use the parent post ID but the
1566                // attachment ID as the image sizes need to be added to it.
1567                post: attachment.id,
1568                image_size: name,
1569                convert_format: false
1570              },
1571              operations: thumbnailOperations
1572            });
1573          }
1574          const { bigImageSizeThreshold } = settings;
1575          if (bigImageSizeThreshold && attachment.id) {
1576            const bitmap = await createImageBitmap(item.sourceFile);
1577            const needsScaling = bitmap.width > bigImageSizeThreshold || bitmap.height > bigImageSizeThreshold;
1578            bitmap.close();
1579            if (needsScaling) {
1580              const sourceForScaled = attachment.filename ? renameFile(item.sourceFile, attachment.filename) : item.sourceFile;
1581              const scaledOperations = [
1582                [
1583                  OperationType.ResizeCrop,
1584                  {
1585                    resize: {
1586                      width: bigImageSizeThreshold,
1587                      height: bigImageSizeThreshold
1588                    },
1589                    isThresholdResize: true
1590                  }
1591                ]
1592              ];
1593              if (thumbnailTranscodeOperation) {
1594                scaledOperations.push(thumbnailTranscodeOperation);
1595              }
1596              scaledOperations.push(OperationType.Upload);
1597              dispatch.addSideloadItem({
1598                file: sourceForScaled,
1599                onChange: ([updatedAttachment]) => {
1600                  if ((0, import_blob.isBlobURL)(updatedAttachment.url)) {
1601                    return;
1602                  }
1603                  item.onChange?.([updatedAttachment]);
1604                },
1605                batchId,
1606                parentId: item.id,
1607                additionalData: {
1608                  post: attachment.id,
1609                  image_size: "scaled",
1610                  convert_format: false
1611                },
1612                operations: scaledOperations
1613              });
1614            }
1615          }
1616        }
1617        dispatch.finishOperation(id, {});
1618      };
1619    }
1620    function finalizeItem(id) {
1621      return async ({ select: select2, dispatch }) => {
1622        const item = select2.getItem(id);
1623        if (!item) {
1624          return;
1625        }
1626        const attachment = item.attachment;
1627        const { mediaFinalize } = select2.getSettings();
1628        if (attachment?.id && mediaFinalize) {
1629          try {
1630            await mediaFinalize(attachment.id);
1631          } catch (error) {
1632            console.warn("Media finalization failed:", error);
1633          }
1634        }
1635        dispatch.finishOperation(id, {});
1636      };
1637    }
1638    function revokeBlobUrls(id) {
1639      return async ({ select: select2, dispatch }) => {
1640        const blobUrls = select2.getBlobUrls(id);
1641        for (const blobUrl of blobUrls) {
1642          (0, import_blob.revokeBlobURL)(blobUrl);
1643        }
1644        dispatch({
1645          type: Type.RevokeBlobUrls,
1646          id
1647        });
1648      };
1649    }
1650    function updateItemProgress(id, progress) {
1651      return async ({ dispatch }) => {
1652        dispatch({
1653          type: Type.UpdateProgress,
1654          id,
1655          progress
1656        });
1657      };
1658    }
1659    function updateSettings(settings) {
1660      return {
1661        type: Type.UpdateSettings,
1662        settings
1663      };
1664    }
1665  
1666    // packages/upload-media/build-module/lock-unlock.mjs
1667    var import_private_apis = __toESM(require_private_apis(), 1);
1668    var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
1669      "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
1670      "@wordpress/upload-media"
1671    );
1672  
1673    // packages/upload-media/build-module/store/index.mjs
1674    var storeConfig = {
1675      reducer: reducer_default,
1676      selectors: selectors_exports,
1677      actions: actions_exports
1678    };
1679    var store = (0, import_data.createReduxStore)(STORE_NAME, {
1680      reducer: reducer_default,
1681      selectors: selectors_exports,
1682      actions: actions_exports
1683    });
1684    if (!(0, import_data.select)(store)) {
1685      (0, import_data.register)(store);
1686    }
1687    unlock(store).registerPrivateActions(private_actions_exports);
1688    unlock(store).registerPrivateSelectors(private_selectors_exports);
1689  
1690    // packages/upload-media/build-module/components/provider/index.mjs
1691    var import_element2 = __toESM(require_element(), 1);
1692    var import_data3 = __toESM(require_data(), 1);
1693  
1694    // packages/upload-media/build-module/components/provider/with-registry-provider.mjs
1695    var import_element = __toESM(require_element(), 1);
1696    var import_data2 = __toESM(require_data(), 1);
1697    var import_compose = __toESM(require_compose(), 1);
1698    var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
1699    function getSubRegistry(subRegistries, registry, useSubRegistry) {
1700      if (!useSubRegistry) {
1701        return registry;
1702      }
1703      let subRegistry = subRegistries.get(registry);
1704      if (!subRegistry) {
1705        subRegistry = (0, import_data2.createRegistry)({}, registry);
1706        subRegistry.registerStore(STORE_NAME, storeConfig);
1707        subRegistries.set(registry, subRegistry);
1708      }
1709      return subRegistry;
1710    }
1711    var withRegistryProvider = (0, import_compose.createHigherOrderComponent)(
1712      (WrappedComponent) => ({ useSubRegistry = true, ...props }) => {
1713        const registry = (0, import_data2.useRegistry)();
1714        const [subRegistries] = (0, import_element.useState)(() => /* @__PURE__ */ new WeakMap());
1715        const subRegistry = getSubRegistry(
1716          subRegistries,
1717          registry,
1718          useSubRegistry
1719        );
1720        if (subRegistry === registry) {
1721          return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WrappedComponent, { registry, ...props });
1722        }
1723        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_data2.RegistryProvider, { value: subRegistry, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(WrappedComponent, { registry: subRegistry, ...props }) });
1724      },
1725      "withRegistryProvider"
1726    );
1727    var with_registry_provider_default = withRegistryProvider;
1728  
1729    // packages/upload-media/build-module/components/provider/index.mjs
1730    var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
1731    var MediaUploadProvider = with_registry_provider_default((props) => {
1732      const { children, settings } = props;
1733      const { updateSettings: updateSettings2 } = unlock((0, import_data3.useDispatch)(store));
1734      (0, import_element2.useEffect)(() => {
1735        updateSettings2(settings);
1736      }, [settings, updateSettings2]);
1737      return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_jsx_runtime2.Fragment, { children });
1738    });
1739    var provider_default = MediaUploadProvider;
1740  
1741    // packages/upload-media/build-module/feature-detection.mjs
1742    var cachedResult = null;
1743    function detectClientSideMediaSupport() {
1744      if (cachedResult !== null) {
1745        return cachedResult;
1746      }
1747      if (typeof WebAssembly === "undefined") {
1748        cachedResult = {
1749          supported: false,
1750          reason: "WebAssembly is not supported in this browser."
1751        };
1752        return cachedResult;
1753      }
1754      if (typeof SharedArrayBuffer === "undefined") {
1755        cachedResult = {
1756          supported: false,
1757          reason: "SharedArrayBuffer is not available. This may be due to missing cross-origin isolation headers."
1758        };
1759        return cachedResult;
1760      }
1761      if (typeof Worker === "undefined") {
1762        cachedResult = {
1763          supported: false,
1764          reason: "Web Workers are not supported in this browser."
1765        };
1766        return cachedResult;
1767      }
1768      if (typeof navigator !== "undefined" && "deviceMemory" in navigator && navigator.deviceMemory <= 2) {
1769        cachedResult = {
1770          supported: false,
1771          reason: "Device has insufficient memory for client-side media processing."
1772        };
1773        return cachedResult;
1774      }
1775      if (typeof navigator !== "undefined" && "hardwareConcurrency" in navigator && navigator.hardwareConcurrency < 2) {
1776        cachedResult = {
1777          supported: false,
1778          reason: "Device has insufficient CPU cores for client-side media processing."
1779        };
1780        return cachedResult;
1781      }
1782      if (typeof navigator !== "undefined") {
1783        const connection = navigator.connection;
1784        if (connection) {
1785          if (connection.saveData) {
1786            cachedResult = {
1787              supported: false,
1788              reason: "Data saver mode is enabled."
1789            };
1790            return cachedResult;
1791          }
1792          if (connection.effectiveType === "slow-2g" || connection.effectiveType === "2g") {
1793            cachedResult = {
1794              supported: false,
1795              reason: "Network connection is too slow for client-side media processing."
1796            };
1797            return cachedResult;
1798          }
1799        }
1800      }
1801      if (typeof window !== "undefined") {
1802        try {
1803          const testBlob = new Blob([""], {
1804            type: "application/javascript"
1805          });
1806          const testUrl = URL.createObjectURL(testBlob);
1807          try {
1808            const testWorker = new Worker(testUrl);
1809            testWorker.terminate();
1810          } finally {
1811            URL.revokeObjectURL(testUrl);
1812          }
1813        } catch {
1814          cachedResult = {
1815            supported: false,
1816            reason: "The site's Content Security Policy (CSP) does not allow blob: workers. The worker-src directive must include blob: to enable client-side media processing."
1817          };
1818          return cachedResult;
1819        }
1820      }
1821      cachedResult = { supported: true };
1822      return cachedResult;
1823    }
1824    function isClientSideMediaSupported() {
1825      return detectClientSideMediaSupport().supported;
1826    }
1827    function clearFeatureDetectionCache() {
1828      cachedResult = null;
1829    }
1830    return __toCommonJS(index_exports);
1831  })();


Generated : Sat Jun 13 09:38:55 2026 Cross-referenced by PHPXref