@od-oneapp/storage 2026.2.1701 → 2026.2.2301-canary

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.
@@ -0,0 +1,723 @@
1
+ import { a as logWarn } from "./env-d2CieWaM.mjs";
2
+ import { t as VercelBlobProvider } from "./vercel-blob-DrfolJEu.mjs";
3
+ import { CloudflareImagesProvider } from "@od-oneapp/integration-cloudflare/storage-provider/images";
4
+ import { CloudflareR2Provider } from "@od-oneapp/integration-cloudflare/storage-provider/r2";
5
+
6
+ //#region providers/cloudflare-images.ts
7
+ /**
8
+ * @fileoverview Cloudflare Images storage provider
9
+ *
10
+ * Static import from the monorepo integration package.
11
+ * The integration code is bundled into the published package by tsdown.
12
+ */
13
+ const CloudflareImagesProvider$1 = CloudflareImagesProvider;
14
+
15
+ //#endregion
16
+ //#region providers/cloudflare-r2.ts
17
+ /**
18
+ * @fileoverview Cloudflare R2 storage provider
19
+ *
20
+ * Static import from the monorepo integration package.
21
+ * The integration code is bundled into the published package by tsdown.
22
+ */
23
+ const CloudflareR2Provider$1 = CloudflareR2Provider;
24
+
25
+ //#endregion
26
+ //#region src/constants.ts
27
+ /**
28
+ * @fileoverview Storage Package Constants
29
+ *
30
+ * Centralized constants for storage operations to avoid magic numbers
31
+ * and improve maintainability.
32
+ *
33
+ * Includes:
34
+ * - URL expiration times
35
+ * - File size limits
36
+ * - Multipart upload thresholds
37
+ * - Retry configuration
38
+ * - Rate limiting settings
39
+ *
40
+ * @module @od-oneapp/storage/constants
41
+ */
42
+ const STORAGE_CONSTANTS = {
43
+ DEFAULT_URL_EXPIRY_SECONDS: 3600,
44
+ PRODUCT_URL_EXPIRY_SECONDS: 3600,
45
+ UPLOAD_URL_EXPIRY_SECONDS: 1800,
46
+ ADMIN_URL_EXPIRY_SECONDS: 7200,
47
+ MULTIPART_THRESHOLD_BYTES: 100 * 1024 * 1024,
48
+ DEFAULT_PART_SIZE_BYTES: 5 * 1024 * 1024,
49
+ DEFAULT_MAX_PART_SIZE_BYTES: 25 * 1024 * 1024,
50
+ DEFAULT_QUEUE_SIZE: 4,
51
+ DEFAULT_BATCH_SIZE: 5,
52
+ MAX_BATCH_SIZE: 50,
53
+ DEFAULT_REQUEST_TIMEOUT_MS: 3e4,
54
+ DEFAULT_UPLOAD_TIMEOUT_MS: 3e5,
55
+ DEFAULT_DOWNLOAD_TIMEOUT_MS: 6e4,
56
+ DEFAULT_MAX_RETRIES: 3,
57
+ RETRY_BASE_DELAY_MS: 1e3,
58
+ MAX_KEY_LENGTH: 1024,
59
+ MAX_FILENAME_LENGTH: 255,
60
+ DEFAULT_RATE_LIMIT_REQUESTS: 100,
61
+ DEFAULT_RATE_LIMIT_WINDOW_MS: 60 * 1e3,
62
+ HEALTH_CHECK_KEY: "__health_check__"
63
+ };
64
+ /**
65
+ * File size thresholds for multipart upload decisions
66
+ */
67
+ const MULTIPART_THRESHOLDS = {
68
+ SMALL_FILE: 100 * 1024 * 1024,
69
+ MEDIUM_FILE: 1024 * 1024 * 1024,
70
+ LARGE_FILE: Infinity
71
+ };
72
+ /**
73
+ * Part sizes based on file size
74
+ */
75
+ const PART_SIZES = {
76
+ SMALL: 5 * 1024 * 1024,
77
+ MEDIUM: 10 * 1024 * 1024,
78
+ LARGE: 25 * 1024 * 1024
79
+ };
80
+ /**
81
+ * Default storage capabilities for providers that don't implement getCapabilities()
82
+ * Single source of truth for capability defaults
83
+ */
84
+ const DEFAULT_STORAGE_CAPABILITIES = {
85
+ multipart: false,
86
+ presignedUrls: false,
87
+ progressTracking: false,
88
+ abortSignal: false,
89
+ metadata: false,
90
+ customDomains: false,
91
+ edgeCompatible: false,
92
+ versioning: false,
93
+ encryption: false,
94
+ directoryListing: false
95
+ };
96
+
97
+ //#endregion
98
+ //#region src/multi-storage.ts
99
+ /**
100
+ * @fileoverview Multi-storage provider manager
101
+ *
102
+ * Manages multiple storage providers with routing and fallback capabilities.
103
+ * Allows using different providers for different use cases or as backups.
104
+ *
105
+ * Features:
106
+ * - Provider routing based on key patterns
107
+ * - Fallback to default provider
108
+ * - Unified API across multiple providers
109
+ *
110
+ * @module @od-oneapp/storage/multi-storage
111
+ */
112
+ var MultiStorageManager = class {
113
+ providers = /* @__PURE__ */ new Map();
114
+ defaultProvider;
115
+ routing;
116
+ constructor(config) {
117
+ for (const [name, providerConfig] of Object.entries(config.providers)) this.providers.set(name, this.createProvider(providerConfig));
118
+ const firstProvider = Object.keys(config.providers)[0];
119
+ this.defaultProvider = config.defaultProvider ?? firstProvider ?? "";
120
+ if (!this.defaultProvider) throw new Error("No storage providers configured");
121
+ this.routing = config.routing;
122
+ }
123
+ createProvider(config) {
124
+ switch (config.provider) {
125
+ case "multi": throw new Error("Multi provider cannot be nested");
126
+ case "cloudflare-r2":
127
+ if (!config.cloudflareR2) throw new Error("Cloudflare R2 configuration is required");
128
+ if (Array.isArray(config.cloudflareR2)) {
129
+ if (config.cloudflareR2.length === 0) throw new Error("No R2 configurations provided");
130
+ const firstR2Config = config.cloudflareR2[0];
131
+ if (!firstR2Config) throw new Error("First R2 configuration is undefined");
132
+ return new CloudflareR2Provider$1(firstR2Config);
133
+ }
134
+ return new CloudflareR2Provider$1(config.cloudflareR2);
135
+ case "cloudflare-images":
136
+ if (!config.cloudflareImages) throw new Error("Cloudflare Images configuration is required");
137
+ return new CloudflareImagesProvider$1(config.cloudflareImages);
138
+ case "vercel-blob":
139
+ if (!config.vercelBlob?.token) throw new Error("Vercel Blob token is required");
140
+ return new VercelBlobProvider(config.vercelBlob.token);
141
+ default: throw new Error(`Unknown storage provider: ${config.provider}`);
142
+ }
143
+ }
144
+ getProviderForKey(key) {
145
+ if (this.routing) {
146
+ const extension = key.split(".").pop()?.toLowerCase();
147
+ if (this.routing.images && this.isImageFile(extension)) {
148
+ const provider = this.providers.get(this.routing.images);
149
+ if (provider) return {
150
+ provider,
151
+ providerName: this.routing.images
152
+ };
153
+ }
154
+ if (this.routing.documents && this.isDocumentFile(extension)) {
155
+ const provider = this.providers.get(this.routing.documents);
156
+ if (provider) return {
157
+ provider,
158
+ providerName: this.routing.documents
159
+ };
160
+ }
161
+ for (const [pattern, providerName] of Object.entries(this.routing)) if (pattern !== "images" && pattern !== "documents" && providerName) {
162
+ if (key.includes(pattern)) {
163
+ const provider = this.providers.get(providerName);
164
+ if (provider) return {
165
+ provider,
166
+ providerName
167
+ };
168
+ }
169
+ }
170
+ }
171
+ const provider = this.providers.get(this.defaultProvider);
172
+ if (!provider) throw new Error(`Default provider '${this.defaultProvider}' not found`);
173
+ return {
174
+ provider,
175
+ providerName: this.defaultProvider
176
+ };
177
+ }
178
+ isImageFile(extension) {
179
+ return extension ? [
180
+ "jpg",
181
+ "jpeg",
182
+ "png",
183
+ "gif",
184
+ "webp",
185
+ "avif",
186
+ "svg",
187
+ "ico"
188
+ ].includes(extension) : false;
189
+ }
190
+ isDocumentFile(extension) {
191
+ return extension ? [
192
+ "pdf",
193
+ "doc",
194
+ "docx",
195
+ "xls",
196
+ "xlsx",
197
+ "ppt",
198
+ "pptx",
199
+ "txt",
200
+ "csv"
201
+ ].includes(extension) : false;
202
+ }
203
+ getProvider(name) {
204
+ return this.providers.get(name);
205
+ }
206
+ async delete(key) {
207
+ const { provider } = this.getProviderForKey(key);
208
+ return provider.delete(key);
209
+ }
210
+ async download(key) {
211
+ const { provider } = this.getProviderForKey(key);
212
+ return provider.download(key);
213
+ }
214
+ async exists(key) {
215
+ const { provider } = this.getProviderForKey(key);
216
+ return provider.exists(key);
217
+ }
218
+ async getMetadata(key) {
219
+ const { provider } = this.getProviderForKey(key);
220
+ return provider.getMetadata(key);
221
+ }
222
+ async getUrl(key, options) {
223
+ const { provider } = this.getProviderForKey(key);
224
+ return provider.getUrl(key, options);
225
+ }
226
+ async list(options) {
227
+ if (options?.provider) {
228
+ const provider = this.providers.get(options.provider);
229
+ if (!provider) throw new Error(`Provider '${options.provider}' not found`);
230
+ return provider.list(options);
231
+ }
232
+ const allResults = [];
233
+ for (const provider of this.providers.values()) {
234
+ const results = await provider.list(options);
235
+ allResults.push(...results);
236
+ }
237
+ return allResults;
238
+ }
239
+ async upload(key, data, options) {
240
+ let provider;
241
+ if (options?.provider) {
242
+ const requestedProvider = this.providers.get(options.provider);
243
+ if (!requestedProvider) throw new Error(`Provider '${options.provider}' not found`);
244
+ provider = requestedProvider;
245
+ } else {
246
+ const { provider: routedProvider } = this.getProviderForKey(key);
247
+ provider = routedProvider;
248
+ }
249
+ return provider.upload(key, data, options);
250
+ }
251
+ async getCloudflareImagesProvider() {
252
+ for (const provider of this.providers.values()) if (provider instanceof CloudflareImagesProvider$1) return provider;
253
+ }
254
+ getProviderNames() {
255
+ return Array.from(this.providers.keys());
256
+ }
257
+ };
258
+
259
+ //#endregion
260
+ //#region src/multipart.ts
261
+ /**
262
+ * @fileoverview Unified Multipart Upload Manager
263
+ *
264
+ * Provides a consistent interface for multipart uploads across all storage providers.
265
+ * Handles provider-specific differences and provides retry logic, progress tracking,
266
+ * and error recovery.
267
+ *
268
+ * Features:
269
+ * - Automatic part size calculation
270
+ * - Concurrent part uploads
271
+ * - Progress tracking
272
+ * - Resume support
273
+ * - Error recovery
274
+ *
275
+ * @module @od-oneapp/storage/multipart
276
+ */
277
+ var MultipartUploadManager = class {
278
+ provider;
279
+ state = null;
280
+ abortController = null;
281
+ constructor(provider) {
282
+ this.provider = provider;
283
+ }
284
+ /**
285
+ * Check if provider supports multipart uploads
286
+ */
287
+ supportsMultipart() {
288
+ return (this.provider.getCapabilities?.())?.multipart ?? false;
289
+ }
290
+ /**
291
+ * Create a new multipart upload
292
+ *
293
+ * @param key - Storage key
294
+ * @param totalSize - Total file size in bytes
295
+ * @param options - Upload options
296
+ * @returns Upload state
297
+ */
298
+ async createUpload(key, totalSize, options = {}) {
299
+ if (!this.supportsMultipart()) throw new Error("Provider does not support multipart uploads");
300
+ if (this.state && !this.state.completed && !this.state.aborted) throw new Error("Upload already in progress. Abort current upload first.");
301
+ const partSize = this.calculatePartSize(totalSize, options.partSize);
302
+ const totalParts = Math.ceil(totalSize / partSize);
303
+ const uploadOptions = { onProgress: options.onProgress ? (progress) => {
304
+ options.onProgress?.({
305
+ key: progress.key,
306
+ loaded: progress.loaded,
307
+ total: progress.total,
308
+ part: progress.part ?? 0,
309
+ percentage: progress.percentage ?? 0
310
+ });
311
+ } : void 0 };
312
+ const result = await this.provider.createMultipartUpload?.(key, uploadOptions);
313
+ if (!result) throw new Error("Failed to create multipart upload");
314
+ this.state = {
315
+ uploadId: result.uploadId,
316
+ key: result.key,
317
+ provider: this.getProviderName(),
318
+ parts: Array.from({ length: totalParts }, (_, i) => ({
319
+ partNumber: i + 1,
320
+ size: i === totalParts - 1 ? totalSize - i * partSize : partSize,
321
+ uploaded: false
322
+ })),
323
+ totalSize,
324
+ uploadedSize: 0,
325
+ completed: false,
326
+ aborted: false
327
+ };
328
+ this.abortController = new AbortController();
329
+ return this.state;
330
+ }
331
+ /**
332
+ * Upload a part
333
+ *
334
+ * @param partNumber - Part number (1-based)
335
+ * @param data - Part data
336
+ * @param options - Upload options
337
+ * @returns Upload result
338
+ */
339
+ async uploadPart(partNumber, data, options = {}) {
340
+ if (!this.state) throw new Error("No active upload. Call createUpload first.");
341
+ if (this.state.completed || this.state.aborted) throw new Error("Upload is completed or aborted");
342
+ const part = this.state.parts.find((p) => p.partNumber === partNumber);
343
+ if (!part) throw new Error(`Part ${partNumber} not found`);
344
+ if (part.uploaded) throw new Error(`Part ${partNumber} already uploaded`);
345
+ if (this.abortController?.signal.aborted) throw new Error("Upload aborted");
346
+ try {
347
+ const result = await this.uploadPartWithRetry(partNumber, data, options);
348
+ part.etag = result.etag;
349
+ part.uploaded = true;
350
+ this.state.uploadedSize += part.size;
351
+ if (options.onProgress) options.onProgress({
352
+ key: this.state.key,
353
+ loaded: this.state.uploadedSize,
354
+ total: this.state.totalSize,
355
+ part: partNumber,
356
+ percentage: this.state.uploadedSize / this.state.totalSize * 100
357
+ });
358
+ return result;
359
+ } catch (error) {
360
+ this.state.error = error instanceof Error ? error.message : String(error);
361
+ throw error;
362
+ }
363
+ }
364
+ /**
365
+ * Complete the multipart upload
366
+ *
367
+ * @returns Final upload result
368
+ */
369
+ async completeUpload() {
370
+ if (!this.state) throw new Error("No active upload. Call createUpload first.");
371
+ if (this.state.completed) throw new Error("Upload already completed");
372
+ if (this.state.aborted) throw new Error("Upload was aborted");
373
+ const unuploadedParts = this.state.parts.filter((p) => !p.uploaded);
374
+ if (unuploadedParts.length > 0) throw new Error(`Upload incomplete: ${unuploadedParts.length} parts not uploaded`);
375
+ try {
376
+ const parts = this.state.parts.filter((p) => p.etag).map((p) => ({
377
+ partNumber: p.partNumber,
378
+ etag: p.etag ?? ""
379
+ })).filter((p) => p.etag !== "");
380
+ const result = await this.provider.completeMultipartUpload?.(this.state.uploadId, parts);
381
+ if (!result) throw new Error("Failed to complete multipart upload");
382
+ this.state.completed = true;
383
+ return {
384
+ ...result,
385
+ key: result.key ?? this.state.key,
386
+ uploadId: this.state.uploadId,
387
+ parts: this.state.parts.filter((p) => p.etag).map((p) => ({
388
+ partNumber: p.partNumber,
389
+ etag: p.etag ?? "",
390
+ size: p.size
391
+ })),
392
+ totalParts: this.state.parts.length
393
+ };
394
+ } catch (error) {
395
+ this.state.error = error instanceof Error ? error.message : String(error);
396
+ throw error;
397
+ }
398
+ }
399
+ /**
400
+ * Abort the multipart upload
401
+ */
402
+ async abortUpload() {
403
+ if (!this.state) return;
404
+ if (this.state.completed) return;
405
+ this.abortController?.abort();
406
+ this.state.aborted = true;
407
+ try {
408
+ await this.provider.abortMultipartUpload?.(this.state.uploadId);
409
+ } catch (error) {
410
+ logWarn("Failed to abort upload on provider", {
411
+ error: error instanceof Error ? error.message : String(error),
412
+ uploadId: this.state.uploadId,
413
+ key: this.state.key
414
+ });
415
+ }
416
+ this.state = null;
417
+ this.abortController = null;
418
+ }
419
+ /**
420
+ * Get current upload state
421
+ */
422
+ getState() {
423
+ return this.state;
424
+ }
425
+ /**
426
+ * Resume upload from state (for recovery)
427
+ *
428
+ * @param state - Previous upload state
429
+ */
430
+ async resumeUpload(state) {
431
+ if (this.state && !this.state.completed && !this.state.aborted) throw new Error("Upload already in progress");
432
+ this.state = { ...state };
433
+ this.abortController = new AbortController();
434
+ }
435
+ /**
436
+ * Upload file in chunks automatically
437
+ *
438
+ * @param key - Storage key
439
+ * @param data - File data
440
+ * @param options - Upload options
441
+ * @returns Upload result
442
+ */
443
+ async uploadFile(key, data, options = {}) {
444
+ const totalSize = data instanceof ArrayBuffer ? data.byteLength : data instanceof Buffer ? data.length : data.size;
445
+ await this.createUpload(key, totalSize, options);
446
+ const partSize = this.calculatePartSize(totalSize, options.partSize);
447
+ const totalParts = Math.ceil(totalSize / partSize);
448
+ for (let i = 0; i < totalParts; i++) {
449
+ const start = i * partSize;
450
+ const end = Math.min(start + partSize, totalSize);
451
+ const partData = data.slice(start, end);
452
+ await this.uploadPart(i + 1, partData, { onProgress: options.onProgress ? (progress) => {
453
+ options.onProgress?.({
454
+ key: progress.key,
455
+ loaded: progress.loaded,
456
+ total: progress.total,
457
+ part: progress.part ?? 0,
458
+ percentage: progress.percentage ?? 0
459
+ });
460
+ } : void 0 });
461
+ }
462
+ return await this.completeUpload();
463
+ }
464
+ async uploadPartWithRetry(partNumber, data, options, maxRetries = 3) {
465
+ let lastError = null;
466
+ for (let attempt = 1; attempt <= maxRetries; attempt++) try {
467
+ if (!this.state?.uploadId) throw new Error("Upload ID not initialized");
468
+ const result = await this.provider.uploadPart?.(this.state.uploadId, partNumber, data, {
469
+ ...options,
470
+ abortSignal: this.abortController?.signal
471
+ });
472
+ if (!result) throw new Error("Failed to upload part");
473
+ return {
474
+ etag: result.etag ?? "",
475
+ partNumber: result.partNumber ?? partNumber,
476
+ size: data instanceof ArrayBuffer ? data.byteLength : data instanceof Buffer ? data.length : data.size
477
+ };
478
+ } catch (error) {
479
+ lastError = error instanceof Error ? error : new Error(String(error));
480
+ if (this.abortController?.signal.aborted) throw lastError;
481
+ if (lastError.message.includes("validation") || lastError.message.includes("invalid")) throw lastError;
482
+ if (attempt < maxRetries) await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempt) * STORAGE_CONSTANTS.RETRY_BASE_DELAY_MS));
483
+ }
484
+ throw lastError ?? /* @__PURE__ */ new Error("Upload failed after retries");
485
+ }
486
+ calculatePartSize(totalSize, userPartSize) {
487
+ if (userPartSize) return Math.min(userPartSize, totalSize);
488
+ if (totalSize < MULTIPART_THRESHOLDS.SMALL_FILE) return PART_SIZES.SMALL;
489
+ else if (totalSize < MULTIPART_THRESHOLDS.MEDIUM_FILE) return PART_SIZES.MEDIUM;
490
+ else {
491
+ const minPartSize = Math.ceil(totalSize / 9999);
492
+ return Math.max(PART_SIZES.LARGE, minPartSize);
493
+ }
494
+ }
495
+ getProviderName() {
496
+ return this.provider.constructor.name;
497
+ }
498
+ };
499
+ /**
500
+ * Create a multipart upload manager for a provider
501
+ *
502
+ * @param provider - Storage provider
503
+ * @returns Multipart upload manager
504
+ */
505
+ function createMultipartUploadManager(provider) {
506
+ if (!hasMultipartSupport(provider)) throw new Error("The provided storage provider does not support multipart uploads");
507
+ return new MultipartUploadManager(provider);
508
+ }
509
+ /**
510
+ * Determines whether the given storage provider supports multipart uploads.
511
+ *
512
+ * @param provider - The storage provider to check
513
+ * @returns `true` if the provider supports multipart uploads, `false` otherwise.
514
+ */
515
+ function hasMultipartSupport(provider) {
516
+ return (provider.getCapabilities?.())?.multipart ?? false;
517
+ }
518
+ /**
519
+ * Selects an appropriate multipart upload part size for a file.
520
+ *
521
+ * If `userPartSize` is provided, it will be capped at the file size; otherwise the part size
522
+ * is chosen from configured thresholds for small, medium, or large files.
523
+ *
524
+ * @param fileSize - File size in bytes
525
+ * @param userPartSize - Optional user-specified part size in bytes; capped to `fileSize` when provided
526
+ * @returns The selected part size in bytes
527
+ */
528
+ function getOptimalPartSize(fileSize, userPartSize) {
529
+ if (userPartSize) return Math.min(userPartSize, fileSize);
530
+ if (fileSize < MULTIPART_THRESHOLDS.SMALL_FILE) return PART_SIZES.SMALL;
531
+ else if (fileSize < MULTIPART_THRESHOLDS.MEDIUM_FILE) return PART_SIZES.MEDIUM;
532
+ else {
533
+ const minPartSize = Math.ceil(fileSize / 9999);
534
+ return Math.max(PART_SIZES.LARGE, minPartSize);
535
+ }
536
+ }
537
+
538
+ //#endregion
539
+ //#region src/capabilities.ts
540
+ /**
541
+ * @fileoverview Storage Provider Capabilities Utilities
542
+ *
543
+ * Provides utilities for checking storage provider capabilities and feature support.
544
+ * Helps determine which features are available for each provider.
545
+ *
546
+ * @module @od-oneapp/storage/capabilities
547
+ */
548
+ /**
549
+ * Check if a storage provider has a specific capability
550
+ * @param provider - The storage provider to check
551
+ * @param capability - The capability to check for
552
+ * @returns True if the provider supports the capability
553
+ */
554
+ function hasCapability(provider, capability) {
555
+ return (provider.getCapabilities?.())?.[capability] ?? false;
556
+ }
557
+ /**
558
+ * Check if a storage provider supports multiple capabilities
559
+ * @param provider - The storage provider to check
560
+ * @param capabilities - Array of capabilities to check for
561
+ * @returns True if the provider supports all capabilities
562
+ */
563
+ function hasAllCapabilities(provider, capabilities) {
564
+ return capabilities.every((capability) => hasCapability(provider, capability));
565
+ }
566
+ /**
567
+ * Check if a storage provider supports any of the specified capabilities
568
+ * @param provider - The storage provider to check
569
+ * @param capabilities - Array of capabilities to check for
570
+ * @returns True if the provider supports at least one capability
571
+ */
572
+ function hasAnyCapability(provider, capabilities) {
573
+ return capabilities.some((capability) => hasCapability(provider, capability));
574
+ }
575
+ /**
576
+ * Get all capabilities supported by a storage provider
577
+ * @param provider - The storage provider to check
578
+ * @returns Object with all capabilities and their support status
579
+ */
580
+ function getProviderCapabilities(provider) {
581
+ return provider.getCapabilities?.() ?? { ...DEFAULT_STORAGE_CAPABILITIES };
582
+ }
583
+ /**
584
+ * Get a human-readable description of provider capabilities
585
+ * @param provider - The storage provider to describe
586
+ * @returns String describing the provider's capabilities
587
+ */
588
+ function describeProviderCapabilities(provider) {
589
+ const capabilities = getProviderCapabilities(provider);
590
+ const supportedFeatures = [];
591
+ const unsupportedFeatures = [];
592
+ if (capabilities.multipart) supportedFeatures.push("multipart uploads");
593
+ else unsupportedFeatures.push("multipart uploads");
594
+ if (capabilities.presignedUrls) supportedFeatures.push("presigned URLs");
595
+ else unsupportedFeatures.push("presigned URLs");
596
+ if (capabilities.progressTracking) supportedFeatures.push("progress tracking");
597
+ else unsupportedFeatures.push("progress tracking");
598
+ if (capabilities.abortSignal) supportedFeatures.push("abort signals");
599
+ else unsupportedFeatures.push("abort signals");
600
+ if (capabilities.metadata) supportedFeatures.push("metadata");
601
+ else unsupportedFeatures.push("metadata");
602
+ if (capabilities.customDomains) supportedFeatures.push("custom domains");
603
+ else unsupportedFeatures.push("custom domains");
604
+ if (capabilities.edgeCompatible) supportedFeatures.push("edge runtime");
605
+ else unsupportedFeatures.push("edge runtime");
606
+ let description = `Provider supports: ${supportedFeatures.join(", ")}`;
607
+ if (unsupportedFeatures.length > 0) description += `\nProvider does not support: ${unsupportedFeatures.join(", ")}`;
608
+ return description;
609
+ }
610
+ /**
611
+ * Validate that a provider supports the required capabilities for an operation
612
+ * @param provider - The storage provider to validate
613
+ * @param requiredCapabilities - Capabilities required for the operation
614
+ * @throws Error if provider doesn't support required capabilities
615
+ */
616
+ function validateProviderCapabilities(provider, requiredCapabilities) {
617
+ const missingCapabilities = requiredCapabilities.filter((capability) => !hasCapability(provider, capability));
618
+ if (missingCapabilities.length > 0) {
619
+ const providerName = provider.constructor.name;
620
+ throw new Error(`Provider ${providerName} does not support required capabilities: ${missingCapabilities.join(", ")}`);
621
+ }
622
+ }
623
+ /**
624
+ * Get the best provider for a specific use case based on capabilities
625
+ * @param providers - Array of storage providers to choose from
626
+ * @param requiredCapabilities - Capabilities required for the use case
627
+ * @returns The best provider or null if none meet the requirements
628
+ */
629
+ function getBestProvider(providers, requiredCapabilities) {
630
+ const suitableProviders = providers.filter((provider) => hasAllCapabilities(provider, requiredCapabilities));
631
+ if (suitableProviders.length === 0) return null;
632
+ const edgeCompatible = suitableProviders.filter((provider) => hasCapability(provider, "edgeCompatible"));
633
+ return edgeCompatible.length > 0 ? edgeCompatible[0] ?? null : suitableProviders[0] ?? null;
634
+ }
635
+ /**
636
+ * Builds a map from provider names to their reported storage capabilities.
637
+ *
638
+ * @param providers - Array of entries each containing a `name` (used as the map key) and a `provider` instance
639
+ * @returns A mapping from each provider name to its `StorageCapabilities`
640
+ */
641
+ function getCapabilityMatrix(providers) {
642
+ const matrix = {};
643
+ for (const { name, provider } of providers) matrix[name] = getProviderCapabilities(provider);
644
+ return matrix;
645
+ }
646
+ /**
647
+ * Evaluate a storage provider's suitability for a specific file and produce actionable recommendations and warnings.
648
+ *
649
+ * @param provider - The storage provider to evaluate
650
+ * @param fileSize - File size in bytes
651
+ * @param fileType - MIME type of the file
652
+ * @returns An object with `suitable` (`true` if there are no warnings, `false` otherwise), `recommendations` (suggested actions to improve handling), and `warnings` (issues that reduce suitability)
653
+ */
654
+ function checkProviderSuitability(provider, fileSize, fileType) {
655
+ const capabilities = getProviderCapabilities(provider);
656
+ const recommendations = [];
657
+ const warnings = [];
658
+ if (fileSize > MULTIPART_THRESHOLDS.SMALL_FILE) if (!capabilities.multipart) warnings.push("Large file detected but provider does not support multipart uploads");
659
+ else recommendations.push("Use multipart upload for this large file");
660
+ if (fileType.startsWith("image/")) {
661
+ if (capabilities.metadata) recommendations.push("Consider storing image metadata for better organization");
662
+ }
663
+ if (fileType.startsWith("video/")) {
664
+ if (!capabilities.multipart) warnings.push("Video files are typically large and benefit from multipart uploads");
665
+ }
666
+ if (fileType.startsWith("text/") && !capabilities.edgeCompatible) recommendations.push("Text files could be processed in edge runtime for better performance");
667
+ return {
668
+ suitable: warnings.length === 0,
669
+ recommendations,
670
+ warnings
671
+ };
672
+ }
673
+
674
+ //#endregion
675
+ //#region src/health-check.ts
676
+ /**
677
+ * Check the health of a storage provider
678
+ *
679
+ * @param provider - The storage provider to check
680
+ * @returns Health check result with status and latency
681
+ */
682
+ async function checkProviderHealth(provider) {
683
+ const startTime = Date.now();
684
+ try {
685
+ await provider.list({ limit: 1 });
686
+ const latencyMs = Date.now() - startTime;
687
+ const HEALTHY_THRESHOLD_MS = 1e3;
688
+ const DEGRADED_THRESHOLD_MS = 3e3;
689
+ let status;
690
+ if (latencyMs < HEALTHY_THRESHOLD_MS) status = "healthy";
691
+ else if (latencyMs < DEGRADED_THRESHOLD_MS) status = "degraded";
692
+ else status = "unhealthy";
693
+ return {
694
+ status,
695
+ latencyMs,
696
+ details: {
697
+ provider: provider.constructor.name,
698
+ threshold_healthy_ms: HEALTHY_THRESHOLD_MS,
699
+ threshold_degraded_ms: DEGRADED_THRESHOLD_MS
700
+ }
701
+ };
702
+ } catch (error) {
703
+ return {
704
+ status: "unhealthy",
705
+ latencyMs: Date.now() - startTime,
706
+ error: error instanceof Error ? error.message : String(error),
707
+ details: { provider: provider.constructor.name }
708
+ };
709
+ }
710
+ }
711
+ /**
712
+ * Perform a comprehensive health check on storage system
713
+ *
714
+ * @param provider - The storage provider to check
715
+ * @returns Detailed health check result
716
+ */
717
+ async function storageHealthCheck(provider) {
718
+ return checkProviderHealth(provider);
719
+ }
720
+
721
+ //#endregion
722
+ export { DEFAULT_STORAGE_CAPABILITIES as _, getBestProvider as a, CloudflareImagesProvider$1 as b, hasAllCapabilities as c, validateProviderCapabilities as d, MultipartUploadManager as f, MultiStorageManager as g, hasMultipartSupport as h, describeProviderCapabilities as i, hasAnyCapability as l, getOptimalPartSize as m, storageHealthCheck as n, getCapabilityMatrix as o, createMultipartUploadManager as p, checkProviderSuitability as r, getProviderCapabilities as s, checkProviderHealth as t, hasCapability as u, STORAGE_CONSTANTS as v, CloudflareR2Provider$1 as y };
723
+ //# sourceMappingURL=health-check-Dij2-CYd.mjs.map