Uppy.ts 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210
  1. /* eslint-disable max-classes-per-file */
  2. /* global AggregateError */
  3. import type { h } from 'preact'
  4. import Translator from '@uppy/utils/lib/Translator'
  5. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  6. // @ts-ignore untyped
  7. import ee from 'namespace-emitter'
  8. import { nanoid } from 'nanoid/non-secure'
  9. import throttle from 'lodash/throttle.js'
  10. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  11. // @ts-ignore store-default types not always available on that branch
  12. import DefaultStore from '@uppy/store-default'
  13. import getFileType from '@uppy/utils/lib/getFileType'
  14. import getFileNameAndExtension from '@uppy/utils/lib/getFileNameAndExtension'
  15. import { getSafeFileId } from '@uppy/utils/lib/generateFileID'
  16. import type {
  17. UppyFile,
  18. Meta,
  19. Body,
  20. MinimalRequiredUppyFile,
  21. } from '@uppy/utils/lib/UppyFile'
  22. import type { CompanionFile } from '@uppy/utils/lib/CompanionFile'
  23. import type {
  24. CompanionClientProvider,
  25. CompanionClientSearchProvider,
  26. } from '@uppy/utils/lib/CompanionClientProvider'
  27. import type {
  28. FileProgressNotStarted,
  29. FileProgressStarted,
  30. } from '@uppy/utils/lib/FileProgress'
  31. import type {
  32. Locale,
  33. I18n,
  34. OptionalPluralizeLocale,
  35. } from '@uppy/utils/lib/Translator'
  36. import supportsUploadProgress from './supportsUploadProgress.ts'
  37. import getFileName from './getFileName.ts'
  38. import { justErrorsLogger, debugLogger } from './loggers.ts'
  39. import {
  40. Restricter,
  41. defaultOptions as defaultRestrictionOptions,
  42. RestrictionError,
  43. } from './Restricter.ts'
  44. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  45. // @ts-ignore We don't want TS to generate types for the package.json
  46. import packageJson from '../package.json'
  47. import locale from './locale.ts'
  48. import type BasePlugin from './BasePlugin.js'
  49. import type { Restrictions, ValidateableFile } from './Restricter.js'
  50. type Processor = (
  51. fileIDs: string[],
  52. uploadID: string,
  53. ) => Promise<unknown> | void
  54. type FileRemoveReason = 'user' | 'cancel-all' | 'unmount'
  55. type LogLevel = 'info' | 'warning' | 'error' | 'success'
  56. export type UnknownPlugin<
  57. M extends Meta,
  58. B extends Body,
  59. PluginState extends Record<string, unknown> = Record<string, unknown>,
  60. > = BasePlugin<any, M, B, PluginState>
  61. export type UnknownProviderPluginState = {
  62. authenticated: boolean | undefined
  63. breadcrumbs: {
  64. requestPath?: string
  65. name?: string
  66. id?: string
  67. }[]
  68. didFirstRender: boolean
  69. currentSelection: CompanionFile[]
  70. filterInput: string
  71. loading: boolean | string
  72. folders: CompanionFile[]
  73. files: CompanionFile[]
  74. isSearchVisible: boolean
  75. }
  76. /*
  77. * UnknownProviderPlugin can be any Companion plugin (such as Google Drive).
  78. * As the plugins are passed around throughout Uppy we need a generic type for this.
  79. * It may seems like duplication, but this type safe. Changing the type of `storage`
  80. * will error in the `Provider` class of @uppy/companion-client and vice versa.
  81. *
  82. * Note that this is the *plugin* class, not a version of the `Provider` class.
  83. * `Provider` does operate on Companion plugins with `uppy.getPlugin()`.
  84. */
  85. export type UnknownProviderPlugin<
  86. M extends Meta,
  87. B extends Body,
  88. > = UnknownPlugin<M, B, UnknownProviderPluginState> & {
  89. onFirstRender: () => void
  90. title: string
  91. files: UppyFile<M, B>[]
  92. icon: () => h.JSX.Element
  93. provider: CompanionClientProvider
  94. storage: {
  95. getItem: (key: string) => Promise<string | null>
  96. setItem: (key: string, value: string) => Promise<void>
  97. removeItem: (key: string) => Promise<void>
  98. }
  99. }
  100. /*
  101. * UnknownSearchProviderPlugin can be any search Companion plugin (such as Unsplash).
  102. * As the plugins are passed around throughout Uppy we need a generic type for this.
  103. * It may seems like duplication, but this type safe. Changing the type of `title`
  104. * will error in the `SearchProvider` class of @uppy/companion-client and vice versa.
  105. *
  106. * Note that this is the *plugin* class, not a version of the `SearchProvider` class.
  107. * `SearchProvider` does operate on Companion plugins with `uppy.getPlugin()`.
  108. */
  109. export type UnknownSearchProviderPluginState = {
  110. isInputMode?: boolean
  111. searchTerm?: string | null
  112. } & Pick<
  113. UnknownProviderPluginState,
  114. | 'loading'
  115. | 'files'
  116. | 'folders'
  117. | 'currentSelection'
  118. | 'filterInput'
  119. | 'didFirstRender'
  120. >
  121. export type UnknownSearchProviderPlugin<
  122. M extends Meta,
  123. B extends Body,
  124. > = UnknownPlugin<M, B, UnknownSearchProviderPluginState> & {
  125. onFirstRender: () => void
  126. title: string
  127. icon: () => h.JSX.Element
  128. provider: CompanionClientSearchProvider
  129. }
  130. export interface UploadResult<M extends Meta, B extends Body> {
  131. successful?: UppyFile<M, B>[]
  132. failed?: UppyFile<M, B>[]
  133. uploadID?: string
  134. [key: string]: unknown
  135. }
  136. interface CurrentUpload<M extends Meta, B extends Body> {
  137. fileIDs: string[]
  138. step: number
  139. result: UploadResult<M, B>
  140. }
  141. // TODO: can we use namespaces in other plugins to populate this?
  142. // eslint-disable-next-line @typescript-eslint/no-empty-interface
  143. interface Plugins extends Record<string, Record<string, unknown> | undefined> {}
  144. export interface State<M extends Meta, B extends Body>
  145. extends Record<string, unknown> {
  146. meta: M
  147. capabilities: {
  148. uploadProgress: boolean
  149. individualCancellation: boolean
  150. resumableUploads: boolean
  151. isMobileDevice?: boolean
  152. darkMode?: boolean
  153. }
  154. currentUploads: Record<string, CurrentUpload<M, B>>
  155. allowNewUpload: boolean
  156. recoveredState: null | Required<Pick<State<M, B>, 'files' | 'currentUploads'>>
  157. error: string | null
  158. files: {
  159. [key: string]: UppyFile<M, B>
  160. }
  161. info: Array<{
  162. isHidden?: boolean
  163. type: LogLevel
  164. message: string
  165. details?: string | Record<string, string> | null
  166. }>
  167. plugins: Plugins
  168. totalProgress: number
  169. companion?: Record<string, string>
  170. }
  171. export interface UppyOptions<M extends Meta, B extends Body> {
  172. id?: string
  173. autoProceed?: boolean
  174. /**
  175. * @deprecated Use allowMultipleUploadBatches
  176. */
  177. allowMultipleUploads?: boolean
  178. allowMultipleUploadBatches?: boolean
  179. logger?: typeof debugLogger
  180. debug?: boolean
  181. restrictions: Restrictions
  182. meta?: M
  183. onBeforeFileAdded?: (
  184. currentFile: UppyFile<M, B>,
  185. files: { [key: string]: UppyFile<M, B> },
  186. ) => UppyFile<M, B> | boolean | undefined
  187. onBeforeUpload?: (files: {
  188. [key: string]: UppyFile<M, B>
  189. }) => { [key: string]: UppyFile<M, B> } | boolean
  190. locale?: Locale
  191. // TODO: add <State<M, B>> when landing on `4.x`
  192. store?: DefaultStore
  193. infoTimeout?: number
  194. }
  195. export interface UppyOptionsWithOptionalRestrictions<
  196. M extends Meta,
  197. B extends Body,
  198. > extends Omit<UppyOptions<M, B>, 'restrictions'> {
  199. restrictions?: Partial<Restrictions>
  200. }
  201. // The user facing type for UppyOptions used in uppy.setOptions()
  202. type MinimalRequiredOptions<M extends Meta, B extends Body> = Partial<
  203. Omit<UppyOptions<M, B>, 'locale' | 'meta' | 'restrictions'> & {
  204. locale: OptionalPluralizeLocale
  205. meta: Partial<M>
  206. restrictions: Partial<Restrictions>
  207. }
  208. >
  209. export type NonNullableUppyOptions<M extends Meta, B extends Body> = Required<
  210. UppyOptions<M, B>
  211. >
  212. export interface _UppyEventMap<M extends Meta, B extends Body> {
  213. 'back-online': () => void
  214. 'cancel-all': (reason: { reason?: FileRemoveReason }) => void
  215. complete: (result: UploadResult<M, B>) => void
  216. error: (
  217. error: { name: string; message: string; details?: string },
  218. file?: UppyFile<M, B>,
  219. response?: UppyFile<M, B>['response'],
  220. ) => void
  221. 'file-added': (file: UppyFile<M, B>) => void
  222. 'file-removed': (file: UppyFile<M, B>, reason?: FileRemoveReason) => void
  223. 'files-added': (files: UppyFile<M, B>[]) => void
  224. 'info-hidden': () => void
  225. 'info-visible': () => void
  226. 'is-offline': () => void
  227. 'is-online': () => void
  228. 'pause-all': () => void
  229. 'plugin-added': (plugin: UnknownPlugin<any, any>) => void
  230. 'plugin-remove': (plugin: UnknownPlugin<any, any>) => void
  231. 'postprocess-complete': (
  232. file: UppyFile<M, B> | undefined,
  233. progress?: NonNullable<FileProgressStarted['preprocess']>,
  234. ) => void
  235. 'postprocess-progress': (
  236. file: UppyFile<M, B> | undefined,
  237. progress: NonNullable<FileProgressStarted['postprocess']>,
  238. ) => void
  239. 'preprocess-complete': (
  240. file: UppyFile<M, B> | undefined,
  241. progress?: NonNullable<FileProgressStarted['preprocess']>,
  242. ) => void
  243. 'preprocess-progress': (
  244. file: UppyFile<M, B> | undefined,
  245. progress: NonNullable<FileProgressStarted['preprocess']>,
  246. ) => void
  247. progress: (progress: number) => void
  248. 'reset-progress': () => void
  249. restored: (pluginData: any) => void
  250. 'restore-confirmed': () => void
  251. 'restore-canceled': () => void
  252. 'restriction-failed': (file: UppyFile<M, B> | undefined, error: Error) => void
  253. 'resume-all': () => void
  254. 'retry-all': (fileIDs: string[]) => void
  255. 'state-update': (
  256. prevState: State<M, B>,
  257. nextState: State<M, B>,
  258. patch?: Partial<State<M, B>>,
  259. ) => void
  260. upload: (data: { id: string; fileIDs: string[] }) => void
  261. 'upload-error': (
  262. file: UppyFile<M, B> | undefined,
  263. error: { name: string; message: string; details?: string },
  264. response?:
  265. | Omit<NonNullable<UppyFile<M, B>['response']>, 'uploadURL'>
  266. | undefined,
  267. ) => void
  268. 'upload-pause': (
  269. fileID: UppyFile<M, B>['id'] | undefined,
  270. isPaused: boolean,
  271. ) => void
  272. 'upload-progress': (
  273. file: UppyFile<M, B> | undefined,
  274. progress: FileProgressStarted,
  275. ) => void
  276. 'upload-retry': (fileID: string) => void
  277. 'upload-stalled': (
  278. error: { message: string; details?: string },
  279. files: UppyFile<M, B>[],
  280. ) => void
  281. 'upload-success': (
  282. file: UppyFile<M, B> | undefined,
  283. response: NonNullable<UppyFile<M, B>['response']>,
  284. ) => void
  285. }
  286. /** @deprecated */
  287. export interface DeprecatedUppyEventMap<M extends Meta, B extends Body> {
  288. 'upload-start': (files: UppyFile<M, B>[]) => void
  289. 'upload-started': (file: UppyFile<M, B>) => void
  290. }
  291. export interface UppyEventMap<M extends Meta, B extends Body>
  292. extends _UppyEventMap<M, B>,
  293. DeprecatedUppyEventMap<M, B> {}
  294. const defaultUploadState = {
  295. totalProgress: 0,
  296. allowNewUpload: true,
  297. error: null,
  298. recoveredState: null,
  299. }
  300. /**
  301. * Uppy Core module.
  302. * Manages plugins, state updates, acts as an event bus,
  303. * adds/removes files and metadata.
  304. */
  305. export class Uppy<M extends Meta, B extends Body> {
  306. static VERSION = packageJson.version
  307. #plugins: Record<string, UnknownPlugin<M, B>[]> = Object.create(null)
  308. #restricter
  309. #storeUnsubscribe
  310. #emitter = ee()
  311. #preProcessors: Set<Processor> = new Set()
  312. #uploaders: Set<Processor> = new Set()
  313. #postProcessors: Set<Processor> = new Set()
  314. defaultLocale: Locale
  315. locale!: Locale
  316. // The user optionally passes in options, but we set defaults for missing options.
  317. // We consider all options present after the contructor has run.
  318. opts: NonNullableUppyOptions<M, B>
  319. store: NonNullableUppyOptions<M, B>['store']
  320. i18n!: I18n
  321. i18nArray!: Translator['translateArray']
  322. scheduledAutoProceed: ReturnType<typeof setTimeout> | null = null
  323. wasOffline = false
  324. /**
  325. * Instantiate Uppy
  326. */
  327. constructor(opts?: UppyOptionsWithOptionalRestrictions<M, B>) {
  328. this.defaultLocale = locale as any as Locale
  329. const defaultOptions: UppyOptions<Record<string, unknown>, B> = {
  330. id: 'uppy',
  331. autoProceed: false,
  332. allowMultipleUploadBatches: true,
  333. debug: false,
  334. restrictions: defaultRestrictionOptions,
  335. meta: {},
  336. onBeforeFileAdded: (file, files) => !Object.hasOwn(files, file.id),
  337. onBeforeUpload: (files) => files,
  338. store: new DefaultStore(),
  339. logger: justErrorsLogger,
  340. infoTimeout: 5000,
  341. }
  342. const merged = { ...defaultOptions, ...opts } as Omit<
  343. NonNullableUppyOptions<M, B>,
  344. 'restrictions'
  345. >
  346. // Merge default options with the ones set by user,
  347. // making sure to merge restrictions too
  348. this.opts = {
  349. ...merged,
  350. restrictions: {
  351. ...(defaultOptions.restrictions as Restrictions),
  352. ...(opts && opts.restrictions),
  353. },
  354. }
  355. // Support debug: true for backwards-compatability, unless logger is set in opts
  356. // opts instead of this.opts to avoid comparing objects — we set logger: justErrorsLogger in defaultOptions
  357. if (opts && opts.logger && opts.debug) {
  358. this.log(
  359. 'You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.',
  360. 'warning',
  361. )
  362. } else if (opts && opts.debug) {
  363. this.opts.logger = debugLogger
  364. }
  365. this.log(`Using Core v${Uppy.VERSION}`)
  366. this.i18nInit()
  367. this.store = this.opts.store
  368. this.setState({
  369. ...defaultUploadState,
  370. plugins: {},
  371. files: {},
  372. currentUploads: {},
  373. capabilities: {
  374. uploadProgress: supportsUploadProgress(),
  375. individualCancellation: true,
  376. resumableUploads: false,
  377. },
  378. meta: { ...this.opts.meta },
  379. info: [],
  380. })
  381. this.#restricter = new Restricter<M, B>(
  382. () => this.opts,
  383. () => this.i18n,
  384. )
  385. this.#storeUnsubscribe = this.store.subscribe(
  386. // eslint-disable-next-line
  387. // @ts-ignore Store is incorrectly typed
  388. (prevState, nextState, patch) => {
  389. // eslint-disable-next-line
  390. // @ts-ignore Store is incorrectly typed
  391. this.emit('state-update', prevState, nextState, patch)
  392. this.updateAll(nextState)
  393. },
  394. )
  395. // Exposing uppy object on window for debugging and testing
  396. if (this.opts.debug && typeof window !== 'undefined') {
  397. // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  398. // @ts-ignore Mutating the global object for debug purposes
  399. window[this.opts.id] = this
  400. }
  401. this.#addListeners()
  402. }
  403. emit<T extends keyof UppyEventMap<M, B>>(
  404. event: T,
  405. ...args: Parameters<UppyEventMap<M, B>[T]>
  406. ): void {
  407. this.#emitter.emit(event, ...args)
  408. }
  409. on<K extends keyof UppyEventMap<M, B>>(
  410. event: K,
  411. callback: UppyEventMap<M, B>[K],
  412. ): this {
  413. this.#emitter.on(event, callback)
  414. return this
  415. }
  416. once<K extends keyof UppyEventMap<M, B>>(
  417. event: K,
  418. callback: UppyEventMap<M, B>[K],
  419. ): this {
  420. this.#emitter.once(event, callback)
  421. return this
  422. }
  423. off<K extends keyof UppyEventMap<M, B>>(
  424. event: K,
  425. callback: UppyEventMap<M, B>[K],
  426. ): this {
  427. this.#emitter.off(event, callback)
  428. return this
  429. }
  430. /**
  431. * Iterate on all plugins and run `update` on them.
  432. * Called each time state changes.
  433. *
  434. */
  435. updateAll(state: Partial<State<M, B>>): void {
  436. this.iteratePlugins((plugin: UnknownPlugin<M, B>) => {
  437. plugin.update(state)
  438. })
  439. }
  440. /**
  441. * Updates state with a patch
  442. */
  443. setState(patch?: Partial<State<M, B>>): void {
  444. // eslint-disable-next-line
  445. // @ts-ignore Store is incorrectly typed
  446. this.store.setState(patch)
  447. }
  448. /**
  449. * Returns current state.
  450. */
  451. getState(): State<M, B> {
  452. // eslint-disable-next-line
  453. // @ts-ignore Store is incorrectly typed
  454. return this.store.getState()
  455. }
  456. patchFilesState(filesWithNewState: {
  457. [id: string]: Partial<UppyFile<M, B>>
  458. }): void {
  459. const existingFilesState = this.getState().files
  460. this.setState({
  461. files: {
  462. ...existingFilesState,
  463. ...Object.fromEntries(
  464. Object.entries(filesWithNewState).map(([fileID, newFileState]) => [
  465. fileID,
  466. {
  467. ...existingFilesState[fileID],
  468. ...newFileState,
  469. },
  470. ]),
  471. ),
  472. },
  473. })
  474. }
  475. /**
  476. * Shorthand to set state for a specific file.
  477. */
  478. setFileState(fileID: string, state: Partial<UppyFile<M, B>>): void {
  479. if (!this.getState().files[fileID]) {
  480. throw new Error(
  481. `Can’t set state for ${fileID} (the file could have been removed)`,
  482. )
  483. }
  484. this.patchFilesState({ [fileID]: state })
  485. }
  486. i18nInit(): void {
  487. const onMissingKey = (key: string): void =>
  488. this.log(`Missing i18n string: ${key}`, 'error')
  489. const translator = new Translator([this.defaultLocale, this.opts.locale], {
  490. onMissingKey,
  491. })
  492. this.i18n = translator.translate.bind(translator)
  493. this.i18nArray = translator.translateArray.bind(translator)
  494. this.locale = translator.locale
  495. }
  496. setOptions(newOpts: MinimalRequiredOptions<M, B>): void {
  497. this.opts = {
  498. ...this.opts,
  499. ...(newOpts as UppyOptions<M, B>),
  500. restrictions: {
  501. ...this.opts.restrictions,
  502. ...(newOpts?.restrictions as Restrictions),
  503. },
  504. }
  505. if (newOpts.meta) {
  506. this.setMeta(newOpts.meta)
  507. }
  508. this.i18nInit()
  509. if (newOpts.locale) {
  510. this.iteratePlugins((plugin) => {
  511. plugin.setOptions(newOpts)
  512. })
  513. }
  514. // Note: this is not the preact `setState`, it's an internal function that has the same name.
  515. this.setState(undefined) // so that UI re-renders with new options
  516. }
  517. // todo next major: remove
  518. resetProgress(): void {
  519. const defaultProgress: Omit<FileProgressNotStarted, 'bytesTotal'> = {
  520. percentage: 0,
  521. bytesUploaded: 0,
  522. uploadComplete: false,
  523. uploadStarted: null,
  524. }
  525. const files = { ...this.getState().files }
  526. const updatedFiles: State<M, B>['files'] = {}
  527. Object.keys(files).forEach((fileID) => {
  528. updatedFiles[fileID] = {
  529. ...files[fileID],
  530. progress: {
  531. ...files[fileID].progress,
  532. ...defaultProgress,
  533. },
  534. }
  535. })
  536. this.setState({ files: updatedFiles, ...defaultUploadState })
  537. this.emit('reset-progress')
  538. }
  539. // @todo next major: rename to `clear()`, make it also cancel ongoing uploads
  540. // or throw and say you need to cancel manually
  541. clearUploadedFiles(): void {
  542. this.setState({ ...defaultUploadState, files: {} })
  543. }
  544. addPreProcessor(fn: Processor): void {
  545. this.#preProcessors.add(fn)
  546. }
  547. removePreProcessor(fn: Processor): boolean {
  548. return this.#preProcessors.delete(fn)
  549. }
  550. addPostProcessor(fn: Processor): void {
  551. this.#postProcessors.add(fn)
  552. }
  553. removePostProcessor(fn: Processor): boolean {
  554. return this.#postProcessors.delete(fn)
  555. }
  556. addUploader(fn: Processor): void {
  557. this.#uploaders.add(fn)
  558. }
  559. removeUploader(fn: Processor): boolean {
  560. return this.#uploaders.delete(fn)
  561. }
  562. setMeta(data: Partial<M>): void {
  563. const updatedMeta = { ...this.getState().meta, ...data }
  564. const updatedFiles = { ...this.getState().files }
  565. Object.keys(updatedFiles).forEach((fileID) => {
  566. updatedFiles[fileID] = {
  567. ...updatedFiles[fileID],
  568. meta: { ...updatedFiles[fileID].meta, ...data },
  569. }
  570. })
  571. this.log('Adding metadata:')
  572. this.log(data)
  573. this.setState({
  574. meta: updatedMeta,
  575. files: updatedFiles,
  576. })
  577. }
  578. setFileMeta(fileID: string, data: State<M, B>['meta']): void {
  579. const updatedFiles = { ...this.getState().files }
  580. if (!updatedFiles[fileID]) {
  581. this.log(
  582. 'Was trying to set metadata for a file that has been removed: ',
  583. fileID,
  584. )
  585. return
  586. }
  587. const newMeta = { ...updatedFiles[fileID].meta, ...data }
  588. updatedFiles[fileID] = { ...updatedFiles[fileID], meta: newMeta }
  589. this.setState({ files: updatedFiles })
  590. }
  591. /**
  592. * Get a file object.
  593. */
  594. getFile(fileID: string): UppyFile<M, B> {
  595. return this.getState().files[fileID]
  596. }
  597. /**
  598. * Get all files in an array.
  599. */
  600. getFiles(): UppyFile<M, B>[] {
  601. const { files } = this.getState()
  602. return Object.values(files)
  603. }
  604. getFilesByIds(ids: string[]): UppyFile<M, B>[] {
  605. return ids.map((id) => this.getFile(id))
  606. }
  607. getObjectOfFilesPerState(): {
  608. newFiles: UppyFile<M, B>[]
  609. startedFiles: UppyFile<M, B>[]
  610. uploadStartedFiles: UppyFile<M, B>[]
  611. pausedFiles: UppyFile<M, B>[]
  612. completeFiles: UppyFile<M, B>[]
  613. erroredFiles: UppyFile<M, B>[]
  614. inProgressFiles: UppyFile<M, B>[]
  615. inProgressNotPausedFiles: UppyFile<M, B>[]
  616. processingFiles: UppyFile<M, B>[]
  617. isUploadStarted: boolean
  618. isAllComplete: boolean
  619. isAllErrored: boolean
  620. isAllPaused: boolean
  621. isUploadInProgress: boolean
  622. isSomeGhost: boolean
  623. } {
  624. const { files: filesObject, totalProgress, error } = this.getState()
  625. const files = Object.values(filesObject)
  626. const inProgressFiles: UppyFile<M, B>[] = []
  627. const newFiles: UppyFile<M, B>[] = []
  628. const startedFiles: UppyFile<M, B>[] = []
  629. const uploadStartedFiles: UppyFile<M, B>[] = []
  630. const pausedFiles: UppyFile<M, B>[] = []
  631. const completeFiles: UppyFile<M, B>[] = []
  632. const erroredFiles: UppyFile<M, B>[] = []
  633. const inProgressNotPausedFiles: UppyFile<M, B>[] = []
  634. const processingFiles: UppyFile<M, B>[] = []
  635. for (const file of files) {
  636. const { progress } = file
  637. if (!progress.uploadComplete && progress.uploadStarted) {
  638. inProgressFiles.push(file)
  639. if (!file.isPaused) {
  640. inProgressNotPausedFiles.push(file)
  641. }
  642. }
  643. if (!progress.uploadStarted) {
  644. newFiles.push(file)
  645. }
  646. if (
  647. progress.uploadStarted ||
  648. progress.preprocess ||
  649. progress.postprocess
  650. ) {
  651. startedFiles.push(file)
  652. }
  653. if (progress.uploadStarted) {
  654. uploadStartedFiles.push(file)
  655. }
  656. if (file.isPaused) {
  657. pausedFiles.push(file)
  658. }
  659. if (progress.uploadComplete) {
  660. completeFiles.push(file)
  661. }
  662. if (file.error) {
  663. erroredFiles.push(file)
  664. }
  665. if (progress.preprocess || progress.postprocess) {
  666. processingFiles.push(file)
  667. }
  668. }
  669. return {
  670. newFiles,
  671. startedFiles,
  672. uploadStartedFiles,
  673. pausedFiles,
  674. completeFiles,
  675. erroredFiles,
  676. inProgressFiles,
  677. inProgressNotPausedFiles,
  678. processingFiles,
  679. isUploadStarted: uploadStartedFiles.length > 0,
  680. isAllComplete:
  681. totalProgress === 100 &&
  682. completeFiles.length === files.length &&
  683. processingFiles.length === 0,
  684. isAllErrored: !!error && erroredFiles.length === files.length,
  685. isAllPaused:
  686. inProgressFiles.length !== 0 &&
  687. pausedFiles.length === inProgressFiles.length,
  688. isUploadInProgress: inProgressFiles.length > 0,
  689. isSomeGhost: files.some((file) => file.isGhost),
  690. }
  691. }
  692. #informAndEmit(
  693. errors: {
  694. name: string
  695. message: string
  696. isUserFacing?: boolean
  697. details?: string
  698. isRestriction?: boolean
  699. file?: UppyFile<M, B>
  700. }[],
  701. ): void {
  702. for (const error of errors) {
  703. if (error.isRestriction) {
  704. this.emit(
  705. 'restriction-failed',
  706. error.file,
  707. error as RestrictionError<M, B>,
  708. )
  709. } else {
  710. this.emit('error', error, error.file)
  711. }
  712. this.log(error, 'warning')
  713. }
  714. const userFacingErrors = errors.filter((error) => error.isUserFacing)
  715. // don't flood the user: only show the first 4 toasts
  716. const maxNumToShow = 4
  717. const firstErrors = userFacingErrors.slice(0, maxNumToShow)
  718. const additionalErrors = userFacingErrors.slice(maxNumToShow)
  719. firstErrors.forEach(({ message, details = '' }) => {
  720. this.info({ message, details }, 'error', this.opts.infoTimeout)
  721. })
  722. if (additionalErrors.length > 0) {
  723. this.info({
  724. message: this.i18n('additionalRestrictionsFailed', {
  725. count: additionalErrors.length,
  726. }),
  727. })
  728. }
  729. }
  730. validateRestrictions(
  731. file: ValidateableFile<M, B>,
  732. files: ValidateableFile<M, B>[] = this.getFiles(),
  733. ): RestrictionError<M, B> | null {
  734. try {
  735. this.#restricter.validate(files, [file])
  736. } catch (err) {
  737. return err as any
  738. }
  739. return null
  740. }
  741. #checkRequiredMetaFieldsOnFile(file: UppyFile<M, B>): boolean {
  742. const { missingFields, error } =
  743. this.#restricter.getMissingRequiredMetaFields(file)
  744. if (missingFields.length > 0) {
  745. this.setFileState(file.id, { missingRequiredMetaFields: missingFields })
  746. this.log(error.message)
  747. this.emit('restriction-failed', file, error)
  748. return false
  749. }
  750. return true
  751. }
  752. #checkRequiredMetaFields(files: State<M, B>['files']): boolean {
  753. let success = true
  754. for (const file of Object.values(files)) {
  755. if (!this.#checkRequiredMetaFieldsOnFile(file)) {
  756. success = false
  757. }
  758. }
  759. return success
  760. }
  761. #assertNewUploadAllowed(file?: UppyFile<M, B>): void {
  762. const { allowNewUpload } = this.getState()
  763. if (allowNewUpload === false) {
  764. const error = new RestrictionError<M, B>(
  765. this.i18n('noMoreFilesAllowed'),
  766. {
  767. file,
  768. },
  769. )
  770. this.#informAndEmit([error])
  771. throw error
  772. }
  773. }
  774. checkIfFileAlreadyExists(fileID: string): boolean {
  775. const { files } = this.getState()
  776. if (files[fileID] && !files[fileID].isGhost) {
  777. return true
  778. }
  779. return false
  780. }
  781. /**
  782. * Create a file state object based on user-provided `addFile()` options.
  783. */
  784. #transformFile(fileDescriptorOrFile: File | UppyFile<M, B>): UppyFile<M, B> {
  785. // Uppy expects files in { name, type, size, data } format.
  786. // If the actual File object is passed from input[type=file] or drag-drop,
  787. // we normalize it to match Uppy file object
  788. const file = (
  789. fileDescriptorOrFile instanceof File ?
  790. {
  791. name: fileDescriptorOrFile.name,
  792. type: fileDescriptorOrFile.type,
  793. size: fileDescriptorOrFile.size,
  794. data: fileDescriptorOrFile,
  795. }
  796. : fileDescriptorOrFile) as UppyFile<M, B>
  797. const fileType = getFileType(file)
  798. const fileName = getFileName(fileType, file)
  799. const fileExtension = getFileNameAndExtension(fileName).extension
  800. const id = getSafeFileId(file, this.getID())
  801. const meta = file.meta || {}
  802. meta.name = fileName
  803. meta.type = fileType
  804. // `null` means the size is unknown.
  805. const size = Number.isFinite(file.data.size) ? file.data.size : null
  806. return {
  807. source: file.source || '',
  808. id,
  809. name: fileName,
  810. extension: fileExtension || '',
  811. meta: {
  812. ...this.getState().meta,
  813. ...meta,
  814. },
  815. type: fileType,
  816. data: file.data,
  817. progress: {
  818. percentage: 0,
  819. bytesUploaded: 0,
  820. bytesTotal: size,
  821. uploadComplete: false,
  822. uploadStarted: null,
  823. } satisfies FileProgressNotStarted,
  824. size,
  825. isGhost: false,
  826. isRemote: file.isRemote || false,
  827. // TODO: this should not be a string
  828. // @ts-expect-error wrong
  829. remote: file.remote || '',
  830. preview: file.preview,
  831. }
  832. }
  833. // Schedule an upload if `autoProceed` is enabled.
  834. #startIfAutoProceed(): void {
  835. if (this.opts.autoProceed && !this.scheduledAutoProceed) {
  836. this.scheduledAutoProceed = setTimeout(() => {
  837. this.scheduledAutoProceed = null
  838. this.upload().catch((err) => {
  839. if (!err.isRestriction) {
  840. this.log(err.stack || err.message || err)
  841. }
  842. })
  843. }, 4)
  844. }
  845. }
  846. #checkAndUpdateFileState(filesToAdd: UppyFile<M, B>[]): {
  847. nextFilesState: State<M, B>['files']
  848. validFilesToAdd: UppyFile<M, B>[]
  849. errors: RestrictionError<M, B>[]
  850. } {
  851. const { files: existingFiles } = this.getState()
  852. // create a copy of the files object only once
  853. const nextFilesState = { ...existingFiles }
  854. const validFilesToAdd: UppyFile<M, B>[] = []
  855. const errors: RestrictionError<M, B>[] = []
  856. for (const fileToAdd of filesToAdd) {
  857. try {
  858. let newFile = this.#transformFile(fileToAdd)
  859. // If a file has been recovered (Golden Retriever), but we were unable to recover its data (probably too large),
  860. // users are asked to re-select these half-recovered files and then this method will be called again.
  861. // In order to keep the progress, meta and everything else, we keep the existing file,
  862. // but we replace `data`, and we remove `isGhost`, because the file is no longer a ghost now
  863. const isGhost = existingFiles[newFile.id]?.isGhost
  864. if (isGhost) {
  865. const existingFileState = existingFiles[newFile.id]
  866. newFile = {
  867. ...existingFileState,
  868. isGhost: false,
  869. data: fileToAdd.data,
  870. }
  871. this.log(
  872. `Replaced the blob in the restored ghost file: ${newFile.name}, ${newFile.id}`,
  873. )
  874. }
  875. const onBeforeFileAddedResult = this.opts.onBeforeFileAdded(
  876. newFile,
  877. nextFilesState,
  878. )
  879. if (
  880. !onBeforeFileAddedResult &&
  881. this.checkIfFileAlreadyExists(newFile.id)
  882. ) {
  883. throw new RestrictionError(
  884. this.i18n('noDuplicates', { fileName: newFile.name }),
  885. { file: fileToAdd },
  886. )
  887. }
  888. // Pass through reselected files from Golden Retriever
  889. if (onBeforeFileAddedResult === false && !isGhost) {
  890. // Don’t show UI info for this error, as it should be done by the developer
  891. throw new RestrictionError(
  892. 'Cannot add the file because onBeforeFileAdded returned false.',
  893. { isUserFacing: false, file: fileToAdd },
  894. )
  895. } else if (
  896. typeof onBeforeFileAddedResult === 'object' &&
  897. onBeforeFileAddedResult !== null
  898. ) {
  899. newFile = onBeforeFileAddedResult
  900. }
  901. this.#restricter.validateSingleFile(newFile)
  902. // need to add it to the new local state immediately, so we can use the state to validate the next files too
  903. nextFilesState[newFile.id] = newFile
  904. validFilesToAdd.push(newFile)
  905. } catch (err) {
  906. errors.push(err as any)
  907. }
  908. }
  909. try {
  910. // need to run this separately because it's much more slow, so if we run it inside the for-loop it will be very slow
  911. // when many files are added
  912. this.#restricter.validateAggregateRestrictions(
  913. Object.values(existingFiles),
  914. validFilesToAdd,
  915. )
  916. } catch (err) {
  917. errors.push(err as any)
  918. // If we have any aggregate error, don't allow adding this batch
  919. return {
  920. nextFilesState: existingFiles,
  921. validFilesToAdd: [],
  922. errors,
  923. }
  924. }
  925. return {
  926. nextFilesState,
  927. validFilesToAdd,
  928. errors,
  929. }
  930. }
  931. /**
  932. * Add a new file to `state.files`. This will run `onBeforeFileAdded`,
  933. * try to guess file type in a clever way, check file against restrictions,
  934. * and start an upload if `autoProceed === true`.
  935. */
  936. addFile(file: File | MinimalRequiredUppyFile<M, B>): UppyFile<M, B>['id'] {
  937. this.#assertNewUploadAllowed(file as UppyFile<M, B>)
  938. const { nextFilesState, validFilesToAdd, errors } =
  939. this.#checkAndUpdateFileState([file as UppyFile<M, B>])
  940. const restrictionErrors = errors.filter((error) => error.isRestriction)
  941. this.#informAndEmit(restrictionErrors)
  942. if (errors.length > 0) throw errors[0]
  943. this.setState({ files: nextFilesState })
  944. const [firstValidFileToAdd] = validFilesToAdd
  945. this.emit('file-added', firstValidFileToAdd)
  946. this.emit('files-added', validFilesToAdd)
  947. this.log(
  948. `Added file: ${firstValidFileToAdd.name}, ${firstValidFileToAdd.id}, mime type: ${firstValidFileToAdd.type}`,
  949. )
  950. this.#startIfAutoProceed()
  951. return firstValidFileToAdd.id
  952. }
  953. /**
  954. * Add multiple files to `state.files`. See the `addFile()` documentation.
  955. *
  956. * If an error occurs while adding a file, it is logged and the user is notified.
  957. * This is good for UI plugins, but not for programmatic use.
  958. * Programmatic users should usually still use `addFile()` on individual files.
  959. */
  960. addFiles(fileDescriptors: MinimalRequiredUppyFile<M, B>[]): void {
  961. this.#assertNewUploadAllowed()
  962. const { nextFilesState, validFilesToAdd, errors } =
  963. this.#checkAndUpdateFileState(fileDescriptors as UppyFile<M, B>[])
  964. const restrictionErrors = errors.filter((error) => error.isRestriction)
  965. this.#informAndEmit(restrictionErrors)
  966. const nonRestrictionErrors = errors.filter((error) => !error.isRestriction)
  967. if (nonRestrictionErrors.length > 0) {
  968. let message = 'Multiple errors occurred while adding files:\n'
  969. nonRestrictionErrors.forEach((subError) => {
  970. message += `\n * ${subError.message}`
  971. })
  972. this.info(
  973. {
  974. message: this.i18n('addBulkFilesFailed', {
  975. smart_count: nonRestrictionErrors.length,
  976. }),
  977. details: message,
  978. },
  979. 'error',
  980. this.opts.infoTimeout,
  981. )
  982. if (typeof AggregateError === 'function') {
  983. throw new AggregateError(nonRestrictionErrors, message)
  984. } else {
  985. const err = new Error(message)
  986. // @ts-expect-error fallback when AggregateError is not available
  987. err.errors = nonRestrictionErrors
  988. throw err
  989. }
  990. }
  991. // OK, we haven't thrown an error, we can start updating state and emitting events now:
  992. this.setState({ files: nextFilesState })
  993. validFilesToAdd.forEach((file) => {
  994. this.emit('file-added', file)
  995. })
  996. this.emit('files-added', validFilesToAdd)
  997. if (validFilesToAdd.length > 5) {
  998. this.log(`Added batch of ${validFilesToAdd.length} files`)
  999. } else {
  1000. Object.values(validFilesToAdd).forEach((file) => {
  1001. this.log(
  1002. `Added file: ${file.name}\n id: ${file.id}\n type: ${file.type}`,
  1003. )
  1004. })
  1005. }
  1006. if (validFilesToAdd.length > 0) {
  1007. this.#startIfAutoProceed()
  1008. }
  1009. }
  1010. removeFiles(fileIDs: string[], reason?: FileRemoveReason): void {
  1011. const { files, currentUploads } = this.getState()
  1012. const updatedFiles = { ...files }
  1013. const updatedUploads = { ...currentUploads }
  1014. const removedFiles = Object.create(null)
  1015. fileIDs.forEach((fileID) => {
  1016. if (files[fileID]) {
  1017. removedFiles[fileID] = files[fileID]
  1018. delete updatedFiles[fileID]
  1019. }
  1020. })
  1021. // Remove files from the `fileIDs` list in each upload.
  1022. function fileIsNotRemoved(uploadFileID: string): boolean {
  1023. return removedFiles[uploadFileID] === undefined
  1024. }
  1025. Object.keys(updatedUploads).forEach((uploadID) => {
  1026. const newFileIDs =
  1027. currentUploads[uploadID].fileIDs.filter(fileIsNotRemoved)
  1028. // Remove the upload if no files are associated with it anymore.
  1029. if (newFileIDs.length === 0) {
  1030. delete updatedUploads[uploadID]
  1031. return
  1032. }
  1033. const { capabilities } = this.getState()
  1034. if (
  1035. newFileIDs.length !== currentUploads[uploadID].fileIDs.length &&
  1036. !capabilities.individualCancellation
  1037. ) {
  1038. throw new Error('individualCancellation is disabled')
  1039. }
  1040. updatedUploads[uploadID] = {
  1041. ...currentUploads[uploadID],
  1042. fileIDs: newFileIDs,
  1043. }
  1044. })
  1045. const stateUpdate: Partial<State<M, B>> = {
  1046. currentUploads: updatedUploads,
  1047. files: updatedFiles,
  1048. }
  1049. // If all files were removed - allow new uploads,
  1050. // and clear recoveredState
  1051. if (Object.keys(updatedFiles).length === 0) {
  1052. stateUpdate.allowNewUpload = true
  1053. stateUpdate.error = null
  1054. stateUpdate.recoveredState = null
  1055. }
  1056. this.setState(stateUpdate)
  1057. this.calculateTotalProgress()
  1058. const removedFileIDs = Object.keys(removedFiles)
  1059. removedFileIDs.forEach((fileID) => {
  1060. this.emit('file-removed', removedFiles[fileID], reason)
  1061. })
  1062. if (removedFileIDs.length > 5) {
  1063. this.log(`Removed ${removedFileIDs.length} files`)
  1064. } else {
  1065. this.log(`Removed files: ${removedFileIDs.join(', ')}`)
  1066. }
  1067. }
  1068. removeFile(fileID: string, reason?: FileRemoveReason): void {
  1069. this.removeFiles([fileID], reason)
  1070. }
  1071. pauseResume(fileID: string): boolean | undefined {
  1072. if (
  1073. !this.getState().capabilities.resumableUploads ||
  1074. this.getFile(fileID).progress.uploadComplete
  1075. ) {
  1076. return undefined
  1077. }
  1078. const wasPaused = this.getFile(fileID).isPaused || false
  1079. const isPaused = !wasPaused
  1080. this.setFileState(fileID, {
  1081. isPaused,
  1082. })
  1083. this.emit('upload-pause', fileID, isPaused)
  1084. return isPaused
  1085. }
  1086. pauseAll(): void {
  1087. const updatedFiles = { ...this.getState().files }
  1088. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  1089. return (
  1090. !updatedFiles[file].progress.uploadComplete &&
  1091. updatedFiles[file].progress.uploadStarted
  1092. )
  1093. })
  1094. inProgressUpdatedFiles.forEach((file) => {
  1095. const updatedFile = { ...updatedFiles[file], isPaused: true }
  1096. updatedFiles[file] = updatedFile
  1097. })
  1098. this.setState({ files: updatedFiles })
  1099. this.emit('pause-all')
  1100. }
  1101. resumeAll(): void {
  1102. const updatedFiles = { ...this.getState().files }
  1103. const inProgressUpdatedFiles = Object.keys(updatedFiles).filter((file) => {
  1104. return (
  1105. !updatedFiles[file].progress.uploadComplete &&
  1106. updatedFiles[file].progress.uploadStarted
  1107. )
  1108. })
  1109. inProgressUpdatedFiles.forEach((file) => {
  1110. const updatedFile = {
  1111. ...updatedFiles[file],
  1112. isPaused: false,
  1113. error: null,
  1114. }
  1115. updatedFiles[file] = updatedFile
  1116. })
  1117. this.setState({ files: updatedFiles })
  1118. this.emit('resume-all')
  1119. }
  1120. retryAll(): Promise<UploadResult<M, B> | undefined> {
  1121. const updatedFiles = { ...this.getState().files }
  1122. const filesToRetry = Object.keys(updatedFiles).filter((file) => {
  1123. return updatedFiles[file].error
  1124. })
  1125. filesToRetry.forEach((file) => {
  1126. const updatedFile = {
  1127. ...updatedFiles[file],
  1128. isPaused: false,
  1129. error: null,
  1130. }
  1131. updatedFiles[file] = updatedFile
  1132. })
  1133. this.setState({
  1134. files: updatedFiles,
  1135. error: null,
  1136. })
  1137. this.emit('retry-all', filesToRetry)
  1138. if (filesToRetry.length === 0) {
  1139. return Promise.resolve({
  1140. successful: [],
  1141. failed: [],
  1142. })
  1143. }
  1144. const uploadID = this.#createUpload(filesToRetry, {
  1145. forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
  1146. })
  1147. return this.#runUpload(uploadID)
  1148. }
  1149. cancelAll({ reason = 'user' }: { reason?: FileRemoveReason } = {}): void {
  1150. this.emit('cancel-all', { reason })
  1151. // Only remove existing uploads if user is canceling
  1152. if (reason === 'user') {
  1153. const { files } = this.getState()
  1154. const fileIDs = Object.keys(files)
  1155. if (fileIDs.length) {
  1156. this.removeFiles(fileIDs, 'cancel-all')
  1157. }
  1158. this.setState(defaultUploadState)
  1159. // todo should we call this.emit('reset-progress') like we do for resetProgress?
  1160. }
  1161. }
  1162. retryUpload(fileID: string): Promise<UploadResult<M, B> | undefined> {
  1163. this.setFileState(fileID, {
  1164. error: null,
  1165. isPaused: false,
  1166. })
  1167. this.emit('upload-retry', fileID)
  1168. const uploadID = this.#createUpload([fileID], {
  1169. forceAllowNewUpload: true, // create new upload even if allowNewUpload: false
  1170. })
  1171. return this.#runUpload(uploadID)
  1172. }
  1173. logout(): void {
  1174. this.iteratePlugins((plugin) => {
  1175. ;(plugin as UnknownProviderPlugin<M, B>).provider?.logout?.()
  1176. })
  1177. }
  1178. // ___Why throttle at 500ms?
  1179. // - We must throttle at >250ms for superfocus in Dashboard to work well
  1180. // (because animation takes 0.25s, and we want to wait for all animations to be over before refocusing).
  1181. // [Practical Check]: if thottle is at 100ms, then if you are uploading a file,
  1182. // and click 'ADD MORE FILES', - focus won't activate in Firefox.
  1183. // - We must throttle at around >500ms to avoid performance lags.
  1184. // [Practical Check] Firefox, try to upload a big file for a prolonged period of time. Laptop will start to heat up.
  1185. // todo when uploading multiple files, this will cause problems because they share the same throttle,
  1186. // meaning some files might never get their progress reported (eaten up by progress events from other files)
  1187. calculateProgress = throttle(
  1188. (file, data) => {
  1189. const fileInState = this.getFile(file?.id)
  1190. if (file == null || !fileInState) {
  1191. this.log(
  1192. `Not setting progress for a file that has been removed: ${file?.id}`,
  1193. )
  1194. return
  1195. }
  1196. if (fileInState.progress.percentage === 100) {
  1197. this.log(
  1198. `Not setting progress for a file that has been already uploaded: ${file.id}`,
  1199. )
  1200. return
  1201. }
  1202. // bytesTotal may be null or zero; in that case we can't divide by it
  1203. const canHavePercentage =
  1204. Number.isFinite(data.bytesTotal) && data.bytesTotal > 0
  1205. this.setFileState(file.id, {
  1206. progress: {
  1207. ...fileInState.progress,
  1208. bytesUploaded: data.bytesUploaded,
  1209. bytesTotal: data.bytesTotal,
  1210. percentage:
  1211. canHavePercentage ?
  1212. Math.round((data.bytesUploaded / data.bytesTotal) * 100)
  1213. : 0,
  1214. },
  1215. })
  1216. this.calculateTotalProgress()
  1217. },
  1218. 500,
  1219. { leading: true, trailing: true },
  1220. )
  1221. calculateTotalProgress(): void {
  1222. // calculate total progress, using the number of files currently uploading,
  1223. // multiplied by 100 and the summ of individual progress of each file
  1224. const files = this.getFiles()
  1225. const inProgress = files.filter((file) => {
  1226. return (
  1227. file.progress.uploadStarted ||
  1228. file.progress.preprocess ||
  1229. file.progress.postprocess
  1230. )
  1231. })
  1232. if (inProgress.length === 0) {
  1233. this.emit('progress', 0)
  1234. this.setState({ totalProgress: 0 })
  1235. return
  1236. }
  1237. const sizedFiles = inProgress.filter(
  1238. (file) => file.progress.bytesTotal != null,
  1239. )
  1240. const unsizedFiles = inProgress.filter(
  1241. (file) => file.progress.bytesTotal == null,
  1242. )
  1243. if (sizedFiles.length === 0) {
  1244. const progressMax = inProgress.length * 100
  1245. const currentProgress = unsizedFiles.reduce((acc, file) => {
  1246. return acc + (file.progress.percentage as number)
  1247. }, 0)
  1248. const totalProgress = Math.round((currentProgress / progressMax) * 100)
  1249. this.setState({ totalProgress })
  1250. return
  1251. }
  1252. let totalSize = sizedFiles.reduce((acc, file) => {
  1253. return (acc + (file.progress.bytesTotal ?? 0)) as number
  1254. }, 0)
  1255. const averageSize = totalSize / sizedFiles.length
  1256. totalSize += averageSize * unsizedFiles.length
  1257. let uploadedSize = 0
  1258. sizedFiles.forEach((file) => {
  1259. uploadedSize += file.progress.bytesUploaded as number
  1260. })
  1261. unsizedFiles.forEach((file) => {
  1262. uploadedSize += (averageSize * (file.progress.percentage || 0)) / 100
  1263. })
  1264. let totalProgress =
  1265. totalSize === 0 ? 0 : Math.round((uploadedSize / totalSize) * 100)
  1266. // hot fix, because:
  1267. // uploadedSize ended up larger than totalSize, resulting in 1325% total
  1268. if (totalProgress > 100) {
  1269. totalProgress = 100
  1270. }
  1271. this.setState({ totalProgress })
  1272. this.emit('progress', totalProgress)
  1273. }
  1274. /**
  1275. * Registers listeners for all global actions, like:
  1276. * `error`, `file-removed`, `upload-progress`
  1277. */
  1278. #addListeners(): void {
  1279. // Type inference only works for inline functions so we have to type it again
  1280. const errorHandler: UppyEventMap<M, B>['error'] = (
  1281. error,
  1282. file,
  1283. response,
  1284. ) => {
  1285. let errorMsg = error.message || 'Unknown error'
  1286. if (error.details) {
  1287. errorMsg += ` ${error.details}`
  1288. }
  1289. this.setState({ error: errorMsg })
  1290. if (file != null && file.id in this.getState().files) {
  1291. this.setFileState(file.id, {
  1292. error: errorMsg,
  1293. response,
  1294. })
  1295. }
  1296. }
  1297. this.on('error', errorHandler)
  1298. this.on('upload-error', (file, error, response) => {
  1299. errorHandler(error, file, response)
  1300. if (typeof error === 'object' && error.message) {
  1301. this.log(error.message, 'error')
  1302. const newError = new Error(
  1303. this.i18n('failedToUpload', { file: file?.name ?? '' }),
  1304. ) as any // we may want a new custom error here
  1305. newError.isUserFacing = true // todo maybe don't do this with all errors?
  1306. newError.details = error.message
  1307. if (error.details) {
  1308. newError.details += ` ${error.details}`
  1309. }
  1310. this.#informAndEmit([newError])
  1311. } else {
  1312. this.#informAndEmit([error])
  1313. }
  1314. })
  1315. let uploadStalledWarningRecentlyEmitted: ReturnType<
  1316. typeof setTimeout
  1317. > | null = null
  1318. this.on('upload-stalled', (error, files) => {
  1319. const { message } = error
  1320. const details = files.map((file) => file.meta.name).join(', ')
  1321. if (!uploadStalledWarningRecentlyEmitted) {
  1322. this.info({ message, details }, 'warning', this.opts.infoTimeout)
  1323. uploadStalledWarningRecentlyEmitted = setTimeout(() => {
  1324. uploadStalledWarningRecentlyEmitted = null
  1325. }, this.opts.infoTimeout)
  1326. }
  1327. this.log(`${message} ${details}`.trim(), 'warning')
  1328. })
  1329. this.on('upload', () => {
  1330. this.setState({ error: null })
  1331. })
  1332. const onUploadStarted = (files: UppyFile<M, B>[]): void => {
  1333. const filesFiltered = files.filter((file) => {
  1334. const exists = file != null && this.getFile(file.id)
  1335. if (!exists)
  1336. this.log(
  1337. `Not setting progress for a file that has been removed: ${file?.id}`,
  1338. )
  1339. return exists
  1340. })
  1341. const filesState = Object.fromEntries(
  1342. filesFiltered.map((file) => [
  1343. file.id,
  1344. {
  1345. progress: {
  1346. uploadStarted: Date.now(),
  1347. uploadComplete: false,
  1348. percentage: 0,
  1349. bytesUploaded: 0,
  1350. bytesTotal: file.size,
  1351. } as FileProgressStarted,
  1352. },
  1353. ]),
  1354. )
  1355. this.patchFilesState(filesState)
  1356. }
  1357. this.on('upload-start', (files) => {
  1358. files.forEach((file: UppyFile<M, B>) => {
  1359. // todo backward compat, remove this event in a next major
  1360. this.emit('upload-started', file)
  1361. })
  1362. onUploadStarted(files)
  1363. })
  1364. this.on('upload-progress', this.calculateProgress)
  1365. this.on('upload-success', (file, uploadResp) => {
  1366. if (file == null || !this.getFile(file.id)) {
  1367. this.log(
  1368. `Not setting progress for a file that has been removed: ${file?.id}`,
  1369. )
  1370. return
  1371. }
  1372. const currentProgress = this.getFile(file.id).progress
  1373. this.setFileState(file.id, {
  1374. progress: {
  1375. ...currentProgress,
  1376. postprocess:
  1377. this.#postProcessors.size > 0 ?
  1378. {
  1379. mode: 'indeterminate',
  1380. }
  1381. : undefined,
  1382. uploadComplete: true,
  1383. percentage: 100,
  1384. bytesUploaded: currentProgress.bytesTotal,
  1385. } as FileProgressStarted,
  1386. response: uploadResp,
  1387. uploadURL: uploadResp.uploadURL,
  1388. isPaused: false,
  1389. })
  1390. // Remote providers sometimes don't tell us the file size,
  1391. // but we can know how many bytes we uploaded once the upload is complete.
  1392. if (file.size == null) {
  1393. this.setFileState(file.id, {
  1394. size: uploadResp.bytesUploaded || currentProgress.bytesTotal,
  1395. })
  1396. }
  1397. this.calculateTotalProgress()
  1398. })
  1399. this.on('preprocess-progress', (file, progress) => {
  1400. if (file == null || !this.getFile(file.id)) {
  1401. this.log(
  1402. `Not setting progress for a file that has been removed: ${file?.id}`,
  1403. )
  1404. return
  1405. }
  1406. this.setFileState(file.id, {
  1407. progress: { ...this.getFile(file.id).progress, preprocess: progress },
  1408. })
  1409. })
  1410. this.on('preprocess-complete', (file) => {
  1411. if (file == null || !this.getFile(file.id)) {
  1412. this.log(
  1413. `Not setting progress for a file that has been removed: ${file?.id}`,
  1414. )
  1415. return
  1416. }
  1417. const files = { ...this.getState().files }
  1418. files[file.id] = {
  1419. ...files[file.id],
  1420. progress: { ...files[file.id].progress },
  1421. }
  1422. delete files[file.id].progress.preprocess
  1423. this.setState({ files })
  1424. })
  1425. this.on('postprocess-progress', (file, progress) => {
  1426. if (file == null || !this.getFile(file.id)) {
  1427. this.log(
  1428. `Not setting progress for a file that has been removed: ${file?.id}`,
  1429. )
  1430. return
  1431. }
  1432. this.setFileState(file.id, {
  1433. progress: {
  1434. ...this.getState().files[file.id].progress,
  1435. postprocess: progress,
  1436. },
  1437. })
  1438. })
  1439. this.on('postprocess-complete', (file) => {
  1440. if (file == null || !this.getFile(file.id)) {
  1441. this.log(
  1442. `Not setting progress for a file that has been removed: ${file?.id}`,
  1443. )
  1444. return
  1445. }
  1446. const files = {
  1447. ...this.getState().files,
  1448. }
  1449. files[file.id] = {
  1450. ...files[file.id],
  1451. progress: {
  1452. ...files[file.id].progress,
  1453. },
  1454. }
  1455. delete files[file.id].progress.postprocess
  1456. this.setState({ files })
  1457. })
  1458. this.on('restored', () => {
  1459. // Files may have changed--ensure progress is still accurate.
  1460. this.calculateTotalProgress()
  1461. })
  1462. // @ts-expect-error should fix itself when dashboard it typed (also this doesn't belong here)
  1463. this.on('dashboard:file-edit-complete', (file) => {
  1464. if (file) {
  1465. this.#checkRequiredMetaFieldsOnFile(file)
  1466. }
  1467. })
  1468. // show informer if offline
  1469. if (typeof window !== 'undefined' && window.addEventListener) {
  1470. window.addEventListener('online', this.#updateOnlineStatus)
  1471. window.addEventListener('offline', this.#updateOnlineStatus)
  1472. setTimeout(this.#updateOnlineStatus, 3000)
  1473. }
  1474. }
  1475. updateOnlineStatus(): void {
  1476. const online = window.navigator.onLine ?? true
  1477. if (!online) {
  1478. this.emit('is-offline')
  1479. this.info(this.i18n('noInternetConnection'), 'error', 0)
  1480. this.wasOffline = true
  1481. } else {
  1482. this.emit('is-online')
  1483. if (this.wasOffline) {
  1484. this.emit('back-online')
  1485. this.info(this.i18n('connectedToInternet'), 'success', 3000)
  1486. this.wasOffline = false
  1487. }
  1488. }
  1489. }
  1490. #updateOnlineStatus = this.updateOnlineStatus.bind(this)
  1491. getID(): string {
  1492. return this.opts.id
  1493. }
  1494. /**
  1495. * Registers a plugin with Core.
  1496. */
  1497. use<T extends typeof BasePlugin<any, M, B>>(
  1498. Plugin: T,
  1499. opts?: ConstructorParameters<T>[1],
  1500. ): this {
  1501. if (typeof Plugin !== 'function') {
  1502. const msg =
  1503. `Expected a plugin class, but got ${
  1504. Plugin === null ? 'null' : typeof Plugin
  1505. }.` +
  1506. ' Please verify that the plugin was imported and spelled correctly.'
  1507. throw new TypeError(msg)
  1508. }
  1509. // Instantiate
  1510. const plugin = new Plugin(this, opts)
  1511. const pluginId = plugin.id
  1512. if (!pluginId) {
  1513. throw new Error('Your plugin must have an id')
  1514. }
  1515. if (!plugin.type) {
  1516. throw new Error('Your plugin must have a type')
  1517. }
  1518. const existsPluginAlready = this.getPlugin(pluginId)
  1519. if (existsPluginAlready) {
  1520. const msg =
  1521. `Already found a plugin named '${existsPluginAlready.id}'. ` +
  1522. `Tried to use: '${pluginId}'.\n` +
  1523. 'Uppy plugins must have unique `id` options. See https://uppy.io/docs/plugins/#id.'
  1524. throw new Error(msg)
  1525. }
  1526. // @ts-expect-error does exist
  1527. if (Plugin.VERSION) {
  1528. // @ts-expect-error does exist
  1529. this.log(`Using ${pluginId} v${Plugin.VERSION}`)
  1530. }
  1531. if (plugin.type in this.#plugins) {
  1532. this.#plugins[plugin.type].push(plugin)
  1533. } else {
  1534. this.#plugins[plugin.type] = [plugin]
  1535. }
  1536. plugin.install()
  1537. this.emit('plugin-added', plugin)
  1538. return this
  1539. }
  1540. /**
  1541. * Find one Plugin by name.
  1542. */
  1543. getPlugin(id: string): UnknownPlugin<M, B> | undefined {
  1544. for (const plugins of Object.values(this.#plugins)) {
  1545. const foundPlugin = plugins.find((plugin) => plugin.id === id)
  1546. if (foundPlugin != null) return foundPlugin
  1547. }
  1548. return undefined
  1549. }
  1550. private [Symbol.for('uppy test: getPlugins')](
  1551. type: string,
  1552. ): UnknownPlugin<M, B>[] {
  1553. return this.#plugins[type]
  1554. }
  1555. /**
  1556. * Iterate through all `use`d plugins.
  1557. *
  1558. */
  1559. iteratePlugins(method: (plugin: UnknownPlugin<M, B>) => void): void {
  1560. Object.values(this.#plugins).flat(1).forEach(method)
  1561. }
  1562. /**
  1563. * Uninstall and remove a plugin.
  1564. *
  1565. * @param {object} instance The plugin instance to remove.
  1566. */
  1567. removePlugin(instance: UnknownPlugin<M, B>): void {
  1568. this.log(`Removing plugin ${instance.id}`)
  1569. this.emit('plugin-remove', instance)
  1570. if (instance.uninstall) {
  1571. instance.uninstall()
  1572. }
  1573. const list = this.#plugins[instance.type]
  1574. // list.indexOf failed here, because Vue3 converted the plugin instance
  1575. // to a Proxy object, which failed the strict comparison test:
  1576. // obj !== objProxy
  1577. const index = list.findIndex((item) => item.id === instance.id)
  1578. if (index !== -1) {
  1579. list.splice(index, 1)
  1580. }
  1581. const state = this.getState()
  1582. const updatedState = {
  1583. plugins: {
  1584. ...state.plugins,
  1585. [instance.id]: undefined,
  1586. },
  1587. }
  1588. this.setState(updatedState)
  1589. }
  1590. /**
  1591. * Uninstall all plugins and close down this Uppy instance.
  1592. */
  1593. // @todo next major: rename to `destroy`.
  1594. // Cancel local uploads, cancel remote uploads, DON'T cancel assemblies
  1595. // document that if you do want to cancel assemblies, you need to call smth manually.
  1596. // Potentially remove reason, as it’s confusing, just come up with a default behaviour.
  1597. close({ reason }: { reason?: FileRemoveReason } | undefined = {}): void {
  1598. this.log(
  1599. `Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`,
  1600. )
  1601. this.cancelAll({ reason })
  1602. this.#storeUnsubscribe()
  1603. this.iteratePlugins((plugin) => {
  1604. this.removePlugin(plugin)
  1605. })
  1606. if (typeof window !== 'undefined' && window.removeEventListener) {
  1607. window.removeEventListener('online', this.#updateOnlineStatus)
  1608. window.removeEventListener('offline', this.#updateOnlineStatus)
  1609. }
  1610. }
  1611. hideInfo(): void {
  1612. const { info } = this.getState()
  1613. this.setState({ info: info.slice(1) })
  1614. this.emit('info-hidden')
  1615. }
  1616. /**
  1617. * Set info message in `state.info`, so that UI plugins like `Informer`
  1618. * can display the message.
  1619. */
  1620. info(
  1621. message:
  1622. | string
  1623. | { message: string; details?: string | Record<string, string> },
  1624. type: LogLevel = 'info',
  1625. duration = 3000,
  1626. ): void {
  1627. const isComplexMessage = typeof message === 'object'
  1628. this.setState({
  1629. info: [
  1630. ...this.getState().info,
  1631. {
  1632. type,
  1633. message: isComplexMessage ? message.message : message,
  1634. details: isComplexMessage ? message.details : null,
  1635. },
  1636. ],
  1637. })
  1638. setTimeout(() => this.hideInfo(), duration)
  1639. this.emit('info-visible')
  1640. }
  1641. /**
  1642. * Passes messages to a function, provided in `opts.logger`.
  1643. * If `opts.logger: Uppy.debugLogger` or `opts.debug: true`, logs to the browser console.
  1644. */
  1645. log(message: string | Record<any, any> | Error, type?: string): void {
  1646. const { logger } = this.opts
  1647. switch (type) {
  1648. case 'error':
  1649. logger.error(message)
  1650. break
  1651. case 'warning':
  1652. logger.warn(message)
  1653. break
  1654. default:
  1655. logger.debug(message)
  1656. break
  1657. }
  1658. }
  1659. // We need to store request clients by a unique ID, so we can share RequestClient instances across files
  1660. // this allows us to do rate limiting and synchronous operations like refreshing provider tokens
  1661. // example: refreshing tokens: if each file has their own requestclient,
  1662. // we don't have any way to synchronize all requests in order to
  1663. // - block all requests
  1664. // - refresh the token
  1665. // - unblock all requests and allow them to run with a the new access token
  1666. // back when we had a requestclient per file, once an access token expired,
  1667. // all 6 files would go ahead and refresh the token at the same time
  1668. // (calling /refresh-token up to 6 times), which will probably fail for some providers
  1669. #requestClientById = new Map<string, unknown>()
  1670. registerRequestClient(id: string, client: unknown): void {
  1671. this.#requestClientById.set(id, client)
  1672. }
  1673. /** @protected */
  1674. getRequestClientForFile<Client>(file: UppyFile<M, B>): Client {
  1675. if (!file.remote)
  1676. throw new Error(
  1677. `Tried to get RequestClient for a non-remote file ${file.id}`,
  1678. )
  1679. const requestClient = this.#requestClientById.get(
  1680. file.remote.requestClientId,
  1681. )
  1682. if (requestClient == null)
  1683. throw new Error(
  1684. `requestClientId "${file.remote.requestClientId}" not registered for file "${file.id}"`,
  1685. )
  1686. return requestClient as Client
  1687. }
  1688. /**
  1689. * Restore an upload by its ID.
  1690. */
  1691. restore(uploadID: string): Promise<UploadResult<M, B> | undefined> {
  1692. this.log(`Core: attempting to restore upload "${uploadID}"`)
  1693. if (!this.getState().currentUploads[uploadID]) {
  1694. this.#removeUpload(uploadID)
  1695. return Promise.reject(new Error('Nonexistent upload'))
  1696. }
  1697. return this.#runUpload(uploadID)
  1698. }
  1699. /**
  1700. * Create an upload for a bunch of files.
  1701. *
  1702. */
  1703. #createUpload(
  1704. fileIDs: string[],
  1705. opts: { forceAllowNewUpload?: boolean } = {},
  1706. ): string {
  1707. // uppy.retryAll sets this to true — when retrying we want to ignore `allowNewUpload: false`
  1708. const { forceAllowNewUpload = false } = opts
  1709. const { allowNewUpload, currentUploads } = this.getState()
  1710. if (!allowNewUpload && !forceAllowNewUpload) {
  1711. throw new Error('Cannot create a new upload: already uploading.')
  1712. }
  1713. const uploadID = nanoid()
  1714. this.emit('upload', {
  1715. id: uploadID,
  1716. fileIDs,
  1717. })
  1718. this.setState({
  1719. allowNewUpload:
  1720. this.opts.allowMultipleUploadBatches !== false &&
  1721. this.opts.allowMultipleUploads !== false,
  1722. currentUploads: {
  1723. ...currentUploads,
  1724. [uploadID]: {
  1725. fileIDs,
  1726. step: 0,
  1727. result: {},
  1728. },
  1729. },
  1730. })
  1731. return uploadID
  1732. }
  1733. private [Symbol.for('uppy test: createUpload')](...args: any[]): string {
  1734. // @ts-expect-error https://github.com/microsoft/TypeScript/issues/47595
  1735. return this.#createUpload(...args)
  1736. }
  1737. #getUpload(uploadID: string): CurrentUpload<M, B> {
  1738. const { currentUploads } = this.getState()
  1739. return currentUploads[uploadID]
  1740. }
  1741. /**
  1742. * Add data to an upload's result object.
  1743. */
  1744. addResultData(uploadID: string, data: CurrentUpload<M, B>['result']): void {
  1745. if (!this.#getUpload(uploadID)) {
  1746. this.log(
  1747. `Not setting result for an upload that has been removed: ${uploadID}`,
  1748. )
  1749. return
  1750. }
  1751. const { currentUploads } = this.getState()
  1752. const currentUpload = {
  1753. ...currentUploads[uploadID],
  1754. result: { ...currentUploads[uploadID].result, ...data },
  1755. }
  1756. this.setState({
  1757. currentUploads: { ...currentUploads, [uploadID]: currentUpload },
  1758. })
  1759. }
  1760. /**
  1761. * Remove an upload, eg. if it has been canceled or completed.
  1762. *
  1763. */
  1764. #removeUpload(uploadID: string): void {
  1765. const currentUploads = { ...this.getState().currentUploads }
  1766. delete currentUploads[uploadID]
  1767. this.setState({
  1768. currentUploads,
  1769. })
  1770. }
  1771. /**
  1772. * Run an upload. This picks up where it left off in case the upload is being restored.
  1773. */
  1774. async #runUpload(uploadID: string): Promise<UploadResult<M, B> | undefined> {
  1775. const getCurrentUpload = (): CurrentUpload<M, B> => {
  1776. const { currentUploads } = this.getState()
  1777. return currentUploads[uploadID]
  1778. }
  1779. let currentUpload = getCurrentUpload()
  1780. const steps = [
  1781. ...this.#preProcessors,
  1782. ...this.#uploaders,
  1783. ...this.#postProcessors,
  1784. ]
  1785. try {
  1786. for (let step = currentUpload.step || 0; step < steps.length; step++) {
  1787. if (!currentUpload) {
  1788. break
  1789. }
  1790. const fn = steps[step]
  1791. this.setState({
  1792. currentUploads: {
  1793. ...this.getState().currentUploads,
  1794. [uploadID]: {
  1795. ...currentUpload,
  1796. step,
  1797. },
  1798. },
  1799. })
  1800. const { fileIDs } = currentUpload
  1801. // TODO give this the `updatedUpload` object as its only parameter maybe?
  1802. // Otherwise when more metadata may be added to the upload this would keep getting more parameters
  1803. await fn(fileIDs, uploadID)
  1804. // Update currentUpload value in case it was modified asynchronously.
  1805. currentUpload = getCurrentUpload()
  1806. }
  1807. } catch (err) {
  1808. this.#removeUpload(uploadID)
  1809. throw err
  1810. }
  1811. // Set result data.
  1812. if (currentUpload) {
  1813. // Mark postprocessing step as complete if necessary; this addresses a case where we might get
  1814. // stuck in the postprocessing UI while the upload is fully complete.
  1815. // If the postprocessing steps do not do any work, they may not emit postprocessing events at
  1816. // all, and never mark the postprocessing as complete. This is fine on its own but we
  1817. // introduced code in the @uppy/core upload-success handler to prepare postprocessing progress
  1818. // state if any postprocessors are registered. That is to avoid a "flash of completed state"
  1819. // before the postprocessing plugins can emit events.
  1820. //
  1821. // So, just in case an upload with postprocessing plugins *has* completed *without* emitting
  1822. // postprocessing completion, we do it instead.
  1823. currentUpload.fileIDs.forEach((fileID) => {
  1824. const file = this.getFile(fileID)
  1825. if (file && file.progress.postprocess) {
  1826. this.emit('postprocess-complete', file)
  1827. }
  1828. })
  1829. const files = currentUpload.fileIDs.map((fileID) => this.getFile(fileID))
  1830. const successful = files.filter((file) => !file.error)
  1831. const failed = files.filter((file) => file.error)
  1832. this.addResultData(uploadID, { successful, failed, uploadID })
  1833. // Update currentUpload value in case it was modified asynchronously.
  1834. currentUpload = getCurrentUpload()
  1835. }
  1836. // Emit completion events.
  1837. // This is in a separate function so that the `currentUploads` variable
  1838. // always refers to the latest state. In the handler right above it refers
  1839. // to an outdated object without the `.result` property.
  1840. let result
  1841. if (currentUpload) {
  1842. result = currentUpload.result
  1843. this.emit('complete', result)
  1844. this.#removeUpload(uploadID)
  1845. }
  1846. if (result == null) {
  1847. this.log(
  1848. `Not setting result for an upload that has been removed: ${uploadID}`,
  1849. )
  1850. }
  1851. return result
  1852. }
  1853. /**
  1854. * Start an upload for all the files that are not currently being uploaded.
  1855. */
  1856. upload(): Promise<NonNullable<UploadResult<M, B>> | undefined> {
  1857. if (!this.#plugins['uploader']?.length) {
  1858. this.log('No uploader type plugins are used', 'warning')
  1859. }
  1860. let { files } = this.getState()
  1861. const onBeforeUploadResult = this.opts.onBeforeUpload(files)
  1862. if (onBeforeUploadResult === false) {
  1863. return Promise.reject(
  1864. new Error(
  1865. 'Not starting the upload because onBeforeUpload returned false',
  1866. ),
  1867. )
  1868. }
  1869. if (onBeforeUploadResult && typeof onBeforeUploadResult === 'object') {
  1870. files = onBeforeUploadResult
  1871. // Updating files in state, because uploader plugins receive file IDs,
  1872. // and then fetch the actual file object from state
  1873. this.setState({
  1874. files,
  1875. })
  1876. }
  1877. return Promise.resolve()
  1878. .then(() => this.#restricter.validateMinNumberOfFiles(files))
  1879. .catch((err) => {
  1880. this.#informAndEmit([err])
  1881. throw err
  1882. })
  1883. .then(() => {
  1884. if (!this.#checkRequiredMetaFields(files)) {
  1885. throw new RestrictionError(this.i18n('missingRequiredMetaField'))
  1886. }
  1887. })
  1888. .catch((err) => {
  1889. // Doing this in a separate catch because we already emited and logged
  1890. // all the errors in `checkRequiredMetaFields` so we only throw a generic
  1891. // missing fields error here.
  1892. throw err
  1893. })
  1894. .then(() => {
  1895. const { currentUploads } = this.getState()
  1896. // get a list of files that are currently assigned to uploads
  1897. const currentlyUploadingFiles = Object.values(currentUploads).flatMap(
  1898. (curr) => curr.fileIDs,
  1899. )
  1900. const waitingFileIDs: string[] = []
  1901. Object.keys(files).forEach((fileID) => {
  1902. const file = this.getFile(fileID)
  1903. // if the file hasn't started uploading and hasn't already been assigned to an upload..
  1904. if (
  1905. !file.progress.uploadStarted &&
  1906. currentlyUploadingFiles.indexOf(fileID) === -1
  1907. ) {
  1908. waitingFileIDs.push(file.id)
  1909. }
  1910. })
  1911. const uploadID = this.#createUpload(waitingFileIDs)
  1912. return this.#runUpload(uploadID)
  1913. })
  1914. .catch((err) => {
  1915. this.emit('error', err)
  1916. this.log(err, 'error')
  1917. throw err
  1918. })
  1919. }
  1920. }
  1921. export default Uppy