@dimah-s3/react 1.7.0 → 2.0.0-beta.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 (148) hide show
  1. package/README.md +53 -13
  2. package/dist/api.d.ts +24 -15
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/chunk-SPUUNLXI.js +824 -0
  5. package/dist/chunk-SPUUNLXI.js.map +1 -0
  6. package/dist/create-s3-client.d.ts +1 -1
  7. package/dist/create-s3-client.d.ts.map +1 -1
  8. package/dist/engine.d.ts +15 -1
  9. package/dist/engine.d.ts.map +1 -1
  10. package/dist/engine.js +204 -512
  11. package/dist/engine.js.map +1 -1
  12. package/dist/helpers/format-accept-labels.d.ts +15 -2
  13. package/dist/helpers/format-accept-labels.d.ts.map +1 -1
  14. package/dist/helpers/format-date.d.ts +7 -0
  15. package/dist/helpers/format-date.d.ts.map +1 -0
  16. package/dist/helpers/format-dimah-error.d.ts +12 -2
  17. package/dist/helpers/format-dimah-error.d.ts.map +1 -1
  18. package/dist/helpers/format-file-size.d.ts +20 -0
  19. package/dist/helpers/format-file-size.d.ts.map +1 -0
  20. package/dist/helpers/format-speed.d.ts +1 -1
  21. package/dist/helpers/format-speed.d.ts.map +1 -1
  22. package/dist/helpers/format-upload-progress.d.ts +1 -1
  23. package/dist/helpers/format-upload-progress.d.ts.map +1 -1
  24. package/dist/helpers/index.d.ts +5 -8
  25. package/dist/helpers/index.d.ts.map +1 -1
  26. package/dist/helpers/load-route-catalog.d.ts +32 -8
  27. package/dist/helpers/load-route-catalog.d.ts.map +1 -1
  28. package/dist/helpers/throttled-speed.d.ts +2 -2
  29. package/dist/helpers/throttled-speed.d.ts.map +1 -1
  30. package/dist/helpers/to-timestamp.d.ts +5 -0
  31. package/dist/helpers/to-timestamp.d.ts.map +1 -0
  32. package/dist/helpers/truncate-file-name.d.ts +8 -0
  33. package/dist/helpers/truncate-file-name.d.ts.map +1 -0
  34. package/dist/helpers/use-format-accept-labels.d.ts +12 -0
  35. package/dist/helpers/use-format-accept-labels.d.ts.map +1 -0
  36. package/dist/helpers/use-format-eta.d.ts +14 -0
  37. package/dist/helpers/use-format-eta.d.ts.map +1 -0
  38. package/dist/helpers/use-format-speed.d.ts +12 -0
  39. package/dist/helpers/use-format-speed.d.ts.map +1 -0
  40. package/dist/hooks/use-delete.d.ts +6 -44
  41. package/dist/hooks/use-delete.d.ts.map +1 -1
  42. package/dist/hooks/use-download.d.ts +7 -117
  43. package/dist/hooks/use-download.d.ts.map +1 -1
  44. package/dist/hooks/use-fetch-download.d.ts +8 -0
  45. package/dist/hooks/use-fetch-download.d.ts.map +1 -0
  46. package/dist/hooks/use-file-intake.d.ts +43 -29
  47. package/dist/hooks/use-file-intake.d.ts.map +1 -1
  48. package/dist/hooks/use-file-upload.d.ts +38 -34
  49. package/dist/hooks/use-file-upload.d.ts.map +1 -1
  50. package/dist/hooks/use-object-list-selection.d.ts +78 -0
  51. package/dist/hooks/use-object-list-selection.d.ts.map +1 -0
  52. package/dist/hooks/use-object-list.d.ts +66 -16
  53. package/dist/hooks/use-object-list.d.ts.map +1 -1
  54. package/dist/hooks/use-object-url.d.ts +27 -10
  55. package/dist/hooks/use-object-url.d.ts.map +1 -1
  56. package/dist/hooks/use-route-upload-policy.d.ts +22 -14
  57. package/dist/hooks/use-route-upload-policy.d.ts.map +1 -1
  58. package/dist/hooks/use-upload.d.ts +72 -65
  59. package/dist/hooks/use-upload.d.ts.map +1 -1
  60. package/dist/index.d.ts +15 -19
  61. package/dist/index.d.ts.map +1 -1
  62. package/dist/index.js +2420 -2164
  63. package/dist/index.js.map +1 -1
  64. package/dist/internal/abortable.d.ts +9 -0
  65. package/dist/internal/abortable.d.ts.map +1 -0
  66. package/dist/internal/browser-download.d.ts +15 -0
  67. package/dist/internal/browser-download.d.ts.map +1 -0
  68. package/dist/internal/callbacks.d.ts +54 -0
  69. package/dist/internal/callbacks.d.ts.map +1 -0
  70. package/dist/internal/client-error.d.ts +15 -0
  71. package/dist/internal/client-error.d.ts.map +1 -0
  72. package/dist/internal/hooks.d.ts +27 -0
  73. package/dist/internal/hooks.d.ts.map +1 -0
  74. package/dist/internal/lru.d.ts +13 -0
  75. package/dist/internal/lru.d.ts.map +1 -0
  76. package/dist/internal/operations.d.ts +74 -0
  77. package/dist/internal/operations.d.ts.map +1 -0
  78. package/dist/internal/pool.d.ts +8 -0
  79. package/dist/internal/pool.d.ts.map +1 -0
  80. package/dist/list/entries.d.ts +14 -0
  81. package/dist/list/entries.d.ts.map +1 -0
  82. package/dist/list/memory-object-source.d.ts +60 -0
  83. package/dist/list/memory-object-source.d.ts.map +1 -0
  84. package/dist/list/types.d.ts +123 -11
  85. package/dist/list/types.d.ts.map +1 -1
  86. package/dist/s3-provider.d.ts +3 -2
  87. package/dist/s3-provider.d.ts.map +1 -1
  88. package/dist/store/local-storage-store.d.ts +5 -4
  89. package/dist/store/local-storage-store.d.ts.map +1 -1
  90. package/dist/store/memory-store.d.ts +3 -4
  91. package/dist/store/memory-store.d.ts.map +1 -1
  92. package/dist/translations/types.d.ts +105 -23
  93. package/dist/translations/types.d.ts.map +1 -1
  94. package/dist/types/delete.d.ts +98 -9
  95. package/dist/types/delete.d.ts.map +1 -1
  96. package/dist/types/download.d.ts +152 -23
  97. package/dist/types/download.d.ts.map +1 -1
  98. package/dist/types/index.d.ts +1 -1
  99. package/dist/types/index.d.ts.map +1 -1
  100. package/dist/types/operation.d.ts +38 -0
  101. package/dist/types/operation.d.ts.map +1 -0
  102. package/dist/types/upload-store.d.ts +30 -40
  103. package/dist/types/upload-store.d.ts.map +1 -1
  104. package/dist/types/upload.d.ts +177 -130
  105. package/dist/types/upload.d.ts.map +1 -1
  106. package/dist/upload/abort.d.ts +10 -0
  107. package/dist/upload/abort.d.ts.map +1 -0
  108. package/dist/upload/constants.d.ts +8 -3
  109. package/dist/upload/constants.d.ts.map +1 -1
  110. package/dist/upload/index.d.ts +3 -2
  111. package/dist/upload/index.d.ts.map +1 -1
  112. package/dist/upload/multipart.d.ts +14 -4
  113. package/dist/upload/multipart.d.ts.map +1 -1
  114. package/dist/upload/part-pool.d.ts +16 -0
  115. package/dist/upload/part-pool.d.ts.map +1 -0
  116. package/dist/upload/presigned-http.d.ts +5 -14
  117. package/dist/upload/presigned-http.d.ts.map +1 -1
  118. package/dist/upload/progress.d.ts +7 -0
  119. package/dist/upload/progress.d.ts.map +1 -0
  120. package/dist/upload/request.d.ts +9 -0
  121. package/dist/upload/request.d.ts.map +1 -0
  122. package/dist/upload/resume-key.d.ts +7 -3
  123. package/dist/upload/resume-key.d.ts.map +1 -1
  124. package/dist/upload/retry.d.ts +27 -2
  125. package/dist/upload/retry.d.ts.map +1 -1
  126. package/dist/upload/stored-upload.d.ts +7 -0
  127. package/dist/upload/stored-upload.d.ts.map +1 -0
  128. package/dist/upload/upload-file.d.ts +10 -11
  129. package/dist/upload/upload-file.d.ts.map +1 -1
  130. package/dist/upload/upload-part.d.ts +6 -3
  131. package/dist/upload/upload-part.d.ts.map +1 -1
  132. package/dist/upload/xhr-upload.d.ts +10 -2
  133. package/dist/upload/xhr-upload.d.ts.map +1 -1
  134. package/package.json +7 -8
  135. package/dist/helpers/format-eta.d.ts +0 -13
  136. package/dist/helpers/format-eta.d.ts.map +0 -1
  137. package/dist/helpers/format-validate-file-error.d.ts +0 -9
  138. package/dist/helpers/format-validate-file-error.d.ts.map +0 -1
  139. package/dist/hooks/index.d.ts +0 -7
  140. package/dist/hooks/index.d.ts.map +0 -1
  141. package/dist/internal-helpers.d.ts +0 -10
  142. package/dist/internal-helpers.d.ts.map +0 -1
  143. package/dist/store/use-immer-state.d.ts +0 -8
  144. package/dist/store/use-immer-state.d.ts.map +0 -1
  145. package/dist/types/error.d.ts +0 -27
  146. package/dist/types/error.d.ts.map +0 -1
  147. package/dist/upload/upload-files.d.ts +0 -26
  148. package/dist/upload/upload-files.d.ts.map +0 -1
@@ -0,0 +1,824 @@
1
+ import { isAPIError, s3Error, APIError, sha256Blob, fitFileName, isS3ErrorCode } from '@dimah-s3/core';
2
+
3
+ // src/upload/constants.ts
4
+ var DEFAULT_MULTIPART_THRESHOLD = 50 * 1024 * 1024;
5
+ var MAX_RETRIES = 3;
6
+ var RETRY_BASE_DELAY = 1e3;
7
+ var DEFAULT_CONCURRENT_PARTS = 4;
8
+ var DEFAULT_CONCURRENT_FILES = 2;
9
+ var DEFAULT_MAX_FILES = 1;
10
+ var URL_EXPIRY_MARGIN_MS = 3e4;
11
+ function isRawAPIError(error) {
12
+ return error instanceof Error && error.name === "APIError";
13
+ }
14
+ function toClientError(error) {
15
+ if (isAPIError(error)) return error;
16
+ if (isRawAPIError(error)) {
17
+ const status = error.statusCode;
18
+ const statusCode = typeof status === "number" ? status : void 0;
19
+ const body = error.body;
20
+ if (!isErrorBody(body)) {
21
+ return s3Error("UNKNOWN_ERROR", void 0, {
22
+ status: statusCode,
23
+ cause: error
24
+ });
25
+ }
26
+ const rebuilt = APIError.fromShape(
27
+ {
28
+ code: body.code,
29
+ message: body.message ?? body.code,
30
+ ...isErrorParams(body.params) ? { params: body.params } : {}
31
+ },
32
+ statusCode
33
+ );
34
+ rebuilt.cause = error;
35
+ return rebuilt;
36
+ }
37
+ return s3Error("UNKNOWN_ERROR", void 0, { cause: error });
38
+ }
39
+ function requireApi(api, hook) {
40
+ if (api) return api;
41
+ throw new Error(
42
+ `[dimah-s3] No S3Api found. Pass \`api\` to ${hook} or wrap with <S3Provider>.`
43
+ );
44
+ }
45
+ function isErrorBody(body) {
46
+ if (typeof body !== "object" || body === null) return false;
47
+ const { code, message } = body;
48
+ return typeof code === "string" && (message === void 0 || typeof message === "string");
49
+ }
50
+ function isErrorParams(params) {
51
+ return typeof params === "object" && params !== null && Object.values(params).every(
52
+ (value) => typeof value === "string" || typeof value === "number"
53
+ );
54
+ }
55
+
56
+ // src/helpers/load-route-catalog.ts
57
+ var catalogByApi = /* @__PURE__ */ new WeakMap();
58
+ function loadRouteCatalog(api) {
59
+ const cached = catalogByApi.get(api);
60
+ if (cached) return cached;
61
+ const pending = api.catalog().catch((error) => {
62
+ catalogByApi.delete(api);
63
+ throw toClientError(error);
64
+ });
65
+ catalogByApi.set(api, pending);
66
+ return pending;
67
+ }
68
+ function resolveRouteUploadPolicy(catalog, route) {
69
+ const upload = catalog?.routes[route]?.upload;
70
+ if (upload?.enabled !== true) return { multipart: false, checksum: false };
71
+ return {
72
+ ...upload.fileTypes?.length ? { accept: [...upload.fileTypes] } : {},
73
+ ...upload.maxFileSize === void 0 ? {} : { maxFileSize: upload.maxFileSize },
74
+ multipart: upload.multipart,
75
+ checksum: upload.checksum
76
+ };
77
+ }
78
+ function mergeRouteUploadPolicy(policy, options) {
79
+ const accept = narrowAccept(options.accept, policy.accept);
80
+ const maxFileSize = smaller(options.maxFileSize, policy.maxFileSize);
81
+ return {
82
+ ...accept ? { accept } : {},
83
+ ...maxFileSize === void 0 ? {} : { maxFileSize },
84
+ multipart: policy.multipart && options.multipart !== false,
85
+ checksum: policy.checksum
86
+ };
87
+ }
88
+ function smaller(a, b) {
89
+ if (a === void 0) return b;
90
+ if (b === void 0) return a;
91
+ return Math.min(a, b);
92
+ }
93
+ function narrowAccept(options, route) {
94
+ if (!options?.length) return route?.length ? [...route] : void 0;
95
+ if (!route?.length) return [...options];
96
+ const tokens = /* @__PURE__ */ new Set();
97
+ for (const option of options) {
98
+ for (const allowed of route) {
99
+ const token = narrowToken(option, allowed);
100
+ if (token !== void 0) tokens.add(token);
101
+ }
102
+ }
103
+ return tokens.size > 0 ? [...tokens] : [...route];
104
+ }
105
+ function narrowToken(option, allowed) {
106
+ const a = option.toLowerCase();
107
+ const b = allowed.toLowerCase();
108
+ if (a === b) return option;
109
+ const aIsExtension = a.startsWith(".");
110
+ const bIsExtension = b.startsWith(".");
111
+ if (aIsExtension || bIsExtension) {
112
+ return aIsExtension && !bIsExtension ? option : void 0;
113
+ }
114
+ if (b.endsWith("/*") && a.startsWith(b.slice(0, -1))) return option;
115
+ if (a.endsWith("/*") && b.startsWith(a.slice(0, -1))) return allowed;
116
+ return void 0;
117
+ }
118
+
119
+ // src/upload/abort.ts
120
+ function uploadAbortReason(kind) {
121
+ return new DOMException(kind, "AbortError");
122
+ }
123
+ function getUploadAbortKind(reason) {
124
+ if (!(reason instanceof DOMException) || reason.name !== "AbortError") {
125
+ return null;
126
+ }
127
+ const kind = reason.message;
128
+ return kind === "cancel" || kind === "detach" ? kind : null;
129
+ }
130
+
131
+ // src/upload/request.ts
132
+ function mergeUploadRequest(base, override) {
133
+ if (!base || !override) return override ?? base ?? {};
134
+ const merged = { ...base, ...override };
135
+ if (base.metadata && override.metadata) {
136
+ merged.metadata = { ...base.metadata, ...override.metadata };
137
+ }
138
+ return merged;
139
+ }
140
+ function resolveUploadRequest(input, file) {
141
+ return typeof input === "function" ? input(file) : input;
142
+ }
143
+
144
+ // src/upload/resume-key.ts
145
+ function multipartResumeKey(route, file, request = {}) {
146
+ const key = `${route}:${file.name}:${file.size}:${file.lastModified}`;
147
+ const { fileName = "", contentType = "", metadata = {} } = request;
148
+ const entries = Object.entries(metadata).toSorted(
149
+ ([a], [b]) => a < b ? -1 : a > b ? 1 : 0
150
+ );
151
+ if (!fileName && !contentType && entries.length === 0) return key;
152
+ return `${key}:${JSON.stringify([fileName, contentType, entries])}`;
153
+ }
154
+ async function runBeforeCallback(name, callback, ...args) {
155
+ if (!callback) return { status: "allowed" };
156
+ try {
157
+ const allowed = await callback(...args);
158
+ return allowed ? { status: "allowed" } : { status: "blocked" };
159
+ } catch (error) {
160
+ return { status: "error", error: hookFailed(name, error) };
161
+ }
162
+ }
163
+ function runStartCallback(name, callback, ...args) {
164
+ try {
165
+ callback?.(...args);
166
+ return null;
167
+ } catch (error) {
168
+ return hookFailed(name, error);
169
+ }
170
+ }
171
+ async function runAfterCallback(callback, ...args) {
172
+ if (!callback) return;
173
+ try {
174
+ await callback(...args);
175
+ } catch (error) {
176
+ reportCallbackError(error);
177
+ }
178
+ }
179
+ async function reportOperationOutcome({ onError, onSuccess, onSettled }, outcome) {
180
+ if (outcome.status === "error") {
181
+ await runAfterCallback(onError, outcome.error, outcome.key);
182
+ } else if (outcome.status === "success") {
183
+ await runAfterCallback(onSuccess, outcome.data, outcome.key);
184
+ }
185
+ await runAfterCallback(onSettled, outcome);
186
+ }
187
+ function notify(callback, ...args) {
188
+ try {
189
+ callback?.(...args);
190
+ } catch (error) {
191
+ reportCallbackError(error);
192
+ }
193
+ }
194
+ function reportCallbackError(error) {
195
+ if (typeof globalThis.reportError === "function") {
196
+ globalThis.reportError(error);
197
+ } else {
198
+ console.error(error);
199
+ }
200
+ }
201
+ function hookFailed(hook, cause) {
202
+ return s3Error("HOOK_FAILED", { hook }, { cause });
203
+ }
204
+
205
+ // src/internal/pool.ts
206
+ async function mapWithConcurrency(items, concurrency, task) {
207
+ const results = new Array(items.length);
208
+ let next = 0;
209
+ let failed = false;
210
+ async function worker() {
211
+ while (!failed && next < items.length) {
212
+ const index = next++;
213
+ try {
214
+ results[index] = await task(items[index], index);
215
+ } catch (error) {
216
+ failed = true;
217
+ throw error;
218
+ }
219
+ }
220
+ }
221
+ const workers = Math.max(1, Math.min(concurrency, items.length));
222
+ await Promise.all(Array.from({ length: workers }, worker));
223
+ return results;
224
+ }
225
+
226
+ // src/upload/progress.ts
227
+ function transferProgress(loaded, total) {
228
+ return {
229
+ loaded,
230
+ total,
231
+ percent: total > 0 ? Math.min(100, Math.round(loaded / total * 100)) : 0
232
+ };
233
+ }
234
+
235
+ // src/internal/abortable.ts
236
+ async function abortable(promise, signal) {
237
+ const work = Promise.resolve(promise);
238
+ if (!signal) return work;
239
+ if (!signal.aborted) {
240
+ const { promise: aborted, resolve } = Promise.withResolvers();
241
+ const onAbort = () => resolve();
242
+ signal.addEventListener("abort", onAbort, { once: true });
243
+ try {
244
+ await Promise.race([work, aborted]);
245
+ } finally {
246
+ signal.removeEventListener("abort", onAbort);
247
+ }
248
+ }
249
+ if (signal.aborted) work.catch(ignore);
250
+ signal.throwIfAborted();
251
+ return work;
252
+ }
253
+ async function delay(ms, signal) {
254
+ signal?.throwIfAborted();
255
+ const { promise, resolve } = Promise.withResolvers();
256
+ const timer = setTimeout(resolve, ms);
257
+ const onAbort = () => {
258
+ clearTimeout(timer);
259
+ resolve();
260
+ };
261
+ signal?.addEventListener("abort", onAbort, { once: true });
262
+ try {
263
+ await promise;
264
+ } finally {
265
+ signal?.removeEventListener("abort", onAbort);
266
+ }
267
+ signal?.throwIfAborted();
268
+ }
269
+ function ignore() {
270
+ }
271
+
272
+ // src/upload/retry.ts
273
+ function isRetryableError(error) {
274
+ if (isS3ErrorCode(error, "NETWORK_ERROR") || isS3ErrorCode(error, "S3_NETWORK_ERROR")) {
275
+ return true;
276
+ }
277
+ if (!isS3ErrorCode(error, "UPLOAD_FAILED")) return false;
278
+ const status = s3Status(error);
279
+ return status >= 500 || status === 429;
280
+ }
281
+ function s3Status(error) {
282
+ return Number(error.params?.status ?? error.statusCode);
283
+ }
284
+ async function withRetry(task, options) {
285
+ const { retry, signal, canRetry = isRetryableError } = options;
286
+ const maxRetries = retry?.maxRetries ?? MAX_RETRIES;
287
+ const baseDelay = retry?.baseDelay ?? RETRY_BASE_DELAY;
288
+ for (let attempt = 0; ; attempt++) {
289
+ signal?.throwIfAborted();
290
+ try {
291
+ return await task();
292
+ } catch (error) {
293
+ signal?.throwIfAborted();
294
+ if (attempt >= maxRetries || !canRetry(error)) throw error;
295
+ }
296
+ await delay(baseDelay * 2 ** attempt, signal);
297
+ }
298
+ }
299
+ async function withPresignedRetry(sign, send, options) {
300
+ let current = null;
301
+ let expired = false;
302
+ return withRetry(
303
+ async () => {
304
+ if (current === null || expired || isPastExpiry(current.expiresAt)) {
305
+ expired = false;
306
+ const signedAt = Date.now();
307
+ const signed2 = await sign();
308
+ current = { signed: signed2, expiresAt: signedAt + signed2.expiresIn * 1e3 };
309
+ }
310
+ const { signed, expiresAt } = current;
311
+ try {
312
+ await send(signed);
313
+ return signed;
314
+ } catch (error) {
315
+ expired = isS3ErrorCode(error, "UPLOAD_FAILED") && s3Status(error) === 403 && isPastExpiry(expiresAt);
316
+ throw error;
317
+ }
318
+ },
319
+ { ...options, canRetry: (error) => expired || isRetryableError(error) }
320
+ );
321
+ }
322
+ function isPastExpiry(expiresAt) {
323
+ return Date.now() >= expiresAt - URL_EXPIRY_MARGIN_MS;
324
+ }
325
+ var CHECKSUM_ERROR_CODES = /* @__PURE__ */ new Set([
326
+ "BadDigest",
327
+ "XAmzContentChecksumMismatch"
328
+ ]);
329
+ async function sendXhrUpload(options) {
330
+ const { method, url, body, headers = {}, signal, onProgress } = options;
331
+ signal?.throwIfAborted();
332
+ const xhr = new XMLHttpRequest();
333
+ const settled = new Promise((resolve) => {
334
+ xhr.upload.addEventListener("progress", (event) => {
335
+ if (event.lengthComputable && event.total > 0) {
336
+ onProgress?.(event.loaded / event.total);
337
+ }
338
+ });
339
+ xhr.addEventListener("load", () => {
340
+ const { status } = xhr;
341
+ if (status >= 200 && status < 300) {
342
+ resolve(null);
343
+ } else if (status === 400 && CHECKSUM_ERROR_CODES.has(s3ErrorCode(xhr))) {
344
+ resolve(s3Error("CHECKSUM_MISMATCH"));
345
+ } else {
346
+ resolve(s3Error("UPLOAD_FAILED", { status }, { status }));
347
+ }
348
+ });
349
+ xhr.addEventListener("error", () => resolve(s3Error("NETWORK_ERROR")));
350
+ xhr.addEventListener("abort", () => resolve(s3Error("NETWORK_ERROR")));
351
+ });
352
+ const onAbort = () => xhr.abort();
353
+ signal?.addEventListener("abort", onAbort, { once: true });
354
+ try {
355
+ xhr.open(method, url);
356
+ for (const [name, value] of Object.entries(headers)) {
357
+ xhr.setRequestHeader(name, value);
358
+ }
359
+ xhr.send(body);
360
+ const error = await settled;
361
+ signal?.throwIfAborted();
362
+ if (error) throw error;
363
+ } finally {
364
+ signal?.removeEventListener("abort", onAbort);
365
+ }
366
+ }
367
+ function s3ErrorCode(xhr) {
368
+ try {
369
+ return /<Code>([^<]+)<\/Code>/.exec(xhr.responseText)?.[1] ?? "";
370
+ } catch {
371
+ return "";
372
+ }
373
+ }
374
+
375
+ // src/upload/upload-part.ts
376
+ function uploadPart(part, signed, options) {
377
+ const { signal, onProgress } = options;
378
+ return sendXhrUpload({
379
+ method: "PUT",
380
+ url: signed.url,
381
+ body: part,
382
+ headers: signed.headers,
383
+ signal,
384
+ onProgress: (fraction) => onProgress?.(Math.round(fraction * part.size))
385
+ });
386
+ }
387
+
388
+ // src/upload/part-pool.ts
389
+ function layoutPartSize(layout, partNumber) {
390
+ const { fileSize, partSize, partCount } = layout;
391
+ return partNumber < partCount ? partSize : fileSize - partSize * (partCount - 1);
392
+ }
393
+ async function uploadParts(api, file, upload, done, options) {
394
+ const { ticket, partSize, partCount, checksum } = upload;
395
+ const { retry, onProgress, onPartUpload } = options;
396
+ const loaded = Array.from(
397
+ { length: partCount },
398
+ (_, index) => done.has(index + 1) ? layoutPartSize(upload, index + 1) : 0
399
+ );
400
+ const report = () => {
401
+ const sent = loaded.reduce((sum, bytes) => sum + bytes, 0);
402
+ onProgress?.(transferProgress(sent, file.size));
403
+ };
404
+ if (done.size > 0) report();
405
+ const pending = Array.from(
406
+ { length: partCount },
407
+ (_, index) => index + 1
408
+ ).filter((partNumber) => !done.has(partNumber));
409
+ const failure = new AbortController();
410
+ const signal = options.signal ? AbortSignal.any([options.signal, failure.signal]) : failure.signal;
411
+ const sendOne = async (partNumber) => {
412
+ const index = partNumber - 1;
413
+ const start = index * partSize;
414
+ const part = file.slice(start, start + layoutPartSize(upload, partNumber));
415
+ const partChecksum = checksum ? await sha256Blob(part, { signal }) : void 0;
416
+ await withPresignedRetry(
417
+ () => api.multipart.signPart(
418
+ {
419
+ ticket,
420
+ partNumber,
421
+ ...partChecksum ? { checksum: partChecksum } : {}
422
+ },
423
+ { signal }
424
+ ),
425
+ (signed) => {
426
+ loaded[index] = 0;
427
+ report();
428
+ return uploadPart(part, signed, {
429
+ signal,
430
+ onProgress: (bytes) => {
431
+ loaded[index] = bytes;
432
+ report();
433
+ }
434
+ });
435
+ },
436
+ { retry, signal }
437
+ );
438
+ loaded[index] = part.size;
439
+ report();
440
+ onPartUpload?.({ partNumber, totalParts: partCount });
441
+ };
442
+ try {
443
+ await mapWithConcurrency(
444
+ pending,
445
+ options.concurrentParts ?? DEFAULT_CONCURRENT_PARTS,
446
+ sendOne
447
+ );
448
+ } catch (error) {
449
+ failure.abort(error);
450
+ throw error;
451
+ }
452
+ }
453
+
454
+ // src/upload/stored-upload.ts
455
+ function isStoredUpload(value) {
456
+ if (typeof value !== "object" || value === null) return false;
457
+ const record = value;
458
+ return isText(record.resumeKey) && isText(record.ticket) && isText(record.key) && isText(record.uploadId) && isCount(record.fileSize) && isCount(record.partSize) && isCount(record.partCount) && typeof record.checksum === "boolean";
459
+ }
460
+ function isText(value) {
461
+ return typeof value === "string" && value !== "";
462
+ }
463
+ function isCount(value) {
464
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
465
+ }
466
+
467
+ // src/upload/multipart.ts
468
+ var activeResumeKeys = /* @__PURE__ */ new Set();
469
+ async function uploadMultipart(api, file, payload, options, setPhase) {
470
+ const resumeKey = multipartResumeKey(options.route, file, options.request);
471
+ const store = activeResumeKeys.has(resumeKey) ? void 0 : options.uploadStore;
472
+ if (store) activeResumeKeys.add(resumeKey);
473
+ try {
474
+ return await runMultipart(api, file, payload, options, setPhase, {
475
+ store,
476
+ resumeKey
477
+ });
478
+ } finally {
479
+ if (store) activeResumeKeys.delete(resumeKey);
480
+ }
481
+ }
482
+ async function runMultipart(api, file, payload, options, setPhase, { store, resumeKey }) {
483
+ const { signal } = options;
484
+ setPhase("preparing");
485
+ const resumed = store ? await resumeSession(api, file, store, resumeKey, options, setPhase) : null;
486
+ let upload;
487
+ let done;
488
+ if (resumed) {
489
+ ({ upload, done } = resumed);
490
+ } else {
491
+ setPhase("presigning");
492
+ const init = await withRetry(
493
+ () => api.multipart.init(payload, { signal }),
494
+ options
495
+ );
496
+ upload = {
497
+ resumeKey,
498
+ ticket: init.ticket,
499
+ key: init.key,
500
+ uploadId: init.uploadId,
501
+ fileSize: file.size,
502
+ partSize: init.partSize,
503
+ partCount: init.partCount,
504
+ checksum: init.checksum
505
+ };
506
+ done = /* @__PURE__ */ new Set();
507
+ }
508
+ try {
509
+ if (store && !resumed) await quietly(() => store.set(upload));
510
+ options.onMultipartInit?.({ uploadId: upload.uploadId, key: upload.key });
511
+ setPhase("uploading");
512
+ await uploadParts(api, file, upload, done, options);
513
+ setPhase("finalizing");
514
+ const { uploadId: _uploadId, ...result } = await withRetry(
515
+ () => api.multipart.complete({ ticket: upload.ticket }, { signal }),
516
+ options
517
+ );
518
+ if (store) await quietly(() => store.delete(resumeKey));
519
+ return result;
520
+ } catch (error) {
521
+ const keep = store !== void 0 && (signal?.aborted ? isDetached(signal) : isRetryableError(error));
522
+ if (!keep) {
523
+ abortQuietly(api, upload.ticket);
524
+ if (store) await quietly(() => store.delete(resumeKey));
525
+ }
526
+ throw error;
527
+ }
528
+ }
529
+ async function resumeSession(api, file, store, resumeKey, options, setPhase) {
530
+ const record = await readRecord(store, resumeKey, file.size);
531
+ if (record === null) return null;
532
+ if (!isStoredUpload(record) || record.resumeKey !== resumeKey || record.fileSize !== file.size) {
533
+ await quietly(() => store.delete(resumeKey));
534
+ return null;
535
+ }
536
+ try {
537
+ options.signal?.throwIfAborted();
538
+ setPhase("presigning");
539
+ const { parts } = await withRetry(
540
+ () => api.multipart.listParts(
541
+ { ticket: record.ticket },
542
+ { signal: options.signal }
543
+ ),
544
+ options
545
+ );
546
+ return { upload: record, done: completedParts(record, parts) };
547
+ } catch (error) {
548
+ const { signal } = options;
549
+ const keep = signal?.aborted ? isDetached(signal) : isRetryableError(error);
550
+ if (keep) throw error;
551
+ abortQuietly(api, record.ticket);
552
+ await quietly(() => store.delete(resumeKey));
553
+ if (signal?.aborted || !isSessionGone(error)) throw error;
554
+ return null;
555
+ }
556
+ }
557
+ function isDetached(signal) {
558
+ return getUploadAbortKind(signal.reason) === "detach";
559
+ }
560
+ async function readRecord(store, resumeKey, fileSize) {
561
+ try {
562
+ return await store.get(resumeKey, fileSize);
563
+ } catch (error) {
564
+ reportCallbackError(error);
565
+ return null;
566
+ }
567
+ }
568
+ function completedParts(upload, parts) {
569
+ const done = /* @__PURE__ */ new Set();
570
+ for (const { partNumber, size, checksum } of parts) {
571
+ if (partNumber >= 1 && partNumber <= upload.partCount && size === layoutPartSize(upload, partNumber) && (!upload.checksum || checksum !== void 0)) {
572
+ done.add(partNumber);
573
+ }
574
+ }
575
+ return done;
576
+ }
577
+ function isSessionGone(error) {
578
+ return isS3ErrorCode(error, "UPLOAD_TICKET_EXPIRED") || isS3ErrorCode(error, "UPLOAD_TICKET_INVALID") || isS3ErrorCode(error, "OBJECT_NOT_FOUND");
579
+ }
580
+ function abortQuietly(api, ticket) {
581
+ api.multipart.abort({ ticket }).catch(() => {
582
+ });
583
+ }
584
+ async function quietly(run) {
585
+ try {
586
+ await run();
587
+ } catch (error) {
588
+ reportCallbackError(error);
589
+ }
590
+ }
591
+
592
+ // src/upload/presigned-http.ts
593
+ var sendPresignedUpload = (file, presign, { onProgress, signal }) => {
594
+ const reportFraction = (fraction) => onProgress?.(transferProgress(Math.round(fraction * file.size), file.size));
595
+ if (presign.method === "PUT") {
596
+ return sendXhrUpload({
597
+ method: "PUT",
598
+ url: presign.url,
599
+ body: file,
600
+ headers: presign.headers,
601
+ signal,
602
+ onProgress: reportFraction
603
+ });
604
+ }
605
+ const form = new FormData();
606
+ for (const [name, value] of Object.entries(presign.fields)) {
607
+ form.append(name, value);
608
+ }
609
+ form.append("file", file);
610
+ return sendXhrUpload({
611
+ method: "POST",
612
+ url: presign.url,
613
+ body: form,
614
+ signal,
615
+ onProgress: reportFraction
616
+ });
617
+ };
618
+
619
+ // src/upload/upload-file.ts
620
+ async function uploadFile(api, file, options) {
621
+ const { signal, policy } = options;
622
+ const setPhase = phaseReporter(options.onPhaseChange);
623
+ try {
624
+ signal?.throwIfAborted();
625
+ const payload = initPayload(file, options);
626
+ if (policy.multipart && file.size >= DEFAULT_MULTIPART_THRESHOLD) {
627
+ return await uploadMultipart(api, file, payload, options, setPhase);
628
+ }
629
+ return await uploadSingle(api, file, payload, options, setPhase);
630
+ } catch (error) {
631
+ signal?.throwIfAborted();
632
+ throw toClientError(error);
633
+ }
634
+ }
635
+ async function uploadSingle(api, file, payload, options, setPhase) {
636
+ const { signal, onProgress } = options;
637
+ const transport = getUploadTransport(api) ?? sendPresignedUpload;
638
+ setPhase("preparing");
639
+ const checksum = options.policy.checksum ? await sha256Blob(file, { signal }) : void 0;
640
+ const presign = await withPresignedRetry(
641
+ () => {
642
+ setPhase("presigning");
643
+ return api.upload(
644
+ { ...payload, ...checksum ? { checksum } : {} },
645
+ { signal }
646
+ );
647
+ },
648
+ (signed) => {
649
+ setPhase("uploading");
650
+ return transport(file, signed, { onProgress, signal });
651
+ },
652
+ options
653
+ );
654
+ onProgress?.(transferProgress(file.size, file.size));
655
+ setPhase("finalizing");
656
+ return withRetry(
657
+ () => api.confirm({ ticket: presign.ticket }, { signal }),
658
+ options
659
+ );
660
+ }
661
+ function initPayload(file, options) {
662
+ const { route, request = {} } = options;
663
+ const type = (request.contentType ?? file.type).trim();
664
+ return {
665
+ route,
666
+ name: fitFileName(request.fileName || file.name),
667
+ size: file.size,
668
+ ...type ? { type } : {},
669
+ ...request.metadata ? { metadata: request.metadata } : {}
670
+ };
671
+ }
672
+ function getUploadTransport(api) {
673
+ const transport = api.uploadTransport;
674
+ return typeof transport === "function" ? transport : void 0;
675
+ }
676
+ function phaseReporter(onPhaseChange) {
677
+ let current = null;
678
+ return (phase) => {
679
+ if (phase === current) return;
680
+ current = phase;
681
+ onPhaseChange?.(phase);
682
+ };
683
+ }
684
+
685
+ // src/list/entries.ts
686
+ function objectListEntryKey(kind, id) {
687
+ return `${kind}:${id}`;
688
+ }
689
+ function createObjectListEntries(folders, items, getKey, getFile) {
690
+ const entries = [];
691
+ for (const folder of folders) {
692
+ entries.push({
693
+ kind: "folder",
694
+ key: objectListEntryKey("folder", folder.id),
695
+ id: folder.id,
696
+ name: folder.name,
697
+ folder
698
+ });
699
+ }
700
+ for (const item of items) {
701
+ const id = getKey(item);
702
+ const file = getFile(item);
703
+ entries.push({
704
+ kind: "file",
705
+ key: objectListEntryKey("file", id),
706
+ id,
707
+ name: file.name,
708
+ item,
709
+ file
710
+ });
711
+ }
712
+ return entries;
713
+ }
714
+ function objectKeyOf(entry) {
715
+ return entry.file.objectKey || entry.id;
716
+ }
717
+
718
+ // src/helpers/format-accept-labels.ts
719
+ var GROUPS = {
720
+ image: "Images",
721
+ video: "Videos",
722
+ audio: "Audio",
723
+ text: "Text files",
724
+ font: "Fonts"
725
+ };
726
+ var MIME_LABELS = {
727
+ "application/msword": "DOC",
728
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "DOCX",
729
+ "application/vnd.ms-excel": "XLS",
730
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "XLSX",
731
+ "application/vnd.ms-powerpoint": "PPT",
732
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "PPTX",
733
+ "application/vnd.oasis.opendocument.text": "ODT",
734
+ "application/vnd.oasis.opendocument.spreadsheet": "ODS",
735
+ "application/vnd.oasis.opendocument.presentation": "ODP",
736
+ "application/x-zip-compressed": "ZIP",
737
+ "application/x-7z-compressed": "7Z",
738
+ "application/x-rar-compressed": "RAR",
739
+ "audio/mpeg": "MP3",
740
+ "text/plain": "TXT",
741
+ "text/markdown": "MD",
742
+ "video/quicktime": "MOV",
743
+ "video/x-matroska": "MKV"
744
+ };
745
+ function formatAcceptLabel(token, groups) {
746
+ const type = token.trim().toLowerCase();
747
+ if (!type || type === "*" || type === "*/*") return null;
748
+ if (type.startsWith(".")) {
749
+ const ext = type.slice(1);
750
+ return ext === "jpg" || ext === "jpeg" ? "JPEG" : ext.toUpperCase();
751
+ }
752
+ const [base = "", sub = ""] = type.split("/");
753
+ if (sub === "*") {
754
+ return groups?.[base] ?? GROUPS[base] ?? `${base.charAt(0).toUpperCase()}${base.slice(1)} files`;
755
+ }
756
+ const known = MIME_LABELS[type];
757
+ if (known) return known;
758
+ const name = sub.replace(/^(?:x-|vnd\.)/, "").replace(/\+.*$/, "");
759
+ return name ? name.toUpperCase() : token.trim();
760
+ }
761
+ function formatAcceptLabels(accept, options = {}) {
762
+ if (!accept?.length) return [];
763
+ const labels = /* @__PURE__ */ new Set();
764
+ for (const token of accept) {
765
+ const label = formatAcceptLabel(token, options.groups);
766
+ if (label) labels.add(label);
767
+ }
768
+ return [...labels];
769
+ }
770
+
771
+ // src/helpers/format-file-size.ts
772
+ var UNITS = [
773
+ "B",
774
+ "KB",
775
+ "MB",
776
+ "GB",
777
+ "TB",
778
+ "PB",
779
+ "EB"
780
+ ];
781
+ var numberFormats = /* @__PURE__ */ new Map();
782
+ function numberFormat(locale, fractionDigits) {
783
+ const id = `${String(locale)}|${fractionDigits}`;
784
+ let format = numberFormats.get(id);
785
+ if (!format) {
786
+ format = new Intl.NumberFormat(
787
+ typeof locale === "string" ? locale : [...locale],
788
+ {
789
+ minimumFractionDigits: fractionDigits,
790
+ maximumFractionDigits: fractionDigits,
791
+ useGrouping: false
792
+ }
793
+ );
794
+ numberFormats.set(id, format);
795
+ }
796
+ return format;
797
+ }
798
+ function formatFileSize(bytes, options = {}) {
799
+ const size = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
800
+ const last = UNITS.length - 1;
801
+ let i = size === 0 ? 0 : Math.min(Math.floor(Math.log(size) / Math.log(1024)), last);
802
+ const decimals = (unit2) => unit2 === 0 ? 0 : 1;
803
+ const rounded = (unit2) => {
804
+ const factor = 10 ** decimals(unit2);
805
+ return Math.round(size / 1024 ** unit2 * factor) / factor;
806
+ };
807
+ if (i < last && rounded(i) >= 1024) i += 1;
808
+ const unit = UNITS[i] ?? "B";
809
+ const value = numberFormat(options.locale ?? "en-US", decimals(i)).format(
810
+ rounded(i)
811
+ );
812
+ return `${value} ${options.units?.[unit] ?? unit}`;
813
+ }
814
+
815
+ // src/helpers/to-timestamp.ts
816
+ function toTimestamp(value) {
817
+ if (value == null || value === "") return null;
818
+ const time = value instanceof Date ? value.getTime() : typeof value === "number" ? value : Date.parse(value);
819
+ return Number.isFinite(time) ? time : null;
820
+ }
821
+
822
+ export { DEFAULT_CONCURRENT_FILES, DEFAULT_MAX_FILES, DEFAULT_MULTIPART_THRESHOLD, abortable, createObjectListEntries, formatAcceptLabels, formatFileSize, getUploadAbortKind, hookFailed, isRawAPIError, isStoredUpload, loadRouteCatalog, mapWithConcurrency, mergeRouteUploadPolicy, mergeUploadRequest, multipartResumeKey, notify, objectKeyOf, objectListEntryKey, reportOperationOutcome, requireApi, resolveRouteUploadPolicy, resolveUploadRequest, runAfterCallback, runBeforeCallback, runStartCallback, toClientError, toTimestamp, transferProgress, uploadAbortReason, uploadFile };
823
+ //# sourceMappingURL=chunk-SPUUNLXI.js.map
824
+ //# sourceMappingURL=chunk-SPUUNLXI.js.map