@visulima/storage 1.0.0-alpha.31 → 1.0.0-alpha.32

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 (173) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +2 -2
  3. package/dist/adapter/nuxt/module.d.ts +4 -4
  4. package/dist/adapter/nuxt/node_modules/.bin/nuxi +2 -2
  5. package/dist/adapter/nuxt/node_modules/.bin/nuxt +2 -2
  6. package/dist/ai/ai-sdk/index.d.ts +3 -3
  7. package/dist/ai/claude/index.d.ts +2 -2
  8. package/dist/ai/openai/index.d.ts +3 -3
  9. package/dist/ai/tanstack/index.d.ts +2 -2
  10. package/dist/handler/http/fetch/index.d.ts +7 -7
  11. package/dist/handler/http/fetch/index.js +1 -1
  12. package/dist/handler/http/hono/index.d.ts +4 -4
  13. package/dist/handler/http/hono/index.js +1 -1
  14. package/dist/handler/http/nextjs/index.d.ts +4 -4
  15. package/dist/handler/http/nextjs/index.js +1 -1
  16. package/dist/handler/http/node/index.d.ts +7 -7
  17. package/dist/handler/http/node/index.js +1 -1
  18. package/dist/handler/http/solid-start/index.d.ts +4 -4
  19. package/dist/handler/http/solid-start/index.js +1 -1
  20. package/dist/index.d.ts +6 -5
  21. package/dist/index.js +1 -1
  22. package/dist/packem_shared/{AwsLightStorage-DbQrK9m7.js → AwsLightStorage-B1jNF7sv.js} +1 -1
  23. package/dist/packem_shared/AzureStorage-B4E6VLn5.js +1 -0
  24. package/dist/packem_shared/{BoxMetaStorage-DLdXbZaV.js → BoxMetaStorage-nESVquA1.js} +1 -1
  25. package/dist/packem_shared/BoxStorage-CHYDrcxw.js +1 -0
  26. package/dist/packem_shared/{BunS3MetaStorage-Bv_CTTMz.js → BunS3MetaStorage-BkZx5q4w.js} +1 -1
  27. package/dist/packem_shared/BunS3Storage-BopE7kmX.js +1 -0
  28. package/dist/packem_shared/{BunnyMetaStorage-DNMTSeoN.js → BunnyMetaStorage-bB8NXGUI.js} +1 -1
  29. package/dist/packem_shared/BunnyStorage-C3IBxJqr.js +1 -0
  30. package/dist/packem_shared/{CloudinaryMetaStorage-DEBk5eQy.js → CloudinaryMetaStorage-BzibHydK.js} +1 -1
  31. package/dist/packem_shared/CloudinaryStorage-Cj00ZXWV.js +1 -0
  32. package/dist/packem_shared/DiskStorage-BrAb28Je.js +1 -0
  33. package/dist/packem_shared/DiskStorageWithChecksum-BX85CHJ6.js +1 -0
  34. package/dist/packem_shared/{DropboxMetaStorage-C6vj1QDA.js → DropboxMetaStorage-Bfm5bblb.js} +1 -1
  35. package/dist/packem_shared/DropboxStorage-Btz9h9Mj.js +1 -0
  36. package/dist/packem_shared/Files-tnc_buzM.js +1 -0
  37. package/dist/packem_shared/{FirebaseMetaStorage-CzyOim-J.js → FirebaseMetaStorage-CshnJMb0.js} +1 -1
  38. package/dist/packem_shared/FirebaseStorage-Y9P6Dx8I.js +2 -0
  39. package/dist/packem_shared/{FtpMetaStorage-1Njy0DpU.js → FtpMetaStorage-CoyWJafY.js} +1 -1
  40. package/dist/packem_shared/FtpStorage-DCKPMX0z.js +1 -0
  41. package/dist/packem_shared/{GCSMetaStorage-DFIjFmn-.js → GCSMetaStorage-CfZj52hQ.js} +1 -1
  42. package/dist/packem_shared/GCStorage-hfL1u2KQ.js +1 -0
  43. package/dist/packem_shared/{GoogleDriveMetaStorage-WGuUZPyx.js → GoogleDriveMetaStorage-CBSdEQr6.js} +1 -1
  44. package/dist/packem_shared/GoogleDriveStorage-C7iuV7qb.js +1 -0
  45. package/dist/packem_shared/{LocalMetaStorage-QMKL7McF.js → LocalMetaStorage-DSwsmdt7.js} +1 -1
  46. package/dist/packem_shared/MemoryMetaStorage-DEzfBNgL.js +1 -0
  47. package/dist/packem_shared/{Multipart-DkH4QwNs.js → Multipart-kQ5wJQaV.js} +1 -1
  48. package/dist/packem_shared/{Multipart-C6Mw7V9W.js → Multipart-qaEOWKz1.js} +1 -1
  49. package/dist/packem_shared/{NetlifyBlobMetaStorage-ClIFdTkT.js → NetlifyBlobMetaStorage-CqluIgV0.js} +1 -1
  50. package/dist/packem_shared/NetlifyBlobStorage-CkMw9Uyv.js +1 -0
  51. package/dist/packem_shared/{OneDriveMetaStorage-DS4f83X2.js → OneDriveMetaStorage-DPTNMpeq.js} +1 -1
  52. package/dist/packem_shared/OneDriveStorage-CEGYb6OC.js +1 -0
  53. package/dist/packem_shared/{PocketBaseMetaStorage-B6utPncj.js → PocketBaseMetaStorage-CemTT_01.js} +1 -1
  54. package/dist/packem_shared/PocketBaseStorage-BZNzWj09.js +1 -0
  55. package/dist/packem_shared/{Rest-DY1neM_3.js → Rest-BAcUFAgk.js} +1 -1
  56. package/dist/packem_shared/{Rest-DWrS4Z_j.js → Rest-DukkeDZe.js} +1 -1
  57. package/dist/packem_shared/S3Storage-7hG3izjU.js +1 -0
  58. package/dist/packem_shared/{SftpMetaStorage-DYqXwCdM.js → SftpMetaStorage-Cs8b7uBO.js} +1 -1
  59. package/dist/packem_shared/SftpStorage-DnigT9GT.js +1 -0
  60. package/dist/packem_shared/{SharePointMetaStorage-DVM5-X6g.js → SharePointMetaStorage-DTVKAx6f.js} +1 -1
  61. package/dist/packem_shared/{SharePointStorage-r934t5HX.js → SharePointStorage-D1cWu-14.js} +1 -1
  62. package/dist/packem_shared/{SupabaseMetaStorage-ivXoYVUu.js → SupabaseMetaStorage-D_fGv0d6.js} +1 -1
  63. package/dist/packem_shared/SupabaseStorage-DbIUa6NZ.js +1 -0
  64. package/dist/packem_shared/{Tus-d2hPK5nV.js → Tus-BYTcw17H.js} +1 -1
  65. package/dist/packem_shared/{Tus-BMd67Cnb.js → Tus-BrP4RFTg.js} +1 -1
  66. package/dist/packem_shared/{UploadThingMetaStorage-BvKNzgm7.js → UploadThingMetaStorage-CAQ1uTfv.js} +1 -1
  67. package/dist/packem_shared/UploadThingStorage-B1qw1GrM.js +1 -0
  68. package/dist/packem_shared/{VercelBlobMetaStorage-CwaqWucZ.js → VercelBlobMetaStorage-DY4zAB6M.js} +1 -1
  69. package/dist/packem_shared/VercelBlobStorage-u6xmp8ox.js +1 -0
  70. package/dist/packem_shared/{base-handler-core-Cwd9uq_E.js → base-handler-core-Ccvdhx-k.js} +1 -1
  71. package/dist/packem_shared/{base-handler-fetch-_BD4V1W2.js → base-handler-fetch-DzbThEWy.js} +1 -1
  72. package/dist/packem_shared/{base-handler-node-BDNRnVIc.js → base-handler-node-CmCpLlBt.js} +1 -1
  73. package/dist/packem_shared/default-BrhEhSqN.js +1 -0
  74. package/dist/packem_shared/{defaultCloudStorageFileNameValidation-hWLdEgOD.js → defaultCloudStorageFileNameValidation-DwDn0XB5.js} +1 -1
  75. package/dist/packem_shared/disk-storage-fWizVrge.js +1 -0
  76. package/dist/packem_shared/{disk-storage-with-checksum.d-Dm4agCey.d.ts → disk-storage-with-checksum.d-aYBmkg45.d.ts} +8 -2
  77. package/dist/packem_shared/{executors.d-Cut3Gstb.d.ts → executors.d-WGJGPSZs.d.ts} +1 -1
  78. package/dist/packem_shared/{gcs-meta-storage-Bwts-MUe.js → gcs-meta-storage-COq32th7.js} +1 -1
  79. package/dist/packem_shared/get-file-status-DLS18Zvd.js +1 -0
  80. package/dist/packem_shared/index.d-CYdFIB-w.d.ts +455 -0
  81. package/dist/packem_shared/isRetryableError-CBZ65V6T.js +1 -0
  82. package/dist/packem_shared/local-meta-storage-Dr891Iy7.js +1 -0
  83. package/dist/packem_shared/{local-meta-storage.d-qZQI1JUe.d.ts → local-meta-storage.d-CuvN-KQ3.d.ts} +1 -1
  84. package/dist/packem_shared/{media-transformer.d-lQ_RUjb5.d.ts → media-transformer.d-DfU7VbFl.d.ts} +2 -2
  85. package/dist/packem_shared/memory-storage.d-DRbE0WMO.d.ts +101 -0
  86. package/dist/packem_shared/part-match-D_NwyoF3.js +1 -0
  87. package/dist/packem_shared/{path-D7rMc9nq-B718mbm6.js → path-D7rMc9nq-CPbxyMDy.js} +1 -1
  88. package/dist/packem_shared/{rest-base-C-a7pXUc.js → rest-base-xrnOBxS9.js} +1 -1
  89. package/dist/packem_shared/s3-base-storage-CqAyWHR6.js +1 -0
  90. package/dist/packem_shared/{s3-base-storage.d-CDIOMTpp.d.ts → s3-base-storage.d-BrHiKWFw.d.ts} +9 -2
  91. package/dist/packem_shared/storage-uhIhcN-O.js +1 -0
  92. package/dist/packem_shared/{storage.d-BoJgdi1n.d.ts → storage.d-X6TimMHY.d.ts} +23 -1
  93. package/dist/packem_shared/{tus-base.d-C28C_AY9.d.ts → tus-base.d-Ds7xYAJC.d.ts} +3 -3
  94. package/dist/packem_shared/{types.d-CPxJpoPH.d.ts → types.d-B72PbsLY.d.ts} +2 -2
  95. package/dist/packem_shared/{types.d-DCPQvHDI.d.ts → types.d-C4QumoP1.d.ts} +2 -2
  96. package/dist/packem_shared/{types.d-C0MDnUYc.d.ts → types.d-a1grKnaX.d.ts} +1 -1
  97. package/dist/storage/aws/index.d.ts +9 -3
  98. package/dist/storage/aws/index.js +1 -1
  99. package/dist/storage/aws-light/index.d.ts +2 -2
  100. package/dist/storage/aws-light/index.js +1 -1
  101. package/dist/storage/azure/index.d.ts +1 -1
  102. package/dist/storage/azure/index.js +1 -1
  103. package/dist/storage/box/index.d.ts +2 -2
  104. package/dist/storage/box/index.js +1 -1
  105. package/dist/storage/bun-s3/index.d.ts +2 -2
  106. package/dist/storage/bun-s3/index.js +1 -1
  107. package/dist/storage/bunny/index.d.ts +2 -2
  108. package/dist/storage/bunny/index.js +1 -1
  109. package/dist/storage/cloudinary/index.d.ts +2 -2
  110. package/dist/storage/cloudinary/index.js +1 -1
  111. package/dist/storage/dropbox/index.d.ts +2 -2
  112. package/dist/storage/dropbox/index.js +1 -1
  113. package/dist/storage/firebase/index.d.ts +2 -2
  114. package/dist/storage/firebase/index.js +1 -1
  115. package/dist/storage/ftp/index.d.ts +2 -2
  116. package/dist/storage/ftp/index.js +1 -1
  117. package/dist/storage/gcs/index.d.ts +1 -1
  118. package/dist/storage/gcs/index.js +1 -1
  119. package/dist/storage/google-drive/index.d.ts +2 -2
  120. package/dist/storage/google-drive/index.js +1 -1
  121. package/dist/storage/local/index.d.ts +3 -3
  122. package/dist/storage/local/index.js +1 -1
  123. package/dist/storage/memory/index.d.ts +6 -0
  124. package/dist/storage/memory/index.js +1 -0
  125. package/dist/storage/netlify-blob/index.d.ts +2 -2
  126. package/dist/storage/netlify-blob/index.js +1 -1
  127. package/dist/storage/onedrive/index.d.ts +4 -4
  128. package/dist/storage/onedrive/index.js +1 -1
  129. package/dist/storage/pocketbase/index.d.ts +2 -2
  130. package/dist/storage/pocketbase/index.js +1 -1
  131. package/dist/storage/sftp/index.d.ts +2 -2
  132. package/dist/storage/sftp/index.js +1 -1
  133. package/dist/storage/sharepoint/index.d.ts +3 -3
  134. package/dist/storage/sharepoint/index.js +1 -1
  135. package/dist/storage/supabase/index.d.ts +2 -2
  136. package/dist/storage/supabase/index.js +1 -1
  137. package/dist/storage/uploadthing/index.d.ts +2 -2
  138. package/dist/storage/uploadthing/index.js +1 -1
  139. package/dist/storage/vercel-blob/index.d.ts +2 -2
  140. package/dist/storage/vercel-blob/index.js +1 -1
  141. package/dist/transformer/audio-transformer.d.ts +2 -2
  142. package/dist/transformer/image-transformer.d.ts +2 -2
  143. package/dist/transformer/index.d.ts +3 -3
  144. package/dist/transformer/video-transformer.d.ts +2 -2
  145. package/package.json +6 -2
  146. package/dist/packem_shared/AzureStorage-Cmr0nPDq.js +0 -1
  147. package/dist/packem_shared/BoxStorage-DYzAYPIr.js +0 -1
  148. package/dist/packem_shared/BunS3Storage-BvaFeKeu.js +0 -1
  149. package/dist/packem_shared/BunnyStorage-DsQndiy5.js +0 -1
  150. package/dist/packem_shared/CloudinaryStorage-DiK0T7N7.js +0 -1
  151. package/dist/packem_shared/DiskStorage-RvZNMWe7.js +0 -1
  152. package/dist/packem_shared/DiskStorageWithChecksum-eGOV3leX.js +0 -1
  153. package/dist/packem_shared/DropboxStorage-Dfd78aJL.js +0 -1
  154. package/dist/packem_shared/Files-CtggibJ-.js +0 -1
  155. package/dist/packem_shared/FirebaseStorage-C-FwZOYA.js +0 -2
  156. package/dist/packem_shared/FtpStorage-DzaP89bG.js +0 -1
  157. package/dist/packem_shared/GCStorage-1vA3xkFO.js +0 -1
  158. package/dist/packem_shared/GoogleDriveStorage-D_RaKV_j.js +0 -1
  159. package/dist/packem_shared/NetlifyBlobStorage-C-IkXF0_.js +0 -1
  160. package/dist/packem_shared/OneDriveStorage-C7rqK2Wp.js +0 -1
  161. package/dist/packem_shared/PocketBaseStorage-Cdgr5w88.js +0 -1
  162. package/dist/packem_shared/S3Storage-Dn3l4WkO.js +0 -1
  163. package/dist/packem_shared/SftpStorage-CBW6MBLV.js +0 -1
  164. package/dist/packem_shared/SupabaseStorage-DMRhLPNo.js +0 -1
  165. package/dist/packem_shared/UploadThingStorage-BjF_gRMY.js +0 -1
  166. package/dist/packem_shared/VercelBlobStorage-Dx2jywjl.js +0 -1
  167. package/dist/packem_shared/disk-storage-Bmvawf-b.js +0 -1
  168. package/dist/packem_shared/index.d-DSZjPbvW.d.ts +0 -230
  169. package/dist/packem_shared/isRetryableError-BhizNeAz.js +0 -1
  170. package/dist/packem_shared/local-meta-storage-Bi0mK6gD.js +0 -1
  171. package/dist/packem_shared/part-match-B5fLLmFw.js +0 -1
  172. package/dist/packem_shared/s3-base-storage-Ek1HinGR.js +0 -1
  173. package/dist/packem_shared/storage-B-NDsI-o.js +0 -1
@@ -1 +0,0 @@
1
- var w=Object.defineProperty;var u=(r,e)=>w(r,"name",{value:e,configurable:!0});import{CreateMultipartUploadCommand as k,UploadPartCommand as y,CompleteMultipartUploadCommand as b,AbortMultipartUploadCommand as B,ListPartsCommand as S,GetObjectCommand as h,HeadObjectCommand as T,DeleteObjectCommand as E,CopyObjectCommand as U,ListObjectsV2Command as x,waitUntilBucketExists as K,S3Client as L,PutObjectCommand as I}from"@aws-sdk/client-s3";import{fromIni as M}from"@aws-sdk/credential-providers";import{getSignedUrl as g}from"@aws-sdk/s3-request-presigner";import{S as P}from"./s3-base-storage-Ek1HinGR.js";import{Readable as m}from"node:stream";import{ReadableStream as C}from"node:stream/web";import O from"./S3File-BfmCOET4.js";import A from"./S3MetaStorage-vcriiosn.js";var j=Object.defineProperty,f=u((r,e)=>j(r,"name",{value:e,configurable:!0}),"d");const s=f(r=>r?.signal?{abortSignal:r.signal}:void 0,"sendOptions");class v{static{u(this,"T")}constructor(e,t){this.client=e}client;static{f(this,"S3ClientAdapter")}async createMultipartUpload(e,t){const a=new k({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),n=await this.client.send(a,s(t));if(!n.UploadId)throw new Error("Failed to create multipart upload");return{UploadId:n.UploadId}}async uploadPart(e,t){const a=e.Body instanceof C?m.fromWeb(e.Body):e.Body,n=new y({Body:a,Bucket:e.Bucket,ContentLength:e.ContentLength,ContentMD5:e.ContentMD5,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId}),o=await this.client.send(n,s(t));if(!o.ETag)throw new Error("Failed to upload part");return{ETag:o.ETag}}async completeMultipartUpload(e,t){const a=new b({Bucket:e.Bucket,Key:e.Key,MultipartUpload:{Parts:e.Parts.map(({ETag:o,PartNumber:i})=>({ETag:o,PartNumber:i}))},UploadId:e.UploadId}),n=await this.client.send(a,s(t));if(!n.Location)throw new Error("Failed to complete multipart upload");return{ETag:n.ETag,Location:n.Location}}async abortMultipartUpload(e,t){const a=new B({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a,s(t))}async listParts(e,t){const a=new S({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),n=await this.client.send(a,s(t)),o=[];if(n.Parts)for(const i of n.Parts)i.ETag&&i.PartNumber&&o.push({ETag:i.ETag,PartNumber:i.PartNumber,Size:i.Size});return{Parts:o.length>0?o:void 0}}async getObject(e,t){const a=new h({Bucket:e.Bucket,Key:e.Key}),n=await this.client.send(a,s(t));let o;if(n.Body){const i=n.Body;i instanceof m||typeof i=="object"&&"transform"in i&&i instanceof C?o=i:o=m.from(i)}return{Body:o,ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified,Metadata:n.Metadata}}async headObject(e,t){const a=new T({Bucket:e.Bucket,Key:e.Key}),n=await this.client.send(a,s(t));return{ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified}}async deleteObject(e,t){const a=new E({Bucket:e.Bucket,Key:e.Key});await this.client.send(a,s(t))}async copyObject(e,t){const a={Bucket:e.Bucket,CopySource:e.CopySource,Key:e.Key};e.StorageClass&&(a.StorageClass=e.StorageClass);const n=new U(a);await this.client.send(n,s(t))}async listObjectsV2(e,t){const a=new x({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,MaxKeys:e.MaxKeys}),n=await this.client.send(a,s(t));return{Contents:n.Contents?.map(o=>({Key:o.Key,LastModified:o.LastModified})),IsTruncated:n.IsTruncated,NextContinuationToken:n.NextContinuationToken}}async getPresignedUrl(e){const t=new y({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return g(this.client,t,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await K({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}var N=Object.defineProperty,D=u((r,e)=>N(r,"name",{value:e,configurable:!0}),"c");class X extends P{static name="s3";s3Api;rawClient;constructor(e){const{bucket:t=process.env.S3_BUCKET,region:a=process.env.S3_REGION}=e;if(!t)throw new Error("S3 bucket is not defined");if(!a)throw new Error("S3 region is not defined");e.region=a;const n=e.keyFile||process.env.S3_KEYFILE;n&&(e.credentials=M({configFilepath:n}));const o=new L(e);super({bucket:t,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:D(c=>{const d=c;if(d.$metadata){const l=d.$metadata.httpStatusCode;if(l&&[408,429,500,502,503,504].includes(l)||d.$fault==="server")return!0}return d.retryable??!1},"shouldRetry")}}),this.s3Api=new v(o,t),this.rawClient=o;const{metaStorage:i,metaStorageConfig:p}=e;if(!i){const c={...e,...p,logger:this.logger};"directory"in c||(this.meta=new A(c))}this.config.clientDirectUpload&&(this.onCreate=async()=>{})}normalizeError(e){return e.$metadata?{code:e.Code||e.name,message:e.message,name:e.name,statusCode:e.$metadata.httpStatusCode||500}:super.normalizeError(e)}async update({id:e},t){if(this.config.clientDirectUpload){const a=await this.getMeta(e);return this.buildPresigned({...a,...t})}return super.update({id:e},t)}async getStream({id:e},t){return this.instrumentOperation("getStream",async()=>{const a=this.getS3Api(),{Body:n,ContentLength:o,ContentType:i,ETag:p,Expires:c,LastModified:d}=await this.runOperation(t,l=>a.getObject({Bucket:this.bucket,Key:e},{signal:l}));return await this.checkIfExpired({expiredAt:c}),{headers:{"Content-Length":o?.toString()??"0","Content-Type":i,...p&&{ETag:p},...c&&{"X-Upload-Expires":c.toString()},...d&&{"Last-Modified":d.toString()}},size:Number(o),stream:n}})}get raw(){return this.rawClient}async getReadUrl(e,t){const a=new h({Bucket:this.bucket,Key:e,...t?.responseContentDisposition&&{ResponseContentDisposition:t.responseContentDisposition},...t?.responseContentType&&{ResponseContentType:t.responseContentType}});return g(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}async getUploadUrl(e,t){const a=new I({Bucket:this.bucket,Key:e,...t?.contentType&&{ContentType:t.contentType},...t?.contentLength!==void 0&&{ContentLength:t.contentLength}});return g(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}getS3Api(){return this.s3Api}getFileClass(){return O}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{X as default};
@@ -1 +0,0 @@
1
- var F=Object.defineProperty;var k=(h,a)=>F(h,"name",{value:a,configurable:!0});import{S as O}from"./index-B4ETk0Lu.js";import M from"ssh2-sftp-client";import{throwErrorCode as d,ERRORS as p}from"./ERRORS-CyOuSMLY.js";import{B as E}from"./storage-B-NDsI-o.js";import P from"./SftpFile-CQCxZNVq.js";import v from"./SftpMetaStorage-DYqXwCdM.js";import{i as w,n as A,o as l}from"./posix-dirname-CiHXPPnw.js";import{o as b,r as S}from"./part-match-B5fLLmFw.js";import{u as $}from"./update-size-DANV7aa2.js";import{o as x}from"./has-content-Bx2p8Okx.js";var L=Object.defineProperty,T=k((h,a)=>L(h,"name",{value:a,configurable:!0}),"l");const f=T(h=>{const a=h?.code,e=h instanceof Error?h.message:String(h);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},"isNotFoundError"),g=T(h=>{if(h instanceof Error&&h.name==="AbortError")return h;const a=new Error(h instanceof Error&&h.message?h.message:"The operation was aborted",{cause:h});return a.name="AbortError",a},"toAbortError");class K extends E{static name="sftp";checksumTypes=[];meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=w(a.rootFolderPath??""),this.meta=a.metaStorage??new v(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new P(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const n=await this.getMeta(t.id);if(n.status==="completed")return n}catch{}return t.bytesWritten=0,t.status=b(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&$(t,a.size),!S(a,t))return d(p.FILE_CONFLICT);const n=await this.lock(a.id);try{if(x(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return d(p.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return d(p.METHOD_NOT_ALLOWED,"SFTP storage does not support chunked or resumable uploads; send the file in a single request.");const r=await A(a.body),i=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,o=>this.run(o,async s=>{const c=l(i);c&&await s.mkdir(c,!0),await s.put(r,i)})),t.bytesWritten=r.length,t.size=r.length,t.path=i,t.ETag=O(r)}return t.status=b(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,n)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),n=t.path??this.keyToPath(t.name||a),r=await this.runOperation(e,i=>this.run(i,async o=>{try{return await o.get(n)}catch(s){if(f(s))return d(p.FILE_NOT_FOUND);throw s}}));return{content:r,contentType:t.contentType,ETag:t.ETag??O(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),n=t.path??this.keyToPath(t.name||a);await this.runOperation(e,i=>this.run(i,async o=>{try{await o.delete(n)}catch(s){if(!f(s))throw s}})),await this.deleteMeta(a);const r={...t,status:"deleted"};return await this.onDelete(r),r})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const n=await this.getMeta(a),r=n.path??this.keyToPath(n.name||a),i=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async c=>{const u=await c.get(r),m=l(i);m&&await c.mkdir(m,!0),await c.put(u,i)}));const o={...n,id:e,name:e,path:i};return await this.saveMeta(o),o})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const n=await this.getMeta(a),r=n.path??this.keyToPath(n.name||a),i=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async c=>{const u=l(i);u&&await c.mkdir(u,!0);try{await c.rename(r,i)}catch(m){try{const y=await c.get(r);await c.put(y,i),await c.delete(r)}catch(y){throw new AggregateError([m,y],`SFTP move failed: rename and copy+delete fallback both failed for "${r}" → "${i}"`)}}}));const o={...n,id:e,name:e,path:i};await this.saveMeta(o);try{await this.deleteMeta(a)}catch{}return o})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,n=>this.run(n,async r=>{const i=[];return await this.walkList(r,t,i),i}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const n=t.path??this.keyToPath(t.name||a);return this.runOperation(e,r=>this.run(r,async i=>{const o=await i.exists(n);return o==="-"||o==="l"}))})}async walkList(a,e,t){let n;try{n=await a.list(e||".")}catch(r){if(f(r))return;throw r}for(const r of n){const i=e?`${e}/${r.name}`:r.name;if(r.type==="d"){await this.walkList(a,i,t);continue}if(r.type!=="-")continue;const o=this.pathToKey(i);if(!o)continue;const s=new P({contentType:"application/octet-stream",metadata:{},originalName:r.name});s.id=o,s.name=o,s.path=i,s.size=r.size,s.modifiedAt=new Date(r.modifyTime).toISOString(),t.push(s)}}async run(a,e){const t=new M;if(a?.aborted)throw g(a.reason);const n=T(()=>{t.end()},"onAbort");a?.addEventListener("abort",n,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(r){throw a?.aborted?g(r):r}finally{a?.removeEventListener("abort",n),await t.end()}}keyToPath(a){const e=w(a);e&&E.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":this.rootFolderPath.startsWith("/")?`/${t.join("/")}`:t.join("/")}pathToKey(a){const e=w(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{K as default};
@@ -1 +0,0 @@
1
- var g=Object.defineProperty;var u=(o,t)=>g(o,"name",{value:t,configurable:!0});import{StorageClient as w}from"@supabase/storage-js";import{throwErrorCode as p,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import{B as y}from"./storage-B-NDsI-o.js";import c from"./SupabaseFile-DZ1iv9gM.js";import b from"./SupabaseMetaStorage-ivXoYVUu.js";import{o as l,r as E}from"./part-match-B5fLLmFw.js";import{u as k}from"./update-size-DANV7aa2.js";import{o as S}from"./has-content-Bx2p8Okx.js";var O=Object.defineProperty,h=u((o,t)=>O(o,"name",{value:t,configurable:!0}),"p");const f=3600*24*7,U=h(o=>{if(!o||!/^attachment(\s*;|\s*$)/i.test(o.trim()))return;const t=o.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),a=t?.[1]??t?.[2];if(!a)return!0;try{return decodeURIComponent(a.trim())}catch{return a.trim()}},"parseDownloadOption"),C=h(async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream");class z extends y{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(t){if(super(t),this.bucket=t.bucket,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,f),t.client)this.storageClient=t.client;else{const a=t.url??process.env.SUPABASE_URL,e=t.serviceKey??process.env.SUPABASE_SERVICE_ROLE_KEY??process.env.SUPABASE_KEY;if(!a)throw new Error("Supabase storage: `url` is required (or set SUPABASE_URL).");if(!e)throw new Error("Supabase storage: `serviceKey` is required (or set SUPABASE_SERVICE_ROLE_KEY / SUPABASE_KEY).");const r=a.replace(/\/+$/,"")+(a.endsWith("/storage/v1")?"":"/storage/v1");this.storageClient=new w(r,{apikey:e,Authorization:`Bearer ${e}`},t.fetch)}this.meta=t.metaStorage??new b(t.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucket,e.path=e.name,await this.validate(e);try{const r=await this.getMeta(e.id);if(r.bytesWritten>=0)return r}catch{}return e.bytesWritten=0,e.status=l(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&k(e,t.size),!E(t,e))throw new Error("File part does not match");const r=await this.lock(t.id);try{if(S(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await C(t.body),n=e.path??e.name,{data:s,error:m}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).upload(n,i,{contentType:e.contentType,upsert:!0}));if(m)throw m;e.bytesWritten=i.length,e.size=i.length,e.path=s?.path??n,e.ETag=s?.id}return e.status=l(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,r)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const r=e?.path??e?.name??t,{error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).remove([r]));if(i&&i.message&&!/not.*found/i.test(i.message))throw i;return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.bucket,id:t,name:t,path:r,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}const{data:r,error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).exists(e));return i?!1:!!r})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,r;try{r=await this.checkIfExpired(await this.getMeta(t)),e=r.path??r.name??t}catch{}const{data:i,error:n}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).download(e));if(n||!i)throw n??new Error(`Supabase: object not found at "${e}"`);const s=Buffer.from(await this.runOperation(a,()=>i.arrayBuffer()));return{content:s,contentType:r?.contentType??i.type??"application/octet-stream",ETag:r?.ETag,expiredAt:r?.expiredAt,id:t,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??e,originalName:r?.originalName??e,size:r?.size??s.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const r=(await this.getMetaSafe(t))?.path??t,i=a,{error:n}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).copy(r,i));if(n)throw n;const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=i,s.bucket=this.bucket,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const r=(await this.getMetaSafe(t))?.path??t,{error:i}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).move(r,a));if(i)throw i;const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucket;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const{data:e,error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).list("",{limit:t}));if(r)throw r;return(e??[]).map(i=>{const n=new c({contentType:i.metadata?.mimetype??"application/octet-stream",metadata:i.metadata??{},originalName:i.name});return n.id=i.name,n.name=i.name,n.path=i.name,n.bucket=this.bucket,n.size=typeof i.metadata?.size=="number"?i.metadata.size:void 0,n.createdAt=i.created_at??void 0,n.modifiedAt=i.updated_at??void 0,n.ETag=i.metadata?.eTag??i.id??void 0,n})},{limit:t})}async getReadUrl(t,a){const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{data:r,error:i}=await this.storageClient.from(this.bucket).createSignedUrl(t,e,{download:U(a?.responseContentDisposition)});return i||!r?p(d.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUrl failed"):r.signedUrl}async getUploadUrl(t,a){const{data:e,error:r}=await this.storageClient.from(this.bucket).createSignedUploadUrl(t);return r||!e?p(d.METHOD_NOT_ALLOWED,r?.message??"Supabase: createSignedUploadUrl failed"):e.signedUrl}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=h(t=>this.deleteMeta(t.id),"internalOnComplete")}export{z as default};
@@ -1 +0,0 @@
1
- var T=Object.defineProperty;var l=(n,t)=>T(n,"name",{value:t,configurable:!0});import{UTApi as U,UTFile as h}from"uploadthing/server";import{throwErrorCode as m,ERRORS as f}from"./ERRORS-CyOuSMLY.js";import{B as I}from"./storage-B-NDsI-o.js";import d from"./UploadThingFile-BpG9mE8K.js";import O from"./UploadThingMetaStorage-BvKNzgm7.js";import{o as y,r as E}from"./part-match-B5fLLmFw.js";import{u as k}from"./update-size-DANV7aa2.js";import{o as v}from"./has-content-Bx2p8Okx.js";var b=Object.defineProperty,u=l((n,t)=>b(n,"name",{value:t,configurable:!0}),"c");const w=3600*24*7,x=u(n=>{let t;try{t=typeof atob=="function"?atob(n):Buffer.from(n,"base64").toString("utf8")}catch(e){throw new Error(`UploadThing: token is not valid base64: ${e.message}`)}let a;try{a=JSON.parse(t)}catch(e){throw new Error(`UploadThing: token does not decode to JSON: ${e.message}`)}if(!a||typeof a!="object"||typeof a.apiKey!="string"||typeof a.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return a},"decodeToken"),N=u(async n=>{const t=[];for await(const a of n)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream"),g=u(n=>{const t=n.lastIndexOf("/");return t===-1?n:n.slice(t+1)},"basename");class F extends I{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(t){super(t);const a=t.token??process.env.UPLOADTHING_TOKEN;if(t.client)this.utapi=t.client;else{if(!a)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new U({defaultKeyType:"customId",token:a})}if(!a)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=x(a).appId,this.acl=t.acl??"public-read",this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w),this.meta=t.metaStorage??new O(t.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new d(t);e.name=this.namingFunction(e),e.customId=e.name,await this.validate(e);try{const i=await this.getMeta(e.id);if(i.bytesWritten>=0)return i}catch{}return e.bytesWritten=0,e.status=y(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&k(e,t.size),!E(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(v(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await N(t.body),p=new Blob([new Uint8Array(r)],{type:e.contentType}),o=new h([p],g(e.name||e.id),{customId:e.name||e.id,type:e.contentType}),s=await this.runOperation(a,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const{data:c}=s;e.bytesWritten=r.length,e.size=r.length,e.ufsKey=c.key,e.url=c.ufsUrl??c.url,e.ETag=c.fileHash,e.fileHash=c.fileHash}return e.status=y(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,i)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const i=e?.customId??e?.name??t;return await this.runOperation(a,()=>this.utapi.deleteFiles(i)),e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:t}),{customId:i,id:t,name:t,status:"deleted"})})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e,i=t;try{e=await this.checkIfExpired(await this.getMeta(t)),i=e.customId??e.name??t}catch{}const r=await this.resolveFetchUrl(i,a),p=await this.runOperation(a,()=>fetch(r));if(!p.ok)throw new Error(`UploadThing: fetch failed: ${p.status} ${p.statusText} for ${i}`);const o=Buffer.from(await p.arrayBuffer());return{content:o,contentType:e?.contentType??p.headers.get("content-type")??"application/octet-stream",ETag:e?.ETag??p.headers.get("etag")??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt,name:e?.name??i,originalName:e?.originalName??i,size:e?.size??o.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=await this.get({id:t},e),r=new Blob([new Uint8Array(i.content)],{type:i.contentType}),p=new h([r],g(a),{customId:a,type:i.contentType}),o=await this.runOperation(e,()=>this.utapi.uploadFiles(p,{acl:this.acl}));if(o.error)throw new Error(o.error.message);const s=new d({contentType:i.contentType,metadata:{},originalName:a});return s.id=a,s.name=a,s.customId=a,s.size=typeof i.size=="string"?Number(i.size):i.size,s.ufsKey=o.data.key,s.url=o.data.ufsUrl??o.data.url,s.ETag=o.data.fileHash,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=await this.copy(t,a,e);return await this.delete({id:t},e),i})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>(await this.runOperation(a,()=>this.utapi.listFiles({limit:t}))).files.map(e=>{const i=e.customId??e.key,r=new d({contentType:"application/octet-stream",metadata:{},originalName:i});return r.id=i,r.name=i,r.customId=e.customId??void 0,r.ufsKey=e.key,r.size=e.size,r.modifiedAt=e.uploadedAt?new Date(e.uploadedAt).toISOString():void 0,r}),{limit:t})}async getReadUrl(t,a){if(a?.responseContentDisposition)return m(f.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition` is not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,w),{ufsUrl:i}=await this.utapi.generateSignedURL(t,{expiresIn:e,keyType:"customId"});return i}async getUploadUrl(t,a){return m(f.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(t,a){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const{ufsUrl:e}=await this.runOperation(a,()=>this.utapi.generateSignedURL(t,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return e}internalOnComplete=u(t=>this.deleteMeta(t.id),"internalOnComplete")}export{F as default};
@@ -1 +0,0 @@
1
- var E=Object.defineProperty;var u=(c,e)=>E(c,"name",{value:e,configurable:!0});import{put as d,list as h,del as m,copy as p}from"@vercel/blob";import{a as g}from"./detect-file-type-5JhzC9RU.js";import{B as v,t as T}from"./storage-B-NDsI-o.js";import{v as b}from"./local-meta-storage-Bi0mK6gD.js";import f from"./VercelBlobFile-Cni_1qwD.js";import{o as w,r as B}from"./part-match-B5fLLmFw.js";import{u as _}from"./update-size-DANV7aa2.js";import{o as k}from"./has-content-Bx2p8Okx.js";var I=Object.defineProperty,C=u((c,e)=>I(c,"name",{value:e,configurable:!0}),"p");class y extends v{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:p,credentials:this.credentials,del:m,list:h,put:d}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=y.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:i,metaStorageConfig:t}=e;this.meta=i||new b(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const i=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,r=t?.startsWith("store_")?t.slice(6):t;if(i&&r)return{oidcToken:i,storeId:r};if(i||r)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${i?"set":"missing"}, storeId=${r?"set":"missing"}.`);const a=process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN;if(a)return{token:a};throw new Error("Vercel Blob credentials are required. Provide `token`, an `oidcToken`+`storeId` pair, or set BLOB_READ_WRITE_TOKEN / (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) env vars.")}async create(e,i){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?T(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const r=new f(t);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);if(a.bytesWritten>=0)return a}catch{}return r.bytesWritten=0,r.status=w(r),await this.saveMeta(r),await this.onCreate(r),r})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&_(t,e.size),!B(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(k(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],n=e.body;for await(const o of n)a.push(Buffer.from(o));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await g(s);o?.mime&&(t.contentType=o.mime)}catch{}const O=new Blob([s],{type:t.contentType}),l=await this.runOperation(i,()=>d(t.name,O,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=l.url,t.pathname=l.pathname,t.downloadUrl=l.downloadUrl,t.bytesWritten=s.length}return t.status=w(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);const{url:r}=t;t.status="deleted";try{await this.runOperation(i,()=>m(r,{...this.credentials}))}catch(n){this.logger?.error("Failed to delete blob from Vercel Blob:",n);const s=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},i){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:r}=t;return(await this.runOperation(i,()=>fetch(r,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},i){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.url||t.url.length===0)throw new Error("File URL not found");const{url:r}=t,a=await this.runOperation(i,()=>fetch(r)),n=Buffer.from(await this.runOperation(i,()=>a.arrayBuffer()));return{content:n,contentType:t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||n.length}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const r=await this.getMeta(e);if(!r.url)throw new Error("Source file URL not found");const a=r.url,n=await this.runOperation(t,()=>p(a,i,{access:"public",...this.credentials}));return{...r,id:i,name:i,pathname:n.pathname,url:n.url}})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const r=await this.copy(e,i,t);return await this.delete({id:e},t),r})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>(await this.runOperation(i,()=>h({limit:e,...this.credentials}))).blobs.map(t=>{const r=new f({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return r.createdAt=t.uploadedAt?.toISOString(),r.id=t.pathname,r.modifiedAt=t.uploadedAt?.toISOString(),r.name=t.pathname,r.pathname=t.pathname,r.size=t.size,r.url=t.url,r.downloadUrl=t.downloadUrl,r}),{limit:e})}internalOnComplete=C(e=>this.deleteMeta(e.id),"internalOnComplete");shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{y as default};
@@ -1 +0,0 @@
1
- var ct=Object.defineProperty;var h=(e,t)=>ct(e,"name",{value:t,configurable:!0});import{createReadStream as lt,createWriteStream as ut}from"node:fs";import{truncate as mt,stat as C,copyFile as z}from"node:fs/promises";import{Transform as Q,PassThrough as dt,pipeline as ht}from"node:stream";import{f as L,l as yt,w as H,U as b,_ as ft,i as pt,v as gt,B as wt,y as W}from"./local-meta-storage-Bi0mK6gD.js";import{createRequire as P}from"node:module";import{K as w,C as F,M as K,L as bt,Q as vt,O as Et}from"./path-D7rMc9nq-B718mbm6.js";import{S as St}from"./index-B4ETk0Lu.js";import{d as $t}from"./detect-file-type-5JhzC9RU.js";import{throwErrorCode as g,ERRORS as y,isUploadError as Ot}from"./ERRORS-CyOuSMLY.js";import{createHash as Tt}from"node:crypto";import{B as Ft,a as kt,t as Nt}from"./storage-B-NDsI-o.js";import Pt from"./File-BhfUgJjs.js";import{o as B,r as Dt}from"./part-match-B5fLLmFw.js";import{u as _t}from"./update-size-DANV7aa2.js";import{o as It}from"./has-content-Bx2p8Okx.js";var Mt=Object.defineProperty,xt=h((e,t)=>Mt(e,"name",{value:t,configurable:!0}),"i$4"),Rt=Object.defineProperty,X=xt((e,t)=>Rt(e,"name",{value:t,configurable:!0}),"t");const Lt=P(import.meta.url),$=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,jt=X(e=>{if(typeof $<"u"&&$.versions&&$.versions.node){const[t,r]=$.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return $.getBuiltinModule(e)}return Lt(e)},"__cjs_getBuiltinModule"),{lstat:At,writeFile:Ct}=jt("node:fs/promises");var zt=Object.defineProperty,Wt=X((e,t)=>zt(e,"name",{value:t,configurable:!0}),"o");const x=Wt(async e=>{L(e);try{const t=await At(e);if(!t.isFile())throw new Error(`Ensure path exists, expected 'file', got '${String(yt(t))}'`)}catch(t){if(t.code==="ENOENT"){await H(w(b(e))),await Ct(e,new Uint8Array);return}throw t}},"ensureFile");var Bt=Object.defineProperty,q=h((e,t)=>Bt(e,"name",{value:t,configurable:!0}),"t$1"),Ut=Object.defineProperty,Y=q((e,t)=>Ut(e,"name",{value:t,configurable:!0}),"t"),Vt=Object.defineProperty,Qt=Y((e,t)=>Vt(e,"name",{value:t,configurable:!0}),"t");let U=class extends Error{static{h(this,"l")}static{q(this,"c")}static{Y(this,"i")}static{Qt(this,"WalkError")}root;constructor(t,r){super(`${t instanceof Error?t.message:String(t)} for path "${r}"`),this.cause=t,this.root=r}get name(){return"WalkError"}set name(t){throw new Error("Cannot overwrite name of WalkError")}};var Ht=Object.defineProperty,Kt=h((e,t)=>Ht(e,"name",{value:t,configurable:!0}),"l$1"),Xt=Object.defineProperty,G=Kt((e,t)=>Xt(e,"name",{value:t,configurable:!0}),"t"),qt=Object.defineProperty,Yt=G((e,t)=>qt(e,"name",{value:t,configurable:!0}),"g");const V=Yt(e=>{const t=e.replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,String.raw`\.`).replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");return new RegExp(`^${t}$`)},"globToRegExp");var Gt=Object.defineProperty,Jt=G((e,t)=>Gt(e,"name",{value:t,configurable:!0}),"t");const N=Jt((e,t,r,i)=>{if(Array.isArray(t)&&t.length>0&&!t.some(a=>e.endsWith(a)))return!1;const n=e.includes("\\")?e.replaceAll("\\","/"):e;return r&&!r.some(a=>a.test(n))?!1:!i?.some(a=>a.test(n))},"walkInclude");var Zt=Object.defineProperty,J=h((e,t)=>Zt(e,"name",{value:t,configurable:!0}),"f$2"),te=Object.defineProperty,j=J((e,t)=>te(e,"name",{value:t,configurable:!0}),"y");const ee=P(import.meta.url),O=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,re=j(e=>{if(typeof O<"u"&&O.versions&&O.versions.node){const[t,r]=O.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return O.getBuiltinModule(e)}return ee(e)},"__cjs_getBuiltinModule"),{readdir:ie,realpath:ae,stat:se}=re("node:fs/promises");var ne=Object.defineProperty,p=j((e,t)=>ne(e,"name",{value:t,configurable:!0}),"r");const oe=p(async e=>{const t=bt(e),r=vt(t),i=await se(t);return{isDirectory:p(()=>i.isDirectory(),"isDirectory"),isFile:p(()=>i.isFile(),"isFile"),isSymbolicLink:p(()=>i.isSymbolicLink(),"isSymbolicLink"),name:r,path:t}},"_createWalkEntry");async function*k(e,{extensions:t,followSymlinks:r=!1,includeDirs:i=!0,includeFiles:n=!0,includeSymlinks:a=!0,match:s,maxDepth:l=Number.POSITIVE_INFINITY,skip:u}={}){if(L(e),l<0)return;const m=s?s.map(c=>typeof c=="string"?V(c):c):void 0,d=u?u.map(c=>typeof c=="string"?V(c):c):void 0;if(e=F(b(e)),i&&N(e,t,m,d)&&(yield await oe(e)),!(l<1||!N(e,void 0,void 0,d)))try{const c=await ie(e,{withFileTypes:!0});for(const o of c){let f=K(e,o.name);if(o.isSymbolicLink())if(r)f=await ae(f);else if(a&&N(f,t,m,d)){yield{isDirectory:p(()=>o.isDirectory(),"isDirectory"),isFile:p(()=>o.isFile(),"isFile"),isSymbolicLink:p(()=>o.isSymbolicLink(),"isSymbolicLink"),name:o.name,path:f};continue}else continue;o.isDirectory()?yield*k(f,{extensions:t,followSymlinks:r,includeDirs:i,includeFiles:n,includeSymlinks:a,match:m,maxDepth:l-1,skip:d}):o.isFile()&&n&&N(f,t,m,d)&&(yield{isDirectory:p(()=>o.isDirectory(),"isDirectory"),isFile:p(()=>o.isFile(),"isFile"),isSymbolicLink:p(()=>o.isSymbolicLink(),"isSymbolicLink"),name:o.name,path:f})}}catch(c){throw c instanceof U?c:new U(c,e)}}h(k,"p$2");J(k,"D");j(k,"g");p(k,"walk");var ce=Object.defineProperty,Z=h((e,t)=>ce(e,"name",{value:t,configurable:!0}),"t"),le=Object.defineProperty,A=Z((e,t)=>le(e,"name",{value:t,configurable:!0}),"t");const ue=P(import.meta.url),T=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,me=A(e=>{if(typeof T<"u"&&T.versions&&T.versions.node){const[t,r]=T.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return T.getBuiltinModule(e)}return ue(e)},"__cjs_getBuiltinModule"),{accessSync:de}=me("node:fs");var he=Object.defineProperty,ye=A((e,t)=>he(e,"name",{value:t,configurable:!0}),"o");function D(e,t=ft){L(e),e=b(e);try{return de(e,t),!0}catch{return!1}}h(D,"i$1");Z(D,"d");A(D,"m");ye(D,"isAccessibleSync");var fe=Object.defineProperty,tt=h((e,t)=>fe(e,"name",{value:t,configurable:!0}),"v"),pe=Object.defineProperty,S=tt((e,t)=>pe(e,"name",{value:t,configurable:!0}),"i");const ge=P(import.meta.url),v=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,et=S(e=>{if(typeof v<"u"&&v.versions&&v.versions.node){const[t,r]=v.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return v.getBuiltinModule(e)}return ge(e)},"__cjs_getBuiltinModule"),{cwd:_}=v,{mkdir:we,rename:be,copyFile:ve,unlink:Ee}=et("node:fs/promises"),{mkdirSync:Se,renameSync:$e,copyFileSync:Oe,unlinkSync:Te}=et("node:fs");var Fe=Object.defineProperty,rt=S((e,t)=>Fe(e,"name",{value:t,configurable:!0}),"o");class ke extends Error{static{h(this,"V")}static{tt(this,"O")}static{S(this,"a")}static{rt(this,"SameDirectoryError")}constructor(t,r){super(`Source directory "${w(t)}" does not match destination directory "${w(r)}"`),this.name="SameDirectoryError"}}const it=rt((e,t)=>{if(!e||!t)throw new Error("Source and destination paths must not be empty");if(w(e)!==w(t))throw new ke(e,t)},"validateSameDirectory");var Ne=Object.defineProperty,Pe=S((e,t)=>Ne(e,"name",{value:t,configurable:!0}),"m$1");const at=Pe(async(e,t,{cwd:r,directoryMode:i,overwrite:n,validateDirectory:a})=>{if(r&&(e=F(r,e),t=F(r,t)),a&&it(e,t),!n&&await pt(t))throw new Error(`The destination file exists: ${t}`);await we(w(t),{mode:i,recursive:!0});try{await be(e,t)}catch(s){if(s.code==="EXDEV")await ve(e,t),await Ee(e);else throw s}},"internalMoveFile");var De=Object.defineProperty,_e=S((e,t)=>De(e,"name",{value:t,configurable:!0}),"m");const st=_e((e,t,{cwd:r,directoryMode:i,overwrite:n,validateDirectory:a})=>{if(r&&(e=F(r,e),t=F(r,t)),a&&it(e,t),!n&&D(t))throw new Error(`The destination file exists: ${t}`);Se(w(t),{mode:i,recursive:!0});try{$e(e,t)}catch(s){if(s.code==="EXDEV")Oe(e,t),Te(e);else throw s}},"internalMoveFileSync");var Ie=Object.defineProperty,I=S((e,t)=>Ie(e,"name",{value:t,configurable:!0}),"i");const Me=I(async(e,t,r={})=>{const i={overwrite:!0,validateDirectory:!1,...r,cwd:r.cwd?b(r.cwd):_()};await at(e,t,i)},"move");I((e,t,r)=>{const i={overwrite:!0,validateDirectory:!1,...r};i.cwd=i.cwd?b(i.cwd):_(),st(e,t,i)},"moveSync");I(async(e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?b(i.cwd):_(),await at(e,t,i)},"rename");I((e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?b(i.cwd):_(),st(e,t,i)},"renameSync");var xe=Object.defineProperty,nt=h((e,t)=>xe(e,"name",{value:t,configurable:!0}),"r");class Re extends Q{static{h(this,"StreamChecksum")}constructor(t,r,i="base64"){super(),this.checksum=t,this.algorithm=r,this.encoding=i,this.hash=Tt(r)}checksum;algorithm;encoding;static{nt(this,"StreamChecksum")}length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(t,r,i){this.push(t),this.hash.update(t),this.length+=t.length,i()}_flush(t){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?t(new Error("Checksum mismatch")):t()}}const Le=nt((e,t,r="base64")=>t?new Re(e,t,r):new dt,"streamChecksum");var je=Object.defineProperty,Ae=h((e,t)=>je(e,"name",{value:t,configurable:!0}),"o");class Ce extends Q{static{h(this,"m")}constructor(t=Number.POSITIVE_INFINITY){super(),this.limit=t}limit;static{Ae(this,"StreamLength")}length=0;_transform(t,r,i){const n=this.length+t.length;this.limit>=n?(this.push(t),this.length=n,i()):i(new Error("Stream length limit exceeded"))}}var ze=Object.defineProperty,R=h((e,t)=>ze(e,"name",{value:t,configurable:!0}),"p");class E extends Ft{static name="disk";checksumTypes=["md5","sha1"];get raw(){return{directory:this.directory}}directory;meta;constructor(t){const r={...t,fileNameValidation:t.fileNameValidation??kt};if(super(r),this.directory=r.directory,r.metaStorage)this.meta=r.metaStorage;else{const i={...r,...r.metaStorageConfig,logger:this.logger};this.meta=new gt(i)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(i=>{this.logger?.error("Storage access check failed: %O",i)})}normalizeError(t){return super.normalizeError(t)}async create(t){return this.instrumentOperation("create",async()=>{const r={...t};if(t.ttl){const a=typeof t.ttl=="string"?Nt(t.ttl):t.ttl;a!==void 0&&(r.expiredAt=Date.now()+a)}r.size!==void 0&&Number(r.size)<0&&g(y.REQUEST_ENTITY_TOO_LARGE,"Request entity too large");const i=new Pt(r);try{const a=await this.getMeta(i.id);if(a.status==="completed")return a}catch{}i.name=this.namingFunction(i),(i.size===void 0||Number.isNaN(i.size))&&(i.size===void 0||(i.size=this.maxUploadSize)),await this.validate(i);const n=this.getFilePath(i.name);try{await x(n),i.bytesWritten=0}catch(a){const s=this.normalizeError(a instanceof Error?a:new Error(String(a)));await this.onError(s),g(y.FILE_ERROR,s.message)}return i.status=B(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(t){return this.instrumentOperation("write",async()=>{let r;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?r=t:(r=await this.getMeta(t.id),await this.checkIfExpired(r)),r.status==="completed")return r;if(t.size!==void 0&&_t(r,t.size),!Dt(t,r))return g(y.FILE_CONFLICT);const i=this.getFilePath(r.name),n=await this.lock(i);try{const a=t.start||0;if(await x(i),r.bytesWritten===0&&(r.bytesWritten=a),It(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return g(y.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(r.bytesWritten===0||Number.isNaN(r.bytesWritten))&&(!r.contentType||r.contentType==="application/octet-stream"))try{const{fileType:c,stream:o}=await $t(t.body);c?.mime&&(r.contentType=c.mime),t.body=o}catch{}const s=t.signal,l={...r,...t,body:t.body};s&&(l.signal=s);const[u,m]=await this.lazyWrite(l);if(m)return await mt(i,r.bytesWritten),g(m);const d=a+(t.contentLength||0);r.bytesWritten=Math.max(r.bytesWritten||0,d),r.bytesWritten=Math.max(r.bytesWritten||0,u),r.status=B(r),await this.saveMeta(r)}else await x(i),r.bytesWritten=0;return r}catch(a){if(Ot(a))throw a;const s=this.normalizeError(a instanceof Error?a:new Error(String(a)));return await this.onError(s),g(y.FILE_ERROR,(typeof s.message=="string"?s.message:String(a))||String(a))}finally{await this.unlock(i,n)}})}async get({id:t}){return this.instrumentOperation("get",async()=>{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:i,contentType:n,expiredAt:a,metadata:s,modifiedAt:l,name:u,originalName:m,size:d}=r;let c;try{c=await wt(this.getFilePath(u),{buffer:!0})}catch(o){const f=o;if(f.code==="ENOENT"||f.code==="EPERM"){const M=this.normalizeError(o instanceof Error?o:new Error(f.message||String(o)));return await this.onError(M),g(y.FILE_NOT_FOUND,(typeof M.message=="string"?M.message:String(o))||String(o))}const ot=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(ot),o}return{content:c,contentType:n,ETag:St(c),expiredAt:a,id:t,metadata:s,modifiedAt:l,name:u,originalName:m,size:d||i}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{const r=await this.getMeta(t),i=this.getFilePath(r.name);return await C(i),!0}catch{return!1}})}async getStream({id:t}){return this.instrumentOperation("getStream",async()=>{try{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:i,contentType:n,expiredAt:a,modifiedAt:s,name:l,size:u}=r,m=lt(this.getFilePath(l));return{headers:{"Content-Length":String(u||i),"Content-Type":n,...a&&{"X-Upload-Expires":a.toString()},...s&&{"Last-Modified":s.toString()}},size:u||i,stream:m}}catch(r){const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));throw await this.onError(i),g(y.FILE_NOT_FOUND,(typeof i.message=="string"?i.message:String(r))||String(r))}})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const r=await this.getMeta(t);await W(this.getFilePath(r.name)),await this.deleteMeta(t);const i={...r,status:"deleted"};return await this.onDelete(i),i})}async copy(t,r){return this.instrumentOperation("copy",async()=>{E.assertSafeId(t),E.assertSafeId(r);const i=await this.getMeta(t);return await z(this.getFilePath(i.name),this.getFilePath(r)),{...i,name:r}})}async move(t,r){return this.instrumentOperation("move",async()=>{E.assertSafeId(t),E.assertSafeId(r);const i=await this.getMeta(t),n=this.getFilePath(i.name),a=this.getFilePath(r);try{await Me(n,a)}catch(s){if(s?.code==="EXDEV")await z(n,a),await W(n);else{const l=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(l),s}}return{...i,id:i.id,name:r}})}async list(){return this.instrumentOperation("list",async()=>{const t={followSymlinks:!1,includeDirs:!1,includeFiles:!0,skip:["*.META$"]},r=[],{directory:i}=this,n=R(s=>s.replaceAll("\\","/"),"toPosix"),a=n(i);for await(const s of k(i,t)){const{suffix:l}=this.meta,{path:u}=s;if(!u.includes(l)){const{birthtime:m,ctime:d,mtime:c}=await C(u),o=n(u),f=o.startsWith(a)?o.slice(a.length):o;r.push({createdAt:m||d,id:f,modifiedAt:c})}}return r})}getFilePath(t){return E.assertSafeId(t),Et(t)&&g(y.INVALID_FILE_NAME,`Invalid file id: "${t}"`),K(this.directory,t)}lazyWrite(t){return new Promise((r,i)=>{const n=ut(this.getFilePath(t.name),{flags:"r+",start:t.start}),a=new Ce(t.contentLength||t.size-t.start),s=Le(t.checksum,t.checksumAlgorithm),l=!t.checksum,{signal:u}=t,m=R(()=>{n.close(),a.destroy(),s.destroy()},"cleanupStreams"),d=R(c=>{m(),r([Number.NaN,c])},"failWithCode");if(a.on("error",()=>{d(y.FILE_CONFLICT)}),s.on("error",()=>{d(y.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{d(l?void 0:y.REQUEST_ABORTED)}),t.body.on("error",c=>{m(),i(c)}),u?.aborted){d(l?void 0:y.REQUEST_ABORTED);return}u&&u.addEventListener("abort",()=>{m(),n.destroy(),a.destroy(),s.destroy(),t.body.destroy(),r([Number.NaN,l?void 0:y.REQUEST_ABORTED])}),ht(t.body,a,s,n,c=>{if(c){if(m(),u?.aborted){r([Number.NaN,l?void 0:y.REQUEST_ABORTED]);return}r([Number.NaN,y.FILE_ERROR]);return}r([t.start+n.bytesWritten])})})}async accessCheck(){await H(this.directory)}}export{E as f,Ce as m,Le as s,x as y};
@@ -1,230 +0,0 @@
1
- import { O as OperationOptions, B as BaseStorage } from "./storage.d-BoJgdi1n.js";
2
- /**
3
- * Web-standard and Node-native body types accepted by {@link Files.upload}.
4
- */
5
- type FileBody = ArrayBuffer | ArrayBufferView | Blob | Buffer | NodeJS.ReadableStream | ReadableStream<Uint8Array> | string;
6
- interface UploadOptions {
7
- contentType?: string;
8
- metadata?: Record<string, unknown>;
9
- /**
10
- * Explicit byte length. Required for {@link NodeJS.ReadableStream} and Web `ReadableStream`
11
- * inputs because their length is not derivable from the value itself; ignored otherwise.
12
- */
13
- size?: number;
14
- storageClass?: string;
15
- }
16
- interface SignedReadUrlOptions {
17
- expiresIn?: number;
18
- responseContentDisposition?: string;
19
- responseContentType?: string;
20
- }
21
- interface SignedUploadUrlOptions {
22
- contentLength?: number;
23
- contentType?: string;
24
- expiresIn?: number;
25
- }
26
- interface ListOptions {
27
- limit?: number;
28
- prefix?: string;
29
- }
30
- /**
31
- * Provider-agnostic metadata-only view of an object.
32
- */
33
- interface FileObject {
34
- contentType: string;
35
- etag?: string;
36
- key: string;
37
- lastModified?: Date | number | string;
38
- metadata?: Record<string, unknown>;
39
- size?: number;
40
- }
41
- interface DownloadResult extends FileObject {
42
- body: Buffer;
43
- }
44
- interface FilesOptions<TStorage extends BaseStorage = BaseStorage> {
45
- adapter: TStorage;
46
- /**
47
- * Default {@link OperationOptions} (`signal`, `timeout`, `retries`) merged into every call.
48
- * Per-call overrides win. The `signal` is combined with any per-call `signal` via
49
- * `AbortSignal.any`, so either one aborts the operation.
50
- */
51
- defaults?: OperationOptions;
52
- /**
53
- * Namespace every key under this prefix. Reads, writes, copies, listings, URLs, and signed
54
- * uploads all resolve keys as `${prefix}/${key}`; returned keys (including from `list()`) have
55
- * the prefix stripped back off. Leading/trailing slashes are normalized so `"/users/"` and
56
- * `"users"` behave identically.
57
- *
58
- * `list()` scopes results on a path boundary, so `prefix: "users"` never matches the sibling
59
- * `users-archive/`.
60
- */
61
- prefix?: string;
62
- }
63
- /**
64
- * One item in a bulk upload call.
65
- */
66
- interface BulkUploadItem extends UploadOptions {
67
- body: FileBody;
68
- key: string;
69
- }
70
- /**
71
- * Per-call options shared by every bulk method (`upload`, `download`, `head`, `exists`, `delete`).
72
- */
73
- interface BulkOptions extends OperationOptions {
74
- /**
75
- * Maximum number of in-flight operations.
76
- * @default 8
77
- */
78
- concurrency?: number;
79
- /**
80
- * When `true`, stop dispatching new operations as soon as one fails. The already-issued
81
- * operations still complete. Defaults to `false`: every key is attempted and per-key failures
82
- * are collected in `errors`.
83
- * @default false
84
- */
85
- stopOnError?: boolean;
86
- }
87
- interface BulkError {
88
- error: Error;
89
- key: string;
90
- }
91
- interface BulkUploadResult {
92
- errors?: BulkError[];
93
- uploaded: FileObject[];
94
- }
95
- interface BulkDownloadResult {
96
- downloaded: DownloadResult[];
97
- errors?: BulkError[];
98
- }
99
- interface BulkHeadResult {
100
- errors?: BulkError[];
101
- files: FileObject[];
102
- }
103
- interface BulkExistsResult {
104
- errors?: BulkError[];
105
- existing: string[];
106
- missing: string[];
107
- }
108
- interface BulkDeleteResult {
109
- deleted: string[];
110
- errors?: BulkError[];
111
- }
112
- /**
113
- * Provider-agnostic facade over a {@link BaseStorage} instance.
114
- *
115
- * Provides a small, consistent surface (`upload`, `download`, `head`, `exists`, `delete`, `copy`,
116
- * `list`, `url`, `signedUploadUrl`) and a `raw` escape hatch to the adapter's native client.
117
- *
118
- * Each operation accepts per-call `signal`, `timeout`, and `retries` via {@link OperationOptions};
119
- * defaults set on the constructor are merged in (per-call wins). Single-key methods also accept an
120
- * array of keys (or {@link BulkUploadItem}s for `upload`) to run a bounded-concurrency batch and
121
- * return a structured `{ ..., errors? }` result instead of throwing on partial failure.
122
- *
123
- * When constructed with a `prefix`, every key is resolved relative to the prefix and the prefix is
124
- * stripped back off the keys returned in results — application code works in its own namespace.
125
- * @example
126
- * ```ts
127
- * import { Files, S3Storage } from "@visulima/storage";
128
- *
129
- * const files = new Files({
130
- * adapter: new S3Storage({ bucket: "uploads", region: "us-east-1" }),
131
- * prefix: "users",
132
- * defaults: { timeout: 30_000 },
133
- * });
134
- *
135
- * await files.upload("123/avatar.png", buffer, { contentType: "image/png" });
136
- * const head = await files.head("123/avatar.png"); // reads users/123/avatar.png
137
- * const url = await files.url("123/avatar.png", { expiresIn: 900 });
138
- *
139
- * const { uploaded, errors } = await files.upload([
140
- * { key: "a.png", body: a, contentType: "image/png" },
141
- * { key: "b.png", body: b },
142
- * ], { concurrency: 4 });
143
- * ```
144
- */
145
- declare class Files<TStorage extends BaseStorage = BaseStorage> {
146
- readonly adapter: TStorage;
147
- private readonly defaults;
148
- private readonly prefix;
149
- constructor(options: FilesOptions<TStorage>);
150
- /**
151
- * Escape hatch to the adapter's native client (S3Client, BlobServiceClient, ...).
152
- * Typed via the `TStorage` parameter, so pinning the adapter type at construction yields a
153
- * typed view of the native client. Returns `undefined` when the adapter has no native client
154
- * (e.g. DiskStorage).
155
- */
156
- get raw(): TStorage["raw"];
157
- /** Resolve a caller-supplied key into the underlying storage key. */
158
- private resolveKey;
159
- /**
160
- * Strip the constructor prefix off a key returned by the adapter. Returns `null` when the key
161
- * is outside the prefix or is the bare prefix itself (used to filter `list()` results on a path
162
- * boundary and drop any synthetic directory entry the adapter may emit).
163
- */
164
- private stripPrefix;
165
- private mergeOptions;
166
- /**
167
- * Upload a single object, or — when passed an array of {@link BulkUploadItem}s — bulk-upload
168
- * many in one call with bounded concurrency.
169
- */
170
- upload(key: string, body: FileBody, options?: OperationOptions & UploadOptions): Promise<FileObject>;
171
- upload(items: BulkUploadItem[], options?: BulkOptions): Promise<BulkUploadResult>;
172
- private uploadOne;
173
- private uploadMany;
174
- /**
175
- * Download a single object, or — when passed an array of keys — bulk-download many in one
176
- * call with bounded concurrency.
177
- */
178
- download(key: string, options?: OperationOptions): Promise<DownloadResult>;
179
- download(keys: string[], options?: BulkOptions): Promise<BulkDownloadResult>;
180
- private downloadOne;
181
- private downloadMany;
182
- /**
183
- * Fetch metadata for a single object, or — when passed an array of keys — bulk-head many in
184
- * one call with bounded concurrency.
185
- */
186
- head(key: string, options?: OperationOptions): Promise<FileObject>;
187
- head(keys: string[], options?: BulkOptions): Promise<BulkHeadResult>;
188
- private headOne;
189
- private headMany;
190
- /**
191
- * Resolves to `true`/`false` for a single key, or — when passed an array — splits the keys
192
- * into `existing` and `missing` arrays. Hard errors (auth, transport) are reported in
193
- * `errors`. Never throws for a missing object.
194
- */
195
- exists(key: string, options?: OperationOptions): Promise<boolean>;
196
- exists(keys: string[], options?: BulkOptions): Promise<BulkExistsResult>;
197
- private existsOne;
198
- private existsMany;
199
- /**
200
- * Delete a single object (resolves to `void`, throws on failure), or — when passed an array
201
- * of keys — delete many in one call. Adapters with a native bulk-delete primitive (S3's
202
- * `DeleteObjects`, Supabase's `remove`, UploadThing's `deleteFiles`) use it via
203
- * {@link BaseStorage.deleteBatch}; otherwise the keys are fanned out with bounded concurrency.
204
- */
205
- delete(key: string, options?: OperationOptions): Promise<void>;
206
- delete(keys: string[], options?: BulkOptions): Promise<BulkDeleteResult>;
207
- private deleteOne;
208
- private deleteMany;
209
- /**
210
- * Copy `source` to `destination` (both resolved under any constructor prefix). Returns the
211
- * destination object's metadata with the caller-facing (un-prefixed) key.
212
- */
213
- copy(source: string, destination: string, options?: OperationOptions & {
214
- storageClass?: string;
215
- }): Promise<FileObject>;
216
- /**
217
- * List objects in the bucket. Returned keys have any constructor prefix stripped off, and
218
- * keys outside the prefix namespace (e.g. `users-archive/` when prefix is `users`) are filtered
219
- * out. The optional `prefix` filter is interpreted *relative to the constructor prefix*.
220
- *
221
- * **Caveat with constructor prefix**: `limit` is applied by the underlying adapter *before*
222
- * the path-boundary filter runs, so the returned array may contain fewer than `limit` items
223
- * even when more in-namespace objects exist. Page through with adapter-specific APIs when you
224
- * need an exact in-namespace count.
225
- */
226
- list(options?: ListOptions & OperationOptions): Promise<FileObject[]>;
227
- url(key: string, options?: OperationOptions & SignedReadUrlOptions): Promise<string>;
228
- signedUploadUrl(key: string, options?: OperationOptions & SignedUploadUrlOptions): Promise<string>;
229
- }
230
- export { BulkDeleteResult as B, DownloadResult as D, Files as F, ListOptions as L, SignedReadUrlOptions as S, UploadOptions as U, BulkDownloadResult as a, BulkError as b, BulkExistsResult as c, BulkHeadResult as d, BulkOptions as e, BulkUploadItem as f, BulkUploadResult as g, FileBody as h, FileObject as i, FilesOptions as j, SignedUploadUrlOptions as k };
@@ -1 +0,0 @@
1
- var m=Object.defineProperty;var d=(e,t)=>m(e,"name",{value:t,configurable:!0});var b=Object.defineProperty,i=d((e,t)=>b(e,"name",{value:t,configurable:!0}),"u");const l={backoffMultiplier:2,calculateDelay:void 0,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:i(()=>!1,"shouldRetry")},p=i((e,t,r,o)=>{const a=Math.min(t*r**e,o);return Math.floor(Math.random()*a)},"calculateExponentialBackoff"),D=i(e=>new Promise(t=>{setTimeout(t,e)}),"sleep"),h=i((e,t=l.retryableStatusCodes)=>{if(e instanceof Error){const r=e.code,o=e.name;if(o==="AbortError"||r==="ABORT_ERR")return!1;if(r==="ECONNRESET"||r==="ETIMEDOUT"||r==="ENOTFOUND"||r==="ECONNREFUSED"||r==="EAI_AGAIN"||o==="NetworkError"||o==="TimeoutError")return!0;const a=e;if(a.$metadata){const u=a.$metadata.httpStatusCode;if(u&&t.includes(u)||a.$fault==="server")return!0}if(a.statusCode&&t.includes(a.statusCode))return!0;const{retryable:s}=a;return s===!0||typeof s=="string"&&s==="true"}return!1},"isRetryableError"),C=i(async(e,t={})=>{const{backoffMultiplier:r=l.backoffMultiplier,calculateDelay:o=l.calculateDelay,initialDelay:a=l.initialDelay,maxDelay:s=l.maxDelay,maxRetries:u=l.maxRetries,retryableStatusCodes:E=l.retryableStatusCodes,shouldRetry:R=l.shouldRetry}=t;let f;for(let n=0;n<=u;n+=1)try{return await e()}catch(c){if(f=c,n>=u)break;if(!(R(c)||h(c,E)))throw c;const y=o?o(n,c):p(n,a,r,s);y!==void 0&&y>0&&await D(y)}throw f},"retry"),N=i((e={})=>t=>C(t,e),"createRetryWrapper");export{N as createRetryWrapper,h as isRetryableError,C as retry};
@@ -1 +0,0 @@
1
- var re=Object.defineProperty;var o=(e,t)=>re(e,"name",{value:t,configurable:!0});import{utimes as ae}from"node:fs/promises";import{tmpdir as oe}from"node:os";import{createRequire as m}from"node:module";import{A as T,M as _,J as ie,K as ne,L as R}from"./path-D7rMc9nq-B718mbm6.js";import{throwErrorCode as j,ERRORS as P}from"./ERRORS-CyOuSMLY.js";import se from"./MetaStorage-Y4m1dWgd.js";import{stringifyMetadata as ce,parseMetadata as ue}from"./Metadata-B6Ir0KO7.js";const E=0,le=4;var fe=Object.defineProperty,pe=o((e,t)=>fe(e,"name",{value:t,configurable:!0}),"t$6"),me=Object.defineProperty,de=pe((e,t)=>me(e,"name",{value:t,configurable:!0}),"t"),ge=Object.defineProperty,be=de((e,t)=>ge(e,"name",{value:t,configurable:!0}),"n");const $=be(e=>{if(!e||!(e instanceof URL)&&typeof e!="string")throw new TypeError("Path must be a non-empty string or URL.")},"assertValidFileOrDirectoryPath");var ve=Object.defineProperty,ye=o((e,t)=>ve(e,"name",{value:t,configurable:!0}),"i$8"),he=Object.defineProperty,$e=ye((e,t)=>he(e,"name",{value:t,configurable:!0}),"r"),we=Object.defineProperty,Oe=$e((e,t)=>we(e,"name",{value:t,configurable:!0}),"i");const S=Oe(e=>{if(e.isFile())return"file";if(e.isDirectory())return"dir";if(e.isSymbolicLink())return"symlink"},"getFileInfoType");var je=Object.defineProperty,Pe=o((e,t)=>je(e,"name",{value:t,configurable:!0}),"i$7"),xe=Object.defineProperty,q=Pe((e,t)=>xe(e,"name",{value:t,configurable:!0}),"s");const Ee=m(import.meta.url),d=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Te=q(e=>{if(typeof d<"u"&&d.versions&&d.versions.node){const[t,r]=d.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return d.getBuiltinModule(e)}return Ee(e)},"__cjs_getBuiltinModule"),{lstat:I,mkdir:_e}=Te("node:fs/promises");var Me=Object.defineProperty,ke=q((e,t)=>Me(e,"name",{value:t,configurable:!0}),"o");const Ne=ke(async e=>{$(e);try{const t=await I(e);if(!t.isDirectory())throw new Error(`Ensure path exists, expected 'dir', got '${String(S(t))}'`);return}catch(t){if(t.code!=="ENOENT")throw t}try{await _e(e,{recursive:!0})}catch(t){if(t.code!=="EEXIST")throw t;const r=await I(e);if(!r.isDirectory())throw new Error(`Ensure path exists, expected 'dir', got '${String(S(r))}'`,{cause:t})}},"ensureDir");var ze=Object.defineProperty,l=o((e,t)=>ze(e,"name",{value:t,configurable:!0}),"n$7"),Be=Object.defineProperty,s=l((e,t)=>Be(e,"name",{value:t,configurable:!0}),"a");const Fe=m(import.meta.url),g=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Ae=s(e=>{if(typeof g<"u"&&g.versions&&g.versions.node){const[t,r]=g.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return g.getBuiltinModule(e)}return Fe(e)},"__cjs_getBuiltinModule"),{fileURLToPath:De}=Ae("node:url");var Re=Object.defineProperty,p=s((e,t)=>Re(e,"name",{value:t,configurable:!0}),"t$1");function O(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}o(O,"m$4");l(O,"d");s(O,"getDefaultExportFromCjs");p(O,"getDefaultExportFromCjs");function M(e){return e&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}o(M,"h$1");l(M,"O");s(M,"getDefaultExportFromNamespaceIfPresent");p(M,"getDefaultExportFromNamespaceIfPresent");function k(e){return e&&Object.prototype.hasOwnProperty.call(e,"default")&&Object.keys(e).length===1?e.default:e}o(k,"x");l(k,"P");s(k,"getDefaultExportFromNamespaceIfNotNamed");p(k,"getDefaultExportFromNamespaceIfNotNamed");function N(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var r=p(s(l(o(function a(){var i=!1;try{i=this instanceof a}catch{}return i?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)},"a"),"s"),"a"),"a");r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(a){var i=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(r,a,i.get?i:{enumerable:!0,get:p(function(){return e[a]},"get")})}),r}o(N,"y$2");l(N,"_");s(N,"getAugmentedNamespace");p(N,"getAugmentedNamespace");var L,U;function z(){return U||(U=1,L=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cr3","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),L}o(z,"w$2");l(z,"k");s(z,"requireBinaryExtensions");var Se=z();const Ie=O(Se);var Le=Object.defineProperty,n=s((e,t)=>Le(e,"name",{value:t,configurable:!0}),"r");const Ue=new Set(Ie),Ce=new Set(["/","\\",void 0]),C=Symbol.for("pathe:normalizedAlias"),We=/(^|[/\\])([^/\\]+?)(?=(?:\.[^.]+)?$)/,qe=n((e,t)=>t.split("/").length-e.split("/").length,"compareAliases"),w=n((e="/")=>{const t=e.at(-1);return t==="/"||t==="\\"},"hasTrailingSlash"),V=n(e=>{if(e[C])return e;const t=Object.fromEntries(Object.entries(e).toSorted(([r],[a])=>qe(r,a)));for(const r in t)for(const a in t)a===r||r.startsWith(a)||t[r].startsWith(a)&&Ce.has(t[r][a.length])&&(t[r]=t[a]+t[r].slice(a.length));return Object.defineProperty(t,C,{enumerable:!1,value:!0}),t},"normalizeAliases");n((e,t)=>{e=T(e),t=V(t);for(const[r,a]of Object.entries(t)){if(!e.startsWith(r))continue;const i=w(r)?r.slice(0,-1):r;if(w(e[i.length]))return _(a,e.slice(r.length))}return e},"resolveAlias");n(e=>We.exec(e)?.[2],"filename");n((e,t)=>{e=T(e),t=V(t);for(const[r,a]of Object.entries(t).toReversed()){if(!e.startsWith(a))continue;const i=w(a)?a.slice(0,-1):a;if(w(e[i.length]))return _(r,e.slice(a.length))}return e},"reverseResolveAlias");const Ve=/^(?:\.?\.[/\\]|\.\.\B)/,Je=/^(?:msys|cygwin)$/;n(e=>Ve.test(e)||e==="..","isRelative");n(e=>Ue.has(ie(e).slice(1).toLowerCase()),"isBinaryPath");const B=n(e=>T(e instanceof URL?De(e):e),"toPath");n(()=>{if(!globalThis.process)return!1;if(globalThis.process.platform==="win32"||globalThis.process.platform==="cygwin")return!0;const e=globalThis.process.env.OSTYPE;return typeof e!="string"?!1:Je.test(e)},"isWindows");var Ke=Object.defineProperty,J=o((e,t)=>Ke(e,"name",{value:t,configurable:!0}),"t$4"),Xe=Object.defineProperty,F=J((e,t)=>Xe(e,"name",{value:t,configurable:!0}),"s");const Ye=m(import.meta.url),b=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Ge=F(e=>{if(typeof b<"u"&&b.versions&&b.versions.node){const[t,r]=b.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return b.getBuiltinModule(e)}return Ye(e)},"__cjs_getBuiltinModule"),{access:He}=Ge("node:fs/promises");var Qe=Object.defineProperty,Ze=F((e,t)=>Qe(e,"name",{value:t,configurable:!0}),"o");async function u(e,t=E){$(e),e=B(e);try{return await He(e,t),!0}catch{return!1}}o(u,"i$5");J(u,"d");F(u,"m");Ze(u,"isAccessible");var et=Object.defineProperty,K=o((e,t)=>et(e,"name",{value:t,configurable:!0}),"t$3"),tt=Object.defineProperty,X=K((e,t)=>tt(e,"name",{value:t,configurable:!0}),"t"),rt=Object.defineProperty,at=X((e,t)=>rt(e,"name",{value:t,configurable:!0}),"o");let ot=class extends Error{static{o(this,"c")}static{K(this,"i")}static{X(this,"n")}static{at(this,"PermissionError")}constructor(t){super(`EPERM: Operation not permitted, ${t}`)}get code(){return"EPERM"}set code(t){throw new Error("Cannot overwrite code EPERM")}get name(){return"PermissionError"}set name(t){throw new Error("Cannot overwrite name of PermissionError")}};var it=Object.defineProperty,nt=o((e,t)=>it(e,"name",{value:t,configurable:!0}),"f$4"),st=Object.defineProperty,Y=nt((e,t)=>st(e,"name",{value:t,configurable:!0}),"i");const ct=m(import.meta.url),v=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,G=Y(e=>{if(typeof v<"u"&&v.versions&&v.versions.node){const[t,r]=v.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return v.getBuiltinModule(e)}return ct(e)},"__cjs_getBuiltinModule"),{readFile:ut}=G("node:fs/promises"),{unzip:lt,brotliDecompress:ft}=G("node:zlib");var pt=Object.defineProperty,H=Y((e,t)=>pt(e,"name",{value:t,configurable:!0}),"n");const mt={brotli:ft,gzip:lt,none:H((e,t)=>{t(null,e)},"none")},dt=H(async(e,t)=>{if($(e),e=B(e),!await u(e))throw new ot(`unable to read the non-accessible file: ${e}`);if(!await u(e,le))throw new Error(`Unable to read the non-readable file: ${e}`);const{buffer:r,compression:a,encoding:i,flag:c}=t??{};return await ut(e,c?{encoding:i,flag:c}:{encoding:i}).then(async f=>await new Promise((ee,te)=>{mt[a??"none"](f,(A,D)=>{A?te(A):ee(r?D:D.toString())})})).catch(f=>{throw f})},"readFile");var gt=Object.defineProperty,bt=o((e,t)=>gt(e,"name",{value:t,configurable:!0}),"a$4"),vt=Object.defineProperty,yt=bt((e,t)=>vt(e,"name",{value:t,configurable:!0}),"t"),ht=Object.defineProperty,$t=yt((e,t)=>ht(e,"name",{value:t,configurable:!0}),"t");const wt=$t(e=>{const t={force:!0,recursive:!0};return e?.maxRetries!==void 0&&(t.maxRetries=e.maxRetries),e?.retryDelay!==void 0&&(t.retryDelay=e.retryDelay),t},"buildRmOptions");var Ot=Object.defineProperty,jt=o((e,t)=>Ot(e,"name",{value:t,configurable:!0}),"i$2"),Pt=Object.defineProperty,Q=jt((e,t)=>Pt(e,"name",{value:t,configurable:!0}),"s");const xt=m(import.meta.url),y=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Et=Q(e=>{if(typeof y<"u"&&y.versions&&y.versions.node){const[t,r]=y.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return y.getBuiltinModule(e)}return xt(e)},"__cjs_getBuiltinModule"),{unlink:Tt,rm:_t}=Et("node:fs/promises");var Mt=Object.defineProperty,kt=Q((e,t)=>Mt(e,"name",{value:t,configurable:!0}),"i");const Nt=kt(async(e,t={})=>{$(e);try{await Tt(e)}catch{}try{await _t(e,wt(t))}catch{}},"remove");var zt=Object.defineProperty,Bt=o((e,t)=>zt(e,"name",{value:t,configurable:!0}),"a$2"),Ft=Object.defineProperty,At=Bt((e,t)=>Ft(e,"name",{value:t,configurable:!0}),"t"),Dt=Object.defineProperty,Rt=At((e,t)=>Dt(e,"name",{value:t,configurable:!0}),"e");const St=Rt(e=>{if(typeof e!="string"&&!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("File contents must be a string, ArrayBuffer, or ArrayBuffer view.")},"assertValidFileContents");var It=Object.defineProperty,Lt=o((e,t)=>It(e,"name",{value:t,configurable:!0}),"t"),Ut=Object.defineProperty,Ct=Lt((e,t)=>Ut(e,"name",{value:t,configurable:!0}),"r"),Wt=Object.defineProperty,qt=Ct((e,t)=>Wt(e,"name",{value:t,configurable:!0}),"f");const Vt=new TextEncoder,Jt=qt(e=>{if(e instanceof Uint8Array)return e;if(typeof e=="string")return Vt.encode(e);if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e)){const t=e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}throw new TypeError("Invalid contents type. Expected string or ArrayBuffer.")},"toUint8Array");var Kt=Object.defineProperty,Xt=o((e,t)=>Kt(e,"name",{value:t,configurable:!0}),"m"),Yt=Object.defineProperty,Z=Xt((e,t)=>Yt(e,"name",{value:t,configurable:!0}),"s");const Gt=m(import.meta.url),h=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Ht=Z(e=>{if(typeof h<"u"&&h.versions&&h.versions.node){const[t,r]=h.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return h.getBuiltinModule(e)}return Gt(e)},"__cjs_getBuiltinModule"),{mkdir:Qt,writeFile:Zt,stat:er,rename:W,chown:tr,chmod:rr,unlink:ar}=Ht("node:fs/promises");var or=Object.defineProperty,ir=Z((e,t)=>or(e,"name",{value:t,configurable:!0}),"d");const nr=ir(async(e,t,r)=>{r={encoding:"utf8",flag:"w",overwrite:!0,recursive:!0,...r},$(e),St(t),e=B(e);const a=`${e}.tmp`;try{const i=await u(e,E);if(!i&&r.recursive){const f=ne(e);await u(f,E)||await Qt(f,{recursive:!0})}let c;if(await Zt(a,Jt(t),{encoding:r.encoding,flag:r.flag}),i&&!r.overwrite&&(c=await er(e),r.chown??={gid:c.gid,uid:c.uid},await W(e,`${e}.bak`)),r.chown)try{await tr(a,r.chown.uid,r.chown.gid)}catch{}await rr(a,c&&!r.mode?c.mode:r.mode??438),await W(a,e)}catch(i){throw new Error(`Failed to write file at: ${e} - ${i.message}`,{cause:i})}finally{await u(a)&&await ar(`${e}.tmp`)}},"writeFile");var sr=Object.defineProperty,x=o((e,t)=>sr(e,"name",{value:t,configurable:!0}),"a");let vr=class extends se{static{o(this,"v")}static{x(this,"LocalMetaStorage")}directory;constructor(t){super(t),this.directory=R(t?.directory||_(oe(),"Upload_meta")),this.accessCheck().catch(r=>{this.logger?.error("Metadata storage access check failed: %O",r)})}getMetaPath=x(t=>{const r=R(`${this.directory}/${this.prefix}${t}${this.suffix}`),a=this.directory.endsWith("/")?this.directory:`${this.directory}/`;return r.startsWith(a)?r:j(P.INVALID_FILE_NAME,`Invalid id: "${t}" resolves outside the meta directory`)},"getMetaPath");getIdFromPath=x(t=>t.slice(`${this.directory}/${this.prefix}`.length,-this.suffix.length),"getIdFromPath");async save(t,r){await this.accessCheck();const a={...r};return a.metadata&&(a.metadata=ce(r.metadata)),await nr(this.getMetaPath(t),JSON.stringify(a),{recursive:!0}),r}async touch(t,r){const a=new Date;return await ae(this.getMetaPath(t),a,a),r}async get(t){try{const r=await dt(this.getMetaPath(t));if(r===void 0)throw j(P.FILE_NOT_FOUND);const a=JSON.parse(r);return a.metadata&&typeof a.metadata=="string"&&(a.metadata=ue(a.metadata)),a}catch(r){const a=r,i=r instanceof SyntaxError;throw a.code==="ENOENT"||i?j(P.FILE_NOT_FOUND):r}}async delete(t){await Nt(this.getMetaPath(t))}async accessCheck(){await Ne(this.directory)}};export{dt as B,B as U,E as _,$ as f,u as i,S as l,vr as v,Ne as w,Nt as y};
@@ -1 +0,0 @@
1
- var i=Object.defineProperty;var r=(e,t)=>i(e,"name",{value:t,configurable:!0});var a=Object.defineProperty,s=r((e,t)=>a(e,"name",{value:t,configurable:!0}),"t");const v=s(e=>e.bytesWritten===e.size?"completed":e.createdAt?"part":"created","getFileStatus");var n=Object.defineProperty,o=r((e,t)=>n(e,"name",{value:t,configurable:!0}),"i");const z=o((e,t)=>e.size!==void 0&&t.size!==void 0&&e.size>0&&t.size>0&&e.size>t.size?!1:t.size===void 0?!0:(e.start||0)+(e.contentLength||0)<=t.size,"partMatch");export{v as o,z as r};
@@ -1 +0,0 @@
1
- var O=Object.defineProperty;var g=(c,t)=>O(c,"name",{value:t,configurable:!0});import{Readable as b}from"node:stream";import{z as C,B as M,$ as A,t as T}from"./storage-B-NDsI-o.js";import{d as I}from"./detect-file-type-5JhzC9RU.js";import{throwErrorCode as y,ERRORS as f}from"./ERRORS-CyOuSMLY.js";import{createRetryWrapper as R}from"./isRetryableError-BhizNeAz.js";import{v as k}from"./local-meta-storage-Bi0mK6gD.js";import{u as z}from"./update-size-DANV7aa2.js";import{r as v,o as P}from"./part-match-B5fLLmFw.js";import{o as x}from"./has-content-Bx2p8Okx.js";var B=Object.defineProperty,L=g((c,t)=>B(c,"name",{value:t,configurable:!0}),"o$1");const N=L((c,t)=>{const a={};return Object.keys(c).forEach(e=>{a[e]=t(c[e])}),a},"mapValues");var $=Object.defineProperty,K=g((c,t)=>$(c,"name",{value:t,configurable:!0}),"t");const j=K(c=>c===Number(c)?c:(C(c)??0)/1e3,"toSeconds");var D=Object.defineProperty,w=g((c,t)=>D(c,"name",{value:t,configurable:!0}),"m");const F=5*1024*1024,W=16*1024*1024;class S extends M{static{g(this,"S3BaseStorage")}static{w(this,"S3BaseStorage")}checksumTypes=["md5","crc32","crc32c","sha1","sha256"];bucket;meta;MAX_PARTS=1e4;partSize;retry;resolvedRetryConfig;constructor(t){if(super(t),this.bucket=t.bucket,this.partSize=typeof t.partSize=="string"?A(t.partSize):t.partSize||W,this.partSize<F)throw new Error("Minimum allowed partSize value is 5MB");const a={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:w(i=>{const s=i;return s.statusCode&&[408,429,500,502,503,504].includes(s.statusCode)?!0:s.retryable??!1},"shouldRetry"),...t.retryConfig};this.retry=R(a),this.resolvedRetryConfig=a;const{metaStorage:e,metaStorageConfig:r}=t;if(e)this.meta=e;else{const i={...t,...r,logger:this.logger};"directory"in i?(this.logger?.debug("Using local meta storage"),this.meta=new k(i)):this.meta=new k(i)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(i=>{this.logger?.error("Storage access check failed: %O",i)})}getRetryConfig(){return this.resolvedRetryConfig}async create(t,a){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const n=typeof t.ttl=="string"?T(t.ttl):t.ttl;n!==void 0&&(e.expiredAt=Date.now()+n)}const r=new(this.getFileClass())(e);r.name=this.namingFunction(r),await this.validate(r);try{const n=await this.getMeta(r.id);if(n.bytesWritten>=0)return n}catch{}const i=this.getS3Api();let s;try{s=await this.runOperation(a,n=>i.createMultipartUpload({ACL:this.getAcl(),Bucket:this.bucket,ContentType:r.contentType,Key:r.name,Metadata:N({originalName:r.originalName,...r.metadata},l=>encodeURI(String(l)))},{signal:n}))}catch{return y(f.FILE_ERROR,"s3 create upload error")}const{UploadId:o}=s||{};return o?(r.UploadId=o,r.bytesWritten=0,this.config.clientDirectUpload&&(r.partSize??=this.partSize),await this.saveMeta(r),r.status="created",await this.onCreate(r),this.config.clientDirectUpload?this.buildPresigned(r):r):y(f.FILE_ERROR,"s3 create upload error")})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(typeof t.size=="number"&&t.size>0&&z(e,t.size),!v(t,e))return y(f.FILE_CONFLICT);if(this.config.clientDirectUpload)return this.buildPresigned(e);e.Parts??=await this.getParts(e),e.bytesWritten=e.Parts.map(i=>i.Size||0).reduce((i,s)=>i+s,0);const r=await this.lock(t.id);try{if(x(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return y(f.UNSUPPORTED_CHECKSUM_ALGORITHM);if(e.Parts.length===0&&(!e.contentType||e.contentType==="application/octet-stream"))try{const p=t.body instanceof b?t.body:b.fromWeb(t.body),{fileType:m,stream:u}=await I(p);m?.mime&&(e.contentType=m.mime),t.body=u}catch{}if(e.Parts.length>this.MAX_PARTS)throw new Error(`Exceeded ${this.MAX_PARTS} as part of the upload to ${this.bucket}.`);const i=e.Parts.length+1,s=this.getS3Api(),o=e.UploadId;if(!o)throw new Error("UploadId is required");const n=t.body,l=n instanceof Uint8Array,{ETag:h}=await this.runOperation(a,p=>s.uploadPart({Body:n,Bucket:this.bucket,ContentLength:t.contentLength||0,Key:e.name,PartNumber:i,UploadId:o,...t.checksumAlgorithm==="md5"?{ContentMD5:t.checksum}:{}},{signal:p}),{replayable:l}),d={ETag:h,PartNumber:i,Size:t.contentLength};e.Parts=[...e.Parts,d],e.bytesWritten+=t.contentLength||0}if(this.cache.set(e.id,e),e.status=P(e),e.status==="completed"){const[i]=await this.internalOnComplete(e);delete e.Parts,e.uri=i.Location,e.ETag=i.ETag}}finally{await this.unlock(t.id,r)}return e})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);e.status="deleted",await this.abortMultipartUpload(e,a),await this.deleteMeta(e.id);const r={...e};return await this.onDelete(r),r})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{S.assertSafeId(t),S.assertSafeId(a);const r=await this.getMeta(t),i=`${this.bucket}/${t}`,s=this.bucket,o=a,n=this.getS3Api();return await this.runOperation(e,l=>n.copyObject({Bucket:s,CopySource:i,Key:o,...e?.storageClass&&{StorageClass:e.storageClass}},{signal:l})),{...r,id:o,name:o}})}async move(t,a,e){return this.instrumentOperation("move",async()=>{await this.copy(t,a,e);const r=this.getS3Api();return await this.runOperation(e,i=>r.deleteObject({Bucket:this.bucket,Key:t},{signal:i})),await this.getMeta(a)})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const e=this.getS3Api(),r=Math.min(t,1e3);let i={Bucket:this.bucket,MaxKeys:r};const s=[];let o=!0;for(;o&&s.length<t;)try{const n=await this.runOperation(a,l=>e.listObjectsV2(i,{signal:l}));for(const{Key:l,LastModified:h}of n?.Contents||[]){if(s.length>=t)break;l!==void 0&&s.push({id:l,...h&&{createdAt:h}})}o=n.IsTruncated||!1,o&&n.NextContinuationToken&&s.length<t&&(i={...i,ContinuationToken:n.NextContinuationToken,MaxKeys:Math.min(r,t-s.length)})}catch(n){const l=this.normalizeError(n instanceof Error?n:new Error(String(n)));throw await this.onError(l),n}return s},{limit:t})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{try{await this.getMeta(t);const e=this.getS3Api();return await this.runOperation(a,r=>e.headObject({Bucket:this.bucket,Key:t},{signal:r})),!0}catch{return!1}})}async get({id:t},a){return this.instrumentOperation("get",async()=>{const e=this.getS3Api(),{Body:r,ContentLength:i,ContentType:s,ETag:o,Expires:n,LastModified:l,Metadata:h}=await this.runOperation(a,u=>e.getObject({Bucket:this.bucket,Key:t},{signal:u}));await this.checkIfExpired({expiredAt:n});const d=[];if(r)if(r instanceof b)for await(const u of r)d.push(u instanceof Uint8Array?u:new Uint8Array(u));else{const u=r.getReader();for(;;){const{done:U,value:E}=await u.read();if(U)break;d.push(E)}}const{originalName:p,...m}=h||{};return{content:Buffer.concat(d),contentType:s,ETag:o,expiredAt:n,id:t,metadata:m,modifiedAt:l,name:t,originalName:p||t,size:Number(i)}})}async buildPresigned(t){const a=t;if(a.Parts?.length||(a.Parts=await this.getParts(t)),a.bytesWritten=a.Parts.map(e=>e.Size||0).reduce((e,r)=>e+r,0),t.status=P(a),a.partsUrls?.length||(a.partsUrls=await this.getPartsPresignedUrls(t)),t.status==="completed"){const[e]=await this.internalOnComplete(t);return delete a.Parts,a.uri=e.Location,t}return t}async getPartsPresignedUrls(t){t.partSize??=this.partSize;const a=t.UploadId;if(!a)throw new Error("UploadId is required for getting presigned URLs");const e=Math.trunc(t.size/this.partSize)+1,r=[],i=Math.trunc(j(this.config.expiration?.maxAge||"6hrs")),s=this.getS3Api();for(let o=0;o<e;o++)r.push(s.getPresignedUrl({Bucket:this.bucket,expiresIn:i,Key:t.name,PartNumber:o+1,UploadId:a}));return Promise.all(r)}async getParts(t){const a=this.getS3Api(),e=t.UploadId;if(!e)throw new Error("UploadId is required");const{Parts:r=[]}=await this.runOperation(void 0,i=>a.listParts({Bucket:this.bucket,Key:t.name,UploadId:e},{signal:i}));return r}completeMultipartUpload(t){const a=this.getS3Api(),e=t.UploadId;if(!e)throw new Error("UploadId is required");const r=t.Parts?.map(({ETag:i,PartNumber:s})=>{if(!i||!s)throw new Error("ETag and PartNumber are required");return{ETag:i,PartNumber:s}})||[];return this.runOperation(void 0,i=>a.completeMultipartUpload({Bucket:this.bucket,Key:t.name,Parts:r,UploadId:e},{signal:i}))}async abortMultipartUpload(t,a){if(t.status!=="completed")try{const e=this.getS3Api(),r=t.UploadId;if(!r)return;await this.runOperation(a,i=>e.abortMultipartUpload({Bucket:this.bucket,Key:t.name,UploadId:r},{signal:i}))}catch(e){this.logger?.error("abortMultipartUploadError: ",e);const r=this.normalizeError(e instanceof Error?e:new Error(String(e)));await this.onError(r)}}internalOnComplete=w(async t=>{const[a]=await Promise.all([this.completeMultipartUpload(t),this.deleteMeta(t.id)]);return[a,t]},"internalOnComplete")}export{S};
@@ -1 +0,0 @@
1
- var H=Object.defineProperty;var p=(t,e)=>H(t,"name",{value:e,configurable:!0});import{Readable as X}from"node:stream";import{setInterval as J}from"node:timers";import{inspect as Q}from"node:util";import{L as ee,O as I}from"./path-D7rMc9nq-B718mbm6.js";import te from"type-is";import re from"./NoOpMetrics-Dky06sf1.js";import{N as oe}from"./cache-qV_5Umeq.js";import{ErrorMap as M,throwErrorCode as E,ERRORS as $}from"./ERRORS-CyOuSMLY.js";import{randomUUID as se}from"node:crypto";import{LRUCache as ae}from"lru-cache";import{retry as ie}from"./isRetryableError-BhizNeAz.js";import{o as ne}from"./is-expired-1JuZjDtb.js";var ce=Object.defineProperty,le=p((t,e)=>ce(t,"name",{value:e,configurable:!0}),"y$3"),ue=Object.defineProperty,me=le((t,e)=>ue(t,"name",{value:e,configurable:!0}),"y"),ge=Object.defineProperty,C=me((t,e)=>ge(t,"name",{value:e,configurable:!0}),"i");const de=/^(?<value>-?\d+(?:[.,]\d+)*) *(?<type>[a-z]+)?$/i,he=/^KIBI/,pe=/^MIBI/,fe=/^GIBI/,ye=/^TEBI/,be=/^PEBI/,we=/^EXBI/,ve=/^ZEBI/,Ee=/^YIBI/,$e=/^(.)IB$/,_={iec:[{long:"Bytes",short:"B"},{long:"Kibibytes",short:"KiB"},{long:"Mebibytes",short:"MiB"},{long:"Gibibytes",short:"GiB"},{long:"Tebibytes",short:"TiB"},{long:"Pebibytes",short:"PiB"},{long:"Exbibytes",short:"EiB"},{long:"Zebibytes",short:"ZiB"},{long:"Yobibytes",short:"YiB"}],iec_octet:[{long:"Octets",short:"o"},{long:"Kibioctets",short:"Kio"},{long:"Mebioctets",short:"Mio"},{long:"Gibioctets",short:"Gio"},{long:"Tebioctets",short:"Tio"},{long:"Pebioctets",short:"Pio"},{long:"Exbioctets",short:"Eio"},{long:"Zebioctets",short:"Zio"},{long:"Yobioctets",short:"Yio"}],metric:[{long:"Bytes",short:"Bytes"},{long:"Kilobytes",short:"KB"},{long:"Megabytes",short:"MB"},{long:"Gigabytes",short:"GB"},{long:"Terabytes",short:"TB"},{long:"Petabytes",short:"PB"},{long:"Exabytes",short:"EB"},{long:"Zettabytes",short:"ZB"},{long:"Yottabytes",short:"YB"}],metric_octet:[{long:"Octets",short:"o"},{long:"Kilo-octets",short:"ko"},{long:"Mega-octets",short:"Mo"},{long:"Giga-octets",short:"Go"},{long:"Tera-octets",short:"To"},{long:"Peta-octets",short:"Po"},{long:"Exa-octets",short:"Eo"},{long:"Zetta-octets",short:"Zo"},{long:"Yotta-octets",short:"Yo"}]},xe=C((t,e)=>{const r=new Intl.NumberFormat(e).format(11111).replaceAll(new RegExp("\\p{Number}","gu"),""),o=new Intl.NumberFormat(e).format(1.1).replaceAll(new RegExp("\\p{Number}","gu"),"");return Number.parseFloat(t.replaceAll(new RegExp(`\\${r}`,"g"),"").replace(new RegExp(`\\${o}`),"."))},"parseLocalizedNumber"),R=C(t=>{switch(t){case 2:return 1024;case 10:return 1e3;default:throw new Error("Unsupported base.")}},"fromBase"),j=C((t,e)=>{const r={base:2,locale:"en-US",units:"metric",...e};if(typeof t!="string"||t.length===0)throw new TypeError("Value is not a string or is empty.");if(t.length>100)throw new TypeError("Value exceeds the maximum length of 100 characters.");const o=de.exec(t)?.groups;if(!o)return Number.NaN;const s=xe(o.value,r.locale),a=(o.type??"Bytes").toUpperCase().replace(he,"KILO").replace(pe,"MEGA").replace(fe,"GIGA").replace(ye,"TERA").replace(be,"PETA").replace(we,"EXA").replace(ve,"ZETTA").replace(Ee,"YOTTA").replace($e,"$1B"),i=_[r.units].findIndex(u=>u.short[0].toUpperCase()===a[0]),l=R(r.base);return s*l**i},"parseBytes");C((t,e)=>{if(typeof t!="number"||!Number.isFinite(t))throw new TypeError("Bytesize is not a number.");const{base:r,decimals:o,locale:s,long:a,unit:i,units:l,...u}={base:2,decimals:0,locale:"en-US",long:!1,units:"metric",...e},n=R(r),m=Math.abs(t),g=e?.space??!0?" ":"",c=_[l],d=c.findIndex(w=>w.short===i);if(t===0){const w=Math.min(0,Math.max(d,c.length-1));return"0"+g+c[w][a?"long":"short"]}const h=d===-1?Math.min(Math.floor(Math.log(m)/Math.log(n)),c.length-1):d,N=c[h][a?"long":"short"],O=t/n**h,v=o<0?void 0:o;return new Intl.NumberFormat(s,{maximumFractionDigits:v,minimumFractionDigits:v,...u}).format(O)+g+N},"formatBytes");var Me=Object.defineProperty,Ne=p((t,e)=>Me(t,"name",{value:e,configurable:!0}),"u$3"),Oe=Object.defineProperty,Ae=Ne((t,e)=>Oe(t,"name",{value:e,configurable:!0}),"v"),Te=Object.defineProperty,Ce=Ae((t,e)=>Te(t,"name",{value:e,configurable:!0}),"D");const Se=Ce((t,e,r,o,s,a,i,l,u,n,m,g,c,d)=>{const h={d:o,h:s,m:a,mo:e,ms:l,s:i,w:r,y:t};return u!==void 0&&(h.future=u),n!==void 0&&(h.past=n),m!==void 0&&(h.decimal=m),g!==void 0&&(h.unitMap=g),c!==void 0&&(h.groupSeparator=c),d!==void 0&&(h.placeholderSeparator=d),h},"createDurationLanguage"),F={d:"d",day:"d",days:"d",h:"h",hour:"h",hours:"h",hr:"h",hrs:"h",m:"m",millisecond:"ms",milliseconds:"ms",min:"m",mins:"m",minute:"m",minutes:"m",mo:"mo",month:"mo",months:"mo",ms:"ms",s:"s",sec:"s",second:"s",seconds:"s",secs:"s",w:"w",week:"w",weeks:"w",y:"y",year:"y",years:"y",yr:"y",yrs:"y"},Ie=Se(t=>`year${t===1?"":"s"}`,t=>`month${t===1?"":"s"}`,t=>`week${t===1?"":"s"}`,t=>`day${t===1?"":"s"}`,t=>`hour${t===1?"":"s"}`,t=>`minute${t===1?"":"s"}`,t=>`second${t===1?"":"s"}`,t=>`millisecond${t===1?"":"s"}`,"in %s","%s ago",".",F,",","_");var Be=Object.defineProperty,Pe=p((t,e)=>Be(t,"name",{value:e,configurable:!0}),"o"),De=Object.defineProperty,Ue=Pe((t,e)=>De(t,"name",{value:e,configurable:!0}),"o"),ze=Object.defineProperty,je=Ue((t,e)=>ze(t,"name",{value:e,configurable:!0}),"o");const ke=je(t=>{const e=["y","mo","w","d","h","m","s","ms","future","past"];for(const o of e)if(!Object.hasOwn(t,o))throw new TypeError(`Missing required property: ${o}`);if(typeof t.future!="string"||typeof t.past!="string")throw new TypeError("Properties future and past must be of type string");const r=["y","mo","w","d","h","m","s","ms"];for(const o of r)if(typeof t[o]!="string"&&typeof t[o]!="function")throw new TypeError(`Property ${o} must be of type string or function`);if(t.decimal&&typeof t.decimal!="string")throw new TypeError("Property decimal must be of type string");if(t.delimiter&&typeof t.delimiter!="string")throw new TypeError("Property delimiter must be of type string");if(t._digitReplacements&&!Array.isArray(t._digitReplacements))throw new TypeError("Property _digitReplacements must be an array");if(t._numberFirst&&typeof t._numberFirst!="boolean")throw new TypeError("Property _numberFirst must be of type boolean");if(t.unitMap&&typeof t.unitMap!="object")throw new TypeError("Property unitMap must be an object");if(t.unitMap&&Object.values(t.unitMap).some(o=>typeof o!="string"))throw new TypeError("All values in unitMap must be of type string")},"validateDurationLanguage");var _e=Object.defineProperty,Re=p((t,e)=>_e(t,"name",{value:e,configurable:!0}),"w"),Fe=Object.defineProperty,Le=Re((t,e)=>Fe(t,"name",{value:e,configurable:!0}),"S"),Ve=Object.defineProperty,Ge=Le((t,e)=>Ve(t,"name",{value:e,configurable:!0}),"h");const k={d:864e5,h:36e5,m:6e4,mo:2629746e3,ms:1,s:1e3,w:6048e5,y:31556952e3},A=/[-/\\^$*+?.()|[\]{}]/g,Ye=/^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/i,Ze=/^(?:(\d+):)?(?:(\d+):)?(\d+)$/,Ke=/^[+-]?\d+(?:\.\d+)?$/,We=/^[-+]/,qe=Ge((t,e)=>{if(typeof t!="string"||t.length===0)return;const{defaultUnit:r="ms",language:o=Ie}=e??{};ke(o);const s=o.decimal??".",a=o.groupSeparator??",",i=o.placeholderSeparator??"_",l=s.replaceAll(A,String.raw`\$&`),u=a.replaceAll(A,String.raw`\$&`),n=i.replaceAll(A,String.raw`\$&`),m=o.unitMap??F;let g=t.replaceAll(new RegExp(String.raw`(\d)[${n}${u}](\d)`,"g"),"$1$2");if(s!=="."&&(g=g.replace(l,".")),Ke.test(t)){const f=Number.parseFloat(g.trim());if(!Number.isNaN(f)){const y=m[r];if(y!==void 0)return f*k[y]}return}const c=Ye.exec(t);if(c){const f=Number.parseInt(c[1]??"0",10),y=Number.parseInt(c[2]??"0",10),x=Number.parseInt(c[3]??"0",10);return f*36e5+y*6e4+x*1e3}const d=Ze.exec(t);if(d){let f=0,y=0;d[2]!==void 0?(f=Number.parseInt(d[1]??"0",10),y=Number.parseInt(d[2],10)):d[1]!==void 0&&(y=Number.parseInt(d[1],10));const x=Number.parseInt(d[3]??"0",10);return f*36e5+y*6e4+x*1e3}const h=Object.keys(m).toSorted((f,y)=>y.length-f.length).map(f=>f.replaceAll(A,String.raw`\$&`)).join("|"),N=new RegExp(String.raw`(-?\d*\.?\d+)\s*(${h})`,"gi");let O=0,v,w=!1,P=-1,D=0;for(N.lastIndex=0;(v=N.exec(g))!==null;){w||(P=v.index),w=!0;const f=v[1],y=v[2];if(!f||!y)continue;const x=f.trim(),K=x.startsWith("-")?-1:1,W=x.replace(We,""),U=Number.parseFloat(W),z=m[y.toLowerCase()];if(z===void 0)continue;const q=k[z];if(Number.isNaN(U))return;O+=K*U*q,D=N.lastIndex}const Y=g.slice(0,P).trim(),Z=g.slice(D).trim();if(!(w&&(Y.length>0||Z.length>0))&&w)return O},"parseDuration");var He=Object.defineProperty,Xe=p((t,e)=>He(t,"name",{value:e,configurable:!0}),"n$1");let Je=class extends ae{static{p(this,"u")}static{Xe(this,"Locker")}constructor(e){super({ttl:3e4,ttlAutopurge:!0,...e})}lock(e){if(this.get(e)!==void 0)throw new Error(`${e} is locked`);const r=se();return this.set(e,r),r}unlock(e,r){return this.get(e)!==r?!1:this.delete(e)}};var Qe=Object.defineProperty,et=p((t,e)=>Qe(t,"name",{value:e,configurable:!0}),"e$1");const T=et(t=>{if(t===Number(t))return t;if(!t)return;const e=qe(t);if(e!==void 0)return e},"toMilliseconds");var tt=Object.defineProperty,rt=p((t,e)=>tt(t,"name",{value:e,configurable:!0}),"t");let ot=class extends Error{static{p(this,"d")}static{rt(this,"ValidationError")}code;statusCode;body;headers;name="ValidationError";constructor(e,r,o,s){const a=typeof o=="string"?o:o?.message||"Validation error";super(a),this.code=e,this.statusCode=r,this.body=o,this.headers=s}};var st=Object.defineProperty,S=p((t,e)=>st(t,"name",{value:e,configurable:!0}),"e");const at=S(t=>t&&t[0].toUpperCase()+t.slice(1),"capitalize"),it=S(t=>{if(!Array.isArray(t))return t;const[e,r,o]=t;return{body:r,headers:o,statusCode:e}},"toResponse");class nt{static{p(this,"Validator")}constructor(e="ValidationError"){this.prefix=e}prefix;static{S(this,"Validator")}validators={};add(e){Object.entries(e).forEach(([r,o])=>{const s=`${this.prefix}${at(r)}`;if(this.validators[s]={...this.validators[s],...o},typeof this.validators[s].isValid!="function")throw new TypeError('Validation config "isValid" is missing, or it is not a function!')})}async verify(e){for(const[r,o]of Object.entries(this.validators))if(!await o.isValid(e)){const s=o.response||(r in M?M[r]:M.UnknownError),a=it(s),{body:i,headers:l,message:u,statusCode:n}=a;throw new ot(r,n,i||u,l)}}}const St=S(t=>t.name==="ValidationError","isValidationError");var ct=Object.defineProperty,B=p((t,e)=>ct(t,"name",{value:e,configurable:!0}),"i");const lt=B(t=>{if(typeof t.name=="string")return t.name;if(typeof t.title=="string")return t.title;if(typeof t.originalName=="string")return t.originalName;if(typeof t.filename=="string")return t.filename},"extractOriginalName"),L=B((t,e)=>{const r={...t};return Object.keys(e).forEach(o=>{const s=e[o];if(s!==null&&typeof s=="object"&&!Array.isArray(s)){const a=r[o],i=a&&typeof a=="object"&&!Array.isArray(a)?a:{};r[o]=L(i,s)}else r[o]=s}),r},"deepMerge"),ut=B((t,e)=>{const r=L(t,e);Object.assign(t,r),t.originalName=lt(t.metadata)||t.originalName},"updateMetadata");var mt=Object.defineProperty,b=p((t,e)=>mt(t,"name",{value:e,configurable:!0}),"d");const gt=/(secret|password|passwd|pwd|token|api[_-]?key|credential|authorization|sas|signature|sessiontoken|connectionstring)/i,V=b(t=>{const e={};for(const[r,o]of Object.entries(t))typeof o=="string"&&gt.test(r)?e[r]="[REDACTED]":o&&typeof o=="object"&&!Array.isArray(o)&&o.constructor===Object?e[r]=V(o):e[r]=o;return e},"redactSecrets"),dt={allowMIME:["*/*"],filename:b(({id:t})=>t,"filename"),maxMetadataSize:"8MB",maxUploadSize:"5TB",onComplete:b(()=>{},"onComplete"),onCreate:b(()=>{},"onCreate"),onDelete:b(()=>{},"onDelete"),onError:b(()=>{},"onError"),onUpdate:b(()=>{},"onUpdate"),useRelativeLocation:!1,validation:{}},ht=b(t=>!t||t.length<3||t.length>255||I(t)?!1:!(t.toUpperCase().includes("../")||t.includes("\0")),"defaultCloudStorageFileNameValidation"),It=b(t=>{if(!t||t.length<3||t.length>255||I(t))return!1;const e=t.toUpperCase();return!['"',"*",":","<",">","?","\\","|","../","\0"].some(r=>e.includes(r))},"defaultFilesystemFileNameValidation");class G{static{p(this,"BaseStorage")}static{b(this,"BaseStorage")}onCreate;onUpdate;onComplete;onDelete;onError;isReady=!0;errorResponses={};cache;logger;metrics;genericConfig;maxMetadataSize;checksumTypes=[];maxUploadSize;expiration;locker;namingFunction;validation=new nt;assetFolder=void 0;concurrency;constructor(e){const r={...dt,...e};this.onCreate=r.onCreate,this.onUpdate=r.onUpdate,this.onComplete=r.onComplete,this.onDelete=r.onDelete,this.onError=r.onError,this.namingFunction=r.filename,this.maxUploadSize=typeof r.maxUploadSize=="string"?j(r.maxUploadSize):r.maxUploadSize,this.maxMetadataSize=typeof r.maxMetadataSize=="string"?j(r.maxMetadataSize):r.maxMetadataSize,this.expiration=r.expiration,this.genericConfig=r,r.assetFolder!==void 0&&(this.assetFolder=ee(r.assetFolder)),this.locker=new Je({max:1e3,ttl:3e4,ttlAutopurge:!0}),this.cache=r.cache??new oe,this.logger=r.logger,this.metrics=r.metrics??new re,this.logger?.debug(`${this.constructor.name} config: ${Q(V({...e,logger:this.logger.constructor}))}`);const o=T(r.expiration?.purgeInterval);o&&this.startAutoPurge(o);const s={isValid(u){if(u.size===void 0)return!0;const n=u.size;if(n==null)return!1;const m=typeof n=="number"?n:Number(n);if(Number.isNaN(m)||m<0)return!1;const g=typeof this.value=="number"?this.value:Number(this.value);return!Number.isNaN(g)&&m<=g},response:M.RequestEntityTooLarge,value:this.maxUploadSize},a={isValid(u){return!!te.is(u.contentType,this.value)},response:M.UnsupportedMediaType,value:r.allowMIME},i=r.fileNameValidation??ht,l={isValid(u){return i(u.name)},response:M.InvalidFileName};this.validation.add({filename:l,mime:a,size:s}),this.validation.add({...r.validation})}get raw(){}async getReadUrl(e,r){return E($.METHOD_NOT_ALLOWED,`${this.constructor.name} does not implement getReadUrl()`)}async getUploadUrl(e,r){return E($.METHOD_NOT_ALLOWED,`${this.constructor.name} does not implement getUploadUrl()`)}get tusExtension(){const e=["creation","creation-with-upload","termination","checksum","creation-defer-length","concatenation"];return this.expiration&&e.push("expiration"),e}async validate(e){await this.validation.verify(e)}async exists(e,r){return this.instrumentOperation("exists",async()=>{try{return await this.getMeta(e.id,r),!0}catch{return!1}})}normalizeError(e){const r={code:e.name,message:e.message,name:e.name,statusCode:500};return{...r,message:`[${this.constructor.name}] ${r.message}`}}get config(){return this.genericConfig}async saveMeta(e){return G.assertSafeId(e.id),this.updateTimestamps(e),this.cache.set(e.id,e),this.meta.save(e.id,e)}static assertSafeId(e){(!e||typeof e!="string"||e.includes("\0")||e.includes("../")||e.includes("..\\")||e===".."||e.startsWith("../")||e.startsWith("..\\")||I(e)||/^[A-Z]:[/\\]/i.test(e))&&E($.INVALID_FILE_NAME,`Invalid file id: "${e}"`)}async deleteMeta(e){return this.cache.delete(e),this.meta.delete(e)}async getMeta(e,r){try{const o=await this.meta.get(e);return this.cache.set(o.id,o),{...o}}catch(o){const s=this.normalizeError(o instanceof Error?o:new Error(String(o)));return await this.onError(s),E($.FILE_NOT_FOUND)}}async checkIfExpired(e){return ne(e)?(this.delete(e).catch(()=>{}),this.deleteMeta(e.id).catch(()=>{}),E($.GONE)):e}async purge(e){return this.instrumentOperation("purge",async()=>{const r=T(e||this.expiration?.maxAge),o={items:[],maxAgeMs:r};if(r){const s=Date.now()-r,a=(await this.list()).filter(i=>Number(new Date(this.expiration?.rolling&&i.modifiedAt||i.createdAt))<s);for await(const{id:i,...l}of a)try{const u=await this.delete({id:i});o.items.push({...u,...l})}catch(u){this.logger?.warn(`Failed to delete file ${i} during purge: ${u instanceof Error?u.message:String(u)}`)}o.items.length>0&&(this.logger?.info(`Purge: removed ${o.items.length} uploads`),this.metrics.gauge("storage.operations.purge.items_count",o.items.length,{storage:this.constructor.name.toLowerCase().replace("storage","")}))}return o})}async getStream({id:e}){return this.instrumentOperation("getStream",async()=>{const r=await this.get({id:e}),o=X.from(r.content);return{headers:{"Content-Length":String(r.size),"Content-Type":r.contentType,...r.ETag&&{ETag:r.ETag},...r.modifiedAt&&{"Last-Modified":r.modifiedAt.toString()}},size:typeof r.size=="number"?r.size:void 0,stream:o}})}async list(e=1e3,r){return this.instrumentOperation("list",async()=>{throw new Error("Not implemented")})}async update({id:e},r){return this.instrumentOperation("update",async()=>{const o=await this.getMeta(e),s={...r};if("ttl"in s&&s.ttl!==void 0){const i=s.ttl,l=typeof i=="string"?T(i):i;l!==void 0&&(s.expiredAt=Date.now()+l),delete s.ttl}ut(o,s),await this.saveMeta(o);const a={...o,status:"updated"};return await this.onUpdate(a),a})}async deleteBatch(e,r){const o=Date.now(),s=this.constructor.name.toLowerCase().replace("storage","");this.metrics.increment("storage.operations.batch.delete.count",1,{batch_size:e.length,storage:s});const a=[],i=[],l=e.map(async m=>{try{return{file:await this.delete({id:m},r),id:m,success:!0}}catch(g){const c=g instanceof Error?g.message:"Delete failed";return this.metrics.increment("storage.operations.delete.error.count",1,{error:c,storage:s}),{error:c,id:m,success:!1}}}),u=await Promise.allSettled(l);for(const m of u)m.status==="fulfilled"?m.value.success?a.push(m.value.file):i.push({error:m.value.error,id:m.value.id}):i.push({error:m.reason?.message||"Delete failed",id:""});const n=Date.now()-o;return this.metrics.timing("storage.operations.batch.delete.duration",n,{batch_size:e.length,storage:s}),this.metrics.gauge("storage.operations.batch.delete.success_count",a.length,{storage:s}),this.metrics.gauge("storage.operations.batch.delete.failed_count",i.length,{storage:s}),{failed:i,failedCount:i.length,successful:a,successfulCount:a.length}}async copyBatch(e){const r=Date.now(),o=this.constructor.name.toLowerCase().replace("storage","");this.metrics.increment("storage.operations.batch.copy.count",1,{batch_size:e.length,storage:o});const s=[],a=[],i=e.map(async({destination:n,options:m,source:g})=>{try{return{file:await this.copy(g,n,m),id:n,success:!0}}catch(c){const d=c instanceof Error?c.message:"Copy failed";return this.metrics.increment("storage.operations.copy.error.count",1,{error:d,storage:o}),{error:d,id:n,success:!1}}}),l=await Promise.allSettled(i);for(const n of l)n.status==="fulfilled"?n.value.success&&n.value.file?s.push(n.value.file):a.push({error:n.value.error||"Copy failed",id:n.value.id}):a.push({error:n.reason?.message||"Copy failed",id:""});const u=Date.now()-r;return this.metrics.timing("storage.operations.batch.copy.duration",u,{batch_size:e.length,storage:o}),this.metrics.gauge("storage.operations.batch.copy.success_count",s.length,{storage:o}),this.metrics.gauge("storage.operations.batch.copy.failed_count",a.length,{storage:o}),{failed:a,failedCount:a.length,successful:s,successfulCount:s.length}}async moveBatch(e){const r=Date.now(),o=this.constructor.name.toLowerCase().replace("storage","");this.metrics.increment("storage.operations.batch.move.count",1,{batch_size:e.length,storage:o});const s=[],a=[],i=e.map(async({destination:n,source:m})=>{try{return{file:await this.move(m,n),id:n,success:!0}}catch(g){const c=g instanceof Error?g.message:"Move failed";return this.metrics.increment("storage.operations.move.error.count",1,{error:c,storage:o}),{error:c,id:n,success:!1}}}),l=await Promise.allSettled(i);for(const n of l)n.status==="fulfilled"?n.value.success&&n.value.file?s.push(n.value.file):a.push({error:n.value.error||"Move failed",id:n.value.id}):a.push({error:n.reason?.message||"Move failed",id:n.reason?.id||""});const u=Date.now()-r;return this.metrics.timing("storage.operations.batch.move.duration",u,{batch_size:e.length,storage:o}),this.metrics.gauge("storage.operations.batch.move.success_count",s.length,{storage:o}),this.metrics.gauge("storage.operations.batch.move.failed_count",a.length,{storage:o}),{failed:a,failedCount:a.length,successful:s,successfulCount:s.length}}async lock(e){const r=[...this.locker.keys()];return r.includes(e)?E($.FILE_LOCKED):this.config.concurrency&&typeof this.config.concurrency=="number"&&this.config.concurrency<r.length?E($.STORAGE_BUSY):this.locker.lock(e)}async unlock(e,r){if(r===void 0){this.locker.delete(e);return}this.locker.unlock(e,r)}async withLock(e,r){const o=await this.lock(e);try{return await r()}finally{await this.unlock(e,o)}}isUnsupportedChecksum(e=""){return!!e&&!this.checksumTypes.includes(e)}startAutoPurge(e){if(e>=2147483647)throw new Error("“purgeInterval” must be less than 2147483647 ms");J(()=>{this.purge().catch(r=>this.logger?.error(r))},e)}updateTimestamps(e){e.createdAt??=new Date().toISOString();const r=T(this.expiration?.maxAge);return r&&!e.expiredAt&&(e.expiredAt=this.expiration?.rolling?Date.now()+r:+new Date(e.createdAt)+r),e}getRetryConfig(){}runOperation(e,r,o){let s;typeof e?.retries=="number"?s={maxRetries:e.retries}:e?.retries&&(s=e.retries);const a={...this.getRetryConfig(),...s};o?.replayable===!1&&(a.maxRetries=0);const i=[];this.genericConfig.defaultSignal&&i.push(this.genericConfig.defaultSignal),e?.signal&&i.push(e.signal);let l;i.length===1?[l]=i:i.length>1&&(l=AbortSignal.any(i));const u=typeof e?.timeout=="number"?e.timeout:this.genericConfig.defaultTimeout,n=typeof u=="number"&&u>0?u:void 0,m=a.shouldRetry;a.shouldRetry=c=>l?.aborted||c instanceof Error&&c.name==="AbortError"?!1:m?m(c):!1;const g=b(c=>{if(c instanceof Error&&c.name==="AbortError")return c;const d=c instanceof Error&&c.message?c.message:"The operation was aborted",h=new Error(d,{cause:c});return h.name="AbortError",h},"toAbortError");return ie(async()=>{if(l?.aborted)throw g(l.reason);let c,d;if(n===void 0)d=l;else{const h=new AbortController;c=setTimeout(()=>{h.abort(new DOMException(`The operation timed out after ${n}ms`,"TimeoutError"))},n),d=l?AbortSignal.any([l,h.signal]):h.signal}try{return await r(d)}catch(h){throw d?.aborted?g(h):h}finally{c&&clearTimeout(c)}},a)}async instrumentOperation(e,r,o){const s=Date.now(),a={storage:this.constructor.name.toLowerCase().replace("storage",""),...o};try{this.metrics.increment(`storage.operations.${e}.count`,1,a);const i=await r(),l=Date.now()-s;return this.metrics.timing(`storage.operations.${e}.duration`,l,a),i&&typeof i=="object"&&"size"in i&&typeof i.size=="number"&&this.metrics.gauge("storage.files.size",i.size,{...a,operation:e}),i}catch(i){const l=Date.now()-s,u=i instanceof Error?i.message:"Unknown error";throw this.metrics.timing(`storage.operations.${e}.duration`,l,{...a,error:"true"}),this.metrics.increment(`storage.operations.${e}.error.count`,1,{...a,error:u}),i}}}export{j as $,G as B,It as a,ot as b,ht as d,St as i,T as t,ut as u,qe as z};