@dimah-s3/react 0.1.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.
- package/LICENSE +21 -0
- package/README.md +31 -0
- package/dist/api.d.ts +29 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/create-s3-client.d.ts +34 -0
- package/dist/create-s3-client.d.ts.map +1 -0
- package/dist/helpers/format-accept-labels.d.ts +3 -0
- package/dist/helpers/format-accept-labels.d.ts.map +1 -0
- package/dist/helpers/format-dimah-error.d.ts +8 -0
- package/dist/helpers/format-dimah-error.d.ts.map +1 -0
- package/dist/helpers/format-dimah-error.test.d.ts +2 -0
- package/dist/helpers/format-dimah-error.test.d.ts.map +1 -0
- package/dist/helpers/format-eta.d.ts +13 -0
- package/dist/helpers/format-eta.d.ts.map +1 -0
- package/dist/helpers/format-speed.d.ts +9 -0
- package/dist/helpers/format-speed.d.ts.map +1 -0
- package/dist/helpers/format-upload-progress.d.ts +18 -0
- package/dist/helpers/format-upload-progress.d.ts.map +1 -0
- package/dist/helpers/format-validate-file-error.d.ts +9 -0
- package/dist/helpers/format-validate-file-error.d.ts.map +1 -0
- package/dist/helpers/helpers.test.d.ts +2 -0
- package/dist/helpers/helpers.test.d.ts.map +1 -0
- package/dist/helpers/index.d.ts +9 -0
- package/dist/helpers/index.d.ts.map +1 -0
- package/dist/helpers/speed-tracker.d.ts +18 -0
- package/dist/helpers/speed-tracker.d.ts.map +1 -0
- package/dist/helpers/throttled-speed.d.ts +8 -0
- package/dist/helpers/throttled-speed.d.ts.map +1 -0
- package/dist/hooks/index.d.ts +8 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/use-delete.d.ts +29 -0
- package/dist/hooks/use-delete.d.ts.map +1 -0
- package/dist/hooks/use-download.d.ts +33 -0
- package/dist/hooks/use-download.d.ts.map +1 -0
- package/dist/hooks/use-fetch-download.d.ts +33 -0
- package/dist/hooks/use-fetch-download.d.ts.map +1 -0
- package/dist/hooks/use-multi-upload-controls.d.ts +45 -0
- package/dist/hooks/use-multi-upload-controls.d.ts.map +1 -0
- package/dist/hooks/use-multi-upload.d.ts +39 -0
- package/dist/hooks/use-multi-upload.d.ts.map +1 -0
- package/dist/hooks/use-upload-controls.d.ts +54 -0
- package/dist/hooks/use-upload-controls.d.ts.map +1 -0
- package/dist/hooks/use-upload.d.ts +83 -0
- package/dist/hooks/use-upload.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1558 -0
- package/dist/index.js.map +1 -0
- package/dist/internal-helpers.d.ts +10 -0
- package/dist/internal-helpers.d.ts.map +1 -0
- package/dist/s3-provider.d.ts +50 -0
- package/dist/s3-provider.d.ts.map +1 -0
- package/dist/store/index.d.ts +4 -0
- package/dist/store/index.d.ts.map +1 -0
- package/dist/store/local-storage-store.d.ts +10 -0
- package/dist/store/local-storage-store.d.ts.map +1 -0
- package/dist/store/memory-store.d.ts +15 -0
- package/dist/store/memory-store.d.ts.map +1 -0
- package/dist/translations/index.d.ts +2 -0
- package/dist/translations/index.d.ts.map +1 -0
- package/dist/translations/types.d.ts +61 -0
- package/dist/translations/types.d.ts.map +1 -0
- package/dist/types/delete.d.ts +11 -0
- package/dist/types/delete.d.ts.map +1 -0
- package/dist/types/download.d.ts +26 -0
- package/dist/types/download.d.ts.map +1 -0
- package/dist/types/error.d.ts +24 -0
- package/dist/types/error.d.ts.map +1 -0
- package/dist/types/index.d.ts +7 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/multi-upload.d.ts +27 -0
- package/dist/types/multi-upload.d.ts.map +1 -0
- package/dist/types/upload-store.d.ts +55 -0
- package/dist/types/upload-store.d.ts.map +1 -0
- package/dist/types/upload.d.ts +102 -0
- package/dist/types/upload.d.ts.map +1 -0
- package/dist/upload/constants.d.ts +7 -0
- package/dist/upload/constants.d.ts.map +1 -0
- package/dist/upload/index.d.ts +3 -0
- package/dist/upload/index.d.ts.map +1 -0
- package/dist/upload/multipart.d.ts +5 -0
- package/dist/upload/multipart.d.ts.map +1 -0
- package/dist/upload/presigned-http.d.ts +17 -0
- package/dist/upload/presigned-http.d.ts.map +1 -0
- package/dist/upload/retry.d.ts +3 -0
- package/dist/upload/retry.d.ts.map +1 -0
- package/dist/upload/upload-file.d.ts +13 -0
- package/dist/upload/upload-file.d.ts.map +1 -0
- package/dist/upload/upload-files.d.ts +26 -0
- package/dist/upload/upload-files.d.ts.map +1 -0
- package/dist/upload/upload-part.d.ts +4 -0
- package/dist/upload/upload-part.d.ts.map +1 -0
- package/package.json +67 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1558 @@
|
|
|
1
|
+
import { DimahS3Error, createS3Client as createS3Client$1, formatFileSize, S3_ERROR_CODES, validateFile, parseFileName } from '@dimah-s3/core';
|
|
2
|
+
import { createContext, useContext, useCallback, useState, useRef, useLayoutEffect } from 'react';
|
|
3
|
+
import { TranslationProvider, useTranslations } from '@fuma-translate/react';
|
|
4
|
+
import { jsx } from 'react/jsx-runtime';
|
|
5
|
+
|
|
6
|
+
var S3UploadError = class extends DimahS3Error {
|
|
7
|
+
code;
|
|
8
|
+
phase;
|
|
9
|
+
constructor(message, code, status = 400, phase) {
|
|
10
|
+
super(message, status);
|
|
11
|
+
this.name = "S3UploadError";
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.phase = phase;
|
|
14
|
+
}
|
|
15
|
+
/** Alias for {@link DimahS3Error.status}. */
|
|
16
|
+
get statusCode() {
|
|
17
|
+
return this.status;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
function toUploadError(err, phase) {
|
|
21
|
+
if (err instanceof S3UploadError) {
|
|
22
|
+
if (phase != null && err.phase == null) {
|
|
23
|
+
return new S3UploadError(err.message, err.code, err.status, phase);
|
|
24
|
+
}
|
|
25
|
+
return err;
|
|
26
|
+
}
|
|
27
|
+
if (err?.name === "AbortError") {
|
|
28
|
+
throw err;
|
|
29
|
+
}
|
|
30
|
+
if (err instanceof DimahS3Error) {
|
|
31
|
+
return new S3UploadError(err.message, "API_ERROR", err.status, phase);
|
|
32
|
+
}
|
|
33
|
+
const message = err instanceof Error ? err.message : "Upload failed";
|
|
34
|
+
return new S3UploadError(message, "UPLOAD_ERROR", 500, phase);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/api.ts
|
|
38
|
+
function defineApi(input) {
|
|
39
|
+
return input;
|
|
40
|
+
}
|
|
41
|
+
var S3Context = createContext(null);
|
|
42
|
+
function S3Provider({
|
|
43
|
+
api,
|
|
44
|
+
translations,
|
|
45
|
+
children
|
|
46
|
+
}) {
|
|
47
|
+
return /* @__PURE__ */ jsx(S3Context.Provider, { value: api, children: translations ? /* @__PURE__ */ jsx(TranslationProvider, { translations, children }) : children });
|
|
48
|
+
}
|
|
49
|
+
function useApi() {
|
|
50
|
+
const ctx = useContext(S3Context);
|
|
51
|
+
if (!ctx) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
"[dimah-s3] No S3Api found. Either wrap your app with <S3Provider api={...}> or pass `api` directly to the hook."
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
return ctx;
|
|
57
|
+
}
|
|
58
|
+
function createS3Client(options) {
|
|
59
|
+
const api = createS3Client$1(options);
|
|
60
|
+
function S3Provider2(props) {
|
|
61
|
+
return /* @__PURE__ */ jsx(S3Provider, { api, ...props });
|
|
62
|
+
}
|
|
63
|
+
function useApi2() {
|
|
64
|
+
return useApi();
|
|
65
|
+
}
|
|
66
|
+
return { api, S3Provider: S3Provider2, useApi: useApi2 };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// src/store/local-storage-store.ts
|
|
70
|
+
var STORAGE_PREFIX = "dimah-s3:upload:";
|
|
71
|
+
function createLocalStorageStore() {
|
|
72
|
+
return {
|
|
73
|
+
get(key, fileSize) {
|
|
74
|
+
try {
|
|
75
|
+
const raw = localStorage.getItem(STORAGE_PREFIX + key);
|
|
76
|
+
if (!raw) return null;
|
|
77
|
+
const stored = JSON.parse(raw);
|
|
78
|
+
return stored.fileSize === fileSize ? stored : null;
|
|
79
|
+
} catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
set(upload) {
|
|
84
|
+
try {
|
|
85
|
+
localStorage.setItem(
|
|
86
|
+
STORAGE_PREFIX + upload.key,
|
|
87
|
+
JSON.stringify(upload)
|
|
88
|
+
);
|
|
89
|
+
} catch {
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
delete(key) {
|
|
93
|
+
try {
|
|
94
|
+
localStorage.removeItem(STORAGE_PREFIX + key);
|
|
95
|
+
} catch {
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/store/memory-store.ts
|
|
102
|
+
function createMemoryStore() {
|
|
103
|
+
const map = /* @__PURE__ */ new Map();
|
|
104
|
+
return {
|
|
105
|
+
get(key, fileSize) {
|
|
106
|
+
const stored = map.get(key);
|
|
107
|
+
if (!stored) return null;
|
|
108
|
+
return stored.fileSize === fileSize ? stored : null;
|
|
109
|
+
},
|
|
110
|
+
set(upload) {
|
|
111
|
+
map.set(upload.key, upload);
|
|
112
|
+
},
|
|
113
|
+
delete(key) {
|
|
114
|
+
map.delete(key);
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/upload/constants.ts
|
|
120
|
+
var DEFAULT_MULTIPART_THRESHOLD = 50 * 1024 * 1024;
|
|
121
|
+
var DEFAULT_PART_SIZE = 5 * 1024 * 1024;
|
|
122
|
+
var MAX_RETRIES = 3;
|
|
123
|
+
var RETRY_BASE_DELAY = 1e3;
|
|
124
|
+
var DEFAULT_CONCURRENT_PARTS = 2;
|
|
125
|
+
var DEFAULT_CONCURRENT_FILES = 2;
|
|
126
|
+
|
|
127
|
+
// src/upload/retry.ts
|
|
128
|
+
async function withRetry(fn, retryConfig, signal) {
|
|
129
|
+
const maxRetries = retryConfig?.maxRetries ?? MAX_RETRIES;
|
|
130
|
+
const baseDelay = retryConfig?.baseDelay ?? RETRY_BASE_DELAY;
|
|
131
|
+
let lastError;
|
|
132
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
133
|
+
try {
|
|
134
|
+
return await fn();
|
|
135
|
+
} catch (err) {
|
|
136
|
+
if (err.name === "AbortError") throw err;
|
|
137
|
+
lastError = err;
|
|
138
|
+
if (attempt < maxRetries) {
|
|
139
|
+
const delay = baseDelay * 2 ** attempt;
|
|
140
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
141
|
+
if (signal?.aborted)
|
|
142
|
+
throw new DOMException("Upload aborted", "AbortError");
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
throw lastError;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// src/upload/presigned-http.ts
|
|
150
|
+
function sendXhrUpload(options) {
|
|
151
|
+
const {
|
|
152
|
+
method,
|
|
153
|
+
url,
|
|
154
|
+
body,
|
|
155
|
+
headers,
|
|
156
|
+
fileSize,
|
|
157
|
+
onProgress,
|
|
158
|
+
signal,
|
|
159
|
+
errorLabel = "Upload"
|
|
160
|
+
} = options;
|
|
161
|
+
return new Promise((resolve, reject) => {
|
|
162
|
+
const xhr = new XMLHttpRequest();
|
|
163
|
+
const onAbort = () => {
|
|
164
|
+
xhr.abort();
|
|
165
|
+
reject(new DOMException("Upload aborted", "AbortError"));
|
|
166
|
+
};
|
|
167
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
168
|
+
xhr.upload.addEventListener("progress", (e) => {
|
|
169
|
+
if (e.lengthComputable) {
|
|
170
|
+
onProgress?.({
|
|
171
|
+
loaded: e.loaded,
|
|
172
|
+
total: e.total,
|
|
173
|
+
percent: Math.round(e.loaded / e.total * 100)
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
xhr.addEventListener("load", () => {
|
|
178
|
+
signal?.removeEventListener("abort", onAbort);
|
|
179
|
+
if (xhr.status >= 200 && xhr.status < 300) {
|
|
180
|
+
onProgress?.({ loaded: fileSize, total: fileSize, percent: 100 });
|
|
181
|
+
resolve();
|
|
182
|
+
} else {
|
|
183
|
+
reject(
|
|
184
|
+
new S3UploadError(
|
|
185
|
+
`${errorLabel} failed: ${xhr.status} ${xhr.statusText}`,
|
|
186
|
+
"HTTP_ERROR",
|
|
187
|
+
xhr.status,
|
|
188
|
+
"uploading"
|
|
189
|
+
)
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
xhr.addEventListener("error", () => {
|
|
194
|
+
signal?.removeEventListener("abort", onAbort);
|
|
195
|
+
reject(
|
|
196
|
+
new S3UploadError(
|
|
197
|
+
`${errorLabel} failed: network error`,
|
|
198
|
+
"NETWORK_ERROR",
|
|
199
|
+
0,
|
|
200
|
+
"uploading"
|
|
201
|
+
)
|
|
202
|
+
);
|
|
203
|
+
});
|
|
204
|
+
xhr.addEventListener("abort", () => {
|
|
205
|
+
signal?.removeEventListener("abort", onAbort);
|
|
206
|
+
reject(new DOMException("Upload aborted", "AbortError"));
|
|
207
|
+
});
|
|
208
|
+
xhr.open(method, url);
|
|
209
|
+
if (headers) {
|
|
210
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
211
|
+
xhr.setRequestHeader(k, v);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
xhr.send(body);
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
function uploadSimple(file, url, fields, onProgress, signal) {
|
|
218
|
+
const formData = new FormData();
|
|
219
|
+
for (const [k, v] of Object.entries(fields)) {
|
|
220
|
+
formData.append(k, v);
|
|
221
|
+
}
|
|
222
|
+
formData.append("file", file);
|
|
223
|
+
return sendXhrUpload({
|
|
224
|
+
method: "POST",
|
|
225
|
+
url,
|
|
226
|
+
body: formData,
|
|
227
|
+
fileSize: file.size,
|
|
228
|
+
onProgress,
|
|
229
|
+
signal
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
function uploadPut(file, url, headers, onProgress, signal) {
|
|
233
|
+
return sendXhrUpload({
|
|
234
|
+
method: "PUT",
|
|
235
|
+
url,
|
|
236
|
+
body: file,
|
|
237
|
+
headers,
|
|
238
|
+
fileSize: file.size,
|
|
239
|
+
onProgress,
|
|
240
|
+
signal
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// src/upload/upload-part.ts
|
|
245
|
+
function uploadPart(blob, presignedUrl, partLoaded, reportProgress, signal) {
|
|
246
|
+
return new Promise((resolve, reject) => {
|
|
247
|
+
const xhr = new XMLHttpRequest();
|
|
248
|
+
const onAbort = () => {
|
|
249
|
+
xhr.abort();
|
|
250
|
+
reject(new DOMException("Upload aborted", "AbortError"));
|
|
251
|
+
};
|
|
252
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
253
|
+
xhr.upload.addEventListener("progress", (e) => {
|
|
254
|
+
if (e.lengthComputable) {
|
|
255
|
+
partLoaded.bytes = e.loaded;
|
|
256
|
+
reportProgress();
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
xhr.addEventListener("load", () => {
|
|
260
|
+
signal?.removeEventListener("abort", onAbort);
|
|
261
|
+
if (xhr.status >= 200 && xhr.status < 300) {
|
|
262
|
+
partLoaded.bytes = blob.size;
|
|
263
|
+
reportProgress();
|
|
264
|
+
resolve();
|
|
265
|
+
} else {
|
|
266
|
+
reject(
|
|
267
|
+
new S3UploadError(
|
|
268
|
+
`Part upload failed: ${xhr.status}`,
|
|
269
|
+
"HTTP_ERROR",
|
|
270
|
+
xhr.status,
|
|
271
|
+
"uploading"
|
|
272
|
+
)
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
xhr.addEventListener("error", () => {
|
|
277
|
+
signal?.removeEventListener("abort", onAbort);
|
|
278
|
+
reject(
|
|
279
|
+
new S3UploadError(
|
|
280
|
+
"Part upload failed: network error",
|
|
281
|
+
"NETWORK_ERROR",
|
|
282
|
+
0,
|
|
283
|
+
"uploading"
|
|
284
|
+
)
|
|
285
|
+
);
|
|
286
|
+
});
|
|
287
|
+
xhr.addEventListener("abort", () => {
|
|
288
|
+
signal?.removeEventListener("abort", onAbort);
|
|
289
|
+
reject(new DOMException("Upload aborted", "AbortError"));
|
|
290
|
+
});
|
|
291
|
+
xhr.open("PUT", presignedUrl);
|
|
292
|
+
xhr.send(blob);
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// src/upload/multipart.ts
|
|
297
|
+
function resolvePartSize(partIndex, totalParts, partSize, fileSize) {
|
|
298
|
+
return partIndex === totalParts - 1 ? fileSize - partIndex * partSize : partSize;
|
|
299
|
+
}
|
|
300
|
+
async function uploadMultipart(api, file, objectKey, partSize, concurrentParts, onProgress, signal, requestOptions, retryConfig, uploadStore, onPartUpload, onMultipartInit) {
|
|
301
|
+
const bucket = requestOptions?.bucket;
|
|
302
|
+
const contentType = requestOptions?.contentType ?? file.type;
|
|
303
|
+
const store = uploadStore != null && uploadStore !== false ? uploadStore : null;
|
|
304
|
+
let uploadId;
|
|
305
|
+
let key;
|
|
306
|
+
const completedPartNumbers = /* @__PURE__ */ new Set();
|
|
307
|
+
const existing = store ? await store.get(objectKey, file.size) : null;
|
|
308
|
+
if (existing) {
|
|
309
|
+
try {
|
|
310
|
+
const { parts: parts2 } = await api.multipart.listParts({
|
|
311
|
+
key: existing.key,
|
|
312
|
+
uploadId: existing.uploadId,
|
|
313
|
+
bucket: bucket ?? existing.bucket
|
|
314
|
+
});
|
|
315
|
+
uploadId = existing.uploadId;
|
|
316
|
+
key = existing.key;
|
|
317
|
+
for (const p of parts2) completedPartNumbers.add(p.partNumber);
|
|
318
|
+
onMultipartInit?.(uploadId, key);
|
|
319
|
+
} catch {
|
|
320
|
+
await store?.delete(objectKey);
|
|
321
|
+
const result = await api.multipart.init({
|
|
322
|
+
key: objectKey,
|
|
323
|
+
contentType,
|
|
324
|
+
fileSize: file.size,
|
|
325
|
+
fileName: requestOptions?.fileName !== null ? requestOptions?.fileName ?? file.name : void 0,
|
|
326
|
+
metadata: requestOptions?.metadata,
|
|
327
|
+
bucket,
|
|
328
|
+
acl: requestOptions?.acl
|
|
329
|
+
});
|
|
330
|
+
uploadId = result.uploadId;
|
|
331
|
+
key = result.key;
|
|
332
|
+
await store?.set({ uploadId, key, fileSize: file.size, bucket });
|
|
333
|
+
onMultipartInit?.(uploadId, key);
|
|
334
|
+
}
|
|
335
|
+
} else {
|
|
336
|
+
const result = await api.multipart.init({
|
|
337
|
+
key: objectKey,
|
|
338
|
+
contentType,
|
|
339
|
+
fileSize: file.size,
|
|
340
|
+
fileName: requestOptions?.fileName !== null ? requestOptions?.fileName ?? file.name : void 0,
|
|
341
|
+
metadata: requestOptions?.metadata,
|
|
342
|
+
bucket,
|
|
343
|
+
acl: requestOptions?.acl
|
|
344
|
+
});
|
|
345
|
+
uploadId = result.uploadId;
|
|
346
|
+
key = result.key;
|
|
347
|
+
await store?.set({ uploadId, key, fileSize: file.size, bucket });
|
|
348
|
+
onMultipartInit?.(uploadId, key);
|
|
349
|
+
}
|
|
350
|
+
const totalParts = Math.ceil(file.size / partSize);
|
|
351
|
+
const partProgress = Array.from(
|
|
352
|
+
{ length: totalParts },
|
|
353
|
+
(_, i) => ({
|
|
354
|
+
bytes: completedPartNumbers.has(i + 1) ? resolvePartSize(i, totalParts, partSize, file.size) : 0
|
|
355
|
+
})
|
|
356
|
+
);
|
|
357
|
+
const parts = Array.from(
|
|
358
|
+
completedPartNumbers,
|
|
359
|
+
(n) => ({ partNumber: n })
|
|
360
|
+
);
|
|
361
|
+
const reportProgress = () => {
|
|
362
|
+
const loaded = partProgress.reduce((sum, p) => sum + p.bytes, 0);
|
|
363
|
+
onProgress?.({
|
|
364
|
+
loaded,
|
|
365
|
+
total: file.size,
|
|
366
|
+
percent: Math.round(loaded / file.size * 100)
|
|
367
|
+
});
|
|
368
|
+
};
|
|
369
|
+
if (completedPartNumbers.size > 0) {
|
|
370
|
+
reportProgress();
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
for (let batchStart = 0; batchStart < totalParts; batchStart += concurrentParts) {
|
|
374
|
+
if (signal?.aborted) {
|
|
375
|
+
throw new DOMException("Upload aborted", "AbortError");
|
|
376
|
+
}
|
|
377
|
+
const batchEnd = Math.min(batchStart + concurrentParts, totalParts);
|
|
378
|
+
const batch = [];
|
|
379
|
+
for (let i = batchStart; i < batchEnd; i++) {
|
|
380
|
+
const partNumber = i + 1;
|
|
381
|
+
if (completedPartNumbers.has(partNumber)) continue;
|
|
382
|
+
const start = i * partSize;
|
|
383
|
+
const end = Math.min(start + partSize, file.size);
|
|
384
|
+
const blob = file.slice(start, end);
|
|
385
|
+
batch.push(
|
|
386
|
+
withRetry(
|
|
387
|
+
async () => {
|
|
388
|
+
const { presignedUrl } = await api.multipart.signPart({
|
|
389
|
+
key,
|
|
390
|
+
uploadId,
|
|
391
|
+
partNumber,
|
|
392
|
+
partSize: blob.size,
|
|
393
|
+
bucket
|
|
394
|
+
});
|
|
395
|
+
partProgress[i].bytes = 0;
|
|
396
|
+
await uploadPart(
|
|
397
|
+
blob,
|
|
398
|
+
presignedUrl,
|
|
399
|
+
partProgress[i],
|
|
400
|
+
reportProgress,
|
|
401
|
+
signal
|
|
402
|
+
);
|
|
403
|
+
onPartUpload?.(partNumber, totalParts);
|
|
404
|
+
return { partNumber };
|
|
405
|
+
},
|
|
406
|
+
retryConfig,
|
|
407
|
+
signal
|
|
408
|
+
)
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
const batchResults = await Promise.all(batch);
|
|
412
|
+
parts.push(...batchResults);
|
|
413
|
+
}
|
|
414
|
+
parts.sort((a, b) => a.partNumber - b.partNumber);
|
|
415
|
+
const result = await api.multipart.complete({
|
|
416
|
+
key,
|
|
417
|
+
uploadId,
|
|
418
|
+
parts,
|
|
419
|
+
bucket
|
|
420
|
+
});
|
|
421
|
+
await store?.delete(objectKey);
|
|
422
|
+
onProgress?.({ loaded: file.size, total: file.size, percent: 100 });
|
|
423
|
+
return result.eTag;
|
|
424
|
+
} catch (err) {
|
|
425
|
+
if (store === null) {
|
|
426
|
+
api.multipart.abort({ key, uploadId, bucket }).catch(() => {
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
throw err;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// src/upload/upload-file.ts
|
|
434
|
+
async function uploadFile(api, file, objectKey, config = {}, callbacks = {}, signal, requestOptions) {
|
|
435
|
+
const threshold = config.multipartThreshold ?? DEFAULT_MULTIPART_THRESHOLD;
|
|
436
|
+
const useMultipart = config.multipart === true && file.size >= threshold;
|
|
437
|
+
const concurrentParts = config.concurrentParts ?? DEFAULT_CONCURRENT_PARTS;
|
|
438
|
+
const partSize = requestOptions?.partSize ?? config.partSize ?? DEFAULT_PART_SIZE;
|
|
439
|
+
const contentType = requestOptions?.contentType ?? file.type;
|
|
440
|
+
try {
|
|
441
|
+
let eTag;
|
|
442
|
+
if (useMultipart) {
|
|
443
|
+
callbacks.onPhaseChange?.("uploading");
|
|
444
|
+
eTag = await uploadMultipart(
|
|
445
|
+
api,
|
|
446
|
+
file,
|
|
447
|
+
objectKey,
|
|
448
|
+
partSize,
|
|
449
|
+
concurrentParts,
|
|
450
|
+
callbacks.onProgress,
|
|
451
|
+
signal,
|
|
452
|
+
requestOptions,
|
|
453
|
+
config.retry,
|
|
454
|
+
config.uploadStore,
|
|
455
|
+
callbacks.onPartUpload,
|
|
456
|
+
callbacks.onMultipartInit
|
|
457
|
+
);
|
|
458
|
+
} else {
|
|
459
|
+
await withRetry(
|
|
460
|
+
async () => {
|
|
461
|
+
callbacks.onPhaseChange?.("presigning");
|
|
462
|
+
const presign = await api.upload({
|
|
463
|
+
key: objectKey,
|
|
464
|
+
contentType,
|
|
465
|
+
fileSize: file.size,
|
|
466
|
+
fileName: requestOptions?.fileName !== null ? requestOptions?.fileName ?? file.name : void 0,
|
|
467
|
+
metadata: requestOptions?.metadata,
|
|
468
|
+
bucket: requestOptions?.bucket,
|
|
469
|
+
acl: requestOptions?.acl
|
|
470
|
+
});
|
|
471
|
+
callbacks.onPhaseChange?.("uploading");
|
|
472
|
+
if (presign.method === "PUT") {
|
|
473
|
+
await uploadPut(
|
|
474
|
+
file,
|
|
475
|
+
presign.url,
|
|
476
|
+
presign.headers ?? {},
|
|
477
|
+
callbacks.onProgress,
|
|
478
|
+
signal
|
|
479
|
+
);
|
|
480
|
+
} else {
|
|
481
|
+
await uploadSimple(
|
|
482
|
+
file,
|
|
483
|
+
presign.url,
|
|
484
|
+
presign.fields ?? {},
|
|
485
|
+
callbacks.onProgress,
|
|
486
|
+
signal
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
},
|
|
490
|
+
config.retry,
|
|
491
|
+
signal
|
|
492
|
+
);
|
|
493
|
+
callbacks.onPhaseChange?.("finalizing");
|
|
494
|
+
const confirmed = await api.confirm({
|
|
495
|
+
key: objectKey,
|
|
496
|
+
bucket: requestOptions?.bucket
|
|
497
|
+
});
|
|
498
|
+
eTag = confirmed.eTag;
|
|
499
|
+
}
|
|
500
|
+
return { key: objectKey, eTag };
|
|
501
|
+
} catch (err) {
|
|
502
|
+
throw toUploadError(err, "uploading");
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// src/upload/upload-files.ts
|
|
507
|
+
async function uploadFiles(api, items, config = {}, callbacks = {}, signal, getRequestOptions) {
|
|
508
|
+
const results = items.map((item) => ({
|
|
509
|
+
...item,
|
|
510
|
+
status: "pending",
|
|
511
|
+
progress: { loaded: 0, total: item.file.size, percent: 0 },
|
|
512
|
+
result: null,
|
|
513
|
+
error: null
|
|
514
|
+
}));
|
|
515
|
+
const reportTotalProgress = () => {
|
|
516
|
+
const loaded = results.reduce((sum, r) => sum + r.progress.loaded, 0);
|
|
517
|
+
const total = results.reduce((sum, r) => sum + r.progress.total, 0);
|
|
518
|
+
callbacks.onTotalProgress?.({
|
|
519
|
+
loaded,
|
|
520
|
+
total,
|
|
521
|
+
percent: total > 0 ? Math.round(loaded / total * 100) : 0
|
|
522
|
+
});
|
|
523
|
+
};
|
|
524
|
+
let nextIndex = 0;
|
|
525
|
+
const processNext = async () => {
|
|
526
|
+
while (nextIndex < results.length) {
|
|
527
|
+
if (signal?.aborted) return;
|
|
528
|
+
const idx = nextIndex++;
|
|
529
|
+
const item = results[idx];
|
|
530
|
+
item.status = "uploading";
|
|
531
|
+
try {
|
|
532
|
+
const result = await uploadFile(
|
|
533
|
+
api,
|
|
534
|
+
item.file,
|
|
535
|
+
item.objectKey,
|
|
536
|
+
config,
|
|
537
|
+
{
|
|
538
|
+
onProgress: (progress) => {
|
|
539
|
+
item.progress = progress;
|
|
540
|
+
callbacks.onFileProgress?.(item.id, progress);
|
|
541
|
+
reportTotalProgress();
|
|
542
|
+
},
|
|
543
|
+
onMultipartInit: (uploadId, key) => {
|
|
544
|
+
callbacks.onMultipartInit?.(item.id, uploadId, key);
|
|
545
|
+
}
|
|
546
|
+
},
|
|
547
|
+
signal,
|
|
548
|
+
getRequestOptions?.(item.file)
|
|
549
|
+
);
|
|
550
|
+
item.status = "success";
|
|
551
|
+
item.result = result;
|
|
552
|
+
item.progress = {
|
|
553
|
+
loaded: item.file.size,
|
|
554
|
+
total: item.file.size,
|
|
555
|
+
percent: 100
|
|
556
|
+
};
|
|
557
|
+
callbacks.onFileSuccess?.(item.id, result);
|
|
558
|
+
reportTotalProgress();
|
|
559
|
+
} catch (err) {
|
|
560
|
+
if (err.name === "AbortError") {
|
|
561
|
+
item.status = "error";
|
|
562
|
+
item.error = "Upload cancelled";
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
const message = err instanceof Error ? err.message : "Upload failed";
|
|
566
|
+
item.status = "error";
|
|
567
|
+
item.error = message;
|
|
568
|
+
callbacks.onFileError?.(item.id, message);
|
|
569
|
+
reportTotalProgress();
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
};
|
|
573
|
+
const concurrentFiles = config.concurrentFiles ?? DEFAULT_CONCURRENT_FILES;
|
|
574
|
+
const workers = Array.from(
|
|
575
|
+
{ length: Math.min(concurrentFiles, items.length) },
|
|
576
|
+
() => processNext()
|
|
577
|
+
);
|
|
578
|
+
await Promise.all(workers);
|
|
579
|
+
return results;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// src/helpers/format-accept-labels.ts
|
|
583
|
+
function formatAcceptLabel(type) {
|
|
584
|
+
if (type.startsWith(".")) {
|
|
585
|
+
const ext = type.slice(1).toLowerCase();
|
|
586
|
+
return ext === "jpg" || ext === "jpeg" ? "JPEG" : ext.toUpperCase();
|
|
587
|
+
}
|
|
588
|
+
if (type.endsWith("/*")) {
|
|
589
|
+
const base = type.slice(0, -2);
|
|
590
|
+
return base.charAt(0).toUpperCase() + base.slice(1) + "s";
|
|
591
|
+
}
|
|
592
|
+
const sub = type.split("/")[1];
|
|
593
|
+
return sub ? sub.toUpperCase() : type;
|
|
594
|
+
}
|
|
595
|
+
function formatAcceptLabels(accept) {
|
|
596
|
+
if (!accept?.length) return [];
|
|
597
|
+
const labels = [];
|
|
598
|
+
const seen = /* @__PURE__ */ new Set();
|
|
599
|
+
for (const type of accept) {
|
|
600
|
+
const label = formatAcceptLabel(type);
|
|
601
|
+
if (!seen.has(label)) {
|
|
602
|
+
seen.add(label);
|
|
603
|
+
labels.push(label);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
return labels;
|
|
607
|
+
}
|
|
608
|
+
function formatUploadProgress(loaded, total, percent) {
|
|
609
|
+
const loadedStr = formatFileSize(loaded);
|
|
610
|
+
if (!total) return loadedStr;
|
|
611
|
+
return `${loadedStr} / ${formatFileSize(total)} (${Math.round(percent)}%)`;
|
|
612
|
+
}
|
|
613
|
+
function formatSpeed(bytesPerSecond) {
|
|
614
|
+
return `${formatFileSize(bytesPerSecond)}/s`;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// src/helpers/format-eta.ts
|
|
618
|
+
function formatEta(remainingBytes, bytesPerSecond) {
|
|
619
|
+
if (bytesPerSecond <= 0 || remainingBytes <= 0) return null;
|
|
620
|
+
const totalSeconds = remainingBytes / bytesPerSecond;
|
|
621
|
+
if (totalSeconds < 60) return `${Math.ceil(totalSeconds)}s`;
|
|
622
|
+
const totalMinutes = totalSeconds / 60;
|
|
623
|
+
if (totalMinutes < 60) return `${Math.ceil(totalMinutes)}m`;
|
|
624
|
+
const hours = Math.floor(totalMinutes / 60);
|
|
625
|
+
const mins = Math.ceil(totalMinutes % 60);
|
|
626
|
+
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
|
|
627
|
+
}
|
|
628
|
+
function useFormatValidateFileError() {
|
|
629
|
+
const t = useTranslations();
|
|
630
|
+
return useCallback(
|
|
631
|
+
(error) => {
|
|
632
|
+
switch (error.code) {
|
|
633
|
+
case "FILE_TYPE_NOT_ALLOWED":
|
|
634
|
+
return t('File type "{type}" is not allowed', {
|
|
635
|
+
note: "file validation",
|
|
636
|
+
variables: { type: String(error.params?.type ?? "") }
|
|
637
|
+
});
|
|
638
|
+
case "FILE_EMPTY":
|
|
639
|
+
return t("File is empty", { note: "file validation" });
|
|
640
|
+
case "FILE_TOO_LARGE":
|
|
641
|
+
return t("File size exceeds {size} limit", {
|
|
642
|
+
note: "file validation",
|
|
643
|
+
variables: { size: String(error.params?.size ?? "") }
|
|
644
|
+
});
|
|
645
|
+
default:
|
|
646
|
+
return error.message;
|
|
647
|
+
}
|
|
648
|
+
},
|
|
649
|
+
[t]
|
|
650
|
+
);
|
|
651
|
+
}
|
|
652
|
+
function param(params, key, fallback = "") {
|
|
653
|
+
const value = params?.[key];
|
|
654
|
+
return value === void 0 ? fallback : String(value);
|
|
655
|
+
}
|
|
656
|
+
function useFormatDimahError() {
|
|
657
|
+
const t = useTranslations();
|
|
658
|
+
return useCallback(
|
|
659
|
+
(err) => {
|
|
660
|
+
if (!(err instanceof DimahS3Error) || err.code === void 0) {
|
|
661
|
+
return err instanceof Error ? err.message : t("Unknown error", { note: "fallback" });
|
|
662
|
+
}
|
|
663
|
+
switch (err.code) {
|
|
664
|
+
case S3_ERROR_CODES.NOT_FOUND:
|
|
665
|
+
return t("Not found", { note: "API error" });
|
|
666
|
+
case S3_ERROR_CODES.INVALID_JSON:
|
|
667
|
+
return t("Invalid request", { note: "API error" });
|
|
668
|
+
case S3_ERROR_CODES.FORBIDDEN:
|
|
669
|
+
return t("Access denied", { note: "API error" });
|
|
670
|
+
case S3_ERROR_CODES.INTERNAL_ERROR:
|
|
671
|
+
return t("Something went wrong", { note: "API error" });
|
|
672
|
+
case S3_ERROR_CODES.OBJECT_NOT_FOUND:
|
|
673
|
+
return t("File not found", { note: "API error" });
|
|
674
|
+
case S3_ERROR_CODES.S3_NETWORK_ERROR:
|
|
675
|
+
return t("Could not reach storage ({code})", {
|
|
676
|
+
note: "API error",
|
|
677
|
+
variables: { code: param(err.params, "code", "UNKNOWN") }
|
|
678
|
+
});
|
|
679
|
+
case S3_ERROR_CODES.FIELD_REQUIRED:
|
|
680
|
+
return t("{name} is required", {
|
|
681
|
+
note: "API error",
|
|
682
|
+
variables: { name: param(err.params, "name") }
|
|
683
|
+
});
|
|
684
|
+
case S3_ERROR_CODES.KEY_REQUIRED:
|
|
685
|
+
return t("Object key is required", { note: "API error" });
|
|
686
|
+
case S3_ERROR_CODES.UPLOAD_ID_REQUIRED:
|
|
687
|
+
return t("Upload ID is required", { note: "API error" });
|
|
688
|
+
case S3_ERROR_CODES.PART_NUMBER_INVALID:
|
|
689
|
+
return t("Part number must be a positive integer", {
|
|
690
|
+
note: "API error"
|
|
691
|
+
});
|
|
692
|
+
case S3_ERROR_CODES.PARTS_REQUIRED:
|
|
693
|
+
return t("At least one upload part is required", {
|
|
694
|
+
note: "API error"
|
|
695
|
+
});
|
|
696
|
+
case S3_ERROR_CODES.FILE_SIZE_REQUIRED_UPLOAD:
|
|
697
|
+
return t("File size is required", { note: "upload" });
|
|
698
|
+
case S3_ERROR_CODES.FILE_SIZE_REQUIRED_MULTIPART:
|
|
699
|
+
return t("File size is required", { note: "multipart" });
|
|
700
|
+
default:
|
|
701
|
+
return err.message;
|
|
702
|
+
}
|
|
703
|
+
},
|
|
704
|
+
[t]
|
|
705
|
+
);
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
// src/helpers/speed-tracker.ts
|
|
709
|
+
function createSpeedTracker(windowMs = 3e3) {
|
|
710
|
+
const samples = [];
|
|
711
|
+
return {
|
|
712
|
+
/**
|
|
713
|
+
* Record the latest cumulative `loaded` byte count.
|
|
714
|
+
* Returns the current speed in bytes/second (0 until at least 2 samples exist).
|
|
715
|
+
*/
|
|
716
|
+
update(loaded) {
|
|
717
|
+
const now = Date.now();
|
|
718
|
+
samples.push({ t: now, loaded });
|
|
719
|
+
const cutoff = now - windowMs;
|
|
720
|
+
while (samples.length > 1 && samples[0].t < cutoff) {
|
|
721
|
+
samples.shift();
|
|
722
|
+
}
|
|
723
|
+
if (samples.length < 2) return 0;
|
|
724
|
+
const oldest = samples[0];
|
|
725
|
+
const newest = samples[samples.length - 1];
|
|
726
|
+
const deltaMs = newest.t - oldest.t;
|
|
727
|
+
const deltaBytes = newest.loaded - oldest.loaded;
|
|
728
|
+
return deltaMs > 0 ? Math.round(deltaBytes / deltaMs * 1e3) : 0;
|
|
729
|
+
},
|
|
730
|
+
reset() {
|
|
731
|
+
samples.length = 0;
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// src/helpers/throttled-speed.ts
|
|
737
|
+
function createThrottledSpeedUpdater(tracker, intervalMs = 500) {
|
|
738
|
+
let lastSpeed;
|
|
739
|
+
let lastUpdate = 0;
|
|
740
|
+
return {
|
|
741
|
+
reset() {
|
|
742
|
+
tracker.reset();
|
|
743
|
+
lastSpeed = void 0;
|
|
744
|
+
lastUpdate = 0;
|
|
745
|
+
},
|
|
746
|
+
apply(progress) {
|
|
747
|
+
const rawSpeed = tracker.update(progress.loaded);
|
|
748
|
+
const now = Date.now();
|
|
749
|
+
if (rawSpeed > 0 && now - lastUpdate >= intervalMs) {
|
|
750
|
+
lastSpeed = rawSpeed;
|
|
751
|
+
lastUpdate = now;
|
|
752
|
+
}
|
|
753
|
+
return lastSpeed ? { ...progress, speed: lastSpeed } : progress;
|
|
754
|
+
}
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
function useLiveRef(value) {
|
|
758
|
+
const ref = useRef(value);
|
|
759
|
+
useLayoutEffect(() => {
|
|
760
|
+
ref.current = value;
|
|
761
|
+
});
|
|
762
|
+
return ref;
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
// src/hooks/use-upload.ts
|
|
766
|
+
var INITIAL_PROGRESS = { loaded: 0, total: 0, percent: 0 };
|
|
767
|
+
var INITIAL_STATE = {
|
|
768
|
+
phase: "idle",
|
|
769
|
+
progress: INITIAL_PROGRESS,
|
|
770
|
+
error: null,
|
|
771
|
+
result: null,
|
|
772
|
+
fileName: null,
|
|
773
|
+
fileSize: null
|
|
774
|
+
};
|
|
775
|
+
function useUpload(options) {
|
|
776
|
+
const [state, setState] = useState(INITIAL_STATE);
|
|
777
|
+
const contextApi = useContext(S3Context);
|
|
778
|
+
const formatValidateFileError = useFormatValidateFileError();
|
|
779
|
+
const optsRef = useLiveRef(options);
|
|
780
|
+
const apiRef = useLiveRef(contextApi);
|
|
781
|
+
const abortRef = useRef(null);
|
|
782
|
+
const activeUploadRef = useRef(null);
|
|
783
|
+
const detachingRef = useRef(false);
|
|
784
|
+
const speedUpdaterRef = useRef(
|
|
785
|
+
createThrottledSpeedUpdater(createSpeedTracker())
|
|
786
|
+
);
|
|
787
|
+
const upload = useCallback(
|
|
788
|
+
async (file, objectKey, requestOptions) => {
|
|
789
|
+
setState({
|
|
790
|
+
...INITIAL_STATE,
|
|
791
|
+
phase: "validating",
|
|
792
|
+
fileName: file.name,
|
|
793
|
+
fileSize: file.size
|
|
794
|
+
});
|
|
795
|
+
const opts = optsRef.current;
|
|
796
|
+
const api = opts.api ?? apiRef.current;
|
|
797
|
+
if (!api)
|
|
798
|
+
throw new Error(
|
|
799
|
+
"[dimah-s3] No S3Api found. Pass `api` to useUpload or wrap with <S3Provider>."
|
|
800
|
+
);
|
|
801
|
+
const validationError = validateFile(file, {
|
|
802
|
+
accept: opts.accept,
|
|
803
|
+
maxFileSize: opts.maxFileSize
|
|
804
|
+
});
|
|
805
|
+
if (validationError) {
|
|
806
|
+
const message = formatValidateFileError(validationError);
|
|
807
|
+
setState((s) => ({ ...s, phase: "error", error: message }));
|
|
808
|
+
opts.onError?.(file, new Error(message), "validating");
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
if (opts.beforeUpload) {
|
|
812
|
+
const allowed = await opts.beforeUpload(file);
|
|
813
|
+
if (!allowed) {
|
|
814
|
+
setState((s) => ({
|
|
815
|
+
...s,
|
|
816
|
+
phase: "error",
|
|
817
|
+
error: "Upload blocked by beforeUpload hook"
|
|
818
|
+
}));
|
|
819
|
+
opts.onError?.(file, new Error("blocked"), "validating");
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
speedUpdaterRef.current.reset();
|
|
824
|
+
setState((s) => ({ ...s, phase: "presigning" }));
|
|
825
|
+
opts.onUploadStart?.(file, objectKey);
|
|
826
|
+
const controller = new AbortController();
|
|
827
|
+
abortRef.current = controller;
|
|
828
|
+
activeUploadRef.current = {
|
|
829
|
+
file,
|
|
830
|
+
objectKey,
|
|
831
|
+
serverKey: objectKey,
|
|
832
|
+
bucket: requestOptions?.bucket,
|
|
833
|
+
requestOptions
|
|
834
|
+
};
|
|
835
|
+
try {
|
|
836
|
+
const result = await uploadFile(
|
|
837
|
+
api,
|
|
838
|
+
file,
|
|
839
|
+
objectKey,
|
|
840
|
+
{
|
|
841
|
+
multipart: opts.multipart,
|
|
842
|
+
multipartThreshold: opts.multipartThreshold,
|
|
843
|
+
concurrentParts: opts.concurrentParts,
|
|
844
|
+
partSize: opts.partSize,
|
|
845
|
+
retry: opts.retry,
|
|
846
|
+
uploadStore: opts.uploadStore
|
|
847
|
+
},
|
|
848
|
+
{
|
|
849
|
+
onProgress: (progress) => {
|
|
850
|
+
const p = speedUpdaterRef.current.apply(progress);
|
|
851
|
+
setState((s) => ({ ...s, progress: p }));
|
|
852
|
+
opts.onProgress?.(file, p);
|
|
853
|
+
},
|
|
854
|
+
onPhaseChange: (phase) => setState((s) => ({ ...s, phase })),
|
|
855
|
+
onPartUpload: (partNumber, totalParts) => opts.onPartUpload?.(file, partNumber, totalParts),
|
|
856
|
+
onMultipartInit: (uploadId, serverKey) => {
|
|
857
|
+
if (activeUploadRef.current) {
|
|
858
|
+
activeUploadRef.current.uploadId = uploadId;
|
|
859
|
+
activeUploadRef.current.serverKey = serverKey;
|
|
860
|
+
}
|
|
861
|
+
opts.onMultipartInit?.(file, uploadId);
|
|
862
|
+
}
|
|
863
|
+
},
|
|
864
|
+
controller.signal,
|
|
865
|
+
requestOptions
|
|
866
|
+
);
|
|
867
|
+
setState((s) => ({
|
|
868
|
+
...s,
|
|
869
|
+
phase: "success",
|
|
870
|
+
result,
|
|
871
|
+
progress: { loaded: file.size, total: file.size, percent: 100 }
|
|
872
|
+
}));
|
|
873
|
+
await opts.onSuccess?.(file, result);
|
|
874
|
+
} catch (err) {
|
|
875
|
+
if (err.name === "AbortError") {
|
|
876
|
+
if (detachingRef.current) {
|
|
877
|
+
detachingRef.current = false;
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
opts.onCancel?.(file);
|
|
881
|
+
setState(INITIAL_STATE);
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
const message = err instanceof Error ? err.message : "Upload failed";
|
|
885
|
+
setState((s) => ({ ...s, phase: "error", error: message }));
|
|
886
|
+
opts.onError?.(file, err, "uploading");
|
|
887
|
+
} finally {
|
|
888
|
+
abortRef.current = null;
|
|
889
|
+
activeUploadRef.current = null;
|
|
890
|
+
}
|
|
891
|
+
},
|
|
892
|
+
[apiRef, optsRef, formatValidateFileError]
|
|
893
|
+
);
|
|
894
|
+
const cancel = useCallback(() => {
|
|
895
|
+
const opts = optsRef.current;
|
|
896
|
+
const api = opts.api ?? apiRef.current;
|
|
897
|
+
const active = activeUploadRef.current;
|
|
898
|
+
abortRef.current?.abort();
|
|
899
|
+
if (active && api) {
|
|
900
|
+
const { objectKey, serverKey, uploadId, bucket } = active;
|
|
901
|
+
const store = opts.uploadStore;
|
|
902
|
+
if (store != null && store !== false) {
|
|
903
|
+
void Promise.resolve(store.delete(objectKey)).catch(() => {
|
|
904
|
+
});
|
|
905
|
+
}
|
|
906
|
+
if (uploadId) {
|
|
907
|
+
api.multipart.abort({ key: serverKey, uploadId, bucket }).catch(() => {
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
setState(INITIAL_STATE);
|
|
912
|
+
}, [apiRef, optsRef]);
|
|
913
|
+
const detach = useCallback(() => {
|
|
914
|
+
const active = activeUploadRef.current;
|
|
915
|
+
if (!active) return;
|
|
916
|
+
detachingRef.current = true;
|
|
917
|
+
abortRef.current?.abort();
|
|
918
|
+
setState(INITIAL_STATE);
|
|
919
|
+
}, []);
|
|
920
|
+
const reset = useCallback(() => {
|
|
921
|
+
abortRef.current?.abort();
|
|
922
|
+
setState(INITIAL_STATE);
|
|
923
|
+
}, []);
|
|
924
|
+
return { ...state, upload, cancel, detach, reset };
|
|
925
|
+
}
|
|
926
|
+
var INITIAL_PROGRESS2 = { loaded: 0, total: 0, percent: 0 };
|
|
927
|
+
var INITIAL_STATE2 = {
|
|
928
|
+
phase: "idle",
|
|
929
|
+
files: [],
|
|
930
|
+
totalProgress: INITIAL_PROGRESS2,
|
|
931
|
+
error: null
|
|
932
|
+
};
|
|
933
|
+
function generateId() {
|
|
934
|
+
return crypto.randomUUID();
|
|
935
|
+
}
|
|
936
|
+
function useMultiUpload(options) {
|
|
937
|
+
const [state, setState] = useState(INITIAL_STATE2);
|
|
938
|
+
const contextApi = useContext(S3Context);
|
|
939
|
+
const formatValidateFileError = useFormatValidateFileError();
|
|
940
|
+
const optsRef = useLiveRef(options);
|
|
941
|
+
const apiRef = useLiveRef(contextApi);
|
|
942
|
+
const abortRef = useRef(null);
|
|
943
|
+
const resettingRef = useRef(false);
|
|
944
|
+
const detachingRef = useRef(false);
|
|
945
|
+
const fileMapRef = useRef(/* @__PURE__ */ new Map());
|
|
946
|
+
const activeUploadsRef = useRef(/* @__PURE__ */ new Map());
|
|
947
|
+
const fileSpeedUpdatersRef = useRef(/* @__PURE__ */ new Map());
|
|
948
|
+
const totalSpeedUpdaterRef = useRef(
|
|
949
|
+
createThrottledSpeedUpdater(createSpeedTracker(), 1e3)
|
|
950
|
+
);
|
|
951
|
+
const upload = useCallback(
|
|
952
|
+
async (files, resolveKey) => {
|
|
953
|
+
const opts = optsRef.current;
|
|
954
|
+
const api = opts.api ?? apiRef.current;
|
|
955
|
+
if (!api)
|
|
956
|
+
throw new Error(
|
|
957
|
+
"[dimah-s3] No S3Api found. Pass `api` to useMultiUpload or wrap with <S3Provider>."
|
|
958
|
+
);
|
|
959
|
+
const items = [];
|
|
960
|
+
const fileStates = [];
|
|
961
|
+
const fileMap = /* @__PURE__ */ new Map();
|
|
962
|
+
setState((s) => ({ ...s, phase: "validating", error: null }));
|
|
963
|
+
if (opts.maxFiles && files.length > opts.maxFiles) {
|
|
964
|
+
const msg = `Too many files. Maximum is ${opts.maxFiles}.`;
|
|
965
|
+
setState((s) => ({ ...s, phase: "error", error: msg }));
|
|
966
|
+
opts.onError?.(new Error(msg));
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
for (const file of files) {
|
|
970
|
+
const validationError = validateFile(file, {
|
|
971
|
+
accept: opts.accept,
|
|
972
|
+
maxFileSize: opts.maxFileSize
|
|
973
|
+
});
|
|
974
|
+
if (validationError) {
|
|
975
|
+
const detail = formatValidateFileError(validationError);
|
|
976
|
+
const msg = `${file.name}: ${detail}`;
|
|
977
|
+
setState((s) => ({ ...s, phase: "error", error: msg }));
|
|
978
|
+
opts.onError?.(new Error(msg));
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
if (opts.beforeUpload) {
|
|
983
|
+
const allowed = await opts.beforeUpload(files);
|
|
984
|
+
if (!allowed) {
|
|
985
|
+
setState((s) => ({
|
|
986
|
+
...s,
|
|
987
|
+
phase: "error",
|
|
988
|
+
error: "Upload blocked by beforeUpload hook"
|
|
989
|
+
}));
|
|
990
|
+
opts.onError?.(new Error("blocked"));
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
for (const file of files) {
|
|
995
|
+
const id = generateId();
|
|
996
|
+
const objectKey = resolveKey(file);
|
|
997
|
+
items.push({ id, file, objectKey });
|
|
998
|
+
fileMap.set(id, file);
|
|
999
|
+
fileStates.push({
|
|
1000
|
+
id,
|
|
1001
|
+
fileName: file.name,
|
|
1002
|
+
fileSize: file.size,
|
|
1003
|
+
status: "pending",
|
|
1004
|
+
progress: { loaded: 0, total: file.size, percent: 0 },
|
|
1005
|
+
error: null
|
|
1006
|
+
});
|
|
1007
|
+
}
|
|
1008
|
+
fileMapRef.current = fileMap;
|
|
1009
|
+
activeUploadsRef.current = new Map(
|
|
1010
|
+
items.map((item) => [
|
|
1011
|
+
item.id,
|
|
1012
|
+
{
|
|
1013
|
+
objectKey: item.objectKey,
|
|
1014
|
+
serverKey: item.objectKey,
|
|
1015
|
+
bucket: opts.getUploadOptions?.(item.file)?.bucket ?? opts.uploadOptions?.bucket
|
|
1016
|
+
}
|
|
1017
|
+
])
|
|
1018
|
+
);
|
|
1019
|
+
setState({
|
|
1020
|
+
phase: "uploading",
|
|
1021
|
+
files: fileStates,
|
|
1022
|
+
totalProgress: {
|
|
1023
|
+
loaded: 0,
|
|
1024
|
+
total: files.reduce((s, f) => s + f.size, 0),
|
|
1025
|
+
percent: 0
|
|
1026
|
+
},
|
|
1027
|
+
error: null
|
|
1028
|
+
});
|
|
1029
|
+
opts.onUploadStart?.(files);
|
|
1030
|
+
fileSpeedUpdatersRef.current.clear();
|
|
1031
|
+
for (const item of items) {
|
|
1032
|
+
fileSpeedUpdatersRef.current.set(
|
|
1033
|
+
item.id,
|
|
1034
|
+
createThrottledSpeedUpdater(createSpeedTracker())
|
|
1035
|
+
);
|
|
1036
|
+
}
|
|
1037
|
+
totalSpeedUpdaterRef.current.reset();
|
|
1038
|
+
const controller = new AbortController();
|
|
1039
|
+
abortRef.current = controller;
|
|
1040
|
+
try {
|
|
1041
|
+
const results = await uploadFiles(
|
|
1042
|
+
api,
|
|
1043
|
+
items,
|
|
1044
|
+
{
|
|
1045
|
+
multipart: opts.multipart,
|
|
1046
|
+
multipartThreshold: opts.multipartThreshold,
|
|
1047
|
+
concurrentParts: opts.concurrentParts,
|
|
1048
|
+
concurrentFiles: opts.concurrentFiles,
|
|
1049
|
+
partSize: opts.partSize,
|
|
1050
|
+
retry: opts.retry,
|
|
1051
|
+
uploadStore: opts.uploadStore
|
|
1052
|
+
},
|
|
1053
|
+
{
|
|
1054
|
+
onFileProgress: (id, progress) => {
|
|
1055
|
+
const updater = fileSpeedUpdatersRef.current.get(id);
|
|
1056
|
+
const p = updater ? updater.apply(progress) : progress;
|
|
1057
|
+
setState((s) => ({
|
|
1058
|
+
...s,
|
|
1059
|
+
files: s.files.map(
|
|
1060
|
+
(f) => f.id === id ? { ...f, status: "uploading", progress: p } : f
|
|
1061
|
+
)
|
|
1062
|
+
}));
|
|
1063
|
+
const file = fileMap.get(id);
|
|
1064
|
+
if (file) opts.onFileProgress?.(file, p);
|
|
1065
|
+
},
|
|
1066
|
+
onFileSuccess: (id, result) => {
|
|
1067
|
+
activeUploadsRef.current.delete(id);
|
|
1068
|
+
setState((s) => ({
|
|
1069
|
+
...s,
|
|
1070
|
+
files: s.files.map(
|
|
1071
|
+
(f) => f.id === id ? {
|
|
1072
|
+
...f,
|
|
1073
|
+
status: "success",
|
|
1074
|
+
progress: {
|
|
1075
|
+
loaded: f.fileSize,
|
|
1076
|
+
total: f.fileSize,
|
|
1077
|
+
percent: 100
|
|
1078
|
+
}
|
|
1079
|
+
} : f
|
|
1080
|
+
)
|
|
1081
|
+
}));
|
|
1082
|
+
const file = fileMap.get(id);
|
|
1083
|
+
if (file) opts.onFileSuccess?.(file, result);
|
|
1084
|
+
},
|
|
1085
|
+
onFileError: (id, error) => {
|
|
1086
|
+
setState((s) => ({
|
|
1087
|
+
...s,
|
|
1088
|
+
files: s.files.map(
|
|
1089
|
+
(f) => f.id === id ? { ...f, status: "error", error } : f
|
|
1090
|
+
)
|
|
1091
|
+
}));
|
|
1092
|
+
const file = fileMap.get(id);
|
|
1093
|
+
if (file) opts.onFileError?.(file, error);
|
|
1094
|
+
},
|
|
1095
|
+
onTotalProgress: (progress) => {
|
|
1096
|
+
const p = totalSpeedUpdaterRef.current.apply(progress);
|
|
1097
|
+
setState((s) => ({ ...s, totalProgress: p }));
|
|
1098
|
+
opts.onProgress?.(p);
|
|
1099
|
+
},
|
|
1100
|
+
onMultipartInit: (id, uploadId, serverKey) => {
|
|
1101
|
+
const active = activeUploadsRef.current.get(id);
|
|
1102
|
+
if (active) {
|
|
1103
|
+
active.uploadId = uploadId;
|
|
1104
|
+
active.serverKey = serverKey;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
},
|
|
1108
|
+
controller.signal,
|
|
1109
|
+
(file) => {
|
|
1110
|
+
const perFile = opts.getUploadOptions?.(file);
|
|
1111
|
+
if (!opts.uploadOptions) return perFile ?? {};
|
|
1112
|
+
return { ...opts.uploadOptions, ...perFile };
|
|
1113
|
+
}
|
|
1114
|
+
);
|
|
1115
|
+
const hasErrors = results.some((r) => r.status === "error");
|
|
1116
|
+
const successResults = results.filter((r) => r.result !== null).map((r) => r.result);
|
|
1117
|
+
setState((s) => ({
|
|
1118
|
+
...s,
|
|
1119
|
+
phase: hasErrors ? "error" : "success",
|
|
1120
|
+
error: hasErrors ? `${results.filter((r) => r.status === "error").length} file(s) failed` : null,
|
|
1121
|
+
totalProgress: hasErrors ? s.totalProgress : {
|
|
1122
|
+
loaded: s.totalProgress.total,
|
|
1123
|
+
total: s.totalProgress.total,
|
|
1124
|
+
percent: 100
|
|
1125
|
+
}
|
|
1126
|
+
}));
|
|
1127
|
+
if (!hasErrors) {
|
|
1128
|
+
await opts.onSuccess?.(successResults);
|
|
1129
|
+
}
|
|
1130
|
+
} catch (err) {
|
|
1131
|
+
if (err.name === "AbortError") {
|
|
1132
|
+
if (detachingRef.current) {
|
|
1133
|
+
detachingRef.current = false;
|
|
1134
|
+
return;
|
|
1135
|
+
}
|
|
1136
|
+
if (!resettingRef.current) opts.onCancel?.();
|
|
1137
|
+
resettingRef.current = false;
|
|
1138
|
+
setState(INITIAL_STATE2);
|
|
1139
|
+
return;
|
|
1140
|
+
}
|
|
1141
|
+
const message = err instanceof Error ? err.message : "Upload failed";
|
|
1142
|
+
setState((s) => ({ ...s, phase: "error", error: message }));
|
|
1143
|
+
opts.onError?.(err);
|
|
1144
|
+
} finally {
|
|
1145
|
+
abortRef.current = null;
|
|
1146
|
+
activeUploadsRef.current.clear();
|
|
1147
|
+
}
|
|
1148
|
+
},
|
|
1149
|
+
[apiRef, optsRef, formatValidateFileError]
|
|
1150
|
+
);
|
|
1151
|
+
const cancel = useCallback(() => {
|
|
1152
|
+
const opts = optsRef.current;
|
|
1153
|
+
const api = opts.api ?? apiRef.current;
|
|
1154
|
+
abortRef.current?.abort();
|
|
1155
|
+
if (api) {
|
|
1156
|
+
const store = opts.uploadStore;
|
|
1157
|
+
for (const active of activeUploadsRef.current.values()) {
|
|
1158
|
+
if (store != null && store !== false) {
|
|
1159
|
+
void Promise.resolve(store.delete(active.objectKey)).catch(() => {
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
if (active.uploadId) {
|
|
1163
|
+
api.multipart.abort({
|
|
1164
|
+
key: active.serverKey,
|
|
1165
|
+
uploadId: active.uploadId,
|
|
1166
|
+
bucket: active.bucket
|
|
1167
|
+
}).catch(() => {
|
|
1168
|
+
});
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
activeUploadsRef.current.clear();
|
|
1173
|
+
setState(INITIAL_STATE2);
|
|
1174
|
+
}, [apiRef, optsRef]);
|
|
1175
|
+
const detach = useCallback(() => {
|
|
1176
|
+
if (activeUploadsRef.current.size === 0) return;
|
|
1177
|
+
detachingRef.current = true;
|
|
1178
|
+
abortRef.current?.abort();
|
|
1179
|
+
setState(INITIAL_STATE2);
|
|
1180
|
+
}, []);
|
|
1181
|
+
const reset = useCallback(() => {
|
|
1182
|
+
resettingRef.current = true;
|
|
1183
|
+
abortRef.current?.abort();
|
|
1184
|
+
setState(INITIAL_STATE2);
|
|
1185
|
+
}, []);
|
|
1186
|
+
return { ...state, upload, cancel, detach, reset };
|
|
1187
|
+
}
|
|
1188
|
+
function useUploadControls(options) {
|
|
1189
|
+
const single = useUpload(options);
|
|
1190
|
+
const inputRef = useRef(null);
|
|
1191
|
+
const [fileInfo, setFileInfo] = useState(null);
|
|
1192
|
+
const resolveKey = (file) => typeof options.objectKey === "function" ? options.objectKey(file) : options.objectKey;
|
|
1193
|
+
const handleFiles = async (files) => {
|
|
1194
|
+
const file = files?.[0];
|
|
1195
|
+
if (!file) return;
|
|
1196
|
+
setFileInfo({ name: file.name, size: file.size });
|
|
1197
|
+
await single.upload(file, resolveKey(file), {
|
|
1198
|
+
...options.uploadOptions,
|
|
1199
|
+
...options.getUploadOptions?.(file)
|
|
1200
|
+
});
|
|
1201
|
+
};
|
|
1202
|
+
return {
|
|
1203
|
+
phase: single.phase,
|
|
1204
|
+
fileInfo,
|
|
1205
|
+
progress: single.progress,
|
|
1206
|
+
error: single.error,
|
|
1207
|
+
isUploading: single.phase === "uploading",
|
|
1208
|
+
handleFiles,
|
|
1209
|
+
openFilePicker: () => inputRef.current?.click(),
|
|
1210
|
+
cancel: single.cancel,
|
|
1211
|
+
detach: single.detach,
|
|
1212
|
+
reset: () => {
|
|
1213
|
+
single.reset();
|
|
1214
|
+
setFileInfo(null);
|
|
1215
|
+
},
|
|
1216
|
+
inputProps: {
|
|
1217
|
+
ref: inputRef,
|
|
1218
|
+
type: "file",
|
|
1219
|
+
accept: options.accept?.join(","),
|
|
1220
|
+
hidden: true,
|
|
1221
|
+
onChange: (e) => {
|
|
1222
|
+
handleFiles(e.target.files);
|
|
1223
|
+
e.target.value = "";
|
|
1224
|
+
}
|
|
1225
|
+
},
|
|
1226
|
+
dropHandlers: {
|
|
1227
|
+
onDragOver: (e) => {
|
|
1228
|
+
e.preventDefault();
|
|
1229
|
+
e.stopPropagation();
|
|
1230
|
+
},
|
|
1231
|
+
onDrop: (e) => {
|
|
1232
|
+
e.preventDefault();
|
|
1233
|
+
e.stopPropagation();
|
|
1234
|
+
if (single.phase !== "uploading") handleFiles(e.dataTransfer.files);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
};
|
|
1238
|
+
}
|
|
1239
|
+
function useMultiUploadControls(options) {
|
|
1240
|
+
const multi = useMultiUpload(options);
|
|
1241
|
+
const inputRef = useRef(null);
|
|
1242
|
+
const resolveKey = (file) => typeof options.objectKey === "function" ? options.objectKey(file) : options.objectKey;
|
|
1243
|
+
const handleFiles = async (files) => {
|
|
1244
|
+
if (!files?.length) return;
|
|
1245
|
+
await multi.upload(Array.from(files), resolveKey);
|
|
1246
|
+
};
|
|
1247
|
+
return {
|
|
1248
|
+
phase: multi.phase,
|
|
1249
|
+
files: multi.files,
|
|
1250
|
+
totalProgress: multi.totalProgress,
|
|
1251
|
+
error: multi.error,
|
|
1252
|
+
isUploading: multi.phase === "uploading",
|
|
1253
|
+
handleFiles,
|
|
1254
|
+
openFilePicker: () => inputRef.current?.click(),
|
|
1255
|
+
cancel: multi.cancel,
|
|
1256
|
+
detach: multi.detach,
|
|
1257
|
+
reset: multi.reset,
|
|
1258
|
+
inputProps: {
|
|
1259
|
+
ref: inputRef,
|
|
1260
|
+
type: "file",
|
|
1261
|
+
multiple: true,
|
|
1262
|
+
accept: options.accept?.join(","),
|
|
1263
|
+
hidden: true,
|
|
1264
|
+
onChange: (e) => {
|
|
1265
|
+
handleFiles(e.target.files);
|
|
1266
|
+
e.target.value = "";
|
|
1267
|
+
}
|
|
1268
|
+
},
|
|
1269
|
+
dropHandlers: {
|
|
1270
|
+
onDragOver: (e) => {
|
|
1271
|
+
e.preventDefault();
|
|
1272
|
+
e.stopPropagation();
|
|
1273
|
+
},
|
|
1274
|
+
onDrop: (e) => {
|
|
1275
|
+
e.preventDefault();
|
|
1276
|
+
e.stopPropagation();
|
|
1277
|
+
if (multi.phase !== "uploading") handleFiles(e.dataTransfer.files);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
}
|
|
1282
|
+
var INITIAL_STATE3 = {
|
|
1283
|
+
phase: "idle",
|
|
1284
|
+
error: null,
|
|
1285
|
+
url: null,
|
|
1286
|
+
expiresIn: null
|
|
1287
|
+
};
|
|
1288
|
+
function useDownload(options) {
|
|
1289
|
+
const [state, setState] = useState(INITIAL_STATE3);
|
|
1290
|
+
const contextApi = useContext(S3Context);
|
|
1291
|
+
const optsRef = useLiveRef(options);
|
|
1292
|
+
const apiRef = useLiveRef(contextApi);
|
|
1293
|
+
const presign = useCallback(
|
|
1294
|
+
async (key, downloadName) => {
|
|
1295
|
+
const opts = optsRef.current;
|
|
1296
|
+
const api = opts.api ?? apiRef.current;
|
|
1297
|
+
if (!api)
|
|
1298
|
+
throw new Error(
|
|
1299
|
+
"[dimah-s3] No S3Api found. Pass `api` to useDownload or wrap with <S3Provider>."
|
|
1300
|
+
);
|
|
1301
|
+
setState({
|
|
1302
|
+
phase: "presigning",
|
|
1303
|
+
error: null,
|
|
1304
|
+
url: null,
|
|
1305
|
+
expiresIn: null
|
|
1306
|
+
});
|
|
1307
|
+
try {
|
|
1308
|
+
const result = await api.download(key, {
|
|
1309
|
+
fileName: downloadName,
|
|
1310
|
+
bucket: opts.bucket
|
|
1311
|
+
});
|
|
1312
|
+
setState({
|
|
1313
|
+
phase: "idle",
|
|
1314
|
+
error: null,
|
|
1315
|
+
url: result.url,
|
|
1316
|
+
expiresIn: result.expiresIn
|
|
1317
|
+
});
|
|
1318
|
+
return { url: result.url, expiresIn: result.expiresIn };
|
|
1319
|
+
} catch (err) {
|
|
1320
|
+
const message = err instanceof Error ? err.message : "Download failed";
|
|
1321
|
+
setState({
|
|
1322
|
+
phase: "error",
|
|
1323
|
+
error: message,
|
|
1324
|
+
url: null,
|
|
1325
|
+
expiresIn: null
|
|
1326
|
+
});
|
|
1327
|
+
opts.onError?.(key, err);
|
|
1328
|
+
return null;
|
|
1329
|
+
}
|
|
1330
|
+
},
|
|
1331
|
+
[apiRef, optsRef]
|
|
1332
|
+
);
|
|
1333
|
+
const download = useCallback(
|
|
1334
|
+
async (key, downloadName) => {
|
|
1335
|
+
const opts = optsRef.current;
|
|
1336
|
+
if (opts.beforeDownload) {
|
|
1337
|
+
const allowed = await opts.beforeDownload(key);
|
|
1338
|
+
if (!allowed) {
|
|
1339
|
+
setState({
|
|
1340
|
+
phase: "error",
|
|
1341
|
+
error: "Download blocked by beforeDownload hook",
|
|
1342
|
+
url: null,
|
|
1343
|
+
expiresIn: null
|
|
1344
|
+
});
|
|
1345
|
+
opts.onError?.(key, new Error("blocked"));
|
|
1346
|
+
return;
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
const result = await presign(key, downloadName);
|
|
1350
|
+
if (!result) return;
|
|
1351
|
+
window.location.href = result.url;
|
|
1352
|
+
opts.onInitiated?.(key);
|
|
1353
|
+
},
|
|
1354
|
+
[optsRef, presign]
|
|
1355
|
+
);
|
|
1356
|
+
const reset = useCallback(() => setState(INITIAL_STATE3), []);
|
|
1357
|
+
return { ...state, download, presign, reset };
|
|
1358
|
+
}
|
|
1359
|
+
var INITIAL_PROGRESS3 = { loaded: 0, total: 0, percent: 0 };
|
|
1360
|
+
var INITIAL_STATE4 = {
|
|
1361
|
+
phase: "idle",
|
|
1362
|
+
progress: INITIAL_PROGRESS3,
|
|
1363
|
+
error: null,
|
|
1364
|
+
fileName: null,
|
|
1365
|
+
fileSize: null
|
|
1366
|
+
};
|
|
1367
|
+
function useFetchDownload(options) {
|
|
1368
|
+
const [state, setState] = useState(INITIAL_STATE4);
|
|
1369
|
+
const contextApi = useContext(S3Context);
|
|
1370
|
+
const optsRef = useLiveRef(options);
|
|
1371
|
+
const apiRef = useLiveRef(contextApi);
|
|
1372
|
+
const abortRef = useRef(null);
|
|
1373
|
+
const resettingRef = useRef(false);
|
|
1374
|
+
const speedUpdaterRef = useRef(
|
|
1375
|
+
createThrottledSpeedUpdater(createSpeedTracker())
|
|
1376
|
+
);
|
|
1377
|
+
const download = useCallback(
|
|
1378
|
+
async (key, downloadName) => {
|
|
1379
|
+
const fallback = key.split("/").pop() ?? key;
|
|
1380
|
+
const opts = optsRef.current;
|
|
1381
|
+
const api = opts.api ?? apiRef.current;
|
|
1382
|
+
if (!api)
|
|
1383
|
+
throw new Error(
|
|
1384
|
+
"[dimah-s3] No S3Api found. Pass `api` to useFetchDownload or wrap with <S3Provider>."
|
|
1385
|
+
);
|
|
1386
|
+
if (opts.beforeDownload) {
|
|
1387
|
+
const allowed = await opts.beforeDownload(key);
|
|
1388
|
+
if (!allowed) {
|
|
1389
|
+
setState((s) => ({
|
|
1390
|
+
...s,
|
|
1391
|
+
phase: "error",
|
|
1392
|
+
error: "Download blocked by beforeDownload hook"
|
|
1393
|
+
}));
|
|
1394
|
+
opts.onError?.(key, new Error("blocked"), "presigning");
|
|
1395
|
+
return;
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
setState({
|
|
1399
|
+
phase: "presigning",
|
|
1400
|
+
progress: INITIAL_PROGRESS3,
|
|
1401
|
+
error: null,
|
|
1402
|
+
fileName: downloadName ?? null,
|
|
1403
|
+
fileSize: null
|
|
1404
|
+
});
|
|
1405
|
+
try {
|
|
1406
|
+
const { url } = await api.download(key, {
|
|
1407
|
+
fileName: downloadName,
|
|
1408
|
+
bucket: opts.bucket
|
|
1409
|
+
});
|
|
1410
|
+
setState((s) => ({ ...s, phase: "downloading" }));
|
|
1411
|
+
opts.onDownloadStart?.(key);
|
|
1412
|
+
speedUpdaterRef.current.reset();
|
|
1413
|
+
const controller = new AbortController();
|
|
1414
|
+
abortRef.current = controller;
|
|
1415
|
+
const res = await fetch(url, { signal: controller.signal });
|
|
1416
|
+
if (!res.ok) {
|
|
1417
|
+
throw new Error(
|
|
1418
|
+
res.status === 404 ? "File not found" : `Download failed (${res.status})`
|
|
1419
|
+
);
|
|
1420
|
+
}
|
|
1421
|
+
const contentLength = Number(res.headers.get("content-length") || 0);
|
|
1422
|
+
const name = downloadName ?? parseFileName(res.headers.get("content-disposition")) ?? fallback;
|
|
1423
|
+
setState((s) => ({
|
|
1424
|
+
...s,
|
|
1425
|
+
fileName: name,
|
|
1426
|
+
fileSize: contentLength || null
|
|
1427
|
+
}));
|
|
1428
|
+
const reader = res.body?.getReader();
|
|
1429
|
+
if (!reader) throw new Error("ReadableStream not supported");
|
|
1430
|
+
const chunks = [];
|
|
1431
|
+
let loaded = 0;
|
|
1432
|
+
while (true) {
|
|
1433
|
+
const { done, value } = await reader.read();
|
|
1434
|
+
if (done) break;
|
|
1435
|
+
chunks.push(value);
|
|
1436
|
+
loaded += value.byteLength;
|
|
1437
|
+
const percent = contentLength > 0 ? Math.round(loaded / contentLength * 100) : 0;
|
|
1438
|
+
const progress = speedUpdaterRef.current.apply({
|
|
1439
|
+
loaded,
|
|
1440
|
+
total: contentLength,
|
|
1441
|
+
percent
|
|
1442
|
+
});
|
|
1443
|
+
setState((s) => ({ ...s, progress }));
|
|
1444
|
+
opts.onProgress?.(key, progress);
|
|
1445
|
+
}
|
|
1446
|
+
const blob = new Blob(chunks);
|
|
1447
|
+
const blobUrl = URL.createObjectURL(blob);
|
|
1448
|
+
const anchor = document.createElement("a");
|
|
1449
|
+
anchor.href = blobUrl;
|
|
1450
|
+
anchor.download = name ?? fallback;
|
|
1451
|
+
anchor.click();
|
|
1452
|
+
URL.revokeObjectURL(blobUrl);
|
|
1453
|
+
setState((s) => ({
|
|
1454
|
+
...s,
|
|
1455
|
+
phase: "success",
|
|
1456
|
+
fileSize: blob.size,
|
|
1457
|
+
progress: { loaded: blob.size, total: blob.size, percent: 100 }
|
|
1458
|
+
}));
|
|
1459
|
+
await opts.onSuccess?.(key, name ?? fallback);
|
|
1460
|
+
} catch (err) {
|
|
1461
|
+
if (err.name === "AbortError") {
|
|
1462
|
+
if (!resettingRef.current) opts.onCancel?.(key);
|
|
1463
|
+
resettingRef.current = false;
|
|
1464
|
+
setState(INITIAL_STATE4);
|
|
1465
|
+
return;
|
|
1466
|
+
}
|
|
1467
|
+
const message = err instanceof Error ? err.message : "Download failed";
|
|
1468
|
+
setState((s) => ({ ...s, phase: "error", error: message }));
|
|
1469
|
+
opts.onError?.(key, err, "downloading");
|
|
1470
|
+
} finally {
|
|
1471
|
+
abortRef.current = null;
|
|
1472
|
+
}
|
|
1473
|
+
},
|
|
1474
|
+
[apiRef, optsRef]
|
|
1475
|
+
);
|
|
1476
|
+
const cancel = useCallback(() => {
|
|
1477
|
+
abortRef.current?.abort();
|
|
1478
|
+
setState(INITIAL_STATE4);
|
|
1479
|
+
}, []);
|
|
1480
|
+
const reset = useCallback(() => {
|
|
1481
|
+
resettingRef.current = true;
|
|
1482
|
+
abortRef.current?.abort();
|
|
1483
|
+
setState(INITIAL_STATE4);
|
|
1484
|
+
}, []);
|
|
1485
|
+
return { ...state, download, cancel, reset };
|
|
1486
|
+
}
|
|
1487
|
+
var INITIAL_STATE5 = {
|
|
1488
|
+
phase: "idle",
|
|
1489
|
+
error: null,
|
|
1490
|
+
pendingKey: null
|
|
1491
|
+
};
|
|
1492
|
+
function useDelete(options) {
|
|
1493
|
+
const [state, setState] = useState(INITIAL_STATE5);
|
|
1494
|
+
const contextApi = useContext(S3Context);
|
|
1495
|
+
const optsRef = useLiveRef(options);
|
|
1496
|
+
const apiRef = useLiveRef(contextApi);
|
|
1497
|
+
const pendingKeyRef = useRef(null);
|
|
1498
|
+
const requestDelete = useCallback((key) => {
|
|
1499
|
+
pendingKeyRef.current = key;
|
|
1500
|
+
setState({ phase: "confirming", error: null, pendingKey: key });
|
|
1501
|
+
}, []);
|
|
1502
|
+
const confirmDelete = useCallback(async () => {
|
|
1503
|
+
const key = pendingKeyRef.current;
|
|
1504
|
+
if (!key) return;
|
|
1505
|
+
const opts = optsRef.current;
|
|
1506
|
+
const api = opts.api ?? apiRef.current;
|
|
1507
|
+
if (!api)
|
|
1508
|
+
throw new Error(
|
|
1509
|
+
"[dimah-s3] No S3Api found. Pass `api` to useDelete or wrap with <S3Provider>."
|
|
1510
|
+
);
|
|
1511
|
+
if (opts.beforeDelete) {
|
|
1512
|
+
const allowed = await opts.beforeDelete(key);
|
|
1513
|
+
if (!allowed) {
|
|
1514
|
+
setState({
|
|
1515
|
+
phase: "error",
|
|
1516
|
+
error: "Delete blocked by beforeDelete hook",
|
|
1517
|
+
pendingKey: null
|
|
1518
|
+
});
|
|
1519
|
+
opts.onError?.(key, new Error("blocked"), "confirming");
|
|
1520
|
+
pendingKeyRef.current = null;
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
setState((s) => ({ ...s, phase: "deleting", error: null }));
|
|
1525
|
+
opts.onDeleteStart?.(key);
|
|
1526
|
+
try {
|
|
1527
|
+
await api.delete(key, { bucket: opts.bucket });
|
|
1528
|
+
pendingKeyRef.current = null;
|
|
1529
|
+
setState({ phase: "success", error: null, pendingKey: null });
|
|
1530
|
+
await opts.onSuccess?.(key);
|
|
1531
|
+
} catch (err) {
|
|
1532
|
+
const message = err instanceof Error ? err.message : "Delete failed";
|
|
1533
|
+
setState((s) => ({ ...s, phase: "error", error: message }));
|
|
1534
|
+
opts.onError?.(key, err, "deleting");
|
|
1535
|
+
}
|
|
1536
|
+
}, [apiRef, optsRef]);
|
|
1537
|
+
const cancelDelete = useCallback(() => {
|
|
1538
|
+
pendingKeyRef.current = null;
|
|
1539
|
+
setState(INITIAL_STATE5);
|
|
1540
|
+
}, []);
|
|
1541
|
+
const reset = useCallback(() => {
|
|
1542
|
+
pendingKeyRef.current = null;
|
|
1543
|
+
setState(INITIAL_STATE5);
|
|
1544
|
+
}, []);
|
|
1545
|
+
return {
|
|
1546
|
+
phase: state.phase,
|
|
1547
|
+
error: state.error,
|
|
1548
|
+
pendingKey: state.pendingKey,
|
|
1549
|
+
requestDelete,
|
|
1550
|
+
confirmDelete,
|
|
1551
|
+
cancelDelete,
|
|
1552
|
+
reset
|
|
1553
|
+
};
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
export { S3Context, S3Provider, S3UploadError, createLocalStorageStore, createMemoryStore, createS3Client, createSpeedTracker, defineApi, formatAcceptLabels, formatEta, formatSpeed, formatUploadProgress, toUploadError, uploadFile, uploadFiles, useApi, useDelete, useDownload, useFetchDownload, useFormatDimahError, useFormatValidateFileError, useMultiUpload, useMultiUploadControls, useUpload, useUploadControls };
|
|
1557
|
+
//# sourceMappingURL=index.js.map
|
|
1558
|
+
//# sourceMappingURL=index.js.map
|