( file: FileProperties, allowedTypes: FileRouterInputKey[], )
| 96 | * Prefers the file's type, then falls back to a extension-based lookup |
| 97 | */ |
| 98 | export const matchFileType = ( |
| 99 | file: FileProperties, |
| 100 | allowedTypes: FileRouterInputKey[], |
| 101 | ): Micro.Micro< |
| 102 | FileRouterInputKey, |
| 103 | UnknownFileTypeError | InvalidFileTypeError |
| 104 | > => { |
| 105 | // Type might be "" if the browser doesn't recognize the mime type |
| 106 | const mimeType = file.type || lookup(file.name); |
| 107 | if (!mimeType) { |
| 108 | if (allowedTypes.includes("blob")) return Micro.succeed("blob"); |
| 109 | return Micro.fail(new UnknownFileTypeError(file.name)); |
| 110 | } |
| 111 | |
| 112 | // If the user has specified a specific mime type, use that |
| 113 | if (allowedTypes.some((type) => type.includes("/"))) { |
| 114 | if (allowedTypes.includes(mimeType as FileRouterInputKey)) { |
| 115 | return Micro.succeed(mimeType as FileRouterInputKey); |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | // Otherwise, we have a "magic" type eg. "image" or "video" |
| 120 | const type = ( |
| 121 | mimeType.toLowerCase() === "application/pdf" |
| 122 | ? "pdf" |
| 123 | : mimeType.split("/")[0] |
| 124 | ) as AllowedFileType; |
| 125 | |
| 126 | if (!allowedTypes.includes(type)) { |
| 127 | // Blob is a catch-all for any file type not explicitly supported |
| 128 | if (allowedTypes.includes("blob")) { |
| 129 | return Micro.succeed("blob"); |
| 130 | } else { |
| 131 | return Micro.fail(new InvalidFileTypeError(type, file.name)); |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | return Micro.succeed(type); |
| 136 | }; |
| 137 | |
| 138 | export const FILESIZE_UNITS = ["B", "KB", "MB", "GB", "TB"] as const; |
| 139 | export type FileSizeUnit = (typeof FILESIZE_UNITS)[number]; |
no test coverage detected
searching dependent graphs…