All files / libs fileValidation.ts

98.95% Statements 95/96
91.25% Branches 73/80
100% Functions 11/11
98.95% Lines 95/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249                                                          33x 33x 33x 33x 33x 25x 3x       33x 6x 3x 3x   3x 1x   2x   3x   6x 2x 2x   2x 1x   1x   2x       33x 8x   25x                           4x 4x 4x 4x 4x 1x     3x 3x 1x     2x 2x       1x     1x     4x             25x 25x 4x 4x     21x 20x   20x 20x 20x   20x       1x 1x     19x 19x 19x 11x       4x     19x 11x       4x       19x 4x     4x     15x 15x 13x 13x   13x   13x 13x   13x 13x     13x   13x         9x     13x 9x 9x   9x         9x 7x       7x   7x 6x         7x   7x               2x         9x 9x     6x     20x               33x 33x 25x       22x 22x            
type Restrictions = {
  accept: string;
  size: {
    min: number;
    max: number;
  };
  width: {
    min: number;
    max: number;
  };
  height: {
    min: number;
    max: number;
  };
  aspectRatio: {
    min: number[];
    max: number[];
  };
  whitelist: Array<{
    fileName: string;
    accept: string;
    dimensions: number[];
  }>;
};
 
function baseRestrictions(
  file: File,
  restrictions: Restrictions,
): Promise<File> {
  const MB = 1000000;
  const KB = 1000;
  return new Promise((resolve, reject) => {
    const errors = [];
    if (restrictions.accept) {
      if (restrictions.accept.indexOf(file.type) === -1) {
        errors.push("file type is incorrect");
      }
    }
 
    if (restrictions.size) {
      if (restrictions.size.max && file.size > restrictions.size.max) {
        const sizeInMB = restrictions.size.max / MB;
        const sizeInKB = restrictions.size.max / KB;
        let errorStr;
        if (sizeInMB >= 1) {
          errorStr = `${sizeInMB.toFixed(2)}MB`;
        } else {
          errorStr = `${sizeInKB.toFixed(0)}KB`;
        }
        errors.push(`file size is over ${errorStr}`);
      }
      if (restrictions.size.min && file.size < restrictions.size.min) {
        const sizeInMB = restrictions.size.min / MB;
        const sizeInKB = restrictions.size.min / KB;
        let errorStr;
        if (sizeInMB >= 1) {
          errorStr = `${sizeInMB.toFixed(2)}MB`;
        } else {
          errorStr = `${sizeInKB.toFixed(0)}KB`;
        }
        errors.push(`file size is below ${errorStr}`);
      }
    }
 
    if (errors.length > 0) {
      reject(errors);
    } else {
      resolve(file);
    }
  });
}
 
function imageWhitelistHandler(
  file: File,
  image: { naturalWidth: number; naturalHeight: number },
  whitelist: Array<{
    fileName: string;
    accept: string;
    dimensions: number[];
  }>,
): boolean {
  const errors = whitelist.filter((whitelistItem) => {
    Eif (whitelistItem.fileName) {
      let fileName: string[] | string = file.name.split(".");
      fileName = fileName.slice(0, fileName.length - 1).join(".");
      if (fileName !== whitelistItem.fileName) {
        return false;
      }
    }
    Eif (whitelistItem.accept) {
      if (!whitelistItem.accept.includes(file.type)) {
        return false;
      }
    }
    Eif (whitelistItem.dimensions) {
      if (
        image.naturalWidth !== whitelistItem.dimensions[0] ||
        image.naturalHeight !== whitelistItem.dimensions[1]
      ) {
        return false;
      }
    }
    return true;
  });
 
  return errors.length > 0;
}
 
function imageRestrictions(
  file: File,
  restrictions: Restrictions,
): Promise<File> {
  return new Promise((resolve, reject) => {
    if (!restrictions.accept || restrictions.accept[0].indexOf("image") < 0) {
      resolve(file);
      return;
    }
 
    const url = URL.createObjectURL(file);
    const image = new Image();
 
    image.addEventListener("load", () => {
      const width = image.naturalWidth;
      const height = image.naturalHeight;
 
      if (
        restrictions.whitelist &&
        imageWhitelistHandler(file, image, restrictions.whitelist)
      ) {
        resolve(file);
        return;
      }
 
      const aspectRatio = width / height;
      let hasDimensionError = false;
      if (restrictions.width) {
        if (
          (restrictions.width.max && width > restrictions.width.max) ||
          (restrictions.width.min && width < restrictions.width.min)
        ) {
          hasDimensionError = true;
        }
      }
      if (restrictions.height) {
        if (
          (restrictions.height.max && height > restrictions.height.max) ||
          (restrictions.height.min && height < restrictions.height.min)
        ) {
          hasDimensionError = true;
        }
      }
 
      if (hasDimensionError) {
        reject([
          `has dimensions ${width} x ${height} pixels. It needs to be at least ${restrictions.width.min} x ${restrictions.height.min} and at most ${restrictions.width.max} x ${restrictions.height.max} pixels.`,
        ]);
        return;
      }
 
      let hasAspectError = false;
      if (restrictions.aspectRatio) {
        const aspectRatioMax = restrictions.aspectRatio.max;
        const aspectRatioMin = restrictions.aspectRatio.min;
 
        const allowedRatios = [];
 
        Eif (aspectRatioMax) {
          allowedRatios.push(aspectRatioMax[0] / aspectRatioMax[1]);
        }
        Eif (aspectRatioMin) {
          allowedRatios.push(aspectRatioMin[0] / aspectRatioMin[1]);
        }
 
        allowedRatios.sort();
 
        if (
          (allowedRatios.length === 1 && aspectRatio !== allowedRatios[0]) ||
          aspectRatio > allowedRatios[1] ||
          aspectRatio < allowedRatios[0]
        ) {
          hasAspectError = true;
        }
 
        if (hasAspectError) {
          const min = aspectRatioMin[1] / aspectRatioMin[0];
          const max = aspectRatioMax[1] / aspectRatioMax[0];
 
          const message = [
            `(${width} x ${height} pixels) does not have the correct aspect ratio:`,
          ];
 
          // If the min and max are the same we only accept 1 aspect ratio
          if (min === max) {
            message.push(
              `it needs to be ${aspectRatioMin[0]}:${aspectRatioMin[1]}`,
            );
 
            const suggestedSize = [height / max];
 
            if (restrictions.width) {
              Iif (suggestedSize[0] > restrictions.width.max) {
                suggestedSize[0] = restrictions.width.max;
              }
            }
 
            suggestedSize.push(suggestedSize[0] * max);
 
            message.push(
              `(e.g., ${Math.round(suggestedSize[0])} x ${Math.round(
                suggestedSize[1],
              )} pixels)`,
            );
 
            // Otherwise it's a range
          } else {
            message.push(
              `it needs to be between ${aspectRatioMin[0]}:${aspectRatioMin[1]} and ${aspectRatioMax[0]}:${aspectRatioMax[1]}`,
            );
          }
 
          reject([message.join(" ")]);
          return;
        }
      }
      resolve(file);
    });
 
    image.src = url;
  });
}
 
function validateRestrictions(
  file: File,
  restrictions: Restrictions,
): Promise<File> {
  return new Promise((resolve) => {
    baseRestrictions(file, restrictions)
      .then((file) => imageRestrictions(file, restrictions))
      .then(resolve)
      .catch((errors) => {
        // @ts-expect-error - Ignoring TypeScript error because we are attaching an 'errors' property to the 'file' object for validation purposes
        file.errors = errors;
        resolve(file);
      });
  });
}
 
export { validateRestrictions };