@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,187 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var subscribers_exports = {};
21
+ __export(subscribers_exports, {
22
+ FinalizeUploadSubscriber: () => FinalizeUploadSubscriber,
23
+ InitializeUploadSubscriber: () => InitializeUploadSubscriber
24
+ });
25
+ module.exports = __toCommonJS(subscribers_exports);
26
+ var import_events = require("../events");
27
+ var import_core = require("@wlindabla/http_client/core");
28
+ var import_exceptions = require("../exceptions");
29
+ class InitializeUploadSubscriber {
30
+ constructor(eventDispatcher) {
31
+ this.eventDispatcher = eventDispatcher;
32
+ }
33
+ eventDispatcher;
34
+ static {
35
+ __name(this, "InitializeUploadSubscriber");
36
+ }
37
+ getSubscribedEvents() {
38
+ return {
39
+ [import_events.HttpFileUploaderEvents.INITIALIZE_UPLOAD]: { listener: "onInitializeUpload", priority: 100 }
40
+ };
41
+ }
42
+ /**
43
+ * Initializes upload session with the server.
44
+ *
45
+ * @param fileHash - SHA-256 hash of the file (first 1MB)
46
+ * @returns Session ID from server, or null if initialization failed
47
+ * @throws {FileUploadInitializationError} If server returns error or network fails
48
+ */
49
+ async onInitializeUpload(event) {
50
+ event.stopPropagation();
51
+ const initialzeUploadRequestOptions = event.initUploadOptions;
52
+ this.eventDispatcher.dispatch(
53
+ new import_events.InitializeUploadStartedEvent(
54
+ initialzeUploadRequestOptions.fileName,
55
+ initialzeUploadRequestOptions.fileSize,
56
+ initialzeUploadRequestOptions.fileHash
57
+ ),
58
+ import_events.HttpFileUploaderEvents.INITIALIZE_UPLOAD_STARTED
59
+ );
60
+ try {
61
+ const response = await (0, import_core.safeFetch)({
62
+ url: initialzeUploadRequestOptions.endpointInit,
63
+ methodSend: "POST",
64
+ headers: {
65
+ "Content-Type": "application/json",
66
+ ...initialzeUploadRequestOptions.headers
67
+ },
68
+ data: {
69
+ fileName: initialzeUploadRequestOptions.fileName,
70
+ fileSize: initialzeUploadRequestOptions.fileSize,
71
+ fileHash: initialzeUploadRequestOptions.fileHash,
72
+ fileType: initialzeUploadRequestOptions.fileType,
73
+ metadata: initialzeUploadRequestOptions.metadata
74
+ },
75
+ responseType: "json",
76
+ retryCount: 3,
77
+ retryOnStatusCode: true,
78
+ timeout: 45e3
79
+ });
80
+ const status = response.status;
81
+ if (response.failed) {
82
+ console.error(`Initialize upload failed (HTTP ${status}):`, response);
83
+ const errorUploadFailure = new import_exceptions.InitializeUploadFailureException(
84
+ response,
85
+ `Server returned error: HTTP ${response.status}`
86
+ );
87
+ this.eventDispatcher.dispatch(
88
+ new import_events.InitializeUploadFailureEvent(
89
+ errorUploadFailure,
90
+ status,
91
+ response.data
92
+ ),
93
+ import_events.HttpFileUploaderEvents.INITIALIZE_UPLOAD_FAILURE
94
+ );
95
+ throw errorUploadFailure;
96
+ }
97
+ const responseData = response.data;
98
+ if (!responseData || typeof responseData !== "object") {
99
+ const validationError = "Invalid server response: expected object, got " + typeof responseData;
100
+ console.error("Invalid response structure:", responseData);
101
+ const err = new import_exceptions.InitializeUploadFailureException(
102
+ responseData,
103
+ validationError
104
+ );
105
+ throw err;
106
+ }
107
+ let sessionId = responseData.mediaId || responseData.mediaIdFromServer || responseData.sessionId || responseData.uploadId;
108
+ if (!sessionId) {
109
+ const missingKeyError = 'Server response missing required field: "mediaId","mediaIdFromServer", "sessionId", or "uploadId"';
110
+ console.error("Missing session ID in response:", responseData);
111
+ const err = new import_exceptions.InitializeUploadFailureException(
112
+ responseData,
113
+ missingKeyError
114
+ );
115
+ throw err;
116
+ }
117
+ if (typeof sessionId === "number") {
118
+ sessionId = sessionId.toString();
119
+ }
120
+ event.setMediaId(sessionId);
121
+ this.eventDispatcher.dispatch(
122
+ new import_events.InitializeUploadSuccessEvent(
123
+ status,
124
+ sessionId,
125
+ responseData
126
+ ),
127
+ import_events.HttpFileUploaderEvents.INITIALIZE_UPLOAD_SUCCESS
128
+ );
129
+ } catch (error) {
130
+ if (error instanceof import_core.HttpFetchError) {
131
+ this.eventDispatcher.dispatch(
132
+ new import_events.InitializeUploadFailureEvent(
133
+ error instanceof Error ? error : new Error(String(error))
134
+ ),
135
+ import_events.HttpFileUploaderEvents.INITIALIZE_UPLOAD_FAILURE
136
+ );
137
+ return;
138
+ }
139
+ console.error("Initialize upload exception:", error);
140
+ throw error;
141
+ }
142
+ }
143
+ }
144
+ class FinalizeUploadSubscriber {
145
+ constructor(eventDispatcher) {
146
+ this.eventDispatcher = eventDispatcher;
147
+ }
148
+ eventDispatcher;
149
+ static {
150
+ __name(this, "FinalizeUploadSubscriber");
151
+ }
152
+ getSubscribedEvents() {
153
+ return {
154
+ [import_events.HttpFileUploaderEvents.FINALIZE_UPLOAD]: { listener: "onFinalizeUpload", priority: 100 }
155
+ };
156
+ }
157
+ async onFinalizeUpload(event) {
158
+ event.stopPropagation();
159
+ try {
160
+ const responseFinalizeUpload = await (0, import_core.safeFetch)({
161
+ url: event.endPoint,
162
+ methodSend: "POST",
163
+ headers: {
164
+ "Content-Type": "application/json",
165
+ ...event.headers
166
+ },
167
+ data: { mediaId: event.mediaId, mediaHash: event.mediaHash }
168
+ });
169
+ event.setResponse(responseFinalizeUpload);
170
+ } catch (error) {
171
+ if (error instanceof import_core.HttpFetchError) {
172
+ this.eventDispatcher.dispatch(
173
+ new import_events.FinalizeUploadFailureEvent(error),
174
+ import_events.HttpFileUploaderEvents.FINALIZE_UPLOAD_FAILURE
175
+ );
176
+ return;
177
+ }
178
+ throw error;
179
+ }
180
+ }
181
+ }
182
+ // Annotate the CommonJS export names for ESM import in node:
183
+ 0 && (module.exports = {
184
+ FinalizeUploadSubscriber,
185
+ InitializeUploadSubscriber
186
+ });
187
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/subscribers/index.ts"],"sourcesContent":["/*\n * This file is part of the project by AGBOKOUDJO Franck.\n *\n * (c) AGBOKOUDJO Franck <internationaleswebservices@gmail.com>\n * Phone: +229 0167 25 18 86\n * LinkedIn: https://www.linkedin.com/in/internationales-web-apps-services-120520193/\n * Company: INTERNATIONALES WEB APPS & SERVICES\n *\n * For more information, please feel free to contact the author.\n */\n\nimport {\n EventSubscriberInterface,\n EventDispatcherInterface\n} from \"@wlindabla/event_dispatcher\";\n\nimport {\n HttpFileUploaderEvents,\n InitializingUploadEvent,\n InitializeUploadStartedEvent,\n InitializeUploadSuccessEvent,\n InitializeUploadFailureEvent,\n FinalizeUploadEvent,\n FinalizeUploadFailureEvent\n} from \"../events\";\n\nimport {\n HttpFetchError,\n safeFetch\n} from \"@wlindabla/http_client/core\";\n\nimport { InitializeUploadResponse } from \"../types\";\n\nimport { InitializeUploadFailureException } from \"../exceptions\";\n\n\n//src/subsciber/index.ts\n\nexport class InitializeUploadSubscriber implements EventSubscriberInterface {\n constructor(private readonly eventDispatcher: EventDispatcherInterface) {\n \n }\n\n public getSubscribedEvents(): Record<string, string | { listener: string; priority?: number | undefined; }> {\n return {\n [HttpFileUploaderEvents.INITIALIZE_UPLOAD]: { listener: \"onInitializeUpload\", priority: 100}\n }\n }\n\n /**\n * Initializes upload session with the server.\n * \n * @param fileHash - SHA-256 hash of the file (first 1MB)\n * @returns Session ID from server, or null if initialization failed\n * @throws {FileUploadInitializationError} If server returns error or network fails\n */\n public async onInitializeUpload(event:InitializingUploadEvent):Promise<void>{\n event.stopPropagation();\n const initialzeUploadRequestOptions = event.initUploadOptions;\n\n this.eventDispatcher.dispatch(\n new InitializeUploadStartedEvent(\n initialzeUploadRequestOptions.fileName,\n initialzeUploadRequestOptions.fileSize,\n initialzeUploadRequestOptions.fileHash\n ),\n HttpFileUploaderEvents.INITIALIZE_UPLOAD_STARTED\n );\n \n try {\n const response = await safeFetch({\n url:initialzeUploadRequestOptions.endpointInit,\n methodSend: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...initialzeUploadRequestOptions.headers\n },\n data: {\n fileName:initialzeUploadRequestOptions.fileName,\n fileSize:initialzeUploadRequestOptions.fileSize,\n fileHash:initialzeUploadRequestOptions.fileHash,\n fileType: initialzeUploadRequestOptions.fileType,\n metadata: initialzeUploadRequestOptions.metadata,\n },\n responseType: \"json\",\n retryCount: 3,\n retryOnStatusCode: true,\n timeout: 45000\n });\n\n const status = response.status;\n \n // Handle error responses (4xx, 5xx)\n if (response.failed) {\n console.error(`Initialize upload failed (HTTP ${status}):`, response);\n\n const errorUploadFailure =new InitializeUploadFailureException(\n response,\n `Server returned error: HTTP ${response.status}`\n );\n\n this.eventDispatcher.dispatch(\n new InitializeUploadFailureEvent(\n errorUploadFailure,\n status,\n response.data),\n HttpFileUploaderEvents.INITIALIZE_UPLOAD_FAILURE\n\n );\n \n throw errorUploadFailure;\n }\n\n const responseData = response.data as InitializeUploadResponse;\n\n // Validate server response struct\n if (!responseData || typeof responseData !== 'object') {\n const validationError = 'Invalid server response: expected object, got ' + typeof responseData\n console.error('Invalid response structure:', responseData);\n\n const err=new InitializeUploadFailureException(\n responseData,\n validationError\n );\n throw err;\n }\n // Extract session ID\n let sessionId =\n responseData.mediaId ||\n responseData.mediaIdFromServer ||\n responseData.sessionId ||\n responseData.uploadId;\n\n if (!sessionId) {\n const missingKeyError = 'Server response missing required field: \"mediaId\",\"mediaIdFromServer\", \"sessionId\", or \"uploadId\"';\n\n console.error('Missing session ID in response:', responseData);\n const err=new InitializeUploadFailureException(\n responseData,\n missingKeyError\n );\n throw err;\n }\n\n if (typeof sessionId === \"number\") { sessionId = sessionId.toString(); }\n\n event.setMediaId(sessionId);\n\n this.eventDispatcher.dispatch(\n new InitializeUploadSuccessEvent(\n status,\n sessionId,\n responseData\n ),\n HttpFileUploaderEvents.INITIALIZE_UPLOAD_SUCCESS\n );\n\n } catch (error) {\n if (error instanceof HttpFetchError) {\n this.eventDispatcher.dispatch(\n new InitializeUploadFailureEvent(\n error instanceof Error ? error : new Error(String(error)),\n ),\n HttpFileUploaderEvents.INITIALIZE_UPLOAD_FAILURE\n );\n return;\n }\n console.error('Initialize upload exception:', error);\n\n throw error;\n }\n }\n}\n\nexport class FinalizeUploadSubscriber implements EventSubscriberInterface{\n\n constructor(private readonly eventDispatcher: EventDispatcherInterface) {\n\n }\n\n public getSubscribedEvents(): Record<string, string | { listener: string; priority?: number | undefined; }> {\n return {\n [HttpFileUploaderEvents.FINALIZE_UPLOAD]: { listener: \"onFinalizeUpload\", priority: 100 }\n }\n }\n\n public async onFinalizeUpload(event: FinalizeUploadEvent): Promise<void>{\n event.stopPropagation();\n try {\n const responseFinalizeUpload = await safeFetch({\n url: event.endPoint,\n methodSend: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...event.headers\n },\n data: { mediaId: event.mediaId, mediaHash: event.mediaHash }\n });\n\n event.setResponse(responseFinalizeUpload)\n } catch (error) {\n if (error instanceof HttpFetchError) {\n this.eventDispatcher.dispatch(\n new FinalizeUploadFailureEvent(error),\n HttpFileUploaderEvents.FINALIZE_UPLOAD_FAILURE\n );\n return;\n }\n\n throw error;\n }\n }\n}"],"mappings":"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","names":[]}
@@ -0,0 +1,110 @@
1
+ import { FetchResponseInterface } from '@wlindabla/http_client';
2
+
3
+ interface UploadOptions {
4
+ autoSave?: boolean;
5
+ chunkSize?: number;
6
+ speedMbps?: number;
7
+ config?: ChunkSizeConfig;
8
+ headers?: HeadersInit;
9
+ chunkOtherData?: Record<string, any>;
10
+ metadata?: Record<string, any>;
11
+ maxRetries?: number;
12
+ timeout?: number;
13
+ initTimeout?: number;
14
+ headerInitialzingUpload?: HeadersInit;
15
+ headerFinalezingUpload?: HeadersInit;
16
+ concurrency?: number;
17
+ }
18
+ interface InitializeUploadOptions {
19
+ metadata?: Record<string, any>;
20
+ fileHash: string;
21
+ fileName: string;
22
+ fileSize: number;
23
+ fileType: string;
24
+ endpointInit: string | URL;
25
+ headers?: HeadersInit;
26
+ }
27
+ interface UploadEndpoints {
28
+ init: string | URL;
29
+ upload: string | URL;
30
+ finalize: string | URL;
31
+ }
32
+ interface ChunkSizeConfig {
33
+ defaultChunkSizeMB: number;
34
+ slowSpeedThresholdMbps: number;
35
+ slowSpeedChunkSizeMB: number;
36
+ fileSizeThresholds: Array<{
37
+ maxSizeMB: number;
38
+ chunkSizeMB: number;
39
+ }>;
40
+ }
41
+ type UploadStatus = 'pending' | 'uploading' | 'success' | 'error';
42
+ interface ChunkInfo {
43
+ index: number;
44
+ start: number;
45
+ end: number;
46
+ size: number;
47
+ attempt: number;
48
+ status: UploadStatus;
49
+ }
50
+ declare enum UploadState {
51
+ IDLE = "idle",
52
+ INITIALIZING = "initializing",
53
+ UPLOADING = "uploading",
54
+ PAUSED = "paused",
55
+ CANCELLED = "cancelled",
56
+ FINALIZING = "finalizing",
57
+ COMPLETED = "completed",
58
+ FAILED = "failed"
59
+ }
60
+ interface UploadResult {
61
+ success: boolean;
62
+ fileId?: string;
63
+ totalChunks: number;
64
+ totalBytes: number;
65
+ duration: number;
66
+ averageSpeed: number;
67
+ finalizeUploadResponse?: FetchResponseInterface | null;
68
+ statusResponse?: number;
69
+ }
70
+ interface ResumeData {
71
+ fileId: string;
72
+ fileName: string;
73
+ fileSize: number;
74
+ uploadedChunks: number;
75
+ lastChunkIndex: number;
76
+ lastBytePosition: number;
77
+ chunkSize: number;
78
+ concurrency: number;
79
+ }
80
+ declare const DEFAULT_CONFIG: Readonly<ChunkSizeConfig>;
81
+ interface UploadProgress {
82
+ uploadedChunks: number;
83
+ totalChunks: number;
84
+ uploadedBytes: number;
85
+ totalBytes: number;
86
+ percentage: number;
87
+ currentChunk: number;
88
+ speed?: number;
89
+ estimatedTimeRemaining?: number | null;
90
+ elapsed: number;
91
+ }
92
+ interface ChunkError {
93
+ chunk: ChunkInfo;
94
+ error: Error;
95
+ attempt: number;
96
+ willRetry: boolean;
97
+ }
98
+ /**
99
+ * Expected response structure from initialize endpoint
100
+ */
101
+ interface InitializeUploadResponse {
102
+ mediaIdFromServer?: string | number;
103
+ sessionId?: string | number;
104
+ uploadId?: string | number;
105
+ mediaId?: string | number;
106
+ message?: string | number;
107
+ [key: string]: any;
108
+ }
109
+
110
+ export { type ChunkError, type ChunkInfo, type ChunkSizeConfig, DEFAULT_CONFIG, type InitializeUploadOptions, type InitializeUploadResponse, type ResumeData, type UploadEndpoints, type UploadOptions, type UploadProgress, type UploadResult, UploadState, type UploadStatus };
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var types_exports = {};
20
+ __export(types_exports, {
21
+ DEFAULT_CONFIG: () => DEFAULT_CONFIG,
22
+ UploadState: () => UploadState
23
+ });
24
+ module.exports = __toCommonJS(types_exports);
25
+ var UploadState = /* @__PURE__ */ ((UploadState2) => {
26
+ UploadState2["IDLE"] = "idle";
27
+ UploadState2["INITIALIZING"] = "initializing";
28
+ UploadState2["UPLOADING"] = "uploading";
29
+ UploadState2["PAUSED"] = "paused";
30
+ UploadState2["CANCELLED"] = "cancelled";
31
+ UploadState2["FINALIZING"] = "finalizing";
32
+ UploadState2["COMPLETED"] = "completed";
33
+ UploadState2["FAILED"] = "failed";
34
+ return UploadState2;
35
+ })(UploadState || {});
36
+ const DEFAULT_CONFIG = Object.freeze({
37
+ defaultChunkSizeMB: 50,
38
+ slowSpeedThresholdMbps: 5,
39
+ slowSpeedChunkSizeMB: 2,
40
+ fileSizeThresholds: [
41
+ { maxSizeMB: 200, chunkSizeMB: 50 },
42
+ { maxSizeMB: 400, chunkSizeMB: 100 },
43
+ { maxSizeMB: 800, chunkSizeMB: 300 },
44
+ { maxSizeMB: 1e3, chunkSizeMB: 500 },
45
+ { maxSizeMB: Infinity, chunkSizeMB: 700 }
46
+ ]
47
+ });
48
+ // Annotate the CommonJS export names for ESM import in node:
49
+ 0 && (module.exports = {
50
+ DEFAULT_CONFIG,
51
+ UploadState
52
+ });
53
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/types/index.ts"],"sourcesContent":["/*\n * This file is part of the project by AGBOKOUDJO Franck.\n *\n * (c) AGBOKOUDJO Franck <internationaleswebservices@gmail.com>\n * Phone: +229 0167 25 18 86\n * LinkedIn: https://www.linkedin.com/in/internationales-web-apps-services-120520193/\n * Company: INTERNATIONALES WEB APPS & SERVICES\n *\n * For more information, please feel free to contact the author.\n */\n\nimport { FetchResponseInterface } from \"@wlindabla/http_client\";\n\nexport interface UploadOptions {\n autoSave?: boolean,\n chunkSize?: number;\n speedMbps?: number;\n config?: ChunkSizeConfig;\n headers?: HeadersInit;\n chunkOtherData?: Record<string, any>;\n metadata?: Record<string, any>;\n maxRetries?: number;\n timeout?: number;\n initTimeout?: number;\n headerInitialzingUpload?: HeadersInit;\n headerFinalezingUpload?: HeadersInit;\n concurrency?: number; // Default: 3\n}\n\nexport interface InitializeUploadOptions{\n metadata?: Record<string, any>;\n fileHash: string;\n fileName: string;\n fileSize: number;\n fileType: string;\n endpointInit: string | URL;\n headers?: HeadersInit;\n}\n\nexport interface UploadEndpoints{\n init: string | URL;\n upload: string | URL;\n finalize: string | URL;\n}\n\nexport interface ChunkSizeConfig {\n defaultChunkSizeMB: number;\n slowSpeedThresholdMbps: number;\n slowSpeedChunkSizeMB: number;\n fileSizeThresholds: Array<{\n maxSizeMB: number;\n chunkSizeMB: number;\n }>;\n}\n\nexport type UploadStatus = 'pending' | 'uploading' | 'success' | 'error';\n\nexport interface ChunkInfo {\n index: number;\n start: number;\n end: number;\n size: number;\n attempt: number;\n status: UploadStatus;\n}\n\nexport enum UploadState {\n IDLE = 'idle',\n INITIALIZING = 'initializing',\n UPLOADING = 'uploading',\n PAUSED = 'paused',\n CANCELLED = 'cancelled',\n FINALIZING = 'finalizing',\n COMPLETED = 'completed',\n FAILED = 'failed'\n}\n\nexport interface UploadResult {\n success: boolean;\n fileId?: string;\n totalChunks: number;\n totalBytes: number;\n duration: number;\n averageSpeed: number;\n finalizeUploadResponse?: FetchResponseInterface | null;\n statusResponse?: number;\n}\n\nexport interface ResumeData {\n fileId: string;\n fileName: string;\n fileSize: number;\n uploadedChunks: number;\n lastChunkIndex: number;\n lastBytePosition: number;\n chunkSize: number;\n concurrency: number;\n}\n\nexport const DEFAULT_CONFIG: Readonly<ChunkSizeConfig> = Object.freeze({\n defaultChunkSizeMB: 50,\n slowSpeedThresholdMbps: 5,\n slowSpeedChunkSizeMB: 2,\n fileSizeThresholds: [\n { maxSizeMB: 200, chunkSizeMB: 50 },\n { maxSizeMB: 400, chunkSizeMB: 100 },\n { maxSizeMB: 800, chunkSizeMB: 300 },\n { maxSizeMB: 1000, chunkSizeMB: 500 },\n { maxSizeMB: Infinity, chunkSizeMB: 700 }\n ]\n});\n\nexport interface UploadProgress {\n uploadedChunks: number;\n totalChunks: number;\n uploadedBytes: number;\n totalBytes: number;\n percentage: number;\n currentChunk: number;\n speed?: number; // bytes per second\n estimatedTimeRemaining?: number | null; // seconds\n elapsed: number;// secondes écoulées\n}\nexport interface ChunkError {\n chunk: ChunkInfo;\n error: Error;\n attempt: number;\n willRetry: boolean;\n}\n\n/**\n * Expected response structure from initialize endpoint\n */\nexport interface InitializeUploadResponse {\n mediaIdFromServer?: string | number;\n sessionId?: string | number;\n uploadId?: string | number;\n mediaId?: string | number;\n message?: string | number;\n [key: string]: any; // Allow extra fields\n}"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkEO,IAAK,cAAL,kBAAKA,iBAAL;AACH,EAAAA,aAAA,UAAO;AACP,EAAAA,aAAA,kBAAe;AACf,EAAAA,aAAA,eAAY;AACZ,EAAAA,aAAA,YAAS;AACT,EAAAA,aAAA,eAAY;AACZ,EAAAA,aAAA,gBAAa;AACb,EAAAA,aAAA,eAAY;AACZ,EAAAA,aAAA,YAAS;AARD,SAAAA;AAAA,GAAA;AAiCL,MAAM,iBAA4C,OAAO,OAAO;AAAA,EACnE,oBAAoB;AAAA,EACpB,wBAAwB;AAAA,EACxB,sBAAsB;AAAA,EACtB,oBAAoB;AAAA,IAChB,EAAE,WAAW,KAAK,aAAa,GAAG;AAAA,IAClC,EAAE,WAAW,KAAK,aAAa,IAAI;AAAA,IACnC,EAAE,WAAW,KAAK,aAAa,IAAI;AAAA,IACnC,EAAE,WAAW,KAAM,aAAa,IAAI;AAAA,IACpC,EAAE,WAAW,UAAU,aAAa,IAAI;AAAA,EAC5C;AACJ,CAAC;","names":["UploadState"]}
@@ -0,0 +1,72 @@
1
+ import { ChunkSizeConfig } from '../types/index.js';
2
+ import '@wlindabla/http_client';
3
+
4
+ declare class FileUtils {
5
+ static readonly MB: number;
6
+ static readonly GB: number;
7
+ static bytesToMB(bytes: number): number;
8
+ static bytesToGB(bytes: number): number;
9
+ static formatBytes(bytes: number): string;
10
+ static formatDuration(seconds: number): string;
11
+ static calculateChunkSize(fileSize: number, speedMbps?: number, config?: ChunkSizeConfig): number;
12
+ static generateFileHash(file: File | Blob): Promise<string>;
13
+ }
14
+ declare function updateProgressBarHTMLNotified(progress: number, media_id: number, filename: string, providerName?: string): string;
15
+ /**
16
+ * Options for creating chunk FormData
17
+ */
18
+ interface ChunkFormDataOptions {
19
+ chunkIndex: number;
20
+ totalChunks: number;
21
+ mediaId: string;
22
+ fileName: string;
23
+ fileSize: number;
24
+ fileHash: string;
25
+ metadata?: Record<string, string | Blob>;
26
+ }
27
+ /**
28
+ * Creates FormData for uploading a single file chunk.
29
+ *
30
+ * @param chunk - The chunk blob to upload
31
+ * @param options - Chunk upload options
32
+ * @returns FormData ready to be sent to the server
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * const formData = createChunkFormData(blob, {
37
+ * chunkIndex: 5,
38
+ * totalChunks: 10,
39
+ * mediaId: 'abc123',
40
+ * fileName: 'video.mp4',
41
+ * fileSize: 104857600,
42
+ * fileHash: 'sha256...'
43
+ * });
44
+ * ```
45
+ */
46
+ declare function createChunkFormData(chunk: Blob, options: ChunkFormDataOptions): FormData;
47
+ /**
48
+ * Builder pattern for creating chunk FormData with fluent API.
49
+ */
50
+ declare class ChunkFormDataBuilder {
51
+ private formData;
52
+ constructor(chunk: Blob);
53
+ withChunkInfo(chunkIndex: number, totalChunks: number): this;
54
+ withFileInfo(fileName: string, fileSize: number, fileHash: string): this;
55
+ withSessionId(sessionId: string): this;
56
+ withMetadata(metadata: Record<string, string | Blob>): this;
57
+ build(): FormData;
58
+ }
59
+ interface RetryStrategyInterface {
60
+ shouldRetry(attempt: number, maxRetries: number, error: Error): boolean;
61
+ getDelay(attempt: number): number;
62
+ }
63
+ declare class ExponentialBackoffStrategy implements RetryStrategyInterface {
64
+ shouldRetry(attempt: number, maxRetries: number): boolean;
65
+ getDelay(attempt: number): number;
66
+ }
67
+ declare class LinearBackoffStrategy implements RetryStrategyInterface {
68
+ shouldRetry(attempt: number, maxRetries: number): boolean;
69
+ getDelay(attempt: number): number;
70
+ }
71
+
72
+ export { ChunkFormDataBuilder, type ChunkFormDataOptions, ExponentialBackoffStrategy, FileUtils, LinearBackoffStrategy, createChunkFormData, updateProgressBarHTMLNotified };
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var utils_exports = {};
21
+ __export(utils_exports, {
22
+ ChunkFormDataBuilder: () => ChunkFormDataBuilder,
23
+ ExponentialBackoffStrategy: () => ExponentialBackoffStrategy,
24
+ FileUtils: () => FileUtils,
25
+ LinearBackoffStrategy: () => LinearBackoffStrategy,
26
+ createChunkFormData: () => createChunkFormData,
27
+ updateProgressBarHTMLNotified: () => updateProgressBarHTMLNotified
28
+ });
29
+ module.exports = __toCommonJS(utils_exports);
30
+ var import_types = require("../types");
31
+ class FileUtils {
32
+ static {
33
+ __name(this, "FileUtils");
34
+ }
35
+ static MB = 1024 * 1024;
36
+ static GB = 1024 * 1024 * 1024;
37
+ static bytesToMB(bytes) {
38
+ return parseFloat((bytes / this.MB).toFixed(2));
39
+ }
40
+ static bytesToGB(bytes) {
41
+ return parseFloat((bytes / this.GB).toFixed(2));
42
+ }
43
+ static formatBytes(bytes) {
44
+ if (bytes === 0) return "0 Bytes";
45
+ const k = 1024;
46
+ const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
47
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
48
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
49
+ }
50
+ static formatDuration(seconds) {
51
+ const hours = Math.floor(seconds / 3600);
52
+ const minutes = Math.floor(seconds % 3600 / 60);
53
+ const secs = Math.floor(seconds % 60);
54
+ if (hours > 0) return `${hours}h ${minutes}m ${secs}s`;
55
+ if (minutes > 0) return `${minutes}m ${secs}s`;
56
+ return `${secs}s`;
57
+ }
58
+ static calculateChunkSize(fileSize, speedMbps, config = import_types.DEFAULT_CONFIG) {
59
+ const fileSizeMB = fileSize / this.MB;
60
+ if (speedMbps && speedMbps < config.slowSpeedThresholdMbps) {
61
+ return Math.min(
62
+ config.defaultChunkSizeMB * this.MB,
63
+ config.slowSpeedChunkSizeMB * this.MB
64
+ );
65
+ }
66
+ for (const threshold of config.fileSizeThresholds) {
67
+ if (fileSizeMB <= threshold.maxSizeMB) {
68
+ return threshold.chunkSizeMB * this.MB;
69
+ }
70
+ }
71
+ return config.defaultChunkSizeMB * this.MB;
72
+ }
73
+ static generateFileHash(file) {
74
+ return new Promise((resolve, reject) => {
75
+ const reader = new FileReader();
76
+ reader.onload = async (e) => {
77
+ try {
78
+ const buffer = e.target?.result;
79
+ const hashBuffer = await crypto.subtle.digest("SHA-256", buffer.slice(0, 1024 * 1024));
80
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
81
+ const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
82
+ resolve(hashHex);
83
+ } catch (error) {
84
+ reject(error);
85
+ }
86
+ };
87
+ reader.onerror = reject;
88
+ reader.readAsArrayBuffer(file.slice(0, 1024 * 1024));
89
+ });
90
+ }
91
+ }
92
+ function updateProgressBarHTMLNotified(progress, media_id, filename, providerName = "LocalVideo") {
93
+ const progressBarId = `progress-bar-item_${providerName}_${media_id}`;
94
+ const progressBarContainer = document.querySelector(`#${progressBarId}`);
95
+ const progressBarInner = progressBarContainer?.querySelector(".progress-bar");
96
+ if (progressBarInner) {
97
+ const roundedProgress = Math.round(progress);
98
+ progressBarInner.style.width = `${progress}%`;
99
+ progressBarInner.setAttribute("aria-valuenow", progress.toString());
100
+ progressBarInner.innerText = `${roundedProgress}%`;
101
+ return progressBarContainer.innerHTML;
102
+ } else {
103
+ return `
104
+ <div id="${progressBarId}" class="mb-2" style="width:100%;">
105
+ <small class="control-label text-dark fw-bolder filename-label w-100 d-block text-truncate" title="${filename}">
106
+ ${filename}
107
+ </small>
108
+ <div class="progress">
109
+ <div class="progress-bar bg-success progress-bar-striped progress-bar-animated"
110
+ role="progressbar"
111
+ style="width: ${progress}%;"
112
+ aria-valuenow="${progress}"
113
+ aria-valuemin="0"
114
+ aria-valuemax="100">${Math.round(progress)}%</div>
115
+ </div>
116
+ </div>`;
117
+ }
118
+ }
119
+ __name(updateProgressBarHTMLNotified, "updateProgressBarHTMLNotified");
120
+ function createChunkFormData(chunk, options) {
121
+ const formData = new FormData();
122
+ formData.append("chunk", chunk);
123
+ formData.append("chunkIndex", options.chunkIndex.toString());
124
+ formData.append("chunkSize", chunk.size.toString());
125
+ formData.append("totalChunks", options.totalChunks.toString());
126
+ formData.append("fileName", options.fileName);
127
+ formData.append("fileSize", options.fileSize.toString());
128
+ formData.append("fileHash", options.fileHash);
129
+ formData.append("mediaId", options.mediaId);
130
+ if (options.metadata) {
131
+ for (const [key, value] of Object.entries(options.metadata)) {
132
+ if (typeof value === "string" || value instanceof Blob) {
133
+ formData.append(key, value);
134
+ }
135
+ }
136
+ }
137
+ return formData;
138
+ }
139
+ __name(createChunkFormData, "createChunkFormData");
140
+ class ChunkFormDataBuilder {
141
+ static {
142
+ __name(this, "ChunkFormDataBuilder");
143
+ }
144
+ formData;
145
+ constructor(chunk) {
146
+ this.formData = new FormData();
147
+ this.formData.append("chunk", chunk);
148
+ this.formData.append("chunkSize", chunk.size.toString());
149
+ }
150
+ withChunkInfo(chunkIndex, totalChunks) {
151
+ this.formData.append("chunkIndex", chunkIndex.toString());
152
+ this.formData.append("totalChunks", totalChunks.toString());
153
+ return this;
154
+ }
155
+ withFileInfo(fileName, fileSize, fileHash) {
156
+ this.formData.append("fileName", fileName);
157
+ this.formData.append("fileSize", fileSize.toString());
158
+ this.formData.append("fileHash", fileHash);
159
+ return this;
160
+ }
161
+ withSessionId(sessionId) {
162
+ this.formData.append("sessionId", sessionId);
163
+ return this;
164
+ }
165
+ withMetadata(metadata) {
166
+ for (const [key, value] of Object.entries(metadata)) {
167
+ if (typeof value === "string" || value instanceof Blob) {
168
+ this.formData.append(key, value);
169
+ }
170
+ }
171
+ return this;
172
+ }
173
+ build() {
174
+ return this.formData;
175
+ }
176
+ }
177
+ class ExponentialBackoffStrategy {
178
+ static {
179
+ __name(this, "ExponentialBackoffStrategy");
180
+ }
181
+ shouldRetry(attempt, maxRetries) {
182
+ return attempt < maxRetries;
183
+ }
184
+ getDelay(attempt) {
185
+ return Math.pow(2, attempt) * 1e3;
186
+ }
187
+ }
188
+ class LinearBackoffStrategy {
189
+ static {
190
+ __name(this, "LinearBackoffStrategy");
191
+ }
192
+ shouldRetry(attempt, maxRetries) {
193
+ return attempt < maxRetries;
194
+ }
195
+ getDelay(attempt) {
196
+ return (attempt + 1) * 1e3;
197
+ }
198
+ }
199
+ // Annotate the CommonJS export names for ESM import in node:
200
+ 0 && (module.exports = {
201
+ ChunkFormDataBuilder,
202
+ ExponentialBackoffStrategy,
203
+ FileUtils,
204
+ LinearBackoffStrategy,
205
+ createChunkFormData,
206
+ updateProgressBarHTMLNotified
207
+ });
208
+ //# sourceMappingURL=index.js.map