@wlindabla/file_uploader 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +51 -20
  2. package/dist/cjs/cache/index.d.ts +198 -0
  3. package/dist/cjs/cache/index.js +318 -0
  4. package/dist/cjs/cache/index.js.map +1 -0
  5. package/dist/cjs/core/index.d.ts +267 -0
  6. package/dist/cjs/core/index.js +753 -0
  7. package/dist/cjs/core/index.js.map +1 -0
  8. package/dist/cjs/events/chunk/index.d.ts +27 -0
  9. package/dist/cjs/events/chunk/index.js +70 -0
  10. package/dist/cjs/events/chunk/index.js.map +1 -0
  11. package/dist/cjs/events/complete/index.d.ts +63 -0
  12. package/dist/cjs/events/complete/index.js +152 -0
  13. package/dist/cjs/events/complete/index.js.map +1 -0
  14. package/dist/cjs/events/index.d.ts +94 -0
  15. package/dist/cjs/events/index.js +85 -0
  16. package/dist/cjs/events/index.js.map +1 -0
  17. package/dist/cjs/events/initialize/index.d.ts +45 -0
  18. package/dist/cjs/events/initialize/index.js +105 -0
  19. package/dist/cjs/events/initialize/index.js.map +1 -0
  20. package/dist/cjs/events/state/index.d.ts +67 -0
  21. package/dist/cjs/events/state/index.js +145 -0
  22. package/dist/cjs/events/state/index.js.map +1 -0
  23. package/dist/cjs/exceptions/index.d.ts +84 -0
  24. package/dist/{exceptions → cjs/exceptions}/index.js +38 -18
  25. package/dist/cjs/exceptions/index.js.map +1 -0
  26. package/dist/cjs/index.d.ts +13 -0
  27. package/dist/cjs/index.js +33 -0
  28. package/dist/cjs/index.js.map +1 -0
  29. package/dist/cjs/subscribers/index.d.ts +33 -0
  30. package/dist/cjs/subscribers/index.js +187 -0
  31. package/dist/cjs/subscribers/index.js.map +1 -0
  32. package/dist/cjs/types/index.d.ts +110 -0
  33. package/dist/cjs/types/index.js +53 -0
  34. package/dist/cjs/types/index.js.map +1 -0
  35. package/dist/cjs/utils/index.d.ts +72 -0
  36. package/dist/cjs/utils/index.js +208 -0
  37. package/dist/cjs/utils/index.js.map +1 -0
  38. package/dist/esm/cache/index.d.mts +198 -0
  39. package/dist/esm/cache/index.js +4 -0
  40. package/dist/{index.js.map → esm/cache/index.js.map} +1 -1
  41. package/dist/{subscribers/index.js → esm/chunk-332NNKOW.js} +36 -34
  42. package/dist/esm/chunk-332NNKOW.js.map +1 -0
  43. package/dist/{events/state/index.js → esm/chunk-6225YMFE.js} +38 -20
  44. package/dist/esm/chunk-6225YMFE.js.map +1 -0
  45. package/dist/{core/index.js → esm/chunk-6DIKDA6J.js} +226 -227
  46. package/dist/esm/chunk-6DIKDA6J.js.map +1 -0
  47. package/dist/esm/chunk-7QVYU63E.js +6 -0
  48. package/dist/esm/chunk-7QVYU63E.js.map +1 -0
  49. package/dist/{events/initialize/index.js → esm/chunk-DN5B6PRW.js} +25 -19
  50. package/dist/esm/chunk-DN5B6PRW.js.map +1 -0
  51. package/dist/{events/index.js → esm/chunk-JDL3U4OX.js} +7 -37
  52. package/dist/esm/chunk-JDL3U4OX.js.map +1 -0
  53. package/dist/{events/chunk/index.js → esm/chunk-LD2DWZRJ.js} +14 -11
  54. package/dist/esm/chunk-LD2DWZRJ.js.map +1 -0
  55. package/dist/{events/complete/index.js → esm/chunk-LTYMA4U4.js} +25 -19
  56. package/dist/{events/complete/index.js.map → esm/chunk-LTYMA4U4.js.map} +1 -1
  57. package/dist/{utils/index.js → esm/chunk-MFYC4PBP.js} +15 -22
  58. package/dist/esm/chunk-MFYC4PBP.js.map +1 -0
  59. package/dist/esm/chunk-NXYS73I4.js +125 -0
  60. package/dist/esm/chunk-NXYS73I4.js.map +1 -0
  61. package/dist/{cache/index.js → esm/chunk-PFALORWQ.js} +10 -11
  62. package/dist/esm/chunk-PFALORWQ.js.map +1 -0
  63. package/dist/{types/index.js → esm/chunk-X757PBC5.js} +5 -7
  64. package/dist/esm/chunk-X757PBC5.js.map +1 -0
  65. package/dist/esm/core/index.d.mts +267 -0
  66. package/dist/esm/core/index.js +12 -0
  67. package/dist/esm/core/index.js.map +1 -0
  68. package/dist/esm/events/chunk/index.d.mts +27 -0
  69. package/dist/esm/events/chunk/index.js +4 -0
  70. package/dist/esm/events/chunk/index.js.map +1 -0
  71. package/dist/esm/events/complete/index.d.mts +63 -0
  72. package/dist/esm/events/complete/index.js +4 -0
  73. package/dist/esm/events/complete/index.js.map +1 -0
  74. package/dist/esm/events/index.d.mts +94 -0
  75. package/dist/esm/events/index.js +8 -0
  76. package/dist/esm/events/index.js.map +1 -0
  77. package/dist/esm/events/initialize/index.d.mts +45 -0
  78. package/dist/esm/events/initialize/index.js +4 -0
  79. package/dist/esm/events/initialize/index.js.map +1 -0
  80. package/dist/esm/events/state/index.d.mts +67 -0
  81. package/dist/esm/events/state/index.js +4 -0
  82. package/dist/esm/events/state/index.js.map +1 -0
  83. package/dist/esm/exceptions/index.d.mts +84 -0
  84. package/dist/esm/exceptions/index.js +4 -0
  85. package/dist/esm/exceptions/index.js.map +1 -0
  86. package/dist/esm/index.d.mts +13 -0
  87. package/dist/esm/index.js +14 -0
  88. package/dist/esm/index.js.map +1 -0
  89. package/dist/esm/subscribers/index.d.mts +33 -0
  90. package/dist/esm/subscribers/index.js +10 -0
  91. package/dist/esm/subscribers/index.js.map +1 -0
  92. package/dist/esm/types/index.d.mts +110 -0
  93. package/dist/esm/types/index.js +4 -0
  94. package/dist/esm/types/index.js.map +1 -0
  95. package/dist/esm/utils/index.d.mts +72 -0
  96. package/dist/esm/utils/index.js +5 -0
  97. package/dist/esm/utils/index.js.map +1 -0
  98. package/package.json +165 -14
  99. package/dist/cache/index.js.map +0 -1
  100. package/dist/core/index.js.map +0 -1
  101. package/dist/events/chunk/index.js.map +0 -1
  102. package/dist/events/index.js.map +0 -1
  103. package/dist/events/initialize/index.js.map +0 -1
  104. package/dist/events/state/index.js.map +0 -1
  105. package/dist/exceptions/index.js.map +0 -1
  106. package/dist/index.js +0 -49
  107. package/dist/subscribers/index.js.map +0 -1
  108. package/dist/types/index.js.map +0 -1
  109. package/dist/utils/index.js.map +0 -1
@@ -0,0 +1,753 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var core_exports = {};
31
+ __export(core_exports, {
32
+ ChunkedFileUploader: () => ChunkedFileUploader
33
+ });
34
+ module.exports = __toCommonJS(core_exports);
35
+ var import_event_dispatcher = require("@wlindabla/event_dispatcher");
36
+ var import_http_client = require("@wlindabla/http_client");
37
+ var import_types = require("../types");
38
+ var import_utils = require("../utils");
39
+ var import_events = require("../events");
40
+ var import_exceptions = require("../exceptions");
41
+ var import_p_limit = __toESM(require("p-limit"));
42
+ /**
43
+ * ChunkedFileUploader
44
+ *
45
+ * A production-ready, event-driven chunked file upload engine for Browser and Node.js.
46
+ *
47
+ * Designed and developed by **AGBOKOUDJO Franck** at
48
+ * **INTERNATIONALES WEB APPS & SERVICES**, this class provides a robust,
49
+ * framework-agnostic solution for uploading large files to a remote server
50
+ * by splitting them into smaller chunks and sending them in parallel with
51
+ * configurable concurrency control.
52
+ *
53
+ * ---
54
+ *
55
+ * ### How It Works
56
+ *
57
+ * The upload process follows a strict three-phase lifecycle:
58
+ *
59
+ * 1. **Initialization** — A session is opened with the server via the `init` endpoint.
60
+ * The file is identified by its name, size, type, and a SHA-256 hash of its
61
+ * first megabyte. The server returns a unique `mediaId` that identifies the session.
62
+ *
63
+ * 2. **Chunk Upload** — The file is sliced into fixed-size chunks and uploaded
64
+ * concurrently using `p-limit`. Each chunk carries its index, the total number
65
+ * of chunks, and the session `mediaId`. Failed chunks are retried automatically
66
+ * with exponential backoff up to `maxRetries` attempts.
67
+ *
68
+ * 3. **Finalization** — Once all chunks are successfully uploaded, the `finalize`
69
+ * endpoint is called to instruct the server to assemble the chunks into the
70
+ * final file.
71
+ *
72
+ * ---
73
+ *
74
+ * ### Event-Driven Architecture
75
+ *
76
+ * This class follows the **Symfony EventDispatcher pattern** via
77
+ * `@wlindabla/event_dispatcher`. Every meaningful moment in the upload
78
+ * lifecycle emits a typed event that your application can listen to:
79
+ *
80
+ * ```
81
+ * IDLE → INITIALIZING → UPLOADING → FINALIZING → COMPLETED
82
+ * ↓ ↓
83
+ * FAILED PAUSED ↔ UPLOADING
84
+ * ↓
85
+ * CANCELLED
86
+ * ```
87
+ *
88
+ * All event name constants are centralized in {@link HttpFileUploaderEvents}.
89
+ *
90
+ * ---
91
+ *
92
+ * ### Subscriber Registration (Required)
93
+ *
94
+ * Before calling `.upload()`, you **must** register the two built-in subscribers
95
+ * on your dispatcher. They handle the HTTP communication for the init and finalize phases:
96
+ *
97
+ * ```typescript
98
+ * // Browser
99
+ * const dispatcher = new BrowserEventDispatcher(document);
100
+ * dispatcher.addSubscriber(new InitializeUploadSubscriber(dispatcher));
101
+ * dispatcher.addSubscriber(new FinalizeUploadSubscriber(dispatcher));
102
+ *
103
+ * // Node.js
104
+ * const dispatcher = new NodeEventDispatcher();
105
+ * dispatcher.addSubscriber(new InitializeUploadSubscriber(dispatcher));
106
+ * dispatcher.addSubscriber(new FinalizeUploadSubscriber(dispatcher));
107
+ * ```
108
+ *
109
+ * ---
110
+ *
111
+ * ### Fluent Builder API
112
+ *
113
+ * The class exposes a fluent API to configure the upload before starting:
114
+ *
115
+ * ```typescript
116
+ * const uploader = new ChunkedFileUploader(dispatcher, cache, options);
117
+ *
118
+ * await uploader
119
+ * .withFile(file)
120
+ * .withEndpoints({
121
+ * init: 'https://api.example.com/upload/init',
122
+ * upload: 'https://api.example.com/upload/chunk',
123
+ * finalize: 'https://api.example.com/upload/finalize'
124
+ * })
125
+ * .upload();
126
+ * ```
127
+ *
128
+ * ---
129
+ *
130
+ * ### Resumable Uploads
131
+ *
132
+ * When `autoSave: true` is set in options, the upload progress is persisted
133
+ * after each successful chunk via the {@link UploadResumeCacheInterface}.
134
+ * A failed or interrupted upload can be resumed later:
135
+ *
136
+ * ```typescript
137
+ * const resumeData = await uploader.loadResumeData(file.name);
138
+ *
139
+ * if (resumeData) {
140
+ * await uploader
141
+ * .withFile(file)
142
+ * .withEndpoints(endpoints)
143
+ * .resumeUpload(resumeData);
144
+ * }
145
+ * ```
146
+ *
147
+ * ---
148
+ *
149
+ * ### Concurrency
150
+ *
151
+ * Multiple chunks can be uploaded simultaneously. The `concurrency` option
152
+ * controls how many parallel uploads are active at any given time.
153
+ * The default value is `3`, which provides a good balance between speed
154
+ * and server/network load:
155
+ *
156
+ * ```typescript
157
+ * // Upload 5 chunks in parallel
158
+ * new ChunkedFileUploader(dispatcher, cache, { concurrency: 5 });
159
+ * ```
160
+ *
161
+ * ---
162
+ *
163
+ * ### Pause, Resume and Cancel
164
+ *
165
+ * The upload can be paused, resumed, or cancelled at any time:
166
+ *
167
+ * ```typescript
168
+ * uploader.pause(); // Pauses after the current chunk finishes
169
+ * uploader.resume(); // Resumes from where it was paused
170
+ * uploader.cancel(); // Aborts immediately via AbortController
171
+ * ```
172
+ *
173
+ * ---
174
+ *
175
+ * ### Cache
176
+ *
177
+ * The library does **not** provide a built-in cache implementation to stay
178
+ * lightweight and environment-agnostic. You must implement
179
+ * {@link UploadResumeCacheInterface} with your preferred storage backend
180
+ * (localStorage, IndexedDB, Redis, filesystem, etc.).
181
+ *
182
+ * ---
183
+ *
184
+ * @author AGBOKOUDJO Franck <internationaleswebservices@gmail.com>
185
+ * @company INTERNATIONALES WEB APPS & SERVICES
186
+ * @phone +229 0167 25 18 86
187
+ * @linkedin https://www.linkedin.com/in/internationales-web-apps-services-120520193/
188
+ * @github https://github.com/Agbokoudjo/file_uploader
189
+ *
190
+ * @version 1.0.0
191
+ * @since 1.0.0
192
+ * @license MIT
193
+ *
194
+ * @see {@link HttpFileUploaderEvents} All event name constants
195
+ * @see {@link UploadResumeCacheInterface} Cache interface to implement
196
+ * @see {@link InitializeUploadSubscriber} Handles the init HTTP phase
197
+ * @see {@link FinalizeUploadSubscriber} Handles the finalize HTTP phase
198
+ * @see {@link UploadOptions} Full configuration reference
199
+ * @see {@link https://github.com/Agbokoudjo/file_uploader | GitHub Repository}
200
+ */
201
+ class ChunkedFileUploader {
202
+ constructor(_uploadEventDispatcher = new import_event_dispatcher.BrowserEventDispatcher(), uploadResumeData, options) {
203
+ this._uploadEventDispatcher = _uploadEventDispatcher;
204
+ this.uploadResumeData = uploadResumeData;
205
+ this.options = options;
206
+ this._file = null;
207
+ this._endpoints = null;
208
+ this.isPaused = false;
209
+ this.startTime = 0;
210
+ this.uploadedBytes = 0;
211
+ this.abortController = new AbortController();
212
+ this.state = import_types.UploadState.IDLE;
213
+ this.totalChunks = 0;
214
+ this.percentage = 0;
215
+ this.uploadedChunks = 0;
216
+ this.lastUploadedChunkIndex = -1;
217
+ }
218
+ _uploadEventDispatcher;
219
+ uploadResumeData;
220
+ options;
221
+ static {
222
+ __name(this, "ChunkedFileUploader");
223
+ }
224
+ _file;
225
+ _endpoints;
226
+ isPaused;
227
+ startTime;
228
+ uploadedBytes;
229
+ abortController;
230
+ state;
231
+ totalChunks;
232
+ percentage;
233
+ uploadedChunks;
234
+ lastUploadedChunkIndex;
235
+ /**
236
+ * Starts the chunked file upload process.
237
+ *
238
+ * @throws {Error} If file or endpoints are not set
239
+ * @throws {InitializeUploadFailureException} If server initialization fails
240
+ * @throws {FileUploadChunkError} If a chunk fails after all retries
241
+ *
242
+ * @example
243
+ * ```typescript
244
+ * const uploader = new ChunkedFileUploader(dispatcher, cache, options);
245
+ *
246
+ * uploader
247
+ * .withFile(file)
248
+ * .withEndpoints({ init, upload, finalize });
249
+ *
250
+ * await uploader.upload();
251
+ * ```
252
+ */
253
+ async upload() {
254
+ this.setState(import_types.UploadState.INITIALIZING);
255
+ const {
256
+ maxRetries = 3,
257
+ config,
258
+ speedMbps,
259
+ metadata,
260
+ headerInitialzingUpload,
261
+ concurrency = 3
262
+ } = this.options;
263
+ const file = this.file;
264
+ const fileHash = await import_utils.FileUtils.generateFileHash(file);
265
+ let fileId;
266
+ try {
267
+ const initializationEvent = await this._uploadEventDispatcher.dispatchAsync(
268
+ new import_events.InitializingUploadEvent(
269
+ {
270
+ fileHash,
271
+ fileName: this.file.name,
272
+ fileSize: this.file.size,
273
+ fileType: this.file.type,
274
+ metadata,
275
+ endpointInit: this.endPointOptions.init,
276
+ headers: headerInitialzingUpload
277
+ }
278
+ ),
279
+ import_events.HttpFileUploaderEvents.INITIALIZE_UPLOAD
280
+ );
281
+ fileId = initializationEvent.mediaId;
282
+ } catch (error) {
283
+ this.setState(import_types.UploadState.FAILED);
284
+ throw error;
285
+ }
286
+ this.setState(import_types.UploadState.UPLOADING);
287
+ this.startTime = Date.now();
288
+ this.uploadedBytes = 0;
289
+ this.uploadedChunks = 0;
290
+ this.lastUploadedChunkIndex = -1;
291
+ const chunkSize = this.options.chunkSize || import_utils.FileUtils.calculateChunkSize(file.size, speedMbps, config);
292
+ this.totalChunks = Math.ceil(file.size / chunkSize);
293
+ try {
294
+ await this.uploadChunksWithConcurrency(
295
+ file,
296
+ chunkSize,
297
+ fileId,
298
+ fileHash,
299
+ maxRetries,
300
+ concurrency,
301
+ 0
302
+ );
303
+ await this.finalizeUpload(fileId, fileHash);
304
+ } catch (error) {
305
+ this.handleUploadFailure(error);
306
+ throw error;
307
+ }
308
+ }
309
+ withFile(file) {
310
+ if (!file) {
311
+ throw new Error("File is required");
312
+ }
313
+ if (file.size === 0) {
314
+ throw new Error("Cannot upload empty file");
315
+ }
316
+ if (!(file instanceof File) || !(file instanceof Blob)) {
317
+ throw new TypeError("Expected File or Blob instance");
318
+ }
319
+ this._file = file;
320
+ return this;
321
+ }
322
+ withEndpoints(endpoints) {
323
+ if (!endpoints.init || !endpoints.upload || !endpoints.finalize) {
324
+ throw new Error("All endpoints (init, upload, finalize) are required");
325
+ }
326
+ this._endpoints = endpoints;
327
+ return this;
328
+ }
329
+ get endPointOptions() {
330
+ if (!this._endpoints) {
331
+ throw new Error("Endpoint URL is required");
332
+ }
333
+ return this._endpoints;
334
+ }
335
+ get file() {
336
+ if (!this._file) {
337
+ throw new Error(`
338
+ This operation requires a mandatory file.Did you forget to upload the file?
339
+ Use the withFile(file: File|Blob) function of the ChunkedFileUploader ${this} class that you instantiated.
340
+ `);
341
+ }
342
+ return this._file;
343
+ }
344
+ /**
345
+ * Upload all chunks with concurrency control using p-limit
346
+ *
347
+ * @param file - File to upload
348
+ * @param chunkSize - Size of each chunk
349
+ * @param fileId - Server file ID
350
+ * @param fileHash - File hash
351
+ * @param maxRetries - Max retry attempts per chunk
352
+ * @param concurrency - Number of concurrent uploads (default: 3)
353
+ */
354
+ async uploadChunksWithConcurrency(file, chunkSize, fileId, fileHash, maxRetries, concurrency, startIndex = 0) {
355
+ try {
356
+ const limit = (0, import_p_limit.default)(concurrency);
357
+ const uploadPromises = [];
358
+ for (let chunkIndex = startIndex; chunkIndex < this.totalChunks; chunkIndex++) {
359
+ const limitedUpload = limit(
360
+ () => this.processChunk(
361
+ file,
362
+ chunkIndex,
363
+ chunkSize,
364
+ fileId,
365
+ fileHash,
366
+ maxRetries
367
+ )
368
+ );
369
+ uploadPromises.push(limitedUpload);
370
+ }
371
+ await Promise.all(uploadPromises);
372
+ } catch (error) {
373
+ throw error;
374
+ }
375
+ }
376
+ /**
377
+ * Process a single chunk: slice, upload with retry, and save progress.
378
+ *
379
+ * @param file - The file being uploaded
380
+ * @param currentChunkIndex - Index of the current chunk (0-based)
381
+ * @param chunkSize - Size of each chunk in bytes
382
+ * @param fileId - Server-provided file/session ID
383
+ * @param fileHash - SHA-256 hash of the file
384
+ * @param maxRetries - Maximum number of retry attempts
385
+ *
386
+ * @throws {UploadCancelledException} If upload is cancelled
387
+ * @throws {FileUploadChunkError} If chunk upload fails after all retries
388
+ */
389
+ async processChunk(file, currentChunkIndex, chunkSize, fileId, fileHash, maxRetries) {
390
+ try {
391
+ if (this.abortController.signal.aborted) {
392
+ this._uploadEventDispatcher.dispatch(
393
+ new import_events.UploadCancelledEvent(
394
+ file.name,
395
+ this.totalChunks,
396
+ this.uploadedBytes,
397
+ this.percentage,
398
+ currentChunkIndex,
399
+ "Upload cancelled by user",
400
+ Date.now()
401
+ ),
402
+ import_events.HttpFileUploaderEvents.UPLOAD_CANCELLED
403
+ );
404
+ return;
405
+ }
406
+ while (this.isPaused) {
407
+ await this.sleep(100);
408
+ }
409
+ const start = currentChunkIndex * chunkSize;
410
+ const end = Math.min(file.size, start + chunkSize);
411
+ const chunk = file.slice(start, end);
412
+ const chunkInfo = {
413
+ index: currentChunkIndex,
414
+ start,
415
+ end,
416
+ size: chunk.size,
417
+ attempt: 0,
418
+ status: "pending"
419
+ };
420
+ this._uploadEventDispatcher.dispatch(
421
+ new import_events.UploadChunkStartedEvent(chunkInfo),
422
+ import_events.HttpFileUploaderEvents.MEDIA_CHUNK_UPLOAD_STARTED
423
+ );
424
+ await this.uploadChunkWithRetry(
425
+ chunk,
426
+ chunkInfo,
427
+ fileId,
428
+ fileHash,
429
+ this.totalChunks,
430
+ maxRetries
431
+ );
432
+ if (this.options.autoSave) {
433
+ await this.saveResumeData(fileId, chunkSize);
434
+ }
435
+ } catch (error) {
436
+ throw error;
437
+ }
438
+ }
439
+ async uploadChunkWithRetry(chunk, chunkInfo, fileId, fileHash, totalChunks, maxRetries) {
440
+ let success = false;
441
+ let lastError = null;
442
+ for (let attempt = 0; attempt < maxRetries && !success; attempt++) {
443
+ chunkInfo.attempt = attempt + 1;
444
+ chunkInfo.status = "uploading";
445
+ try {
446
+ const response = await this.uploadChunk(chunk, chunkInfo, fileId, fileHash, totalChunks);
447
+ success = true;
448
+ chunkInfo.status = "success";
449
+ this.updateProgress(chunk.size, chunkInfo.index);
450
+ this.notifyProgress(
451
+ this.uploadedChunks,
452
+ totalChunks,
453
+ this.file.size,
454
+ response
455
+ );
456
+ return;
457
+ } catch (error) {
458
+ if (error instanceof import_exceptions.ChunkUploadHttpErrorException) {
459
+ this._uploadEventDispatcher.dispatch(
460
+ new import_events.ChunkUploadHttpErrorResponseEvent(
461
+ error.errorPayload,
462
+ error.statusResponse,
463
+ this.endPointOptions.upload,
464
+ chunkInfo
465
+ ),
466
+ import_events.HttpFileUploaderEvents.MEDIA_CHUNK_UPLOAD_HTTP_ERROR_RESPONSE
467
+ );
468
+ }
469
+ lastError = error;
470
+ chunkInfo.status = "error";
471
+ const chunkError = {
472
+ chunk: chunkInfo,
473
+ error: lastError,
474
+ attempt: attempt + 1,
475
+ willRetry: attempt < maxRetries - 1
476
+ };
477
+ if (error instanceof import_http_client.HttpFetchError) {
478
+ this._uploadEventDispatcher.dispatch(chunkError, import_events.HttpFileUploaderEvents.MEDIA_CHUNK_UPLOAD_FAILED);
479
+ }
480
+ if (attempt < maxRetries - 1) {
481
+ const delay = Math.pow(2, attempt) * 1e3;
482
+ await this.sleep(delay);
483
+ console.info(`Retry #${attempt + 2} in ${delay / 1e3}s...`);
484
+ }
485
+ }
486
+ }
487
+ if (!success) {
488
+ const fileUploadChunkError = new import_exceptions.FileUploadChunkError(
489
+ `Failed to upload chunk ${chunkInfo.index} after ${maxRetries} attempts`,
490
+ {
491
+ chunk: chunkInfo,
492
+ error: lastError,
493
+ attempt: maxRetries,
494
+ willRetry: false
495
+ }
496
+ );
497
+ this._uploadEventDispatcher.dispatch(
498
+ fileUploadChunkError,
499
+ import_events.HttpFileUploaderEvents.MEDIA_CHUNK_UPLOAD_MAXRETRY_EXPIRE
500
+ );
501
+ throw fileUploadChunkError;
502
+ }
503
+ }
504
+ async uploadChunk(chunk, chunkInfo, mediaIdFromServer, fileHash, totalChunks) {
505
+ const media = this.file;
506
+ const chunkFormData = (0, import_utils.createChunkFormData)(
507
+ chunk,
508
+ {
509
+ chunkIndex: chunkInfo.index,
510
+ mediaId: mediaIdFromServer,
511
+ fileSize: media.size,
512
+ fileName: media.name,
513
+ fileHash,
514
+ totalChunks
515
+ }
516
+ );
517
+ try {
518
+ const response_of_server = await (0, import_http_client.safeFetch)({
519
+ url: this.endPointOptions.upload,
520
+ headers: this.options.headers,
521
+ data: chunkFormData,
522
+ methodSend: "POST",
523
+ responseType: "json",
524
+ timeout: this.options.timeout ?? 6e4,
525
+ retryCount: 2,
526
+ retryOnStatusCode: false,
527
+ signal: this.createChunkAbortSignal()
528
+ });
529
+ const statusResponse = response_of_server.status;
530
+ if (response_of_server.failed) {
531
+ throw new import_exceptions.ChunkUploadHttpErrorException(response_of_server.data, statusResponse);
532
+ }
533
+ return response_of_server;
534
+ } catch (error) {
535
+ throw error;
536
+ }
537
+ }
538
+ createChunkAbortSignal() {
539
+ const chunkController = new AbortController();
540
+ this.abortController.signal.addEventListener("abort", () => {
541
+ chunkController.abort();
542
+ });
543
+ return chunkController.signal;
544
+ }
545
+ notifyProgress(uploadedChunks, totalChunks, totalBytes, httpResponse) {
546
+ const elapsed = Math.max((Date.now() - this.startTime) / 1e3, 0.1);
547
+ const speed = this.uploadedBytes / elapsed;
548
+ const remainingBytes = totalBytes - this.uploadedBytes;
549
+ const estimatedTimeRemaining = uploadedChunks < 2 ? null : remainingBytes / speed;
550
+ this.percentage = Math.round(this.uploadedBytes / totalBytes * 100);
551
+ const progress = {
552
+ uploadedChunks,
553
+ totalChunks,
554
+ uploadedBytes: this.uploadedBytes,
555
+ totalBytes,
556
+ percentage: this.percentage,
557
+ currentChunk: uploadedChunks,
558
+ speed,
559
+ // bytes/seconde
560
+ estimatedTimeRemaining,
561
+ // secondes (ou null)
562
+ elapsed
563
+ // secondes écoulées
564
+ };
565
+ this._uploadEventDispatcher.dispatch(
566
+ new import_events.UploadProgressEvent(
567
+ progress,
568
+ httpResponse.data,
569
+ httpResponse.status
570
+ )
571
+ );
572
+ console.info(
573
+ `Progress: ${this.percentage}% | Speed: ${import_utils.FileUtils.formatBytes(speed)}/s | ETA: ${estimatedTimeRemaining ? import_utils.FileUtils.formatDuration(estimatedTimeRemaining) : "Calculating..."}`
574
+ );
575
+ }
576
+ sleep(ms) {
577
+ return new Promise((resolve) => setTimeout(resolve, ms));
578
+ }
579
+ /**
580
+ * Save current upload progress to cache for resume capability
581
+ *
582
+ * @param fileId - Server-provided file/session ID
583
+ * @param chunkSize - Size of each chunk in bytes
584
+ * @returns Saved resume data
585
+ */
586
+ async saveResumeData(fileId, chunkSize) {
587
+ const data = {
588
+ fileId,
589
+ fileName: this.file.name,
590
+ fileSize: this.file.size,
591
+ uploadedChunks: this.uploadedChunks,
592
+ lastChunkIndex: this.lastUploadedChunkIndex,
593
+ lastBytePosition: this.uploadedBytes,
594
+ chunkSize,
595
+ concurrency: this.options.concurrency || 3
596
+ };
597
+ await this.uploadResumeData.setItem(`upload_${this.file.name}`, data);
598
+ console.info(
599
+ `Resume data saved: ${this.uploadedChunks}/${Math.ceil(this.file.size / chunkSize)} chunks, last chunk index: ${this.lastUploadedChunkIndex}`
600
+ );
601
+ return data;
602
+ }
603
+ setState(newState) {
604
+ const oldState = this.state;
605
+ this.state = newState;
606
+ this._uploadEventDispatcher.dispatch(
607
+ new import_events.UploadStateChangedEvent(
608
+ oldState,
609
+ newState,
610
+ Date.now()
611
+ ),
612
+ import_events.HttpFileUploaderEvents.UPLOAD_STATE_CHANGED
613
+ );
614
+ }
615
+ getState() {
616
+ return this.state;
617
+ }
618
+ handleUploadFailure(error) {
619
+ this.setState(import_types.UploadState.FAILED);
620
+ this._uploadEventDispatcher.dispatch(error, import_events.HttpFileUploaderEvents.DOWNLOAD_MEDIA_FAILURE);
621
+ console.error("Upload failed:", error);
622
+ }
623
+ cancel() {
624
+ this.abortController.abort();
625
+ this.setState(import_types.UploadState.CANCELLED);
626
+ }
627
+ pause() {
628
+ this.isPaused = true;
629
+ this.setState(import_types.UploadState.PAUSED);
630
+ this._uploadEventDispatcher.dispatch(
631
+ new import_events.UploadPausedEvent(
632
+ this.file.name,
633
+ this.totalChunks,
634
+ this.uploadedBytes,
635
+ this.percentage,
636
+ Date.now()
637
+ ),
638
+ import_events.HttpFileUploaderEvents.UPLOAD_PAUSED
639
+ );
640
+ }
641
+ resume() {
642
+ this.isPaused = false;
643
+ this.setState(import_types.UploadState.UPLOADING);
644
+ this._uploadEventDispatcher.dispatch(
645
+ new import_events.UploadResumedEvent(
646
+ this.file.name,
647
+ this.totalChunks,
648
+ this.uploadedBytes,
649
+ this.percentage
650
+ ),
651
+ import_events.HttpFileUploaderEvents.UPLOAD_RESUMED
652
+ );
653
+ }
654
+ /**
655
+ * Load previously saved resume data
656
+ *
657
+ * @param fileName - Name of the file to resume
658
+ * @returns Resume data or null if not found
659
+ */
660
+ async loadResumeData(fileName) {
661
+ try {
662
+ const data = await this.uploadResumeData.getItem(`upload_${fileName}`);
663
+ if (data) {
664
+ console.info(
665
+ `Resume data loaded: ${data.uploadedChunks} chunks uploaded, last index: ${data.lastChunkIndex}`
666
+ );
667
+ }
668
+ return data;
669
+ } catch (error) {
670
+ console.warn(`No resume data found for ${fileName}`);
671
+ return null;
672
+ }
673
+ }
674
+ /**
675
+ * Resume upload from saved state
676
+ *
677
+ * @param resumeData - Previously saved resume data
678
+ * @returns Upload result
679
+ */
680
+ async resumeUpload(resumeData) {
681
+ const __message = `Resuming upload from chunk ${resumeData.lastChunkIndex + 1} (${resumeData.uploadedChunks} chunks already uploaded)`;
682
+ this.uploadedBytes = resumeData.lastBytePosition;
683
+ this.uploadedChunks = resumeData.uploadedChunks;
684
+ this.lastUploadedChunkIndex = resumeData.lastChunkIndex;
685
+ const assumedSpeed = 5e5;
686
+ const timeAlreadySpent = resumeData.lastBytePosition / assumedSpeed;
687
+ this.startTime = Date.now() - timeAlreadySpent * 1e3;
688
+ const { maxRetries = 3 } = this.options;
689
+ const fileHash = await import_utils.FileUtils.generateFileHash(this.file);
690
+ const chunkSize = resumeData.chunkSize;
691
+ this.totalChunks = Math.ceil(this.file.size / chunkSize);
692
+ try {
693
+ this._uploadEventDispatcher.dispatch(
694
+ new import_events.ResumeUploadEvent(resumeData, __message),
695
+ import_events.HttpFileUploaderEvents.MEDIA_CHUNK_UPLOAD_RESUME
696
+ );
697
+ await this.uploadChunksWithConcurrency(
698
+ this.file,
699
+ chunkSize,
700
+ resumeData.fileId,
701
+ fileHash,
702
+ maxRetries,
703
+ resumeData.concurrency,
704
+ resumeData.lastChunkIndex + 1
705
+ );
706
+ await this.finalizeUpload(resumeData.fileId, fileHash);
707
+ } catch (error) {
708
+ this.handleUploadFailure(error);
709
+ throw error;
710
+ }
711
+ }
712
+ updateProgress(chunkSize, chunkIndex) {
713
+ this.uploadedBytes += chunkSize;
714
+ this.uploadedChunks++;
715
+ this.lastUploadedChunkIndex = Math.max(this.lastUploadedChunkIndex, chunkIndex);
716
+ }
717
+ async finalizeUpload(mediaId, fileHash) {
718
+ try {
719
+ const finalizeUploadEvent = await this._uploadEventDispatcher.dispatchAsync(
720
+ new import_events.FinalizeUploadEvent(
721
+ this.endPointOptions.finalize,
722
+ mediaId,
723
+ fileHash,
724
+ this.options.headerFinalezingUpload
725
+ ),
726
+ import_events.HttpFileUploaderEvents.FINALIZE_UPLOAD
727
+ );
728
+ this.setState(import_types.UploadState.FINALIZING);
729
+ const duration = (Date.now() - this.startTime) / 1e3;
730
+ const uploadResult = {
731
+ success: true,
732
+ finalizeUploadResponse: finalizeUploadEvent.hasResponse() ? finalizeUploadEvent.getResponse() : null,
733
+ totalChunks: this.totalChunks,
734
+ totalBytes: this.file.size,
735
+ duration,
736
+ averageSpeed: this.file.size / duration,
737
+ fileId: mediaId
738
+ };
739
+ this.setState(import_types.UploadState.COMPLETED);
740
+ this._uploadEventDispatcher.dispatch(
741
+ new import_events.UploadMediaCompleteEvent(uploadResult),
742
+ import_events.HttpFileUploaderEvents.DOWNLOAD_MEDIA_COMPLETE
743
+ );
744
+ } catch (error) {
745
+ throw error;
746
+ }
747
+ }
748
+ }
749
+ // Annotate the CommonJS export names for ESM import in node:
750
+ 0 && (module.exports = {
751
+ ChunkedFileUploader
752
+ });
753
+ //# sourceMappingURL=index.js.map