@visulima/storage 1.0.10 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/LICENSE.md +33 -22
  3. package/dist/adapter/nuxt/module.d.ts +5 -4
  4. package/dist/ai/ai-sdk/index.d.ts +4 -3
  5. package/dist/ai/claude/index.d.ts +3 -2
  6. package/dist/ai/openai/index.d.ts +4 -3
  7. package/dist/ai/tanstack/index.d.ts +3 -2
  8. package/dist/handler/http/fetch/index.d.ts +8 -7
  9. package/dist/handler/http/fetch/index.js +1 -1
  10. package/dist/handler/http/hono/index.d.ts +5 -4
  11. package/dist/handler/http/hono/index.js +1 -1
  12. package/dist/handler/http/nextjs/index.d.ts +5 -4
  13. package/dist/handler/http/nextjs/index.js +1 -1
  14. package/dist/handler/http/node/index.d.ts +8 -7
  15. package/dist/handler/http/node/index.js +1 -1
  16. package/dist/handler/http/solid-start/index.d.ts +5 -4
  17. package/dist/handler/http/solid-start/index.js +1 -1
  18. package/dist/index.d.ts +8 -7
  19. package/dist/index.js +1 -1
  20. package/dist/packem_shared/{AbstractBaseStorage-CiPEMcuo.js → AbstractBaseStorage-CLsYmMZg.js} +1 -1
  21. package/dist/packem_shared/AwsLightStorage-DGSPFUqr.js +1 -0
  22. package/dist/packem_shared/AzureStorage-DvKk_hhz.js +1 -0
  23. package/dist/packem_shared/BoxMetaStorage-CJsyeQ63.js +1 -0
  24. package/dist/packem_shared/{BoxStorage-B8_oCz27.js → BoxStorage-CmM95wi2.js} +1 -1
  25. package/dist/packem_shared/BunS3MetaStorage-CJsyeQ63.js +1 -0
  26. package/dist/packem_shared/{BunS3Storage-_PVXu_na.js → BunS3Storage-B_roVJ29.js} +1 -1
  27. package/dist/packem_shared/BunnyMetaStorage-CJsyeQ63.js +1 -0
  28. package/dist/packem_shared/{BunnyStorage-BsoWjScH.js → BunnyStorage-eZ1QDVaY.js} +1 -1
  29. package/dist/packem_shared/CloudinaryMetaStorage-Bv_YCZ0Q.js +1 -0
  30. package/dist/packem_shared/{CloudinaryStorage-BNwiLF9V.js → CloudinaryStorage-CpH2f0Fv.js} +1 -1
  31. package/dist/packem_shared/DiskStorage-DzjjqCzo.js +1 -0
  32. package/dist/packem_shared/{DiskStorageWithChecksum-UnCtyEvs.js → DiskStorageWithChecksum-MZkDEyts.js} +1 -1
  33. package/dist/packem_shared/DropboxMetaStorage-CJsyeQ63.js +1 -0
  34. package/dist/packem_shared/{DropboxStorage-BS9kj0nH.js → DropboxStorage-BB9NoWK2.js} +1 -1
  35. package/dist/packem_shared/{Files-CpIcMjP0.js → Files-DyMJ9FPN.js} +1 -1
  36. package/dist/packem_shared/FirebaseMetaStorage-Bv_YCZ0Q.js +1 -0
  37. package/dist/packem_shared/{FirebaseStorage-DNquii2p.js → FirebaseStorage-BgbxzYNC.js} +1 -1
  38. package/dist/packem_shared/FtpMetaStorage-CJsyeQ63.js +1 -0
  39. package/dist/packem_shared/{FtpStorage-Bd004--s.js → FtpStorage-CNqXDz7P.js} +1 -1
  40. package/dist/packem_shared/{GCSMetaStorage-Bf4qDFB1.js → GCSMetaStorage-Cm_XzR0C.js} +1 -1
  41. package/dist/packem_shared/GCStorage-DcvsI7eu.js +1 -0
  42. package/dist/packem_shared/GoogleDriveMetaStorage-B0gLF7Io.js +1 -0
  43. package/dist/packem_shared/{GoogleDriveStorage-v1glykjd.js → GoogleDriveStorage-Du7uBhSm.js} +1 -1
  44. package/dist/packem_shared/{LocalMetaStorage-YWPBYEe7.js → LocalMetaStorage-CcGfFG39.js} +1 -1
  45. package/dist/packem_shared/{MemoryStorage-9gbWd09l.js → MemoryStorage-ChKyI6OY.js} +1 -1
  46. package/dist/packem_shared/{Multipart-D0ok6BBy.js → Multipart-C35TR2qL.js} +1 -1
  47. package/dist/packem_shared/{Multipart-CQjYqU--.js → Multipart-V64Bg5dt.js} +1 -1
  48. package/dist/packem_shared/NetlifyBlobMetaStorage-Bv_YCZ0Q.js +1 -0
  49. package/dist/packem_shared/NetlifyBlobStorage-CZsr_0DF.js +1 -0
  50. package/dist/packem_shared/OneDriveMetaStorage-B0gLF7Io.js +1 -0
  51. package/dist/packem_shared/{OneDriveStorage-BJ3Kzxc5.js → OneDriveStorage-B8qFgMq1.js} +1 -1
  52. package/dist/packem_shared/PocketBaseMetaStorage-Cm3v8g1-.js +1 -0
  53. package/dist/packem_shared/{PocketBaseStorage-DqKHbbvn.js → PocketBaseStorage-D2vMN-oY.js} +1 -1
  54. package/dist/packem_shared/{Rest-DvfN4-kf.js → Rest-BrEMYgxZ.js} +1 -1
  55. package/dist/packem_shared/{Rest-CI_BiZPv.js → Rest-aPVP2ww1.js} +1 -1
  56. package/dist/packem_shared/{S3Storage-BiI2k6d1.js → S3Storage-CTe_BMDl.js} +1 -1
  57. package/dist/packem_shared/SftpMetaStorage-CJsyeQ63.js +1 -0
  58. package/dist/packem_shared/{SftpStorage-w8XdtZtw.js → SftpStorage-BKeAzuej.js} +1 -1
  59. package/dist/packem_shared/SharePointMetaStorage-CJsyeQ63.js +1 -0
  60. package/dist/packem_shared/{SharePointStorage-DpDpI7Ln.js → SharePointStorage-Dtnt5-wk.js} +1 -1
  61. package/dist/packem_shared/SupabaseMetaStorage-B0gLF7Io.js +1 -0
  62. package/dist/packem_shared/{SupabaseStorage-B_ugUCs7.js → SupabaseStorage-CmGQjqXf.js} +1 -1
  63. package/dist/packem_shared/{Tus-BlBZykIL.js → Tus-CJBgnJrn.js} +1 -1
  64. package/dist/packem_shared/{Tus-BBVt2ky3.js → Tus-D9c7KDnl.js} +1 -1
  65. package/dist/packem_shared/UploadThingMetaStorage-Bv_YCZ0Q.js +1 -0
  66. package/dist/packem_shared/{UploadThingStorage-_H45IVqX.js → UploadThingStorage-DZ4zNvDH.js} +1 -1
  67. package/dist/packem_shared/VercelBlobMetaStorage-CJsyeQ63.js +1 -0
  68. package/dist/packem_shared/{VercelBlobStorage-U1YMKeHs.js → VercelBlobStorage-DDNEofR3.js} +1 -1
  69. package/dist/packem_shared/{base-handler-core-D-9Ku1h-.js → base-handler-core-BJP9jHCE.js} +1 -1
  70. package/dist/packem_shared/{base-handler-fetch-CfkNakv8.js → base-handler-fetch-yrYrukwL.js} +1 -1
  71. package/dist/packem_shared/base-handler-node-C8P9rkaH.js +1 -0
  72. package/dist/packem_shared/{createRetryWrapper-CxgiV_hH.js → createRetryWrapper-DgmeHPNF.js} +1 -1
  73. package/dist/packem_shared/disk-storage-DqnnFQAQ.js +1 -0
  74. package/dist/packem_shared/{disk-storage-with-checksum.d-CQucFacO.d.ts → disk-storage-with-checksum.d-Dgwyza8a.d.ts} +1 -1
  75. package/dist/packem_shared/{executors.d-DeDH3Ilt.d.ts → executors.d-B9dIy3NT.d.ts} +2 -1
  76. package/dist/packem_shared/{files.d-D8H_ge9Y.d.ts → files.d-CmSZi3M0.d.ts} +1 -1
  77. package/dist/packem_shared/gcs-meta-storage-Bu2upyHK.js +1 -0
  78. package/dist/packem_shared/local-meta-storage-BELb1YwO.js +11 -0
  79. package/dist/packem_shared/{local-meta-storage.d-DuTEzyii.d.ts → local-meta-storage.d-cRTXr1kb.d.ts} +1 -1
  80. package/dist/packem_shared/{media-transformer.d-CvMFjINm.d.ts → media-transformer.d-C8tn4J2Z.d.ts} +2 -2
  81. package/dist/packem_shared/{memory-storage.d-BRdTiY8y.d.ts → memory-storage.d-BNZvDG1b.d.ts} +1 -1
  82. package/dist/packem_shared/path-C-OWflAo-_mqb5p5d.js +1 -0
  83. package/dist/packem_shared/{rest-base-e0reNDE_.js → rest-base-BQ_dhWyV.js} +1 -1
  84. package/dist/packem_shared/s3-base-storage-CX94H-Za.js +1 -0
  85. package/dist/packem_shared/{s3-base-storage.d-Cg7m4FuH.d.ts → s3-base-storage.d-ks99NSs-.d.ts} +1 -1
  86. package/dist/packem_shared/storage-DR7qdwBN.js +1 -0
  87. package/dist/packem_shared/{storage.d-DIav_lF1.d.ts → storage.d-DwdJrArF.d.ts} +26 -3
  88. package/dist/packem_shared/{tus-base.d-BiEg5t4t.d.ts → tus-base.d-BKBoJVy0.d.ts} +4 -3
  89. package/dist/packem_shared/{types.d-DgHhkCAl.d.ts → types.d-B1_xZIhu.d.ts} +1 -1
  90. package/dist/packem_shared/{types.d-CAAzKiI6.d.ts → types.d-BEUv414z.d.ts} +1 -1
  91. package/dist/packem_shared/{types.d-jAs_Rp_v.d.ts → types.d-D7Zlz5RE.d.ts} +2 -2
  92. package/dist/storage/aws/index.d.ts +3 -2
  93. package/dist/storage/aws/index.js +1 -1
  94. package/dist/storage/aws-light/index.d.ts +3 -2
  95. package/dist/storage/aws-light/index.js +1 -1
  96. package/dist/storage/azure/index.d.ts +2 -1
  97. package/dist/storage/azure/index.js +1 -1
  98. package/dist/storage/box/index.d.ts +3 -2
  99. package/dist/storage/box/index.js +1 -1
  100. package/dist/storage/bun-s3/index.d.ts +3 -2
  101. package/dist/storage/bun-s3/index.js +1 -1
  102. package/dist/storage/bunny/index.d.ts +3 -2
  103. package/dist/storage/bunny/index.js +1 -1
  104. package/dist/storage/cloudinary/index.d.ts +3 -2
  105. package/dist/storage/cloudinary/index.js +1 -1
  106. package/dist/storage/dropbox/index.d.ts +3 -2
  107. package/dist/storage/dropbox/index.js +1 -1
  108. package/dist/storage/firebase/index.d.ts +3 -2
  109. package/dist/storage/firebase/index.js +1 -1
  110. package/dist/storage/ftp/index.d.ts +3 -2
  111. package/dist/storage/ftp/index.js +1 -1
  112. package/dist/storage/gcs/index.d.ts +2 -1
  113. package/dist/storage/gcs/index.js +1 -1
  114. package/dist/storage/google-drive/index.d.ts +3 -2
  115. package/dist/storage/google-drive/index.js +1 -1
  116. package/dist/storage/local/index.d.ts +4 -3
  117. package/dist/storage/local/index.js +1 -1
  118. package/dist/storage/memory/index.d.ts +3 -2
  119. package/dist/storage/memory/index.js +1 -1
  120. package/dist/storage/netlify-blob/index.d.ts +3 -2
  121. package/dist/storage/netlify-blob/index.js +1 -1
  122. package/dist/storage/onedrive/index.d.ts +5 -4
  123. package/dist/storage/onedrive/index.js +1 -1
  124. package/dist/storage/pocketbase/index.d.ts +3 -2
  125. package/dist/storage/pocketbase/index.js +1 -1
  126. package/dist/storage/sftp/index.d.ts +3 -2
  127. package/dist/storage/sftp/index.js +1 -1
  128. package/dist/storage/sharepoint/index.d.ts +4 -3
  129. package/dist/storage/sharepoint/index.js +1 -1
  130. package/dist/storage/supabase/index.d.ts +3 -2
  131. package/dist/storage/supabase/index.js +1 -1
  132. package/dist/storage/uploadthing/index.d.ts +3 -2
  133. package/dist/storage/uploadthing/index.js +1 -1
  134. package/dist/storage/vercel-blob/index.d.ts +3 -2
  135. package/dist/storage/vercel-blob/index.js +1 -1
  136. package/dist/transformer/audio-transformer.d.ts +3 -2
  137. package/dist/transformer/image-transformer.d.ts +3 -2
  138. package/dist/transformer/index.d.ts +4 -3
  139. package/dist/transformer/video-transformer.d.ts +3 -2
  140. package/package.json +2 -2
  141. package/dist/packem_shared/AwsLightStorage-EsqkAtU5.js +0 -1
  142. package/dist/packem_shared/AzureStorage-DL-U7qFG.js +0 -1
  143. package/dist/packem_shared/BoxMetaStorage-CHWrhgg2.js +0 -1
  144. package/dist/packem_shared/BunS3MetaStorage-CHWrhgg2.js +0 -1
  145. package/dist/packem_shared/BunnyMetaStorage-CHWrhgg2.js +0 -1
  146. package/dist/packem_shared/CloudinaryMetaStorage-BI9YXcwU.js +0 -1
  147. package/dist/packem_shared/DiskStorage-D-NtQDms.js +0 -1
  148. package/dist/packem_shared/DropboxMetaStorage-CHWrhgg2.js +0 -1
  149. package/dist/packem_shared/FirebaseMetaStorage-BI9YXcwU.js +0 -1
  150. package/dist/packem_shared/FtpMetaStorage-CHWrhgg2.js +0 -1
  151. package/dist/packem_shared/GCStorage-ChqEpgqR.js +0 -1
  152. package/dist/packem_shared/GoogleDriveMetaStorage-xlHfKwmR.js +0 -1
  153. package/dist/packem_shared/NetlifyBlobMetaStorage-BI9YXcwU.js +0 -1
  154. package/dist/packem_shared/NetlifyBlobStorage-BPyEWSnx.js +0 -1
  155. package/dist/packem_shared/OneDriveMetaStorage-xlHfKwmR.js +0 -1
  156. package/dist/packem_shared/PocketBaseMetaStorage-DnrxOQhO.js +0 -1
  157. package/dist/packem_shared/SftpMetaStorage-CHWrhgg2.js +0 -1
  158. package/dist/packem_shared/SharePointMetaStorage-CHWrhgg2.js +0 -1
  159. package/dist/packem_shared/SupabaseMetaStorage-xlHfKwmR.js +0 -1
  160. package/dist/packem_shared/UploadThingMetaStorage-BI9YXcwU.js +0 -1
  161. package/dist/packem_shared/VercelBlobMetaStorage-CHWrhgg2.js +0 -1
  162. package/dist/packem_shared/base-handler-node-BF1v1qDa.js +0 -1
  163. package/dist/packem_shared/disk-storage-BwPk2IRa.js +0 -1
  164. package/dist/packem_shared/gcs-meta-storage-DQGu_cHq.js +0 -1
  165. package/dist/packem_shared/local-meta-storage-DJDcuxf1.js +0 -11
  166. package/dist/packem_shared/path-0oTTdkvl-DvWvbDbh.js +0 -1
  167. package/dist/packem_shared/s3-base-storage-CMUui93V.js +0 -1
  168. package/dist/packem_shared/storage-0j5nCAUp.js +0 -1
@@ -1 +1 @@
1
- import{v2 as p}from"cloudinary";import{throwErrorCode as u,ERRORS as l}from"./ERRORS-BIBxE2oR.js";import{B as d}from"./storage-0j5nCAUp.js";import c from"./CloudinaryFile-Bo5B-vM1.js";import h from"./CloudinaryMetaStorage-BI9YXcwU.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as m}from"./update-size-DuNuLyxj.js";import{i as f}from"./part-match-D-9dGX42.js";import{e as w}from"./has-content-50BsqrWw.js";const v=async o=>{const e=[];for await(const a of o)e.push(Buffer.from(a));return Buffer.concat(e)},_=o=>{if(!o)return{};const e=o.match(/^cloudinary:\/\/([^:]+):([^@]+)@(.+)$/);return e?{apiKey:e[1],apiSecret:e[2],cloudName:e[3]}:{}};class M extends d{static name="cloudinary";checksumTypes=[];meta;client;defaultUrlExpiresIn;deliveryType;resourceType;secure;constructor(e){if(super(e),this.resourceType=e.resourceType??"raw",this.deliveryType=e.type??"upload",this.secure=e.secure??!0,this.defaultUrlExpiresIn=e.defaultUrlExpiresIn??3600,e.client)this.client=e.client;else{const a=_(process.env.CLOUDINARY_URL),t=e.cloudName??process.env.CLOUDINARY_CLOUD_NAME??a.cloudName,r=e.apiKey??process.env.CLOUDINARY_API_KEY??a.apiKey,i=e.apiSecret??process.env.CLOUDINARY_API_SECRET??a.apiSecret;if(!t)throw new Error("Cloudinary storage: `cloudName` is required (or set CLOUDINARY_CLOUD_NAME / CLOUDINARY_URL).");p.config({api_key:r,api_secret:i,cloud_name:t,secure:this.secure}),this.client=p}this.meta=e.metaStorage??new h(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new c(e);t.name=this.namingFunction(t),t.path=t.name,await this.validate(t);try{const r=await this.getMeta(t.id);if(r.bytesWritten>=0)return r}catch{}return t.bytesWritten=0,t.status=y(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,a){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&&m(t,e.size),!f(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(w(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await v(e.body),s=t.path??t.name,n=await this.runOperation(a,()=>this.uploadBuffer(s,i));t.bytesWritten=i.length,t.size=i.length,t.path=n.public_id??s,t.publicUrl=n.secure_url??n.url,t.ETag=n.version===void 0?void 0:String(n.version)}return t.status=y(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const r=t?.path??t?.name??e;return await this.runOperation(a,()=>this.client.uploader.destroy(r,{invalidate:!0,resource_type:this.resourceType,type:this.deliveryType})),t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,path:r,status:"deleted"})})}async exists({id:e},a){return this.instrumentOperation("exists",async()=>{let t=e;try{t=(await this.getMeta(e)).path??e}catch{}try{return await this.runOperation(a,()=>this.client.api.resource(t,{resource_type:this.resourceType,type:this.deliveryType})),!0}catch{return!1}})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t=e,r;try{r=await this.checkIfExpired(await this.getMeta(e)),t=r.path??r.name??e}catch{}const i=await this.runOperation(a,()=>this.client.api.resource(t,{resource_type:this.resourceType,type:this.deliveryType})),s=await this.runOperation(a,()=>fetch(this.client.url(t,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType})));if(!s.ok)throw new Error(`Cloudinary: object not found at "${t}"`);const n=Buffer.from(await s.arrayBuffer());return{content:n,contentType:r?.contentType??(i.resource_type&&i.format?`${i.resource_type}/${i.format}`:void 0)??"application/octet-stream",ETag:r?.ETag??(i.version===void 0?void 0:String(i.version)),expiredAt:r?.expiredAt,id:e,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??t,originalName:r?.originalName??t,size:r?.size??(typeof i.bytes=="number"?i.bytes:n.length)}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const r=(await this.getMetaSafe(e))?.path??e,i=this.client.url(r,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType});await this.runOperation(t,()=>this.client.uploader.upload(i,{overwrite:!0,public_id:a,resource_type:this.resourceType,type:this.deliveryType}));const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=a,s})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const r=(await this.getMetaSafe(e))?.path??e;await this.runOperation(t,()=>this.client.uploader.rename(r,a,{resource_type:this.resourceType}));const i=new c({contentType:"application/octet-stream",metadata:{},originalName:a});i.id=a,i.name=a,i.path=a;try{await this.deleteMeta(e)}catch{}return i})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>{const{resources:t}=await this.runOperation(a,()=>this.client.api.resources({max_results:e,resource_type:this.resourceType,type:this.deliveryType}));return(t??[]).map(r=>{const i=new c({contentType:r.resource_type&&r.format?`${r.resource_type}/${r.format}`:"application/octet-stream",metadata:{},originalName:r.public_id});return i.id=r.public_id,i.name=r.public_id,i.path=r.public_id,i.size=typeof r.bytes=="number"?r.bytes:void 0,i.createdAt=r.created_at??void 0,i.ETag=r.version===void 0?void 0:String(r.version),i})},{limit:e})}async getReadUrl(e,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return u(l.BAD_REQUEST,"cloudinary: `responseContentDisposition`/`responseContentType` are not supported. A public delivery URL has no signature in which to bind the override, and Cloudinary's signed download URL cannot pin an arbitrary Content-Disposition/Content-Type; set the disposition via a Cloudinary delivery transformation instead.");if(this.deliveryType==="upload")return this.client.url(e,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType});const t=a?.expiresIn??this.defaultUrlExpiresIn,r=e.lastIndexOf("."),i=r>0?e.slice(r+1):"";try{return this.client.utils.private_download_url(e,i,{expires_at:Math.floor(Date.now()/1e3)+t,resource_type:this.resourceType,type:this.deliveryType})}catch(s){return u(l.METHOD_NOT_ALLOWED,s instanceof Error?s.message:"Cloudinary: private_download_url failed")}}uploadBuffer(e,a){return new Promise((t,r)=>{this.client.uploader.upload_stream({overwrite:!0,public_id:e,resource_type:this.resourceType,type:this.deliveryType},(i,s)=>{if(i||!s){r(i instanceof Error?i:new Error(i?.message??"Cloudinary: upload failed"));return}t(s)}).end(a)})}async getMetaSafe(e){try{return await this.getMeta(e)}catch{return}}internalOnComplete=e=>this.deleteMeta(e.id)}export{M as default};
1
+ import{v2 as p}from"cloudinary";import{throwErrorCode as u,ERRORS as l}from"./ERRORS-BIBxE2oR.js";import{B as d}from"./storage-DR7qdwBN.js";import c from"./CloudinaryFile-Bo5B-vM1.js";import h from"./CloudinaryMetaStorage-Bv_YCZ0Q.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as m}from"./update-size-DuNuLyxj.js";import{i as f}from"./part-match-D-9dGX42.js";import{e as w}from"./has-content-50BsqrWw.js";const v=async o=>{const e=[];for await(const a of o)e.push(Buffer.from(a));return Buffer.concat(e)},_=o=>{if(!o)return{};const e=o.match(/^cloudinary:\/\/([^:]+):([^@]+)@(.+)$/);return e?{apiKey:e[1],apiSecret:e[2],cloudName:e[3]}:{}};class M extends d{static name="cloudinary";checksumTypes=[];meta;client;defaultUrlExpiresIn;deliveryType;resourceType;secure;constructor(e){if(super(e),this.resourceType=e.resourceType??"raw",this.deliveryType=e.type??"upload",this.secure=e.secure??!0,this.defaultUrlExpiresIn=e.defaultUrlExpiresIn??3600,e.client)this.client=e.client;else{const a=_(process.env.CLOUDINARY_URL),t=e.cloudName??process.env.CLOUDINARY_CLOUD_NAME??a.cloudName,r=e.apiKey??process.env.CLOUDINARY_API_KEY??a.apiKey,i=e.apiSecret??process.env.CLOUDINARY_API_SECRET??a.apiSecret;if(!t)throw new Error("Cloudinary storage: `cloudName` is required (or set CLOUDINARY_CLOUD_NAME / CLOUDINARY_URL).");p.config({api_key:r,api_secret:i,cloud_name:t,secure:this.secure}),this.client=p}this.meta=e.metaStorage??new h(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new c(e);t.name=this.namingFunction(t),t.path=t.name,await this.validate(t);try{const r=await this.getMeta(t.id);if(r.bytesWritten>=0)return r}catch{}return t.bytesWritten=0,t.status=y(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,a){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&&m(t,e.size),!f(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(w(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await v(e.body),s=t.path??t.name,n=await this.runOperation(a,()=>this.uploadBuffer(s,i));t.bytesWritten=i.length,t.size=i.length,t.path=n.public_id??s,t.publicUrl=n.secure_url??n.url,t.ETag=n.version===void 0?void 0:String(n.version)}return t.status=y(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const r=t?.path??t?.name??e;return await this.runOperation(a,()=>this.client.uploader.destroy(r,{invalidate:!0,resource_type:this.resourceType,type:this.deliveryType})),t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,path:r,status:"deleted"})})}async exists({id:e},a){return this.instrumentOperation("exists",async()=>{let t=e;try{t=(await this.getMeta(e)).path??e}catch{}try{return await this.runOperation(a,()=>this.client.api.resource(t,{resource_type:this.resourceType,type:this.deliveryType})),!0}catch{return!1}})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t=e,r;try{r=await this.checkIfExpired(await this.getMeta(e)),t=r.path??r.name??e}catch{}const i=await this.runOperation(a,()=>this.client.api.resource(t,{resource_type:this.resourceType,type:this.deliveryType})),s=await this.runOperation(a,()=>fetch(this.client.url(t,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType})));if(!s.ok)throw new Error(`Cloudinary: object not found at "${t}"`);const n=Buffer.from(await s.arrayBuffer());return{content:n,contentType:r?.contentType??(i.resource_type&&i.format?`${i.resource_type}/${i.format}`:void 0)??"application/octet-stream",ETag:r?.ETag??(i.version===void 0?void 0:String(i.version)),expiredAt:r?.expiredAt,id:e,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??t,originalName:r?.originalName??t,size:r?.size??(typeof i.bytes=="number"?i.bytes:n.length)}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const r=(await this.getMetaSafe(e))?.path??e,i=this.client.url(r,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType});await this.runOperation(t,()=>this.client.uploader.upload(i,{overwrite:!0,public_id:a,resource_type:this.resourceType,type:this.deliveryType}));const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=a,s})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const r=(await this.getMetaSafe(e))?.path??e;await this.runOperation(t,()=>this.client.uploader.rename(r,a,{resource_type:this.resourceType}));const i=new c({contentType:"application/octet-stream",metadata:{},originalName:a});i.id=a,i.name=a,i.path=a;try{await this.deleteMeta(e)}catch{}return i})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>{const{resources:t}=await this.runOperation(a,()=>this.client.api.resources({max_results:e,resource_type:this.resourceType,type:this.deliveryType}));return(t??[]).map(r=>{const i=new c({contentType:r.resource_type&&r.format?`${r.resource_type}/${r.format}`:"application/octet-stream",metadata:{},originalName:r.public_id});return i.id=r.public_id,i.name=r.public_id,i.path=r.public_id,i.size=typeof r.bytes=="number"?r.bytes:void 0,i.createdAt=r.created_at??void 0,i.ETag=r.version===void 0?void 0:String(r.version),i})},{limit:e})}async getReadUrl(e,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return u(l.BAD_REQUEST,"cloudinary: `responseContentDisposition`/`responseContentType` are not supported. A public delivery URL has no signature in which to bind the override, and Cloudinary's signed download URL cannot pin an arbitrary Content-Disposition/Content-Type; set the disposition via a Cloudinary delivery transformation instead.");if(this.deliveryType==="upload")return this.client.url(e,{resource_type:this.resourceType,secure:this.secure,type:this.deliveryType});const t=a?.expiresIn??this.defaultUrlExpiresIn,r=e.lastIndexOf("."),i=r>0?e.slice(r+1):"";try{return this.client.utils.private_download_url(e,i,{expires_at:Math.floor(Date.now()/1e3)+t,resource_type:this.resourceType,type:this.deliveryType})}catch(s){return u(l.METHOD_NOT_ALLOWED,s instanceof Error?s.message:"Cloudinary: private_download_url failed")}}uploadBuffer(e,a){return new Promise((t,r)=>{this.client.uploader.upload_stream({overwrite:!0,public_id:e,resource_type:this.resourceType,type:this.deliveryType},(i,s)=>{if(i||!s){r(i instanceof Error?i:new Error(i?.message??"Cloudinary: upload failed"));return}t(s)}).end(a)})}async getMetaSafe(e){try{return await this.getMeta(e)}catch{return}}internalOnComplete=e=>this.deleteMeta(e.id)}export{M as default};
@@ -0,0 +1 @@
1
+ import"node:fs";import"node:fs/promises";import"node:stream";import"./local-meta-storage-BELb1YwO.js";import"./path-C-OWflAo-_mqb5p5d.js";import"./index-nZWCQrSe.js";import"./detect-file-type-BA7UBLKA.js";import"./ERRORS-BIBxE2oR.js";import{w as c}from"./disk-storage-DqnnFQAQ.js";import"./storage-DR7qdwBN.js";import"./File-W8aOo15X.js";import"./get-file-status-y3wTtDQs.js";import"./update-size-DuNuLyxj.js";import"./part-match-D-9dGX42.js";import"./has-content-50BsqrWw.js";export{c as default};
@@ -1 +1 @@
1
- import{createReadStream as l,createWriteStream as y}from"node:fs";import{truncate as g}from"node:fs/promises";import{Transform as f,pipeline as w}from"node:stream";import{u as b,h as E}from"./local-meta-storage-DJDcuxf1.js";import{d as F}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as c,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{F as C,n as T,s as W}from"./disk-storage-BwPk2IRa.js";import{LRUCache as N}from"lru-cache";import{createHash as S}from"node:crypto";import{t as R}from"./update-size-DuNuLyxj.js";import{i as x}from"./part-match-D-9dGX42.js";import{e as M}from"./has-content-50BsqrWw.js";import{t as _}from"./get-file-status-y3wTtDQs.js";class k extends f{constructor(t,e){super(),this.path=e,this.hashes=t,this.hash=this.hashes.get(e)||S(this.hashes.algorithm),this.hashCopy=this.hash.copy()}path;hash;hashCopy;hashes;reset(){this.hashes.set(this.path,this.hashCopy)}digest(t="hex"){return this.hash.copy().digest(t)}_transform(t,e,s){this.push(t),this.hash.update(t),s()}_flush(t){t()}}class I extends N{constructor(t="sha1",e){super({ttl:1e3,ttlAutopurge:!0,...e}),this.algorithm=t}algorithm;hex(t){return this.get(t)?.copy().digest("hex")||""}base64(t){return this.get(t)?.copy().digest("base64")||""}async init(t,e=0){return this.get(t)?.copy()||this.updateFromFs(t,e)}digester(t){return new k(this,t)}async updateFromFs(t,e=0,s){const r=await this.fromFs(t,e,s);return this.set(t,r),r}fromFs(t,e=0,s){return new Promise((r,i)=>{const a=this.digester(t);s!==void 0&&(a.hash=s),l(t,{start:e}).on("error",i).on("end",()=>{r(a.hash)}).pipe(a).resume()})}}class j extends C{hashes;constructor(t){super(t),this.hashes=new I(t?.checksum==="sha1"?"sha1":"md5")}async delete({id:t}){try{const e=await this.getMeta(t),s=this.getFilePath(e.name);this.hashes.delete(s),await b(s),await this.deleteMeta(t);const r={...e,status:"deleted"};return await this.onDelete(r),r}catch(e){this.logger?.error("[error]: Could not delete file: %O",e);const s=this.normalizeError(e instanceof Error?e:new Error(String(e)));await this.onError(s)}return{id:t}}async write(t){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&&R(e,t.size),!x(t,e))return c(h.FILE_CONFLICT);const s=this.getFilePath(e.name);try{const r=t.start||0;if(await E(s),(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(e.bytesWritten=r),await this.hashes.init(s),M(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return c(h.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:o,stream:n}=await F(t.body);o?.mime&&(e.contentType=o.mime),t.body=n}catch{}const[i,a]=await this.lazyWrite({...t,...e});if(a)return await g(s,e.bytesWritten),c(a);typeof i!="number"&&await this.hashes.updateFromFs(s,e.bytesWritten),e.bytesWritten=i}return e.status=_(e),e.hash={algorithm:this.hashes.algorithm,value:this.hashes.hex(s)},e.status==="completed"&&this.hashes.delete(s),await this.saveMeta(e),e}catch(r){await this.hashes.updateFromFs(s,e.bytesWritten);const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));return await this.onError(i),c(h.FILE_ERROR,(typeof i.message=="string"?i.message:String(r))||String(r))}}lazyWrite(t){return new Promise((e,s)=>{const r=this.getFilePath(t.name),i=y(r,{flags:"r+",start:t.start}),a=new T(t.contentLength||Number(t.size)-t.start),o=W(t.checksum,t.checksumAlgorithm),n=this.hashes.digester(r),d=!t.checksum,u=m=>{n.reset(),i.close(),e([Number.NaN,m])};a.on("error",()=>{u(h.FILE_CONFLICT)}),o.on("error",()=>{u(h.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{u(d?void 0:h.REQUEST_ABORTED)}),w(t.body,a,o,n,i,m=>{if(m){n.reset(),s(m);return}e([t.start+i.bytesWritten])})})}}export{j as default};
1
+ import{createReadStream as l,createWriteStream as y}from"node:fs";import{truncate as g}from"node:fs/promises";import{Transform as f,pipeline as w}from"node:stream";import{u as b,h as E}from"./local-meta-storage-BELb1YwO.js";import{d as F}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as c,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{w as C,n as T,s as W}from"./disk-storage-DqnnFQAQ.js";import{LRUCache as N}from"lru-cache";import{createHash as S}from"node:crypto";import{t as R}from"./update-size-DuNuLyxj.js";import{i as x}from"./part-match-D-9dGX42.js";import{e as M}from"./has-content-50BsqrWw.js";import{t as _}from"./get-file-status-y3wTtDQs.js";class k extends f{constructor(t,e){super(),this.path=e,this.hashes=t,this.hash=this.hashes.get(e)||S(this.hashes.algorithm),this.hashCopy=this.hash.copy()}path;hash;hashCopy;hashes;reset(){this.hashes.set(this.path,this.hashCopy)}digest(t="hex"){return this.hash.copy().digest(t)}_transform(t,e,s){this.push(t),this.hash.update(t),s()}_flush(t){t()}}class I extends N{constructor(t="sha1",e){super({ttl:1e3,ttlAutopurge:!0,...e}),this.algorithm=t}algorithm;hex(t){return this.get(t)?.copy().digest("hex")||""}base64(t){return this.get(t)?.copy().digest("base64")||""}async init(t,e=0){return this.get(t)?.copy()||this.updateFromFs(t,e)}digester(t){return new k(this,t)}async updateFromFs(t,e=0,s){const r=await this.fromFs(t,e,s);return this.set(t,r),r}fromFs(t,e=0,s){return new Promise((r,i)=>{const a=this.digester(t);s!==void 0&&(a.hash=s),l(t,{start:e}).on("error",i).on("end",()=>{r(a.hash)}).pipe(a).resume()})}}class j extends C{hashes;constructor(t){super(t),this.hashes=new I(t?.checksum==="sha1"?"sha1":"md5")}async delete({id:t}){try{const e=await this.getMeta(t),s=this.getFilePath(e.name);this.hashes.delete(s),await b(s),await this.deleteMeta(t);const r={...e,status:"deleted"};return await this.onDelete(r),r}catch(e){this.logger?.error("[error]: Could not delete file: %O",e);const s=this.normalizeError(e instanceof Error?e:new Error(String(e)));await this.onError(s)}return{id:t}}async write(t){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&&R(e,t.size),!x(t,e))return c(h.FILE_CONFLICT);const s=this.getFilePath(e.name);try{const r=t.start||0;if(await E(s),(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(e.bytesWritten=r),await this.hashes.init(s),M(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return c(h.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:o,stream:n}=await F(t.body);o?.mime&&(e.contentType=o.mime),t.body=n}catch{}const[i,a]=await this.lazyWrite({...t,...e});if(a)return await g(s,e.bytesWritten),c(a);typeof i!="number"&&await this.hashes.updateFromFs(s,e.bytesWritten),e.bytesWritten=i}return e.status=_(e),e.hash={algorithm:this.hashes.algorithm,value:this.hashes.hex(s)},e.status==="completed"&&this.hashes.delete(s),await this.saveMeta(e),e}catch(r){await this.hashes.updateFromFs(s,e.bytesWritten);const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));return await this.onError(i),c(h.FILE_ERROR,(typeof i.message=="string"?i.message:String(r))||String(r))}}lazyWrite(t){return new Promise((e,s)=>{const r=this.getFilePath(t.name),i=y(r,{flags:"r+",start:t.start}),a=new T(t.contentLength||Number(t.size)-t.start),o=W(t.checksum,t.checksumAlgorithm),n=this.hashes.digester(r),d=!t.checksum,u=m=>{n.reset(),i.close(),e([Number.NaN,m])};a.on("error",()=>{u(h.FILE_CONFLICT)}),o.on("error",()=>{u(h.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{u(d?void 0:h.REQUEST_ABORTED)}),w(t.body,a,o,n,i,m=>{if(m){n.reset(),s(m);return}e([t.start+i.bytesWritten])})})}}export{j as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-BELb1YwO.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{DropboxResponseError as _,DropboxAuth as u,Dropbox as d}from"dropbox";import{throwErrorCode as m,ERRORS as y}from"./ERRORS-BIBxE2oR.js";import{c as E}from"./oauth-refresh-EdGzlcOZ.js";import{B as v}from"./storage-0j5nCAUp.js";import l from"./DropboxFile-BFb7eOzy.js";import A from"./DropboxMetaStorage-CHWrhgg2.js";import{t as g}from"./get-file-status-y3wTtDQs.js";import{t as D}from"./update-size-DuNuLyxj.js";import{i as S}from"./part-match-D-9dGX42.js";import{e as x}from"./has-content-50BsqrWw.js";const w=14400,B=150*1024*1024,p=8*1024*1024,k=(r,t)=>{r.auth.setAccessToken(t)},R=r=>r.auth.getAccessToken(),T=r=>{let t=0,n=r.length;for(;t<n&&r[t]==="/";)t+=1;for(;n>t&&r[n-1]==="/";)n-=1;return t===0&&n===r.length?r:r.slice(t,n)},H=async r=>{const t=[];for await(const n of r)t.push(Buffer.from(n));return Buffer.concat(t)},O=r=>r.includes("?dl=0")?r.replace("?dl=0","?dl=1"):r.includes("?dl=")?r:r+(r.includes("?")?"&dl=1":"?dl=1"),b=(r,t)=>(k(r,t),{ensureAccessToken:()=>Promise.resolve(),getAccessToken:()=>Promise.resolve(t)}),U=(r,t)=>{const n=async()=>{const e=await t();return k(r,e),e};return{async ensureAccessToken(){await n()},getAccessToken:n}},P=(r,t)=>{const n=E({buildBody:()=>new URLSearchParams({client_id:t.appKey,grant_type:"refresh_token",refresh_token:t.refreshToken,...t.appSecret&&{client_secret:t.appSecret}}),onRefresh:e=>{k(r,e)},provider:"Dropbox",tokenUrl:"https://api.dropboxapi.com/oauth2/token"});return{async ensureAccessToken(){await n.getAccessToken()},getAccessToken:()=>n.getAccessToken()}},C=r=>{if(r.client){const i=r.client;return{authHandle:{ensureAccessToken:()=>Promise.resolve(),getAccessToken:()=>Promise.resolve(R(i))},client:i}}const t=r.accessToken,n=r.refreshToken!==void 0||r.appKey!==void 0||r.appSecret!==void 0;if(t!==void 0&&n)throw new Error("Dropbox storage: pass exactly one of `accessToken` or `refreshToken` (with `appKey`).");if(t!==void 0){const i=new u({accessToken:typeof t=="string"?t:void 0}),s=new d({auth:i});return{authHandle:typeof t=="function"?U(s,t):b(s,t),client:s}}if(n){if(!r.refreshToken||!r.appKey)throw new Error("Dropbox storage: refresh-token auth requires both `refreshToken` and `appKey`.");const i=new u({}),s=new d({auth:i});return{authHandle:P(s,{appKey:r.appKey,...r.appSecret&&{appSecret:r.appSecret},refreshToken:r.refreshToken}),client:s}}const e=process.env.DROPBOX_ACCESS_TOKEN;if(e){const i=new u({accessToken:e}),s=new d({auth:i});return{authHandle:b(s,e),client:s}}const o=process.env.DROPBOX_REFRESH_TOKEN,a=process.env.DROPBOX_APP_KEY;if(o&&a){const i=process.env.DROPBOX_APP_SECRET,s=new u({}),h=new d({auth:s});return{authHandle:P(h,{appKey:a,...i&&{appSecret:i},refreshToken:o}),client:h}}throw new Error("Dropbox storage: missing auth. Pass `client`, `accessToken`, or `refreshToken` + `appKey`. Env fallbacks: DROPBOX_ACCESS_TOKEN, or DROPBOX_REFRESH_TOKEN + DROPBOX_APP_KEY (+ DROPBOX_APP_SECRET).")};class q extends v{static name="dropbox";checksumTypes=[];meta;authHandle;client;defaultUrlExpiresIn;publicByDefault;rootFolderPath;constructor(t){super(t),this.rootFolderPath=T(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w);const n=C(t);this.client=n.client,this.authHandle=n.authHandle,this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,n){return this.instrumentOperation("create",async()=>{const e=new l(t);e.name=this.namingFunction(e),e.path=this.keyToPath(e.name),await this.validate(e);try{const o=await this.getMeta(e.id);if(o.bytesWritten>=0)return o}catch{}return e.bytesWritten=0,e.status=g(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,n){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&&D(e,t.size),!S(t,e))throw new Error("File part does not match");const o=await this.lock(t.id);try{if(x(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await H(t.body),i=e.path??this.keyToPath(e.name||e.id);await this.authHandle.ensureAccessToken();const s=a.byteLength<=B?await this.uploadSimple(i,a,n):await this.uploadSession(i,a,n);e.bytesWritten=a.length,e.size=a.length,e.path=s.path_display??i,e.rev=s.rev,e.ETag=s.rev}return e.status=g(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,o)}})}async delete({id:t},n){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const o=e?.path??this.keyToPath(e?.name??t);await this.authHandle.ensureAccessToken();try{await this.runOperation(n,()=>this.client.filesDeleteV2({path:o}))}catch(a){if(!L(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new l({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,path:o,status:"deleted"})})}async get({id:t},n){return this.instrumentOperation("get",async()=>{let e,o=this.keyToPath(t);try{e=await this.checkIfExpired(await this.getMeta(t)),o=e.path??this.keyToPath(e.name??t)}catch{}await this.authHandle.ensureAccessToken();const a=(await this.runOperation(n,()=>this.client.filesDownload({path:o}))).result;let i;if(a.fileBinary instanceof Uint8Array)i=Buffer.from(a.fileBinary.buffer,a.fileBinary.byteOffset,a.fileBinary.byteLength);else if(a.fileBlob instanceof Blob)i=Buffer.from(await a.fileBlob.arrayBuffer());else throw new TypeError("Dropbox: unexpected download response shape — neither fileBinary nor fileBlob present");return{content:i,contentType:e?.contentType??"application/octet-stream",ETag:e?.ETag??a.rev,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??a.server_modified,name:e?.name??a.name,originalName:e?.originalName??a.name,size:e?.size??a.size??i.length}})}async copy(t,n,e){return this.instrumentOperation("copy",async()=>{const o=this.keyToPath(t),a=this.keyToPath(n);await this.authHandle.ensureAccessToken(),await this.runOperation(e,()=>this.client.filesCopyV2({from_path:o,to_path:a}));const i=new l({contentType:"application/octet-stream",metadata:{},originalName:n});return i.id=n,i.name=n,i.path=a,i})}async move(t,n,e){return this.instrumentOperation("move",async()=>{const o=this.keyToPath(t),a=this.keyToPath(n);await this.authHandle.ensureAccessToken(),await this.runOperation(e,()=>this.client.filesMoveV2({from_path:o,to_path:a}));const i=new l({contentType:"application/octet-stream",metadata:{},originalName:n});i.id=n,i.name=n,i.path=a;try{await this.deleteMeta(t)}catch{}return i})}async list(t=1e3,n){return this.instrumentOperation("list",async()=>{await this.authHandle.ensureAccessToken();const e=await this.runOperation(n,()=>this.client.filesListFolder({limit:t,path:this.rootFolderPath?`/${this.rootFolderPath}`:"",recursive:!0})),{result:o}=e,a=[];for(const i of o.entries){if(i[".tag"]!=="file")continue;const s=i,h=s.path_display??s.path_lower??`/${s.name}`,f=this.pathToKey(h);if(!f)continue;const c=new l({contentType:"application/octet-stream",metadata:{},originalName:s.name});c.id=f,c.name=f,c.path=h,c.size=s.size,c.rev=s.rev,c.ETag=s.rev,c.modifiedAt=s.server_modified,a.push(c)}return a},{limit:t})}async getReadUrl(t,n){if(n?.responseContentDisposition!==void 0||n?.responseContentType!==void 0)return m(y.METHOD_NOT_ALLOWED,"Dropbox: `responseContentDisposition`/`responseContentType` are not supported — Dropbox temporary links have no Content-Disposition/Content-Type override.");const e=n?.expiresIn??this.defaultUrlExpiresIn;return e>w?m(y.METHOD_NOT_ALLOWED,`Dropbox: \`expiresIn\` of ${e}s exceeds the ${w}s (4h) maximum. Use \`publicByDefault: true\` for a permanent shared link.`):(await this.authHandle.ensureAccessToken(),this.publicByDefault?await this.createPublicSharedLink(t):(await this.client.filesGetTemporaryLink({path:this.keyToPath(t)})).result.link)}async getUploadUrl(t,n){return m(y.METHOD_NOT_ALLOWED,"Dropbox: presigned upload URLs use POST with a raw body, which doesn't fit the PUT-style upload-url contract. Use `write()` or `storage.raw.filesGetTemporaryUploadLink(...)` directly.")}keyToPath(t){const n=T(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),n&&e.push(n),e.length===0?"":`/${e.join("/")}`}pathToKey(t){const n=T(t);if(!this.rootFolderPath)return n;if(n===this.rootFolderPath)return"";const e=`${this.rootFolderPath}/`;return n.startsWith(e)?n.slice(e.length):n}async uploadSimple(t,n,e){return(await this.runOperation(e,()=>this.client.filesUpload({contents:n,mode:{".tag":"overwrite"},mute:!0,path:t}))).result}async uploadSession(t,n,e){const o=n.byteLength;let a=0;const i=(await this.runOperation(e,()=>this.client.filesUploadSessionStart({close:!1,contents:n.subarray(a,Math.min(a+p,o))}))).result.session_id;for(a=Math.min(a+p,o);o-a>p;){const h=n.subarray(a,a+p);await this.runOperation(e,()=>this.client.filesUploadSessionAppendV2({close:!1,contents:h,cursor:{offset:a,session_id:i}})),a+=p}const s=n.subarray(a,o);return(await this.runOperation(e,()=>this.client.filesUploadSessionFinish({commit:{mode:{".tag":"overwrite"},mute:!0,path:t},contents:s,cursor:{offset:a,session_id:i}}))).result}async createPublicSharedLink(t){try{const n=await this.client.sharingCreateSharedLinkWithSettings({path:this.keyToPath(t),settings:{requested_visibility:{".tag":"public"}}});return O(n.result.url)}catch(n){if(n instanceof _){const e=n.error?.shared_link_already_exists?.metadata?.url;if(typeof e=="string"&&e.length>0)return O(e)}throw n}}internalOnComplete=t=>this.deleteMeta(t.id)}const L=r=>{if(!(r instanceof _))return!1;if(r.status===404)return!0;const t=[],n=(e,o)=>{if(o>6||e===null||typeof e!="object")return;const a=e,i=a[".tag"];typeof i=="string"&&t.push(i);for(const s of Object.values(a))s&&typeof s=="object"&&n(s,o+1)};return n(r.error,0),t.includes("not_found")||t.includes("not_file")||t.includes("not_folder")};export{q as default};
1
+ import{DropboxResponseError as _,DropboxAuth as u,Dropbox as d}from"dropbox";import{throwErrorCode as m,ERRORS as y}from"./ERRORS-BIBxE2oR.js";import{c as E}from"./oauth-refresh-EdGzlcOZ.js";import{B as v}from"./storage-DR7qdwBN.js";import l from"./DropboxFile-BFb7eOzy.js";import A from"./DropboxMetaStorage-CJsyeQ63.js";import{t as g}from"./get-file-status-y3wTtDQs.js";import{t as D}from"./update-size-DuNuLyxj.js";import{i as S}from"./part-match-D-9dGX42.js";import{e as x}from"./has-content-50BsqrWw.js";const w=14400,B=150*1024*1024,p=8*1024*1024,k=(r,t)=>{r.auth.setAccessToken(t)},R=r=>r.auth.getAccessToken(),T=r=>{let t=0,n=r.length;for(;t<n&&r[t]==="/";)t+=1;for(;n>t&&r[n-1]==="/";)n-=1;return t===0&&n===r.length?r:r.slice(t,n)},H=async r=>{const t=[];for await(const n of r)t.push(Buffer.from(n));return Buffer.concat(t)},O=r=>r.includes("?dl=0")?r.replace("?dl=0","?dl=1"):r.includes("?dl=")?r:r+(r.includes("?")?"&dl=1":"?dl=1"),b=(r,t)=>(k(r,t),{ensureAccessToken:()=>Promise.resolve(),getAccessToken:()=>Promise.resolve(t)}),U=(r,t)=>{const n=async()=>{const e=await t();return k(r,e),e};return{async ensureAccessToken(){await n()},getAccessToken:n}},P=(r,t)=>{const n=E({buildBody:()=>new URLSearchParams({client_id:t.appKey,grant_type:"refresh_token",refresh_token:t.refreshToken,...t.appSecret&&{client_secret:t.appSecret}}),onRefresh:e=>{k(r,e)},provider:"Dropbox",tokenUrl:"https://api.dropboxapi.com/oauth2/token"});return{async ensureAccessToken(){await n.getAccessToken()},getAccessToken:()=>n.getAccessToken()}},C=r=>{if(r.client){const i=r.client;return{authHandle:{ensureAccessToken:()=>Promise.resolve(),getAccessToken:()=>Promise.resolve(R(i))},client:i}}const t=r.accessToken,n=r.refreshToken!==void 0||r.appKey!==void 0||r.appSecret!==void 0;if(t!==void 0&&n)throw new Error("Dropbox storage: pass exactly one of `accessToken` or `refreshToken` (with `appKey`).");if(t!==void 0){const i=new u({accessToken:typeof t=="string"?t:void 0}),s=new d({auth:i});return{authHandle:typeof t=="function"?U(s,t):b(s,t),client:s}}if(n){if(!r.refreshToken||!r.appKey)throw new Error("Dropbox storage: refresh-token auth requires both `refreshToken` and `appKey`.");const i=new u({}),s=new d({auth:i});return{authHandle:P(s,{appKey:r.appKey,...r.appSecret&&{appSecret:r.appSecret},refreshToken:r.refreshToken}),client:s}}const e=process.env.DROPBOX_ACCESS_TOKEN;if(e){const i=new u({accessToken:e}),s=new d({auth:i});return{authHandle:b(s,e),client:s}}const o=process.env.DROPBOX_REFRESH_TOKEN,a=process.env.DROPBOX_APP_KEY;if(o&&a){const i=process.env.DROPBOX_APP_SECRET,s=new u({}),h=new d({auth:s});return{authHandle:P(h,{appKey:a,...i&&{appSecret:i},refreshToken:o}),client:h}}throw new Error("Dropbox storage: missing auth. Pass `client`, `accessToken`, or `refreshToken` + `appKey`. Env fallbacks: DROPBOX_ACCESS_TOKEN, or DROPBOX_REFRESH_TOKEN + DROPBOX_APP_KEY (+ DROPBOX_APP_SECRET).")};class q extends v{static name="dropbox";checksumTypes=[];meta;authHandle;client;defaultUrlExpiresIn;publicByDefault;rootFolderPath;constructor(t){super(t),this.rootFolderPath=T(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w);const n=C(t);this.client=n.client,this.authHandle=n.authHandle,this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,n){return this.instrumentOperation("create",async()=>{const e=new l(t);e.name=this.namingFunction(e),e.path=this.keyToPath(e.name),await this.validate(e);try{const o=await this.getMeta(e.id);if(o.bytesWritten>=0)return o}catch{}return e.bytesWritten=0,e.status=g(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,n){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&&D(e,t.size),!S(t,e))throw new Error("File part does not match");const o=await this.lock(t.id);try{if(x(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await H(t.body),i=e.path??this.keyToPath(e.name||e.id);await this.authHandle.ensureAccessToken();const s=a.byteLength<=B?await this.uploadSimple(i,a,n):await this.uploadSession(i,a,n);e.bytesWritten=a.length,e.size=a.length,e.path=s.path_display??i,e.rev=s.rev,e.ETag=s.rev}return e.status=g(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,o)}})}async delete({id:t},n){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const o=e?.path??this.keyToPath(e?.name??t);await this.authHandle.ensureAccessToken();try{await this.runOperation(n,()=>this.client.filesDeleteV2({path:o}))}catch(a){if(!L(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new l({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,path:o,status:"deleted"})})}async get({id:t},n){return this.instrumentOperation("get",async()=>{let e,o=this.keyToPath(t);try{e=await this.checkIfExpired(await this.getMeta(t)),o=e.path??this.keyToPath(e.name??t)}catch{}await this.authHandle.ensureAccessToken();const a=(await this.runOperation(n,()=>this.client.filesDownload({path:o}))).result;let i;if(a.fileBinary instanceof Uint8Array)i=Buffer.from(a.fileBinary.buffer,a.fileBinary.byteOffset,a.fileBinary.byteLength);else if(a.fileBlob instanceof Blob)i=Buffer.from(await a.fileBlob.arrayBuffer());else throw new TypeError("Dropbox: unexpected download response shape — neither fileBinary nor fileBlob present");return{content:i,contentType:e?.contentType??"application/octet-stream",ETag:e?.ETag??a.rev,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??a.server_modified,name:e?.name??a.name,originalName:e?.originalName??a.name,size:e?.size??a.size??i.length}})}async copy(t,n,e){return this.instrumentOperation("copy",async()=>{const o=this.keyToPath(t),a=this.keyToPath(n);await this.authHandle.ensureAccessToken(),await this.runOperation(e,()=>this.client.filesCopyV2({from_path:o,to_path:a}));const i=new l({contentType:"application/octet-stream",metadata:{},originalName:n});return i.id=n,i.name=n,i.path=a,i})}async move(t,n,e){return this.instrumentOperation("move",async()=>{const o=this.keyToPath(t),a=this.keyToPath(n);await this.authHandle.ensureAccessToken(),await this.runOperation(e,()=>this.client.filesMoveV2({from_path:o,to_path:a}));const i=new l({contentType:"application/octet-stream",metadata:{},originalName:n});i.id=n,i.name=n,i.path=a;try{await this.deleteMeta(t)}catch{}return i})}async list(t=1e3,n){return this.instrumentOperation("list",async()=>{await this.authHandle.ensureAccessToken();const e=await this.runOperation(n,()=>this.client.filesListFolder({limit:t,path:this.rootFolderPath?`/${this.rootFolderPath}`:"",recursive:!0})),{result:o}=e,a=[];for(const i of o.entries){if(i[".tag"]!=="file")continue;const s=i,h=s.path_display??s.path_lower??`/${s.name}`,f=this.pathToKey(h);if(!f)continue;const c=new l({contentType:"application/octet-stream",metadata:{},originalName:s.name});c.id=f,c.name=f,c.path=h,c.size=s.size,c.rev=s.rev,c.ETag=s.rev,c.modifiedAt=s.server_modified,a.push(c)}return a},{limit:t})}async getReadUrl(t,n){if(n?.responseContentDisposition!==void 0||n?.responseContentType!==void 0)return m(y.METHOD_NOT_ALLOWED,"Dropbox: `responseContentDisposition`/`responseContentType` are not supported — Dropbox temporary links have no Content-Disposition/Content-Type override.");const e=n?.expiresIn??this.defaultUrlExpiresIn;return e>w?m(y.METHOD_NOT_ALLOWED,`Dropbox: \`expiresIn\` of ${e}s exceeds the ${w}s (4h) maximum. Use \`publicByDefault: true\` for a permanent shared link.`):(await this.authHandle.ensureAccessToken(),this.publicByDefault?await this.createPublicSharedLink(t):(await this.client.filesGetTemporaryLink({path:this.keyToPath(t)})).result.link)}async getUploadUrl(t,n){return m(y.METHOD_NOT_ALLOWED,"Dropbox: presigned upload URLs use POST with a raw body, which doesn't fit the PUT-style upload-url contract. Use `write()` or `storage.raw.filesGetTemporaryUploadLink(...)` directly.")}keyToPath(t){const n=T(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),n&&e.push(n),e.length===0?"":`/${e.join("/")}`}pathToKey(t){const n=T(t);if(!this.rootFolderPath)return n;if(n===this.rootFolderPath)return"";const e=`${this.rootFolderPath}/`;return n.startsWith(e)?n.slice(e.length):n}async uploadSimple(t,n,e){return(await this.runOperation(e,()=>this.client.filesUpload({contents:n,mode:{".tag":"overwrite"},mute:!0,path:t}))).result}async uploadSession(t,n,e){const o=n.byteLength;let a=0;const i=(await this.runOperation(e,()=>this.client.filesUploadSessionStart({close:!1,contents:n.subarray(a,Math.min(a+p,o))}))).result.session_id;for(a=Math.min(a+p,o);o-a>p;){const h=n.subarray(a,a+p);await this.runOperation(e,()=>this.client.filesUploadSessionAppendV2({close:!1,contents:h,cursor:{offset:a,session_id:i}})),a+=p}const s=n.subarray(a,o);return(await this.runOperation(e,()=>this.client.filesUploadSessionFinish({commit:{mode:{".tag":"overwrite"},mute:!0,path:t},contents:s,cursor:{offset:a,session_id:i}}))).result}async createPublicSharedLink(t){try{const n=await this.client.sharingCreateSharedLinkWithSettings({path:this.keyToPath(t),settings:{requested_visibility:{".tag":"public"}}});return O(n.result.url)}catch(n){if(n instanceof _){const e=n.error?.shared_link_already_exists?.metadata?.url;if(typeof e=="string"&&e.length>0)return O(e)}throw n}}internalOnComplete=t=>this.deleteMeta(t.id)}const L=r=>{if(!(r instanceof _))return!1;if(r.status===404)return!0;const t=[],n=(e,o)=>{if(o>6||e===null||typeof e!="object")return;const a=e,i=a[".tag"];typeof i=="string"&&t.push(i);for(const s of Object.values(a))s&&typeof s=="object"&&n(s,o+1)};return n(r.error,0),t.includes("not_found")||t.includes("not_file")||t.includes("not_folder")};export{q as default};
@@ -1 +1 @@
1
- import{PassThrough as K}from"node:stream";import{B as f}from"./storage-0j5nCAUp.js";import{throwErrorCode as R,ERRORS as P}from"./ERRORS-BIBxE2oR.js";import{n as D,a as H,m as z,b as L,s as T,r as O,t as u,c as w,D as v}from"./internal-D_cZIFwI.js";class U{adapter;defaults;hooks;prefix;readonlyMode;constructor(t){this.adapter=t.adapter,this.defaults=t.defaults??{},this.hooks=t.hooks??{},this.prefix=D(t.prefix??""),this.readonlyMode=t.readonly??!1}get capabilities(){return{cacheControl:this.adapter.supportsCacheControl,metadata:this.adapter.supportsMetadata,range:this.adapter.supportsRange,readonly:this.readonlyMode}}readonly(){return new U({adapter:this.adapter,defaults:this.defaults,hooks:this.hooks,prefix:this.prefix,readonly:!0})}assertWritable(){this.readonlyMode&&R(P.READ_ONLY,"This Files instance is read-only")}get raw(){return this.adapter.raw}resolveKey(t){const e=t.replace(/^\/+/u,"");return H(e,"key"),this.prefix?`${this.prefix}/${e}`:e}stripPrefix(t){const e=t.startsWith("/")?t.slice(1):t;if(!this.prefix)return e;const s=`${this.prefix}/`;return e.startsWith(s)?e.slice(s.length):null}mergeOptions(t,e){const s=z(this.defaults,t);if(!e||!this.hooks.onRetry)return s;const i=s?.retries,r=typeof i=="number"?{maxRetries:i}:{...i},p=r.onRetry,c=this.hooks.onRetry;return r.onRetry=(a,o)=>{if(p)try{p(a,o)}catch{}try{const n=typeof o=="string"?o:"Unknown error",l=o instanceof Error?o:new Error(n,{cause:o});c({...e,attempt:a,error:l})}catch{}},{...s,retries:r}}emitAction(t,e){if(this.hooks.onAction)try{this.hooks.onAction({type:t,...e})}catch{}}emitError(t,e,s){if(this.hooks.onError)try{this.hooks.onError({error:s,type:t,...e})}catch{}}async withHooks(t,e,s){const i=Date.now();try{const r=await s();return this.emitAction(t,{...e,durationMs:Date.now()-i}),r}catch(r){const p=typeof r=="string"?r:"Unknown error",c=r instanceof Error?r:new Error(p,{cause:r});throw this.emitError(t,{...e,durationMs:Date.now()-i},c),c}}async upload(t,e,s){return Array.isArray(t)?this.uploadMany(t,e):this.uploadOne(t,e,s)}async uploadOne(t,e,s){this.assertWritable(),s?.metadata&&Object.keys(s.metadata).length>0&&!this.adapter.supportsMetadata&&R(P.METHOD_NOT_ALLOWED,`Adapter ${this.adapter.constructor.name} does not persist custom metadata`);const i=s?.control;return this.withHooks("upload",{key:t},async()=>{const r=this.resolveKey(t);f.assertSafeId(r);const{size:p,stream:c}=await L(e,s?.size),a=s?.size??p,o={...s?.metadata??{},name:r,...s?.contentType?{type:s.contentType}:{},...a===void 0?{}:{size:a}},n=i?{...s,signal:s?.signal?AbortSignal.any([s.signal,i.signal]):i.signal}:s,l=this.mergeOptions(n,{key:t,type:"upload"}),d=s?.multipart;i?._bind(c,t);const h=await this.adapter.create({contentType:s?.contentType,id:r,metadata:o,originalName:r,size:a,storageClass:s?.storageClass},l),y=this.adapter.reportsUploadProgress,g=s?.onProgress,x=!!g||!!i;let m=c;if(x&&!y){let M=0;const C=new K;a!==void 0&&g&&T(g,{loaded:0,total:a}),c.on("data",b=>{const I=typeof b=="string"?Buffer.byteLength(b):b.byteLength;M+=I,i?._progress(M),g&&T(g,{loaded:M,total:a})}),c.pipe(C),m=C}const k={body:m,contentLength:a,id:h.id,start:0,...s?.checksum!==void 0&&{checksum:s.checksum},...s?.checksumAlgorithm!==void 0&&{checksumAlgorithm:s.checksumAlgorithm},...d!==void 0&&{multipart:d},...y&&g&&{onProgress:g}},A=await this.adapter.write(k,l);i?._complete();const E=w(A,r),S=this.stripPrefix(E.key);return S!==null&&(E.key=S),E})}async uploadMany(t,e){this.assertWritable();const{concurrency:s=v,multipart:i,onProgress:r,stopOnError:p=!1,...c}=e??{},a=await O(t,async({body:l,key:d,...h})=>{const y=h.onProgress??(r?g=>{r({...g,key:d})}:void 0);return this.uploadOne(d,l,{...c,multipart:i,...h,...y&&{onProgress:y}})},{concurrency:s,signal:c.signal,stopOnError:p}),o=[],n=[];for(const[l,d]of a.entries()){const h=t[l];if(!d){n.push(u(h.key,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?o.push(d.value):n.push(u(h.key,d.reason))}return n.length>0?{errors:n,uploaded:o}:{uploaded:o}}async download(t,e){return Array.isArray(t)?this.downloadMany(t,e):this.downloadOne(t,e)}assertRangeSupported(t){if(t){if(!Number.isFinite(t.start)||t.start<0)throw new TypeError(`Invalid range.start: ${String(t.start)}`);if(t.end!==void 0&&(!Number.isFinite(t.end)||t.end<t.start))throw new TypeError(`Invalid range.end: ${String(t.end)}`);if(!this.adapter.supportsRange)throw new Error(`Adapter ${this.adapter.constructor.name} does not support range downloads`)}}async downloadOne(t,e){return this.withHooks("download",{key:t},async()=>{const s=this.resolveKey(t);f.assertSafeId(s),this.assertRangeSupported(e?.range);const i=this.mergeOptions(e,{key:t,type:"download"})??{},r=e?.range?{...i,range:e.range}:i,p=await this.adapter.get({id:s},r);return{body:p.content,contentType:p.contentType??"application/octet-stream",etag:p.ETag,key:t,lastModified:p.modifiedAt,metadata:p.metadata,size:typeof p.size=="number"?p.size:void 0}})}async downloadMany(t,e){const{concurrency:s=v,range:i,stopOnError:r=!1,...p}=e??{},c=await O(t,async n=>this.downloadOne(n,i?{...p,range:i}:p),{concurrency:s,signal:p.signal,stopOnError:r}),a=[],o=[];for(const[n,l]of c.entries()){const d=t[n];if(!l){o.push(u(d,new Error("Operation skipped (stopOnError)")));continue}l.status==="fulfilled"?a.push(l.value):o.push(u(d,l.reason))}return o.length>0?{downloaded:a,errors:o}:{downloaded:a}}async downloadStream(t,e){return this.withHooks("download",{key:t},async()=>{const s=this.resolveKey(t);f.assertSafeId(s);const i=this.mergeOptions(e,{key:t,type:"download"}),{headers:r,size:p,stream:c}=await this.adapter.getStream({id:s},i),a=l=>r?Object.entries(r).find(([d])=>d.toLowerCase()===l.toLowerCase())?.[1]:void 0,o=a("Content-Length"),n=p??(o===void 0?void 0:Number(o));return{body:c,contentType:a("Content-Type")??"application/octet-stream",etag:a("ETag"),key:t,lastModified:a("Last-Modified"),size:typeof n=="number"&&Number.isFinite(n)?n:void 0}})}async head(t,e){return Array.isArray(t)?this.headMany(t,e):this.headOne(t,e)}async headOne(t,e){return this.withHooks("head",{key:t},async()=>{const s=this.resolveKey(t);f.assertSafeId(s);const i=await this.adapter.getMeta(s,this.mergeOptions(e,{key:t,type:"head"})),r=w(i,s);return r.key=t,r})}async headMany(t,e){const{concurrency:s=v,stopOnError:i=!1,...r}=e??{},p=await O(t,async o=>this.headOne(o,r),{concurrency:s,signal:r.signal,stopOnError:i}),c=[],a=[];for(const[o,n]of p.entries()){const l=t[o];if(!n){a.push(u(l,new Error("Operation skipped (stopOnError)")));continue}n.status==="fulfilled"?c.push(n.value):a.push(u(l,n.reason))}return a.length>0?{errors:a,files:c}:{files:c}}async exists(t,e){return Array.isArray(t)?this.existsMany(t,e):this.existsOne(t,e)}async existsOne(t,e){return this.withHooks("exists",{key:t},async()=>{const s=this.resolveKey(t);return f.assertSafeId(s),this.adapter.exists({id:s},this.mergeOptions(e,{key:t,type:"exists"}))})}async existsMany(t,e){const{concurrency:s=v,stopOnError:i=!1,...r}=e??{},p=await O(t,async n=>this.existsOne(n,r),{concurrency:s,signal:r.signal,stopOnError:i}),c=[],a=[],o=[];for(const[n,l]of p.entries()){const d=t[n];if(!l){o.push(u(d,new Error("Operation skipped (stopOnError)")));continue}l.status==="fulfilled"?l.value?c.push(d):a.push(d):o.push(u(d,l.reason))}return o.length>0?{errors:o,existing:c,missing:a}:{existing:c,missing:a}}async delete(t,e){if(this.assertWritable(),Array.isArray(t))return this.deleteMany(t,e);await this.deleteOne(t,e)}async deleteOne(t,e){await this.withHooks("delete",{key:t},async()=>{const s=this.resolveKey(t);f.assertSafeId(s),await this.adapter.delete({id:s},this.mergeOptions(e,{key:t,type:"delete"}))})}async deleteMany(t,e){const{concurrency:s=v,stopOnError:i=!1,...r}=e??{},p=this.mergeOptions(r,{keys:t,type:"delete"});if(!i&&typeof this.adapter.deleteBatch=="function"){const n=[],l=[],d=[];for(const h of t)try{const y=this.resolveKey(h);f.assertSafeId(y),n.push(h),l.push(y)}catch(y){d.push(u(h,y))}return this.withHooks("delete",{keys:n},async()=>{const h=l.length>0?await this.adapter.deleteBatch(l,p):{failed:[],successful:[]},y=new Map(l.map((m,k)=>[m,k])),g=h.successful.map(m=>this.stripPrefix(m.id)??m.id),x=[...d,...h.failed.map(({error:m,id:k})=>{const A=y.get(k),E=A===void 0?k:n[A];return u(E,new Error(m))})];return x.length>0?{deleted:g,errors:x}:{deleted:g}})}const c=await O(t,async n=>this.deleteOne(n,r),{concurrency:s,signal:r.signal,stopOnError:i}),a=[],o=[];for(const[n,l]of c.entries()){const d=t[n];if(!l){o.push(u(d,new Error("Operation skipped (stopOnError)")));continue}l.status==="fulfilled"?a.push(d):o.push(u(d,l.reason))}return o.length>0?{deleted:a,errors:o}:{deleted:a}}async copy(t,e,s){return this.assertWritable(),this.withHooks("copy",{from:t,to:e},async()=>{const i=this.resolveKey(t),r=this.resolveKey(e);f.assertSafeId(i),f.assertSafeId(r);const p=await this.adapter.copy(i,r,{...this.mergeOptions(s,{from:t,to:e,type:"copy"}),storageClass:s?.storageClass}),c=w(p,r);return c.key=e,c})}async move(t,e,s){return this.assertWritable(),Array.isArray(t)?this.moveMany(t,e):this.moveOne(t,e,s)}async moveOne(t,e,s){return this.withHooks("move",{from:t,to:e},async()=>{const i=this.resolveKey(t);if(f.assertSafeId(i),t===e){const o=await this.adapter.getMeta(i,this.mergeOptions(s,{from:t,to:e,type:"move"})),n=w(o,i);return n.key=t,n}const r=this.resolveKey(e);f.assertSafeId(r);const p={...this.mergeOptions(s,{from:t,to:e,type:"move"}),...s?.storageClass!==void 0&&{storageClass:s.storageClass}},c=await this.adapter.move(i,r,p),a=w(c,r);return a.key=e,a})}async moveMany(t,e){const{concurrency:s=v,stopOnError:i=!1,...r}=e??{},p=await O(t,async({from:o,to:n})=>this.moveOne(o,n,r),{concurrency:s,signal:r.signal,stopOnError:i}),c=[],a=[];for(const[o,n]of p.entries()){const l=t[o];if(!n){a.push(u(l.from,new Error("Operation skipped (stopOnError)")));continue}n.status==="fulfilled"?c.push(n.value):a.push(u(l.from,n.reason))}return a.length>0?{errors:a,moved:c}:{moved:c}}async list(t={}){return this.withHooks("list",{},async()=>{const{delimiter:e,limit:s,prefix:i,...r}=t;if(e!==void 0&&this.adapter.supportsDelimiter)return this.listDirectoryNative(e,i,s,r);const p=await this.adapter.list(s??1e3,this.mergeOptions(r,{type:"list"})),c=[];for(const d of p){const h=w(d),y=this.stripPrefix(h.key);y!==null&&(h.key=y,c.push(h))}const a=i?c.filter(d=>d.key.startsWith(i)):c;if(e===void 0)return a;const o=i??"",n=[],l=new Set;for(const d of a){const h=d.key.slice(o.length),y=h.indexOf(e);y===-1?n.push(d):l.add(o+h.slice(0,y+e.length))}return{files:n,prefixes:[...l].toSorted()}})}async listDirectoryNative(t,e,s,i){const r=[this.prefix,e].filter(Boolean).join("/"),{files:p,prefixes:c}=await this.adapter.listDirectory({delimiter:t,...s!==void 0&&{limit:s},...r&&{prefix:r},...this.mergeOptions(i,{type:"list"})}),a=[];for(const n of p){const l=w(n),d=this.stripPrefix(l.key);d!==null&&(l.key=d,a.push(l))}const o=[];for(const n of c){const l=this.stripPrefix(n);l!==null&&o.push(l)}return{files:a,prefixes:o.toSorted()}}async*listAll(t={}){const{limit:e,prefix:s,...i}=t,r=Math.max(1,e??1e3),p=Date.now(),c=new Set;let a;try{for(;;){const o=await this.adapter.list(r,this.mergeOptions(i,{type:"listAll"}));let n=0;for(const l of o){const d=w(l),h=this.stripPrefix(d.key);h!==null&&(d.key=h,!(s&&!d.key.startsWith(s))&&(c.has(d.key)||(c.add(d.key),n+=1,yield d)))}if(n===0||o.length<r)break}}catch(o){const n=typeof o=="string"?o:"Unknown error";throw a=o instanceof Error?o:new Error(n,{cause:o}),a}finally{const o=Date.now()-p;a?this.emitError("listAll",{durationMs:o},a):this.emitAction("listAll",{durationMs:o})}}async url(t,e){return this.withHooks("url",{key:t},async()=>{const s=this.resolveKey(t);return f.assertSafeId(s),this.adapter.getReadUrl(s,{...this.mergeOptions(e,{key:t,type:"url"}),...e})})}async signedUploadUrl(t,e){return this.assertWritable(),this.withHooks("signedUploadUrl",{key:t},async()=>{const s=this.resolveKey(t);return f.assertSafeId(s),this.adapter.getUploadUrl(s,{...this.mergeOptions(e,{key:t,type:"signedUploadUrl"}),...e})})}}export{U as Files};
1
+ import{PassThrough as K}from"node:stream";import{B as f}from"./storage-DR7qdwBN.js";import{throwErrorCode as R,ERRORS as P}from"./ERRORS-BIBxE2oR.js";import{n as D,a as H,m as z,b as L,s as T,r as O,t as u,c as w,D as v}from"./internal-D_cZIFwI.js";class U{adapter;defaults;hooks;prefix;readonlyMode;constructor(t){this.adapter=t.adapter,this.defaults=t.defaults??{},this.hooks=t.hooks??{},this.prefix=D(t.prefix??""),this.readonlyMode=t.readonly??!1}get capabilities(){return{cacheControl:this.adapter.supportsCacheControl,metadata:this.adapter.supportsMetadata,range:this.adapter.supportsRange,readonly:this.readonlyMode}}readonly(){return new U({adapter:this.adapter,defaults:this.defaults,hooks:this.hooks,prefix:this.prefix,readonly:!0})}assertWritable(){this.readonlyMode&&R(P.READ_ONLY,"This Files instance is read-only")}get raw(){return this.adapter.raw}resolveKey(t){const e=t.replace(/^\/+/u,"");return H(e,"key"),this.prefix?`${this.prefix}/${e}`:e}stripPrefix(t){const e=t.startsWith("/")?t.slice(1):t;if(!this.prefix)return e;const s=`${this.prefix}/`;return e.startsWith(s)?e.slice(s.length):null}mergeOptions(t,e){const s=z(this.defaults,t);if(!e||!this.hooks.onRetry)return s;const i=s?.retries,r=typeof i=="number"?{maxRetries:i}:{...i},p=r.onRetry,c=this.hooks.onRetry;return r.onRetry=(a,o)=>{if(p)try{p(a,o)}catch{}try{const n=typeof o=="string"?o:"Unknown error",l=o instanceof Error?o:new Error(n,{cause:o});c({...e,attempt:a,error:l})}catch{}},{...s,retries:r}}emitAction(t,e){if(this.hooks.onAction)try{this.hooks.onAction({type:t,...e})}catch{}}emitError(t,e,s){if(this.hooks.onError)try{this.hooks.onError({error:s,type:t,...e})}catch{}}async withHooks(t,e,s){const i=Date.now();try{const r=await s();return this.emitAction(t,{...e,durationMs:Date.now()-i}),r}catch(r){const p=typeof r=="string"?r:"Unknown error",c=r instanceof Error?r:new Error(p,{cause:r});throw this.emitError(t,{...e,durationMs:Date.now()-i},c),c}}async upload(t,e,s){return Array.isArray(t)?this.uploadMany(t,e):this.uploadOne(t,e,s)}async uploadOne(t,e,s){this.assertWritable(),s?.metadata&&Object.keys(s.metadata).length>0&&!this.adapter.supportsMetadata&&R(P.METHOD_NOT_ALLOWED,`Adapter ${this.adapter.constructor.name} does not persist custom metadata`);const i=s?.control;return this.withHooks("upload",{key:t},async()=>{const r=this.resolveKey(t);f.assertSafeId(r);const{size:p,stream:c}=await L(e,s?.size),a=s?.size??p,o={...s?.metadata??{},name:r,...s?.contentType?{type:s.contentType}:{},...a===void 0?{}:{size:a}},n=i?{...s,signal:s?.signal?AbortSignal.any([s.signal,i.signal]):i.signal}:s,l=this.mergeOptions(n,{key:t,type:"upload"}),d=s?.multipart;i?._bind(c,t);const h=await this.adapter.create({contentType:s?.contentType,id:r,metadata:o,originalName:r,size:a,storageClass:s?.storageClass},l),y=this.adapter.reportsUploadProgress,g=s?.onProgress,x=!!g||!!i;let m=c;if(x&&!y){let M=0;const C=new K;a!==void 0&&g&&T(g,{loaded:0,total:a}),c.on("data",b=>{const I=typeof b=="string"?Buffer.byteLength(b):b.byteLength;M+=I,i?._progress(M),g&&T(g,{loaded:M,total:a})}),c.pipe(C),m=C}const k={body:m,contentLength:a,id:h.id,start:0,...s?.checksum!==void 0&&{checksum:s.checksum},...s?.checksumAlgorithm!==void 0&&{checksumAlgorithm:s.checksumAlgorithm},...d!==void 0&&{multipart:d},...y&&g&&{onProgress:g}},A=await this.adapter.write(k,l);i?._complete();const E=w(A,r),S=this.stripPrefix(E.key);return S!==null&&(E.key=S),E})}async uploadMany(t,e){this.assertWritable();const{concurrency:s=v,multipart:i,onProgress:r,stopOnError:p=!1,...c}=e??{},a=await O(t,async({body:l,key:d,...h})=>{const y=h.onProgress??(r?g=>{r({...g,key:d})}:void 0);return this.uploadOne(d,l,{...c,multipart:i,...h,...y&&{onProgress:y}})},{concurrency:s,signal:c.signal,stopOnError:p}),o=[],n=[];for(const[l,d]of a.entries()){const h=t[l];if(!d){n.push(u(h.key,new Error("Operation skipped (stopOnError)")));continue}d.status==="fulfilled"?o.push(d.value):n.push(u(h.key,d.reason))}return n.length>0?{errors:n,uploaded:o}:{uploaded:o}}async download(t,e){return Array.isArray(t)?this.downloadMany(t,e):this.downloadOne(t,e)}assertRangeSupported(t){if(t){if(!Number.isFinite(t.start)||t.start<0)throw new TypeError(`Invalid range.start: ${String(t.start)}`);if(t.end!==void 0&&(!Number.isFinite(t.end)||t.end<t.start))throw new TypeError(`Invalid range.end: ${String(t.end)}`);if(!this.adapter.supportsRange)throw new Error(`Adapter ${this.adapter.constructor.name} does not support range downloads`)}}async downloadOne(t,e){return this.withHooks("download",{key:t},async()=>{const s=this.resolveKey(t);f.assertSafeId(s),this.assertRangeSupported(e?.range);const i=this.mergeOptions(e,{key:t,type:"download"})??{},r=e?.range?{...i,range:e.range}:i,p=await this.adapter.get({id:s},r);return{body:p.content,contentType:p.contentType??"application/octet-stream",etag:p.ETag,key:t,lastModified:p.modifiedAt,metadata:p.metadata,size:typeof p.size=="number"?p.size:void 0}})}async downloadMany(t,e){const{concurrency:s=v,range:i,stopOnError:r=!1,...p}=e??{},c=await O(t,async n=>this.downloadOne(n,i?{...p,range:i}:p),{concurrency:s,signal:p.signal,stopOnError:r}),a=[],o=[];for(const[n,l]of c.entries()){const d=t[n];if(!l){o.push(u(d,new Error("Operation skipped (stopOnError)")));continue}l.status==="fulfilled"?a.push(l.value):o.push(u(d,l.reason))}return o.length>0?{downloaded:a,errors:o}:{downloaded:a}}async downloadStream(t,e){return this.withHooks("download",{key:t},async()=>{const s=this.resolveKey(t);f.assertSafeId(s);const i=this.mergeOptions(e,{key:t,type:"download"}),{headers:r,size:p,stream:c}=await this.adapter.getStream({id:s},i),a=l=>r?Object.entries(r).find(([d])=>d.toLowerCase()===l.toLowerCase())?.[1]:void 0,o=a("Content-Length"),n=p??(o===void 0?void 0:Number(o));return{body:c,contentType:a("Content-Type")??"application/octet-stream",etag:a("ETag"),key:t,lastModified:a("Last-Modified"),size:typeof n=="number"&&Number.isFinite(n)?n:void 0}})}async head(t,e){return Array.isArray(t)?this.headMany(t,e):this.headOne(t,e)}async headOne(t,e){return this.withHooks("head",{key:t},async()=>{const s=this.resolveKey(t);f.assertSafeId(s);const i=await this.adapter.getMeta(s,this.mergeOptions(e,{key:t,type:"head"})),r=w(i,s);return r.key=t,r})}async headMany(t,e){const{concurrency:s=v,stopOnError:i=!1,...r}=e??{},p=await O(t,async o=>this.headOne(o,r),{concurrency:s,signal:r.signal,stopOnError:i}),c=[],a=[];for(const[o,n]of p.entries()){const l=t[o];if(!n){a.push(u(l,new Error("Operation skipped (stopOnError)")));continue}n.status==="fulfilled"?c.push(n.value):a.push(u(l,n.reason))}return a.length>0?{errors:a,files:c}:{files:c}}async exists(t,e){return Array.isArray(t)?this.existsMany(t,e):this.existsOne(t,e)}async existsOne(t,e){return this.withHooks("exists",{key:t},async()=>{const s=this.resolveKey(t);return f.assertSafeId(s),this.adapter.exists({id:s},this.mergeOptions(e,{key:t,type:"exists"}))})}async existsMany(t,e){const{concurrency:s=v,stopOnError:i=!1,...r}=e??{},p=await O(t,async n=>this.existsOne(n,r),{concurrency:s,signal:r.signal,stopOnError:i}),c=[],a=[],o=[];for(const[n,l]of p.entries()){const d=t[n];if(!l){o.push(u(d,new Error("Operation skipped (stopOnError)")));continue}l.status==="fulfilled"?l.value?c.push(d):a.push(d):o.push(u(d,l.reason))}return o.length>0?{errors:o,existing:c,missing:a}:{existing:c,missing:a}}async delete(t,e){if(this.assertWritable(),Array.isArray(t))return this.deleteMany(t,e);await this.deleteOne(t,e)}async deleteOne(t,e){await this.withHooks("delete",{key:t},async()=>{const s=this.resolveKey(t);f.assertSafeId(s),await this.adapter.delete({id:s},this.mergeOptions(e,{key:t,type:"delete"}))})}async deleteMany(t,e){const{concurrency:s=v,stopOnError:i=!1,...r}=e??{},p=this.mergeOptions(r,{keys:t,type:"delete"});if(!i&&typeof this.adapter.deleteBatch=="function"){const n=[],l=[],d=[];for(const h of t)try{const y=this.resolveKey(h);f.assertSafeId(y),n.push(h),l.push(y)}catch(y){d.push(u(h,y))}return this.withHooks("delete",{keys:n},async()=>{const h=l.length>0?await this.adapter.deleteBatch(l,p):{failed:[],successful:[]},y=new Map(l.map((m,k)=>[m,k])),g=h.successful.map(m=>this.stripPrefix(m.id)??m.id),x=[...d,...h.failed.map(({error:m,id:k})=>{const A=y.get(k),E=A===void 0?k:n[A];return u(E,new Error(m))})];return x.length>0?{deleted:g,errors:x}:{deleted:g}})}const c=await O(t,async n=>this.deleteOne(n,r),{concurrency:s,signal:r.signal,stopOnError:i}),a=[],o=[];for(const[n,l]of c.entries()){const d=t[n];if(!l){o.push(u(d,new Error("Operation skipped (stopOnError)")));continue}l.status==="fulfilled"?a.push(d):o.push(u(d,l.reason))}return o.length>0?{deleted:a,errors:o}:{deleted:a}}async copy(t,e,s){return this.assertWritable(),this.withHooks("copy",{from:t,to:e},async()=>{const i=this.resolveKey(t),r=this.resolveKey(e);f.assertSafeId(i),f.assertSafeId(r);const p=await this.adapter.copy(i,r,{...this.mergeOptions(s,{from:t,to:e,type:"copy"}),storageClass:s?.storageClass}),c=w(p,r);return c.key=e,c})}async move(t,e,s){return this.assertWritable(),Array.isArray(t)?this.moveMany(t,e):this.moveOne(t,e,s)}async moveOne(t,e,s){return this.withHooks("move",{from:t,to:e},async()=>{const i=this.resolveKey(t);if(f.assertSafeId(i),t===e){const o=await this.adapter.getMeta(i,this.mergeOptions(s,{from:t,to:e,type:"move"})),n=w(o,i);return n.key=t,n}const r=this.resolveKey(e);f.assertSafeId(r);const p={...this.mergeOptions(s,{from:t,to:e,type:"move"}),...s?.storageClass!==void 0&&{storageClass:s.storageClass}},c=await this.adapter.move(i,r,p),a=w(c,r);return a.key=e,a})}async moveMany(t,e){const{concurrency:s=v,stopOnError:i=!1,...r}=e??{},p=await O(t,async({from:o,to:n})=>this.moveOne(o,n,r),{concurrency:s,signal:r.signal,stopOnError:i}),c=[],a=[];for(const[o,n]of p.entries()){const l=t[o];if(!n){a.push(u(l.from,new Error("Operation skipped (stopOnError)")));continue}n.status==="fulfilled"?c.push(n.value):a.push(u(l.from,n.reason))}return a.length>0?{errors:a,moved:c}:{moved:c}}async list(t={}){return this.withHooks("list",{},async()=>{const{delimiter:e,limit:s,prefix:i,...r}=t;if(e!==void 0&&this.adapter.supportsDelimiter)return this.listDirectoryNative(e,i,s,r);const p=await this.adapter.list(s??1e3,this.mergeOptions(r,{type:"list"})),c=[];for(const d of p){const h=w(d),y=this.stripPrefix(h.key);y!==null&&(h.key=y,c.push(h))}const a=i?c.filter(d=>d.key.startsWith(i)):c;if(e===void 0)return a;const o=i??"",n=[],l=new Set;for(const d of a){const h=d.key.slice(o.length),y=h.indexOf(e);y===-1?n.push(d):l.add(o+h.slice(0,y+e.length))}return{files:n,prefixes:[...l].toSorted()}})}async listDirectoryNative(t,e,s,i){const r=[this.prefix,e].filter(Boolean).join("/"),{files:p,prefixes:c}=await this.adapter.listDirectory({delimiter:t,...s!==void 0&&{limit:s},...r&&{prefix:r},...this.mergeOptions(i,{type:"list"})}),a=[];for(const n of p){const l=w(n),d=this.stripPrefix(l.key);d!==null&&(l.key=d,a.push(l))}const o=[];for(const n of c){const l=this.stripPrefix(n);l!==null&&o.push(l)}return{files:a,prefixes:o.toSorted()}}async*listAll(t={}){const{limit:e,prefix:s,...i}=t,r=Math.max(1,e??1e3),p=Date.now(),c=new Set;let a;try{for(;;){const o=await this.adapter.list(r,this.mergeOptions(i,{type:"listAll"}));let n=0;for(const l of o){const d=w(l),h=this.stripPrefix(d.key);h!==null&&(d.key=h,!(s&&!d.key.startsWith(s))&&(c.has(d.key)||(c.add(d.key),n+=1,yield d)))}if(n===0||o.length<r)break}}catch(o){const n=typeof o=="string"?o:"Unknown error";throw a=o instanceof Error?o:new Error(n,{cause:o}),a}finally{const o=Date.now()-p;a?this.emitError("listAll",{durationMs:o},a):this.emitAction("listAll",{durationMs:o})}}async url(t,e){return this.withHooks("url",{key:t},async()=>{const s=this.resolveKey(t);return f.assertSafeId(s),this.adapter.getReadUrl(s,{...this.mergeOptions(e,{key:t,type:"url"}),...e})})}async signedUploadUrl(t,e){return this.assertWritable(),this.withHooks("signedUploadUrl",{key:t},async()=>{const s=this.resolveKey(t);return f.assertSafeId(s),this.adapter.getUploadUrl(s,{...this.mergeOptions(e,{key:t,type:"signedUploadUrl"}),...e})})}}export{U as Files};
@@ -0,0 +1 @@
1
+ import{y as s}from"./local-meta-storage-BELb1YwO.js";class o extends s{constructor(r){super(r)}}export{o as default};
@@ -1,2 +1,2 @@
1
- import{readFileSync as y}from"node:fs";import{getApps as g,getApp as m,initializeApp as E,cert as w}from"firebase-admin/app";import{getStorage as b}from"firebase-admin/storage";import{throwErrorCode as u,ERRORS as l}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import c from"./FirebaseFile-BLaBxa2A.js";import T from"./FirebaseMetaStorage-BI9YXcwU.js";import{t as d}from"./get-file-status-y3wTtDQs.js";import{t as k}from"./update-size-DuNuLyxj.js";import{i as A}from"./part-match-D-9dGX42.js";import{e as I}from"./has-content-50BsqrWw.js";const v=3600,S=async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},U=o=>typeof o=="object"&&o!==null&&typeof o.file=="function"&&typeof o.getFiles=="function";class f extends O{static name="firebase";checksumTypes=[];meta;bucket;bucketName;defaultUrlExpiresIn;publicBaseUrl;constructor(t){if(super(t),this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??v,this.publicBaseUrl=t.publicBaseUrl?.replace(/\/+$/,""),t.app&&U(t.app))this.bucket=t.app,this.bucketName=t.app.name??"";else{const a=t.bucket??process.env.FIREBASE_STORAGE_BUCKET;if(!a)throw new Error("Firebase storage: `bucket` is required (or set FIREBASE_STORAGE_BUCKET).");this.bucketName=a;const e=t.app??f.resolveApp(t,a);this.bucket=b(e).bucket(a)}this.meta=t.metaStorage??new T(t.metaStorageConfig),this.isReady=!0}get raw(){return this.bucket}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucketName,e.path=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=d(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),!A(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(I(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await S(t.body),s=e.path??e.name;await this.runOperation(a,()=>this.bucket.file(s).save(n,{contentType:e.contentType,resumable:!1})),e.bytesWritten=n.length,e.size=n.length,e.path=s}return e.status=d(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?.path??e?.name??t;return await this.runOperation(a,()=>this.bucket.file(i).delete({ignoreNotFound:!0})),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.bucketName,id:t,name:t,path:i,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}try{const[i]=await this.runOperation(a,()=>this.bucket.file(e).exists());return i}catch{return!1}})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,i;try{i=await this.checkIfExpired(await this.getMeta(t)),e=i.path??i.name??t}catch{}const n=this.bucket.file(e),[s]=await this.runOperation(a,()=>n.download());let r={};try{[r]=await this.runOperation(a,()=>n.getMetadata())}catch{}return{content:s,contentType:i?.contentType??r.contentType??"application/octet-stream",ETag:i?.ETag??r.etag,expiredAt:i?.expiredAt,id:t,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt??r.updated,name:i?.name??e,originalName:i?.originalName??e,size:i?.size??(r.size===void 0?s.length:Number(r.size))}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(i).copy(this.bucket.file(a)));const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return n.id=a,n.name=a,n.path=a,n.bucket=this.bucketName,n})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(i).move(a));const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucketName;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const[e]=await this.runOperation(a,()=>this.bucket.getFiles({maxResults:t}));return(e??[]).map(i=>{const n=new c({contentType:"application/octet-stream",metadata:{},originalName:i.name});return n.id=i.name,n.name=i.name,n.path=i.name,n.bucket=this.bucketName,n})},{limit:t})}async getReadUrl(t,a){if(this.publicBaseUrl)return a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0?u(l.BAD_REQUEST,"Firebase: `responseContentDisposition`/`responseContentType` are not supported when `publicBaseUrl` is configured — a static public URL has no signature in which to bind the override."):`${this.publicBaseUrl}/${t}`;const e=a?.expiresIn??this.defaultUrlExpiresIn;try{const[i]=await this.bucket.file(t).getSignedUrl({action:"read",expires:Date.now()+e*1e3,...a?.responseContentDisposition!==void 0&&{responseDisposition:a.responseContentDisposition},...a?.responseContentType!==void 0&&{responseType:a.responseContentType}});return i}catch(i){return u(l.METHOD_NOT_ALLOWED,i instanceof Error?i.message:"Firebase: getSignedUrl failed")}}async getUploadUrl(t,a){if(a?.contentLength!==void 0)return u(l.BAD_REQUEST,"Firebase: `contentLength` is not supported for upload URLs. A GCS signed PUT has no content-length-range policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the URL.");const e=a?.expiresIn??this.defaultUrlExpiresIn;try{const[i]=await this.bucket.file(t).getSignedUrl({action:"write",contentType:a?.contentType,expires:Date.now()+e*1e3});return i}catch(i){return u(l.METHOD_NOT_ALLOWED,i instanceof Error?i.message:"Firebase: getSignedUrl failed")}}static resolveApp(t,a){const{appName:e}=t,i=g();if(e?i.find(p=>p.name===e):i[0])return e?m(e):m();const n=t.projectId??process.env.FIREBASE_PROJECT_ID??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT;let s=t.credentials?.clientEmail??process.env.FIREBASE_CLIENT_EMAIL,r=t.credentials?.privateKey??process.env.FIREBASE_PRIVATE_KEY;const h=t.serviceAccountPath??process.env.GOOGLE_APPLICATION_CREDENTIALS;if((!s||!r)&&h){const p=JSON.parse(y(h,"utf8"));s??=p.client_email,r??=p.private_key}if(!s||!r)throw new Error("Firebase storage: service-account credentials are required. Provide `credentials` ({ clientEmail, privateKey }), `serviceAccountPath`, or set FIREBASE_CLIENT_EMAIL / FIREBASE_PRIVATE_KEY / GOOGLE_APPLICATION_CREDENTIALS.");return E({credential:w({clientEmail:s,privateKey:r.replaceAll(String.raw`\n`,`
1
+ import{readFileSync as y}from"node:fs";import{getApps as g,getApp as m,initializeApp as E,cert as w}from"firebase-admin/app";import{getStorage as b}from"firebase-admin/storage";import{throwErrorCode as u,ERRORS as l}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-DR7qdwBN.js";import c from"./FirebaseFile-BLaBxa2A.js";import T from"./FirebaseMetaStorage-Bv_YCZ0Q.js";import{t as d}from"./get-file-status-y3wTtDQs.js";import{t as k}from"./update-size-DuNuLyxj.js";import{i as A}from"./part-match-D-9dGX42.js";import{e as I}from"./has-content-50BsqrWw.js";const v=3600,S=async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},U=o=>typeof o=="object"&&o!==null&&typeof o.file=="function"&&typeof o.getFiles=="function";class f extends O{static name="firebase";checksumTypes=[];meta;bucket;bucketName;defaultUrlExpiresIn;publicBaseUrl;constructor(t){if(super(t),this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??v,this.publicBaseUrl=t.publicBaseUrl?.replace(/\/+$/,""),t.app&&U(t.app))this.bucket=t.app,this.bucketName=t.app.name??"";else{const a=t.bucket??process.env.FIREBASE_STORAGE_BUCKET;if(!a)throw new Error("Firebase storage: `bucket` is required (or set FIREBASE_STORAGE_BUCKET).");this.bucketName=a;const e=t.app??f.resolveApp(t,a);this.bucket=b(e).bucket(a)}this.meta=t.metaStorage??new T(t.metaStorageConfig),this.isReady=!0}get raw(){return this.bucket}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucketName,e.path=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=d(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),!A(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(I(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await S(t.body),s=e.path??e.name;await this.runOperation(a,()=>this.bucket.file(s).save(n,{contentType:e.contentType,resumable:!1})),e.bytesWritten=n.length,e.size=n.length,e.path=s}return e.status=d(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?.path??e?.name??t;return await this.runOperation(a,()=>this.bucket.file(i).delete({ignoreNotFound:!0})),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.bucketName,id:t,name:t,path:i,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}try{const[i]=await this.runOperation(a,()=>this.bucket.file(e).exists());return i}catch{return!1}})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,i;try{i=await this.checkIfExpired(await this.getMeta(t)),e=i.path??i.name??t}catch{}const n=this.bucket.file(e),[s]=await this.runOperation(a,()=>n.download());let r={};try{[r]=await this.runOperation(a,()=>n.getMetadata())}catch{}return{content:s,contentType:i?.contentType??r.contentType??"application/octet-stream",ETag:i?.ETag??r.etag,expiredAt:i?.expiredAt,id:t,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt??r.updated,name:i?.name??e,originalName:i?.originalName??e,size:i?.size??(r.size===void 0?s.length:Number(r.size))}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(i).copy(this.bucket.file(a)));const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return n.id=a,n.name=a,n.path=a,n.bucket=this.bucketName,n})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.runOperation(e,()=>this.bucket.file(i).move(a));const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucketName;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const[e]=await this.runOperation(a,()=>this.bucket.getFiles({maxResults:t}));return(e??[]).map(i=>{const n=new c({contentType:"application/octet-stream",metadata:{},originalName:i.name});return n.id=i.name,n.name=i.name,n.path=i.name,n.bucket=this.bucketName,n})},{limit:t})}async getReadUrl(t,a){if(this.publicBaseUrl)return a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0?u(l.BAD_REQUEST,"Firebase: `responseContentDisposition`/`responseContentType` are not supported when `publicBaseUrl` is configured — a static public URL has no signature in which to bind the override."):`${this.publicBaseUrl}/${t}`;const e=a?.expiresIn??this.defaultUrlExpiresIn;try{const[i]=await this.bucket.file(t).getSignedUrl({action:"read",expires:Date.now()+e*1e3,...a?.responseContentDisposition!==void 0&&{responseDisposition:a.responseContentDisposition},...a?.responseContentType!==void 0&&{responseType:a.responseContentType}});return i}catch(i){return u(l.METHOD_NOT_ALLOWED,i instanceof Error?i.message:"Firebase: getSignedUrl failed")}}async getUploadUrl(t,a){if(a?.contentLength!==void 0)return u(l.BAD_REQUEST,"Firebase: `contentLength` is not supported for upload URLs. A GCS signed PUT has no content-length-range policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the URL.");const e=a?.expiresIn??this.defaultUrlExpiresIn;try{const[i]=await this.bucket.file(t).getSignedUrl({action:"write",contentType:a?.contentType,expires:Date.now()+e*1e3});return i}catch(i){return u(l.METHOD_NOT_ALLOWED,i instanceof Error?i.message:"Firebase: getSignedUrl failed")}}static resolveApp(t,a){const{appName:e}=t,i=g();if(e?i.find(p=>p.name===e):i[0])return e?m(e):m();const n=t.projectId??process.env.FIREBASE_PROJECT_ID??process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT;let s=t.credentials?.clientEmail??process.env.FIREBASE_CLIENT_EMAIL,r=t.credentials?.privateKey??process.env.FIREBASE_PRIVATE_KEY;const h=t.serviceAccountPath??process.env.GOOGLE_APPLICATION_CREDENTIALS;if((!s||!r)&&h){const p=JSON.parse(y(h,"utf8"));s??=p.client_email,r??=p.private_key}if(!s||!r)throw new Error("Firebase storage: service-account credentials are required. Provide `credentials` ({ clientEmail, privateKey }), `serviceAccountPath`, or set FIREBASE_CLIENT_EMAIL / FIREBASE_PRIVATE_KEY / GOOGLE_APPLICATION_CREDENTIALS.");return E({credential:w({clientEmail:s,privateKey:r.replaceAll(String.raw`\n`,`
2
2
  `),projectId:n}),projectId:n,storageBucket:a},e)}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=t=>this.deleteMeta(t.id)}export{f as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-BELb1YwO.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{Readable as y,Writable as E}from"node:stream";import{Client as F}from"basic-ftp";import{F as T}from"./index-nZWCQrSe.js";import{throwErrorCode as u,ERRORS as m}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-0j5nCAUp.js";import k from"./FtpFile-ClWDYnt2.js";import b from"./FtpMetaStorage-CHWrhgg2.js";import{r as l,t as v,e as M}from"./posix-dirname-CfpH5wZi.js";import{t as P}from"./get-file-status-y3wTtDQs.js";import{t as A}from"./update-size-DuNuLyxj.js";import{i as R}from"./part-match-D-9dGX42.js";import{e as D}from"./has-content-50BsqrWw.js";const d=h=>{const a=h?.code;if(a===550||a===450||a===553)return!0;const e=h instanceof Error?h.message:String(h);return/no such file|not exist|cannot find|file unavailable/i.test(e)},f=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},g=async(h,a,e)=>{const t=[],n=new E({write(i,r,s){t.push(Buffer.from(i)),s()}});return await h.downloadTo(n,a,e&&e>0?e:void 0),Buffer.concat(t)};class H extends O{static name="ftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=l(a.rootFolderPath??""),this.meta=a.metaStorage??new b(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new k(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=P(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&&A(t,a.size),!R(a,t))return u(m.FILE_CONFLICT);const n=await this.lock(a.id);try{if(D(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return u(m.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return u(m.METHOD_NOT_ALLOWED,"FTP storage does not support chunked or resumable uploads; send the file in a single request.");const i=await v(a.body),r=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,s=>this.run(s,async o=>{await this.ensureRemoteDirectory(o,r),await o.uploadFrom(y.from(i),r)})),t.bytesWritten=i.length,t.size=i.length,t.path=r,t.ETag=T(i)}return t.status=P(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),{range:i}=e??{},r=await this.runOperation(e,s=>this.run(s,async o=>{try{const c=await g(o,n,i?.start);return i?.end!==void 0?c.subarray(0,i.end-i.start+1):c}catch(c){if(d(c))return u(m.FILE_NOT_FOUND);throw c}}));return{content:r,contentType:t.contentType,ETag:t.ETag??T(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:i?r.length: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,r=>this.run(r,async s=>{try{await s.remove(n)}catch(o){if(!d(o))throw o}})),await this.deleteMeta(a);const i={...t,status:"deleted"};return await this.onDelete(i),i})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const n=await this.getMeta(a),i=n.path??this.keyToPath(n.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async c=>{const p=await g(c,i);await this.ensureRemoteDirectory(c,r),await c.uploadFrom(y.from(p),r)}));const s={...n,id:e,name:e,path:r};return await this.saveMeta(s),s})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const n=await this.getMeta(a),i=n.path??this.keyToPath(n.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async c=>{try{await this.ensureRemoteDirectory(c,r),await c.rename(i,r)}catch(p){try{const w=await g(c,i);await this.ensureRemoteDirectory(c,r),await c.uploadFrom(y.from(w),r),await c.remove(i)}catch(w){throw new AggregateError([p,w],`FTP move failed: rename and copy+delete fallback both failed for "${i}" → "${r}"`)}}}));const s={...n,id:e,name:e,path:r};await this.saveMeta(s);try{await this.deleteMeta(a)}catch{}return s})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,n=>this.run(n,async i=>{const r=[];return await this.walkList(i,t,r),r}))})}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,i=>this.run(i,async r=>{try{return await r.size(n),!0}catch(s){if(d(s))return!1;throw s}}))})}async walkList(a,e,t){let n;try{n=await a.list(e||".")}catch(i){if(d(i))return;throw i}for(const i of n){const r=e?`${e}/${i.name}`:i.name;if(i.isDirectory){await this.walkList(a,r,t);continue}if(!i.isFile)continue;const s=this.pathToKey(r);if(!s)continue;const o=new k({contentType:"application/octet-stream",metadata:{},originalName:i.name});o.id=s,o.name=s,o.path=r,o.size=i.size,i.modifiedAt&&(o.modifiedAt=i.modifiedAt.toISOString()),t.push(o)}}async run(a,e){const t=new F;if(a?.aborted)throw f(a.reason);const n=()=>{t.close()};a?.addEventListener("abort",n,{once:!0});try{if(await t.access(this.connection),a?.aborted)throw f(a.reason);return await e(t)}catch(i){throw a?.aborted?f(i):i}finally{a?.removeEventListener("abort",n),t.close()}}async ensureRemoteDirectory(a,e){const t=M(e);t&&(await a.ensureDir(t),await a.cd("/"))}keyToPath(a){const e=l(a);e&&O.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":`/${t.join("/")}`}pathToKey(a){const e=l(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{H as default};
1
+ import{Readable as y,Writable as E}from"node:stream";import{Client as F}from"basic-ftp";import{F as T}from"./index-nZWCQrSe.js";import{throwErrorCode as u,ERRORS as m}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-DR7qdwBN.js";import k from"./FtpFile-ClWDYnt2.js";import b from"./FtpMetaStorage-CJsyeQ63.js";import{r as l,t as v,e as M}from"./posix-dirname-CfpH5wZi.js";import{t as P}from"./get-file-status-y3wTtDQs.js";import{t as A}from"./update-size-DuNuLyxj.js";import{i as R}from"./part-match-D-9dGX42.js";import{e as D}from"./has-content-50BsqrWw.js";const d=h=>{const a=h?.code;if(a===550||a===450||a===553)return!0;const e=h instanceof Error?h.message:String(h);return/no such file|not exist|cannot find|file unavailable/i.test(e)},f=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},g=async(h,a,e)=>{const t=[],n=new E({write(i,r,s){t.push(Buffer.from(i)),s()}});return await h.downloadTo(n,a,e&&e>0?e:void 0),Buffer.concat(t)};class H extends O{static name="ftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=l(a.rootFolderPath??""),this.meta=a.metaStorage??new b(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new k(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=P(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&&A(t,a.size),!R(a,t))return u(m.FILE_CONFLICT);const n=await this.lock(a.id);try{if(D(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return u(m.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return u(m.METHOD_NOT_ALLOWED,"FTP storage does not support chunked or resumable uploads; send the file in a single request.");const i=await v(a.body),r=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,s=>this.run(s,async o=>{await this.ensureRemoteDirectory(o,r),await o.uploadFrom(y.from(i),r)})),t.bytesWritten=i.length,t.size=i.length,t.path=r,t.ETag=T(i)}return t.status=P(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),{range:i}=e??{},r=await this.runOperation(e,s=>this.run(s,async o=>{try{const c=await g(o,n,i?.start);return i?.end!==void 0?c.subarray(0,i.end-i.start+1):c}catch(c){if(d(c))return u(m.FILE_NOT_FOUND);throw c}}));return{content:r,contentType:t.contentType,ETag:t.ETag??T(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:i?r.length: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,r=>this.run(r,async s=>{try{await s.remove(n)}catch(o){if(!d(o))throw o}})),await this.deleteMeta(a);const i={...t,status:"deleted"};return await this.onDelete(i),i})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const n=await this.getMeta(a),i=n.path??this.keyToPath(n.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async c=>{const p=await g(c,i);await this.ensureRemoteDirectory(c,r),await c.uploadFrom(y.from(p),r)}));const s={...n,id:e,name:e,path:r};return await this.saveMeta(s),s})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const n=await this.getMeta(a),i=n.path??this.keyToPath(n.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async c=>{try{await this.ensureRemoteDirectory(c,r),await c.rename(i,r)}catch(p){try{const w=await g(c,i);await this.ensureRemoteDirectory(c,r),await c.uploadFrom(y.from(w),r),await c.remove(i)}catch(w){throw new AggregateError([p,w],`FTP move failed: rename and copy+delete fallback both failed for "${i}" → "${r}"`)}}}));const s={...n,id:e,name:e,path:r};await this.saveMeta(s);try{await this.deleteMeta(a)}catch{}return s})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,n=>this.run(n,async i=>{const r=[];return await this.walkList(i,t,r),r}))})}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,i=>this.run(i,async r=>{try{return await r.size(n),!0}catch(s){if(d(s))return!1;throw s}}))})}async walkList(a,e,t){let n;try{n=await a.list(e||".")}catch(i){if(d(i))return;throw i}for(const i of n){const r=e?`${e}/${i.name}`:i.name;if(i.isDirectory){await this.walkList(a,r,t);continue}if(!i.isFile)continue;const s=this.pathToKey(r);if(!s)continue;const o=new k({contentType:"application/octet-stream",metadata:{},originalName:i.name});o.id=s,o.name=s,o.path=r,o.size=i.size,i.modifiedAt&&(o.modifiedAt=i.modifiedAt.toISOString()),t.push(o)}}async run(a,e){const t=new F;if(a?.aborted)throw f(a.reason);const n=()=>{t.close()};a?.addEventListener("abort",n,{once:!0});try{if(await t.access(this.connection),a?.aborted)throw f(a.reason);return await e(t)}catch(i){throw a?.aborted?f(i):i}finally{a?.removeEventListener("abort",n),t.close()}}async ensureRemoteDirectory(a,e){const t=M(e);t&&(await a.ensureDir(t),await a.cd("/"))}keyToPath(a){const e=l(a);e&&O.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":`/${t.join("/")}`}pathToKey(a){const e=l(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{H as default};
@@ -1 +1 @@
1
- import"node:crypto";import"gaxios";import"google-auth-library";import{v as f}from"./gcs-meta-storage-DQGu_cHq.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-B7CcBueg.js";import"./GCSConfig-BQ0OpVhe.js";export{f as default};
1
+ import"node:crypto";import"gaxios";import"google-auth-library";import{v as f}from"./gcs-meta-storage-Bu2upyHK.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-B7CcBueg.js";import"./GCSConfig-BQ0OpVhe.js";export{f as default};
@@ -0,0 +1 @@
1
+ import{randomUUID as g}from"node:crypto";import{request as f}from"gaxios";import{GoogleAuth as y}from"google-auth-library";import{r as w,v as R,g as C,m,b}from"./gcs-meta-storage-Bu2upyHK.js";import{d as E}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as k,ERRORS as U}from"./ERRORS-BIBxE2oR.js";import{B as I,c as S}from"./storage-DR7qdwBN.js";import{y as T}from"./local-meta-storage-BELb1YwO.js";import d from"./GCSConfig-BQ0OpVhe.js";import x from"./GCSFile-Cero7qZN.js";import{i as O}from"./part-match-D-9dGX42.js";import{e as v}from"./has-content-50BsqrWw.js";import{t as A}from"./get-file-status-y3wTtDQs.js";class $ extends Error{constructor(t,a,e){super(t),this.code=a,this.config=e}code;config;name="FetchError"}const B=l=>l>=200&&l<300||l===308||l===499;class p extends I{static name="gcs";checksumTypes=["md5","crc32c"];supportsDelimiter=!0;get raw(){return this.authClient}meta;bucket;authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;constructor(t){super(t);const a=t.bucket||process.env.GCS_BUCKET;if(!a)throw new Error("GCS bucket is not defined");if(!t.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");this.bucket=a,this.storageBaseURI=`${t.storageAPI||d.storageAPI}/${this.bucket}/o`,this.uploadBaseURI=`${t.uploadAPI||d.uploadAPI}/${this.bucket}/o`,this.isCustomEndpoint=new URL(this.storageBaseURI).hostname!=="storage.googleapis.com";const{retryOptions:e,useAuthWithCustomEndpoint:r,userProject:s}=t;this.userProject=s,this.useAuthWithCustomEndpoint=r||!1,this.retryOptions={...w,...e},t.scopes||=d.authScopes,this.authClient=new y(t);const{bucket:n,metaStorage:c,metaStorageConfig:o,projectId:i}=t;if(c)this.meta=c;else{let u={...t,...o,logger:this.logger};"directory"in u?(this.logger?.debug("Using local meta storage"),this.meta=new T(u)):(n===u.bucket&&i===u.projectId&&(u={...u,authClient:this.authClient}),this.meta=new R(u))}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(u=>{this.logger?.error("Storage access check failed: %O",u)})}normalizeError(t){if(t.config){const a=+t.code||500;return{code:`GCS${a}`,message:t.message,name:t.name,retryable:a>=499,statusCode:a}}return{code:"GenericUploadError",message:`[${this.constructor.name}] ${t.message}`,name:t.name,statusCode:500}}async create(t,a){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const i=typeof t.ttl=="string"?S(t.ttl):t.ttl;i!==void 0&&(e.expiredAt=Date.now()+i)}const r=new x(e);r.name=this.namingFunction(r),await this.validate(r);try{const i=await this.getMeta(r.id);return i.bytesWritten=await this.internalWrite(i,a),i}catch{}const s={"Content-Type":"application/json; charset=utf-8","X-Goog-Upload-Command":"start","X-Goog-Upload-Protocol":"resumable","X-Upload-Content-Length":r.size.toString(),"X-Upload-Content-Type":r.contentType},n={body:JSON.stringify({metadata:r.metadata}),headers:s,method:"POST",params:{name:r.name,size:r.size,uploadType:"resumable"},url:this.uploadBaseURI},c=await this.makeRequest(n,a);if(c.status!==200)throw new Error("Expected 200 response from GCS");const o=c.headers.get("X-Goog-Upload-Status")||c.headers.get("x-goog-upload-status");if(o!=="active")throw new Error(`X-Goog-Upload-Status response header expected 'active' got: ${o}`);return r.uri=c.headers.get("location"),this.config.clientDirectUpload?(r.GCSUploadURI=r.uri,this.logger?.debug("send uploadURI to client: %s",r.GCSUploadURI),r.status="created",r):(r.bytesWritten=0,await this.saveMeta(r),r.status="created",await this.onCreate(r),r)})}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(!O(t,e))return k(U.FILE_CONFLICT);const r=await this.lock(t.id);try{if(v(t)&&(e.bytesWritten===0||Number.isNaN(e.bytesWritten))&&(!e.contentType||e.contentType==="application/octet-stream"))try{const{fileType:s,stream:n}=await E(t.body);s?.mime&&(e.contentType=s.mime),t.body=n}catch{}e.bytesWritten=await this.internalWrite({...e,...t},a),e.status=A(e),e.status==="completed"&&(e.uri=`${this.storageBaseURI}/${e.name}`,await this.internalOnComplete(e))}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);if(!e.uri)throw new Error(`File ${t} does not have a valid URI`);e.status="deleted",await this.makeRequest({method:"DELETE",url:e.uri,validateStatus:B},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()=>{const r=new URL(`/${this.bucket}/${t}`,"file://"),s=new URL(encodeURI(a),r).pathname,[,n,...c]=s.split("/"),o=c.join("/"),i=`${this.storageBaseURI}/${t}/rewriteTo/b/${n}/o/${o}`;let u={};const h={body:"",headers:{"Content-Type":"application/json"},method:"POST",url:i};do h.body=u.rewriteToken?JSON.stringify({rewriteToken:u.rewriteToken}):"",u=(await this.makeRequest(h,e)).data||{};while(u.rewriteToken);return await this.getMeta(a)})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const r=await this.copy(t,a,e),s=`${this.storageBaseURI}/${t}`;return await this.makeRequest({method:"DELETE",url:s},e),r})}async get({id:t},a){return this.instrumentOperation("get",async()=>{const{data:e}=await this.makeRequest({params:{alt:"json"},url:`${this.storageBaseURI}/${t}`},a);if(await this.checkIfExpired({expiredAt:e.timeDeleted}),!e.uri)throw new Error("File URI not found");const r=(await this.makeRequest({params:{alt:"media"},url:e.uri},a)).data;let s;if(typeof r=="string")s=Buffer.from(r,"utf8");else if(r&&typeof r=="object"&&"data"in r){const n=r.data;s=Buffer.from(n)}else s=Buffer.from(r);return{...e,content:s}})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{try{return await this.getMeta(t),await this.makeRequest({method:"HEAD",url:`${this.storageBaseURI}/${t}`},a),!0}catch{return!1}})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const e=[],r=Math.min(t,1e3);let s=!0,n={params:{maxResults:r},url:this.storageBaseURI};for(;s&&e.length<t;)try{const{data:c}=await this.makeRequest(n,a);for(const{name:o,timeCreated:i,updated:u}of c?.items||[]){if(e.length>=t)break;e.push({createdAt:i,id:o,modifiedAt:u})}s=c?.nextPageToken!==void 0,s&&e.length<t&&(n={...n,params:{...n.params,maxResults:Math.min(r,t-e.length),pageToken:c.nextPageToken}})}catch(c){const o=this.normalizeError(c instanceof Error?c:new Error(String(c)));throw await this.onError(o),c}return e},{limit:t})}async listDirectory(t){return this.instrumentOperation("listDirectory",async()=>{const a=t?.limit??1e3,e=Math.min(a,1e3),r=[],s=new Set;let n=!0,c={params:{delimiter:t?.delimiter,maxResults:e,...t?.prefix!==void 0&&{prefix:t.prefix}},url:this.storageBaseURI};for(;n&&r.length<a;)try{const{data:o}=await this.makeRequest(c,t);for(const i of o?.prefixes||[])s.add(i);for(const{name:i,timeCreated:u,updated:h}of o?.items||[]){if(r.length>=a)break;r.push({createdAt:u,id:i,modifiedAt:h})}n=o?.nextPageToken!==void 0,n&&r.length<a&&(c={...c,params:{...c.params,maxResults:Math.min(e,a-r.length),pageToken:o.nextPageToken}})}catch(o){const i=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(i),o}return{files:r,prefixes:[...s]}},{limit:t?.limit??1e3})}async internalWrite(t,a){const{body:e,bytesWritten:r,size:s,uri:n=""}=t,c=b(t),o={method:"PUT"};if(e?.on){const i=new AbortController;e.on("aborted",()=>{i.abort()}),o.body=e,o.signal=i.signal,o.retry=!1}o.headers={Accept:"application/json","Content-Range":c,...s===r?{"X-Goog-Upload-Command":"upload, finalize"}:{}};try{const i=await this.makeRequest({url:n,...o},a);if(i.status===308){const u=i.headers.get("range");return u?C(u):0}if(i.status===200)return this.logger?.debug("uploaded %O",i.data),s;throw new $(String(i.data),`GCS${i.status}`,{uri:n})}catch(i){this.logger?.error(n,i);const u=this.normalizeError(i instanceof Error?i:new Error(String(i)));throw await this.onError(u),i}}internalOnComplete=t=>this.deleteMeta(t.id);static buildCallSignal(t,a){const e=[];if(a&&e.push(a),t?.signal&&e.push(t.signal),e.length!==0)return e.length===1?e[0]:AbortSignal.any(e)}async makeRequest(t,a){typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":"));const e=p.buildCallSignal(a,t.signal);let r=this.retryOptions;if(a?.retries!==void 0){const n=typeof a.retries=="number"?a.retries:a.retries.maxRetries;typeof n=="number"&&(r={...this.retryOptions,retry:n})}const s=typeof a?.timeout=="number"&&a.timeout>0?a.timeout:6e4;return t={...t,headers:{"User-Agent":`${m.name}/${m.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${m.version} gccl-invocation-id/${g()}`,...t.headers},params:{...this.userProject===void 0?{}:{userProject:this.userProject},...t.params},retry:t.retry===!1?!1:a?.retries!==0,retryConfig:r,timeout:s,...e?{signal:e}:{}},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?f(t):this.authClient.request(t)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}}export{p as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-BELb1YwO.js";class o extends r{constructor(t){super(t)}}export{o as default};
@@ -1 +1 @@
1
- import{Readable as D}from"node:stream";import{drive as C}from"@googleapis/drive";import{JWT as g,GoogleAuth as T,OAuth2Client as b}from"google-auth-library";import{throwErrorCode as u,ERRORS as p,wrapStorageError as E}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-0j5nCAUp.js";import m from"./GoogleDriveFile-DHpLhzg9.js";import F from"./GoogleDriveMetaStorage-xlHfKwmR.js";import{t as I}from"./get-file-status-y3wTtDQs.js";import{t as _}from"./update-size-DuNuLyxj.js";import{i as L}from"./part-match-D-9dGX42.js";import{e as G}from"./has-content-50BsqrWw.js";const f="https://www.googleapis.com/auth/drive",A=1024,h="fsdkKey",y="fsdkContentType",O="id, name, size, mimeType, md5Checksum, modifiedTime, appProperties",v=r=>{const e=r.lastIndexOf("/");return e===-1?r:r.slice(e+1)},w=r=>r.replaceAll("\\","\\\\").replaceAll("'",String.raw`\'`);class R{#t;#e=new Map;constructor(e){this.#t=Math.max(1,e)}delete(e){this.#e.delete(e)}get(e){const i=this.#e.get(e);if(i!==void 0)return this.#e.delete(e),this.#e.set(e,i),i}set(e,i){if(this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,i),this.#e.size>this.#t){const t=this.#e.keys().next().value;t!==void 0&&this.#e.delete(t)}}}const P=r=>{const e=r.subject??process.env.GOOGLE_DRIVE_SUBJECT;if(r.credentials)return new g({email:r.credentials.client_email,key:r.credentials.private_key,scopes:[f],...e&&{subject:e}});if(r.keyFilename)return new T({keyFile:r.keyFilename,scopes:[f],...e&&{clientOptions:{subject:e}}});if(r.oauth){const s=new b({clientId:r.oauth.clientId,clientSecret:r.oauth.clientSecret});return s.setCredentials({refresh_token:r.oauth.refreshToken}),s}const i=process.env.GOOGLE_DRIVE_CLIENT_EMAIL,t=process.env.GOOGLE_DRIVE_PRIVATE_KEY;if(i&&t)return new g({email:i,key:t,scopes:[f],...e&&{subject:e}});const o=process.env.GOOGLE_DRIVE_KEY_FILE;if(o)return new T({keyFile:o,scopes:[f],...e&&{clientOptions:{subject:e}}})},B=async r=>{const e=[];for await(const i of r)e.push(Buffer.from(i));return Buffer.concat(e)},U=r=>{if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(Buffer.isBuffer(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(ArrayBuffer.isView(r)){const e=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof r=="string")return new TextEncoder().encode(r);throw new Error("Google Drive: unexpected response payload shape")};class H extends k{static name="google-drive";checksumTypes=[];meta;authForTokens;driveClient;fileIdCache;publicByDefault;rootFolderId;sharedDriveParams;constructor(e){if(super(e),e.client)this.driveClient=e.client,this.authForTokens=void 0;else{const t=P(e);if(!t)throw new Error("Google Drive storage: missing auth. Pass `client`, `credentials`, `keyFilename`, or `oauth`. Env fallbacks: GOOGLE_DRIVE_CLIENT_EMAIL + GOOGLE_DRIVE_PRIVATE_KEY, or GOOGLE_DRIVE_KEY_FILE.");this.authForTokens=t,this.driveClient=C({auth:t,version:"v3"})}const i=e.driveId??process.env.GOOGLE_DRIVE_ID;this.rootFolderId=e.rootFolderId??process.env.GOOGLE_DRIVE_ROOT_FOLDER_ID??i??"root",this.publicByDefault=e.publicByDefault??!1,this.fileIdCache=new R(e.fileIdCacheSize??A),this.sharedDriveParams={includeItemsFromAllDrives:!0,supportsAllDrives:!0,...i&&{corpora:"drive",driveId:i}},this.meta=e.metaStorage??new F(e.metaStorageConfig),this.isReady=!0}get raw(){return this.driveClient}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new m(e);t.name=this.namingFunction(t),await this.validate(t);try{const o=await this.getMeta(t.id);if(o.bytesWritten>=0)return o}catch{}return t.bytesWritten=0,t.status=I(t),await this.saveMeta(t),await this.onCreate(t),t})}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),!L(e,t))throw new Error("File part does not match");const o=await this.lock(e.id);try{if(G(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const s=await B(e.body),n=t.name||t.id,a={[y]:t.contentType,[h]:n},l=await this.runOperation(i,()=>this.driveClient.files.create({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum, modifiedTime",media:{body:D.from(s),mimeType:t.contentType},requestBody:{appProperties:a,mimeType:t.contentType,name:v(n),parents:[this.rootFolderId]}})),{data:d}=l,c=d.id??void 0;c&&(this.fileIdCache.set(n,c),this.publicByDefault&&await this.runOperation(i,()=>this.driveClient.permissions.create({...this.sharedDriveParams,fileId:c,requestBody:{role:"reader",type:"anyone"}}))),t.bytesWritten=s.length,t.size=s.length,t.driveFileId=c,t.mimeType=d.mimeType??t.contentType,t.ETag=d.md5Checksum??void 0}return t.status=I(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,o)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;const o=e;try{t=await this.getMeta(e)}catch{}try{const s=t?.driveFileId??await this.resolveFileId(o,i);await this.runOperation(i,()=>this.driveClient.files.delete({...this.sharedDriveParams,fileId:s})),this.fileIdCache.delete(o)}catch(s){if(!z(s))throw s;this.fileIdCache.delete(o)}return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new m({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,status:"deleted"})})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,o;try{t=await this.checkIfExpired(await this.getMeta(e)),o=t.driveFileId??await this.resolveFileId(t.name??e,i)}catch{o=await this.resolveFileId(e,i)}const[s,n]=await Promise.all([this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,fields:O,fileId:o})),this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,alt:"media",fileId:o},{responseType:"arraybuffer"}))]),{data:a}=s,l=U(n.data),d=Buffer.from(l.buffer,l.byteOffset,l.byteLength),c=a.appProperties??{};return{content:d,contentType:t?.contentType??c[y]??a.mimeType??"application/octet-stream",ETag:t?.ETag??a.md5Checksum??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??a.modifiedTime??void 0,name:t?.name??a.name??e,originalName:t?.originalName??a.name??e,size:t?.size??Number(a.size??d.length)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const o=await this.resolveFileId(e,t),s=await this.runOperation(t,()=>this.driveClient.files.copy({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum",fileId:o,requestBody:{appProperties:{[h]:i},name:v(i),parents:[this.rootFolderId]}})),n=s.data.id??void 0;n&&this.fileIdCache.set(i,n);const a=new m({contentType:s.data.mimeType??"application/octet-stream",metadata:{},originalName:i});return a.id=i,a.name=i,a.driveFileId=n,a.mimeType=s.data.mimeType??void 0,a.ETag=s.data.md5Checksum??void 0,a.size=Number(s.data.size??0),a})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const o=await this.copy(e,i,t);return await this.delete({id:e},t),o})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{const t=`'${w(this.rootFolderId)}' in parents and trashed=false`,o=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:`nextPageToken, files(${O})`,pageSize:e,q:t}))).data.files??[],s=[];for(const n of o){const a=n.appProperties??{},l=a[h];if(!l)continue;n.id&&this.fileIdCache.set(l,n.id);const d=new m({contentType:a[y]??n.mimeType??"application/octet-stream",metadata:{},originalName:n.name??l});d.id=l,d.name=l,d.driveFileId=n.id??void 0,d.mimeType=n.mimeType??void 0,d.size=Number(n.size??0),d.modifiedAt=n.modifiedTime??void 0,d.ETag=n.md5Checksum??void 0,s.push(d)}return s},{limit:e})}async getReadUrl(e,i){return i?.responseContentDisposition!==void 0||i?.responseContentType!==void 0?u(p.METHOD_NOT_ALLOWED,"Google Drive: `responseContentDisposition`/`responseContentType` are not supported — Drive's webContentLink has no Content-Disposition/Content-Type override."):this.publicByDefault?`https://drive.google.com/uc?export=download&id=${await this.resolveFileId(e)}`:u(p.METHOD_NOT_ALLOWED,"Google Drive: getReadUrl() requires the adapter to be constructed with `publicByDefault: true`. Drive has no signed URL primitive — use get() for private files.")}async getUploadUrl(e,i){if(i?.contentLength!==void 0)return u(p.BAD_REQUEST,"Google Drive: `contentLength` is not supported for upload URLs. A Drive resumable upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");if(!this.authForTokens)return u(p.METHOD_NOT_ALLOWED,"Google Drive: getUploadUrl() requires `credentials`, `keyFilename`, or `oauth` — not the pre-built `client` escape hatch.");const t=await this.authForTokens.getAccessToken(),o=typeof t=="string"?t:t?.token;if(!o)throw new Error("Google Drive: failed to mint access token for resumable upload session");const s={Authorization:`Bearer ${o}`,"Content-Type":"application/json; charset=UTF-8"};i?.contentType&&(s["X-Upload-Content-Type"]=i.contentType);const n={appProperties:{[h]:e},name:v(e),parents:[this.rootFolderId]},a=await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",{body:JSON.stringify(n),headers:s,method:"POST"});if(!a.ok){const d=await a.text().catch(()=>"");throw E(new Error(`${a.statusText} ${d}`.trim()||a.statusText),{adapter:"Google Drive",operation:"resumable upload session",status:a.status})}const l=a.headers.get("location")??a.headers.get("Location");if(!l)throw E(new Error("response missing Location header"),{adapter:"Google Drive",code:p.STORAGE_ERROR,operation:"resumable upload session"});return l}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const o=`appProperties has { key='${h}' and value='${w(e)}' } and '${w(this.rootFolderId)}' in parents and trashed=false`,s=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:"files(id)",pageSize:2,q:o}))).data.files??[];if(s.length===0)throw new Error(`Google Drive: not found: ${e}`);if(s.length>1)throw new Error(`Google Drive: multiple files share virtual key '${e}'. Resolve via storage.raw.`);const n=s[0]?.id;if(!n)throw new Error(`Google Drive: list returned no fileId for ${e}`);return this.fileIdCache.set(e,n),n}internalOnComplete=e=>this.deleteMeta(e.id)}const z=r=>{if(r===null||typeof r!="object")return!1;const e=r;return typeof e.code=="number"&&e.code===404||typeof e.status=="number"&&e.status===404?!0:typeof e.response?.status=="number"&&e.response.status===404};export{H as default};
1
+ import{Readable as D}from"node:stream";import{drive as C}from"@googleapis/drive";import{JWT as g,GoogleAuth as T,OAuth2Client as b}from"google-auth-library";import{throwErrorCode as u,ERRORS as p,wrapStorageError as E}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-DR7qdwBN.js";import m from"./GoogleDriveFile-DHpLhzg9.js";import F from"./GoogleDriveMetaStorage-B0gLF7Io.js";import{t as I}from"./get-file-status-y3wTtDQs.js";import{t as _}from"./update-size-DuNuLyxj.js";import{i as L}from"./part-match-D-9dGX42.js";import{e as G}from"./has-content-50BsqrWw.js";const f="https://www.googleapis.com/auth/drive",A=1024,h="fsdkKey",y="fsdkContentType",O="id, name, size, mimeType, md5Checksum, modifiedTime, appProperties",v=r=>{const e=r.lastIndexOf("/");return e===-1?r:r.slice(e+1)},w=r=>r.replaceAll("\\","\\\\").replaceAll("'",String.raw`\'`);class R{#t;#e=new Map;constructor(e){this.#t=Math.max(1,e)}delete(e){this.#e.delete(e)}get(e){const i=this.#e.get(e);if(i!==void 0)return this.#e.delete(e),this.#e.set(e,i),i}set(e,i){if(this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,i),this.#e.size>this.#t){const t=this.#e.keys().next().value;t!==void 0&&this.#e.delete(t)}}}const P=r=>{const e=r.subject??process.env.GOOGLE_DRIVE_SUBJECT;if(r.credentials)return new g({email:r.credentials.client_email,key:r.credentials.private_key,scopes:[f],...e&&{subject:e}});if(r.keyFilename)return new T({keyFile:r.keyFilename,scopes:[f],...e&&{clientOptions:{subject:e}}});if(r.oauth){const s=new b({clientId:r.oauth.clientId,clientSecret:r.oauth.clientSecret});return s.setCredentials({refresh_token:r.oauth.refreshToken}),s}const i=process.env.GOOGLE_DRIVE_CLIENT_EMAIL,t=process.env.GOOGLE_DRIVE_PRIVATE_KEY;if(i&&t)return new g({email:i,key:t,scopes:[f],...e&&{subject:e}});const o=process.env.GOOGLE_DRIVE_KEY_FILE;if(o)return new T({keyFile:o,scopes:[f],...e&&{clientOptions:{subject:e}}})},B=async r=>{const e=[];for await(const i of r)e.push(Buffer.from(i));return Buffer.concat(e)},U=r=>{if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(Buffer.isBuffer(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(ArrayBuffer.isView(r)){const e=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof r=="string")return new TextEncoder().encode(r);throw new Error("Google Drive: unexpected response payload shape")};class H extends k{static name="google-drive";checksumTypes=[];meta;authForTokens;driveClient;fileIdCache;publicByDefault;rootFolderId;sharedDriveParams;constructor(e){if(super(e),e.client)this.driveClient=e.client,this.authForTokens=void 0;else{const t=P(e);if(!t)throw new Error("Google Drive storage: missing auth. Pass `client`, `credentials`, `keyFilename`, or `oauth`. Env fallbacks: GOOGLE_DRIVE_CLIENT_EMAIL + GOOGLE_DRIVE_PRIVATE_KEY, or GOOGLE_DRIVE_KEY_FILE.");this.authForTokens=t,this.driveClient=C({auth:t,version:"v3"})}const i=e.driveId??process.env.GOOGLE_DRIVE_ID;this.rootFolderId=e.rootFolderId??process.env.GOOGLE_DRIVE_ROOT_FOLDER_ID??i??"root",this.publicByDefault=e.publicByDefault??!1,this.fileIdCache=new R(e.fileIdCacheSize??A),this.sharedDriveParams={includeItemsFromAllDrives:!0,supportsAllDrives:!0,...i&&{corpora:"drive",driveId:i}},this.meta=e.metaStorage??new F(e.metaStorageConfig),this.isReady=!0}get raw(){return this.driveClient}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new m(e);t.name=this.namingFunction(t),await this.validate(t);try{const o=await this.getMeta(t.id);if(o.bytesWritten>=0)return o}catch{}return t.bytesWritten=0,t.status=I(t),await this.saveMeta(t),await this.onCreate(t),t})}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),!L(e,t))throw new Error("File part does not match");const o=await this.lock(e.id);try{if(G(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const s=await B(e.body),n=t.name||t.id,a={[y]:t.contentType,[h]:n},l=await this.runOperation(i,()=>this.driveClient.files.create({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum, modifiedTime",media:{body:D.from(s),mimeType:t.contentType},requestBody:{appProperties:a,mimeType:t.contentType,name:v(n),parents:[this.rootFolderId]}})),{data:d}=l,c=d.id??void 0;c&&(this.fileIdCache.set(n,c),this.publicByDefault&&await this.runOperation(i,()=>this.driveClient.permissions.create({...this.sharedDriveParams,fileId:c,requestBody:{role:"reader",type:"anyone"}}))),t.bytesWritten=s.length,t.size=s.length,t.driveFileId=c,t.mimeType=d.mimeType??t.contentType,t.ETag=d.md5Checksum??void 0}return t.status=I(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,o)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;const o=e;try{t=await this.getMeta(e)}catch{}try{const s=t?.driveFileId??await this.resolveFileId(o,i);await this.runOperation(i,()=>this.driveClient.files.delete({...this.sharedDriveParams,fileId:s})),this.fileIdCache.delete(o)}catch(s){if(!z(s))throw s;this.fileIdCache.delete(o)}return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new m({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,status:"deleted"})})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,o;try{t=await this.checkIfExpired(await this.getMeta(e)),o=t.driveFileId??await this.resolveFileId(t.name??e,i)}catch{o=await this.resolveFileId(e,i)}const[s,n]=await Promise.all([this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,fields:O,fileId:o})),this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,alt:"media",fileId:o},{responseType:"arraybuffer"}))]),{data:a}=s,l=U(n.data),d=Buffer.from(l.buffer,l.byteOffset,l.byteLength),c=a.appProperties??{};return{content:d,contentType:t?.contentType??c[y]??a.mimeType??"application/octet-stream",ETag:t?.ETag??a.md5Checksum??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??a.modifiedTime??void 0,name:t?.name??a.name??e,originalName:t?.originalName??a.name??e,size:t?.size??Number(a.size??d.length)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const o=await this.resolveFileId(e,t),s=await this.runOperation(t,()=>this.driveClient.files.copy({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum",fileId:o,requestBody:{appProperties:{[h]:i},name:v(i),parents:[this.rootFolderId]}})),n=s.data.id??void 0;n&&this.fileIdCache.set(i,n);const a=new m({contentType:s.data.mimeType??"application/octet-stream",metadata:{},originalName:i});return a.id=i,a.name=i,a.driveFileId=n,a.mimeType=s.data.mimeType??void 0,a.ETag=s.data.md5Checksum??void 0,a.size=Number(s.data.size??0),a})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const o=await this.copy(e,i,t);return await this.delete({id:e},t),o})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{const t=`'${w(this.rootFolderId)}' in parents and trashed=false`,o=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:`nextPageToken, files(${O})`,pageSize:e,q:t}))).data.files??[],s=[];for(const n of o){const a=n.appProperties??{},l=a[h];if(!l)continue;n.id&&this.fileIdCache.set(l,n.id);const d=new m({contentType:a[y]??n.mimeType??"application/octet-stream",metadata:{},originalName:n.name??l});d.id=l,d.name=l,d.driveFileId=n.id??void 0,d.mimeType=n.mimeType??void 0,d.size=Number(n.size??0),d.modifiedAt=n.modifiedTime??void 0,d.ETag=n.md5Checksum??void 0,s.push(d)}return s},{limit:e})}async getReadUrl(e,i){return i?.responseContentDisposition!==void 0||i?.responseContentType!==void 0?u(p.METHOD_NOT_ALLOWED,"Google Drive: `responseContentDisposition`/`responseContentType` are not supported — Drive's webContentLink has no Content-Disposition/Content-Type override."):this.publicByDefault?`https://drive.google.com/uc?export=download&id=${await this.resolveFileId(e)}`:u(p.METHOD_NOT_ALLOWED,"Google Drive: getReadUrl() requires the adapter to be constructed with `publicByDefault: true`. Drive has no signed URL primitive — use get() for private files.")}async getUploadUrl(e,i){if(i?.contentLength!==void 0)return u(p.BAD_REQUEST,"Google Drive: `contentLength` is not supported for upload URLs. A Drive resumable upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");if(!this.authForTokens)return u(p.METHOD_NOT_ALLOWED,"Google Drive: getUploadUrl() requires `credentials`, `keyFilename`, or `oauth` — not the pre-built `client` escape hatch.");const t=await this.authForTokens.getAccessToken(),o=typeof t=="string"?t:t?.token;if(!o)throw new Error("Google Drive: failed to mint access token for resumable upload session");const s={Authorization:`Bearer ${o}`,"Content-Type":"application/json; charset=UTF-8"};i?.contentType&&(s["X-Upload-Content-Type"]=i.contentType);const n={appProperties:{[h]:e},name:v(e),parents:[this.rootFolderId]},a=await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",{body:JSON.stringify(n),headers:s,method:"POST"});if(!a.ok){const d=await a.text().catch(()=>"");throw E(new Error(`${a.statusText} ${d}`.trim()||a.statusText),{adapter:"Google Drive",operation:"resumable upload session",status:a.status})}const l=a.headers.get("location")??a.headers.get("Location");if(!l)throw E(new Error("response missing Location header"),{adapter:"Google Drive",code:p.STORAGE_ERROR,operation:"resumable upload session"});return l}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const o=`appProperties has { key='${h}' and value='${w(e)}' } and '${w(this.rootFolderId)}' in parents and trashed=false`,s=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:"files(id)",pageSize:2,q:o}))).data.files??[];if(s.length===0)throw new Error(`Google Drive: not found: ${e}`);if(s.length>1)throw new Error(`Google Drive: multiple files share virtual key '${e}'. Resolve via storage.raw.`);const n=s[0]?.id;if(!n)throw new Error(`Google Drive: list returned no fileId for ${e}`);return this.fileIdCache.set(e,n),n}internalOnComplete=e=>this.deleteMeta(e.id)}const z=r=>{if(r===null||typeof r!="object")return!1;const e=r;return typeof e.code=="number"&&e.code===404||typeof e.status=="number"&&e.status===404?!0:typeof e.response?.status=="number"&&e.response.status===404};export{H as default};
@@ -1 +1 @@
1
- import"node:fs/promises";import"node:os";import{y as f}from"./local-meta-storage-DJDcuxf1.js";import"./path-0oTTdkvl-DvWvbDbh.js";import"./ERRORS-BIBxE2oR.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-B7CcBueg.js";export{f as default};
1
+ import"node:fs/promises";import"node:os";import{y as f}from"./local-meta-storage-BELb1YwO.js";import"./path-C-OWflAo-_mqb5p5d.js";import"./ERRORS-BIBxE2oR.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-B7CcBueg.js";export{f as default};
@@ -1 +1 @@
1
- import{Readable as w}from"node:stream";import{F as p}from"./index-nZWCQrSe.js";import{throwErrorCode as f,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as c}from"./storage-0j5nCAUp.js";import T from"./MemoryMetaStorage-Ksgh9pe7.js";import l from"./File-W8aOo15X.js";import{t as u}from"./get-file-status-y3wTtDQs.js";import{e as b}from"./has-content-50BsqrWw.js";import{t as A}from"./update-size-DuNuLyxj.js";class D extends c{static name="memory";checksumTypes=["md5"];supportsRange=!0;meta;store;constructor(e={}){if(super(e),this.store=new Map,this.meta=e.metaStorage??new T({...e.metaStorageConfig,logger:this.logger}),e.initial)for(const[s,t]of Object.entries(e.initial)){c.assertSafeId(s);const a=Buffer.from(t),r=new Date().toISOString(),n=p(a);this.store.set(s,{bytes:a,contentType:"application/octet-stream",createdAt:r,eTag:n,metadata:{},modifiedAt:r});const i=new l({contentType:"application/octet-stream",id:s,metadata:{name:s,size:a.length},originalName:s,size:a.length});i.name=s,i.bytesWritten=a.length,i.ETag=n,i.createdAt=r,i.modifiedAt=r,i.status=u(i),this.meta.save(s,i).catch(()=>{})}}get raw(){return this.store}async create(e,s){return this.instrumentOperation("create",async()=>{const t=new l(e);return t.name=this.namingFunction(t),c.assertSafeId(t.name),await this.validate(t),t.bytesWritten=0,t.status=u(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,s){return this.instrumentOperation("write",async()=>{const t=await this.getMeta(e.id);if(!b(e))return t;const{body:a,start:r}=e,n=[];for await(const o of a)Buffer.isBuffer(o)?n.push(o):typeof o=="string"?n.push(Buffer.from(o)):ArrayBuffer.isView(o)?n.push(Buffer.from(o.buffer,o.byteOffset,o.byteLength)):n.push(Buffer.from(o));const i=Buffer.concat(n),m=this.store.get(t.name)?.bytes,d=r===0||!m?i:Buffer.concat([m.subarray(0,r),i]),y=new Date().toISOString(),g={bytes:d,contentType:t.contentType,createdAt:this.store.get(t.name)?.createdAt??y,eTag:p(d),metadata:{...t.metadata},modifiedAt:y};return this.store.set(t.name,g),t.bytesWritten=d.length,t.ETag=g.eTag,t.modifiedAt=g.modifiedAt,A(t,d.length),t.status=u(t),await this.saveMeta(t),t.status==="completed"&&await this.onComplete(t,{}),t})}async get({id:e},s){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);if(i>m||i>=a.bytes.length)return f(h.BAD_REQUEST,`Invalid range ${i}-${n.end??""}`);r=a.bytes.subarray(i,m+1)}return{content:r,contentType:a.contentType,ETag:a.eTag,expiredAt:t.expiredAt,id:e,metadata:{...a.metadata},modifiedAt:a.modifiedAt,name:t.name,originalName:t.originalName,size:r.length}})}async getStream({id:e},s){return this.instrumentOperation("getStream",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);r=a.bytes.subarray(i,m+1)}return{headers:{"Content-Length":String(r.length),"Content-Type":a.contentType,ETag:a.eTag,"Last-Modified":a.modifiedAt},size:r.length,stream:w.from(r)}})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const s=await this.meta.get(e);return this.store.has(s.name)}catch{return!1}})}async delete({id:e}){return this.instrumentOperation("delete",async()=>{const s=await this.getMeta(e);this.store.delete(s.name),await this.deleteMeta(e);const t={...s,status:"deleted"};return await this.onDelete(t),t})}async copy(e,s){return this.instrumentOperation("copy",async()=>{c.assertSafeId(e),c.assertSafeId(s);const t=await this.getMeta(e),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);const r=new Date().toISOString();this.store.set(s,{...a,bytes:Buffer.from(a.bytes),metadata:{...a.metadata},modifiedAt:r});const n={...t,ETag:a.eTag,id:s,modifiedAt:r,name:s};return await this.saveMeta(n),n})}async move(e,s){return this.instrumentOperation("move",async()=>{if(e===s)return this.getMeta(e);const t=await this.copy(e,s);return await this.delete({id:e}),t})}async list(){return this.instrumentOperation("list",async()=>{const e=[];for(const[s,t]of this.store)e.push({contentType:t.contentType,createdAt:t.createdAt,ETag:t.eTag,id:s,metadata:{...t.metadata},modifiedAt:t.modifiedAt,name:s,size:t.bytes.length});return e})}async getReadUrl(e){return c.assertSafeId(e),`memory://${e}`}async getUploadUrl(e){return c.assertSafeId(e),`memory://${e}`}}export{D as default};
1
+ import{Readable as w}from"node:stream";import{F as p}from"./index-nZWCQrSe.js";import{throwErrorCode as f,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as c}from"./storage-DR7qdwBN.js";import T from"./MemoryMetaStorage-Ksgh9pe7.js";import l from"./File-W8aOo15X.js";import{t as u}from"./get-file-status-y3wTtDQs.js";import{e as b}from"./has-content-50BsqrWw.js";import{t as A}from"./update-size-DuNuLyxj.js";class F extends c{static name="memory";checksumTypes=["md5"];supportsRange=!0;meta;store;constructor(e={}){if(super(e),this.store=new Map,this.meta=e.metaStorage??new T({...e.metaStorageConfig,logger:this.logger}),e.initial)for(const[s,t]of Object.entries(e.initial)){c.assertSafeId(s);const a=Buffer.from(t),r=new Date().toISOString(),n=p(a);this.store.set(s,{bytes:a,contentType:"application/octet-stream",createdAt:r,eTag:n,metadata:{},modifiedAt:r});const i=new l({contentType:"application/octet-stream",id:s,metadata:{name:s,size:a.length},originalName:s,size:a.length});i.name=s,i.bytesWritten=a.length,i.ETag=n,i.createdAt=r,i.modifiedAt=r,i.status=u(i),this.meta.save(s,i).catch(()=>{})}}get raw(){return this.store}async create(e,s){return this.instrumentOperation("create",async()=>{const t=new l(e);return t.name=this.namingFunction(t),c.assertSafeId(t.name),await this.validate(t),t.bytesWritten=0,t.status=u(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,s){return this.instrumentOperation("write",async()=>{const t=await this.getMeta(e.id);if(!b(e))return t;const{body:a,start:r}=e,n=[];for await(const o of a)Buffer.isBuffer(o)?n.push(o):typeof o=="string"?n.push(Buffer.from(o)):ArrayBuffer.isView(o)?n.push(Buffer.from(o.buffer,o.byteOffset,o.byteLength)):n.push(Buffer.from(o));const i=Buffer.concat(n),m=this.store.get(t.name)?.bytes,d=r===0||!m?i:Buffer.concat([m.subarray(0,r),i]),y=new Date().toISOString(),g={bytes:d,contentType:t.contentType,createdAt:this.store.get(t.name)?.createdAt??y,eTag:p(d),metadata:{...t.metadata},modifiedAt:y};return this.store.set(t.name,g),t.bytesWritten=d.length,t.ETag=g.eTag,t.modifiedAt=g.modifiedAt,A(t,d.length),t.status=u(t),await this.saveMeta(t),t.status==="completed"&&await this.onComplete(t,{}),t})}async get({id:e},s){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);if(i>m||i>=a.bytes.length)return f(h.BAD_REQUEST,`Invalid range ${i}-${n.end??""}`);r=a.bytes.subarray(i,m+1)}return{content:r,contentType:a.contentType,ETag:a.eTag,expiredAt:t.expiredAt,id:e,metadata:{...a.metadata},modifiedAt:a.modifiedAt,name:t.name,originalName:t.originalName,size:r.length}})}async getStream({id:e},s){return this.instrumentOperation("getStream",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);r=a.bytes.subarray(i,m+1)}return{headers:{"Content-Length":String(r.length),"Content-Type":a.contentType,ETag:a.eTag,"Last-Modified":a.modifiedAt},size:r.length,stream:w.from(r)}})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const s=await this.meta.get(e);return this.store.has(s.name)}catch{return!1}})}async delete({id:e}){return this.instrumentOperation("delete",async()=>{const s=await this.getMeta(e);this.store.delete(s.name),await this.deleteMeta(e);const t={...s,status:"deleted"};return await this.onDelete(t),t})}async copy(e,s){return this.instrumentOperation("copy",async()=>{c.assertSafeId(e),c.assertSafeId(s);const t=await this.getMeta(e),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);const r=new Date().toISOString();this.store.set(s,{...a,bytes:Buffer.from(a.bytes),metadata:{...a.metadata},modifiedAt:r});const n={...t,ETag:a.eTag,id:s,modifiedAt:r,name:s};return await this.saveMeta(n),n})}async move(e,s){return this.instrumentOperation("move",async()=>{if(e===s)return this.getMeta(e);const t=await this.copy(e,s);return await this.delete({id:e}),t})}async list(){return this.instrumentOperation("list",async()=>{const e=[];for(const[s,t]of this.store)e.push({contentType:t.contentType,createdAt:t.createdAt,ETag:t.eTag,id:s,metadata:{...t.metadata},modifiedAt:t.modifiedAt,name:s,size:t.bytes.length});return e})}async getReadUrl(e){return c.assertSafeId(e),`memory://${e}`}async getUploadUrl(e){return c.assertSafeId(e),`memory://${e}`}}export{F as default};
@@ -1 +1 @@
1
- import{Readable as s}from"node:stream";import{parseMultipartRequest as n,MaxFileSizeExceededError as d,MultipartParseError as l}from"@remix-run/multipart-parser/node";import{n as i}from"./headers-BAiAKekR.js";import{g as m}from"./base-handler-core-D-9Ku1h-.js";import{b as f}from"./storage-0j5nCAUp.js";import{T as u}from"./base-handler-node-BF1v1qDa.js";import{p as h}from"./multipart-base-BOzY19lb.js";const c=/^multipart\/.+|application\/x-www-form-urlencoded$/i;class b extends u{static methods=["delete","download","get","options","post"];multipartBase;maxFileSize;maxHeaderSize;constructor(t){super(t),this.maxFileSize=t.maxFileSize??Math.min(this.storage.maxUploadSize,1024*1024*1024),this.maxHeaderSize=t.maxHeaderSize??64*1024;const e=this;this.multipartBase=new class extends h{get storage(){return e.storage}get maxFileSize(){return e.maxFileSize}get maxHeaderSize(){return e.maxHeaderSize}buildFileUrl(r,a){return e.buildFileUrl({url:r},a)}createStreamFromBytes(r){return r instanceof Uint8Array||Buffer.isBuffer(r)?s.from(Buffer.from(r)):typeof r=="number"?s.from(Buffer.alloc(0)):s.from(Buffer.from(String(r)))}createEmptyStream(){return s.from(new Uint8Array(0))}}}async post(t){if(!c.test(t.headers["content-type"]?.split(";")[0]??""))throw i(400,"Invalid content-type");try{const e=[];for await(const o of n(t,{maxFileSize:this.maxFileSize,maxHeaderSize:this.maxHeaderSize}))e.push(o);const r=e.find(o=>o.isFile);if(!r)throw i(400,"No file found in multipart request");const a=t.originalUrl||t.url||"";return this.multipartBase.handlePost(r,e,a)}catch(e){throw e instanceof d?i(413,"File size limit exceeded"):e instanceof l?i(400,"Invalid multipart request"):e instanceof f&&e.statusCode?i(e.statusCode,e.message||e.body||"Validation failed"):e}}async delete(t){try{const e=m(t);return this.multipartBase.handleDelete(e)}catch(e){throw this.checkForUndefinedIdOrPath(e),e.code==="ENOENT"?i(404,"File not found"):e}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}}export{b as default};
1
+ import{Readable as s}from"node:stream";import{parseMultipartRequest as n,MaxFileSizeExceededError as d,MultipartParseError as l}from"@remix-run/multipart-parser/node";import{n as i}from"./headers-BAiAKekR.js";import{g as m}from"./base-handler-core-BJP9jHCE.js";import{b as f}from"./storage-DR7qdwBN.js";import{T as u}from"./base-handler-node-C8P9rkaH.js";import{p as h}from"./multipart-base-BOzY19lb.js";const c=/^multipart\/.+|application\/x-www-form-urlencoded$/i;class b extends u{static methods=["delete","download","get","options","post"];multipartBase;maxFileSize;maxHeaderSize;constructor(t){super(t),this.maxFileSize=t.maxFileSize??Math.min(this.storage.maxUploadSize,1024*1024*1024),this.maxHeaderSize=t.maxHeaderSize??64*1024;const e=this;this.multipartBase=new class extends h{get storage(){return e.storage}get maxFileSize(){return e.maxFileSize}get maxHeaderSize(){return e.maxHeaderSize}buildFileUrl(r,a){return e.buildFileUrl({url:r},a)}createStreamFromBytes(r){return r instanceof Uint8Array||Buffer.isBuffer(r)?s.from(Buffer.from(r)):typeof r=="number"?s.from(Buffer.alloc(0)):s.from(Buffer.from(String(r)))}createEmptyStream(){return s.from(new Uint8Array(0))}}}async post(t){if(!c.test(t.headers["content-type"]?.split(";")[0]??""))throw i(400,"Invalid content-type");try{const e=[];for await(const o of n(t,{maxFileSize:this.maxFileSize,maxHeaderSize:this.maxHeaderSize}))e.push(o);const r=e.find(o=>o.isFile);if(!r)throw i(400,"No file found in multipart request");const a=t.originalUrl||t.url||"";return this.multipartBase.handlePost(r,e,a)}catch(e){throw e instanceof d?i(413,"File size limit exceeded"):e instanceof l?i(400,"Invalid multipart request"):e instanceof f&&e.statusCode?i(e.statusCode,e.message||e.body||"Validation failed"):e}}async delete(t){try{const e=m(t);return this.multipartBase.handleDelete(e)}catch(e){throw this.checkForUndefinedIdOrPath(e),e.code==="ENOENT"?i(404,"File not found"):e}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}}export{b as default};
@@ -1 +1 @@
1
- import{Readable as a}from"node:stream";import{parseMultipartRequest as m,MaxFileSizeExceededError as h,MultipartParseError as c}from"@remix-run/multipart-parser";import{n as i}from"./headers-BAiAKekR.js";import{b as u,B as f}from"./storage-0j5nCAUp.js";import{C as p}from"./base-handler-fetch-CfkNakv8.js";import{p as g}from"./multipart-base-BOzY19lb.js";const x=/^multipart\/.+|application\/x-www-form-urlencoded$/i,S=d=>{let t;try{const r=new URL(d).pathname.split("/").filter(Boolean);t=r[r.length-1]||void 0}catch{return}if(t){try{f.assertSafeId(t)}catch{throw i(400,`Invalid file id: "${t}"`)}return t}};class n extends p{static methods=["delete","download","get","options","post"];multipartBase;maxFileSize;maxHeaderSize;constructor(t){super(t),this.maxFileSize=t.maxFileSize??Math.min(this.storage.maxUploadSize,1024*1024*1024),this.maxHeaderSize=t.maxHeaderSize??64*1024;const r=this;this.multipartBase=new class extends g{get storage(){return r.storage}get maxFileSize(){return r.maxFileSize}get maxHeaderSize(){return r.maxHeaderSize}buildFileUrl(e,s){return r.buildFileUrl({url:e},s)}createStreamFromBytes(e){return e instanceof Uint8Array?a.from(Buffer.from(e)):e instanceof ArrayBuffer?a.from(Buffer.from(e)):a.from(new Uint8Array(0))}createEmptyStream(){return a.from(new Uint8Array(0))}}}async post(t){const r=t.headers.get("content-type")||"";if(!x.test(r.split(";")[0]||""))throw i(400,"Invalid content-type");try{const e=[];for await(const o of m(t,{maxFileSize:this.maxFileSize,maxHeaderSize:this.maxHeaderSize}))e.push(o);const s=e.find(o=>o.isFile);if(!s)throw i(400,"No file found in multipart request");const l=t.url;return this.multipartBase.handlePost(s,e,l)}catch(e){throw e instanceof h?i(413,"File size limit exceeded"):e instanceof c?i(400,"Invalid multipart request"):e instanceof u&&e.statusCode?i(e.statusCode,e.message||e.body||"Validation failed"):e}}async delete(t){const r=S(t.url);if(!r)throw i(404,"File not found");try{return this.multipartBase.handleDelete(r)}catch(e){throw e.code==="ENOENT"?i(404,"File not found"):e}}async options(t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||n.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(t){throw i(500,"GET requests should be handled via fetch() method")}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}}export{n as default};
1
+ import{Readable as a}from"node:stream";import{parseMultipartRequest as m,MaxFileSizeExceededError as h,MultipartParseError as c}from"@remix-run/multipart-parser";import{n as i}from"./headers-BAiAKekR.js";import{b as u,B as f}from"./storage-DR7qdwBN.js";import{C as p}from"./base-handler-fetch-yrYrukwL.js";import{p as g}from"./multipart-base-BOzY19lb.js";const x=/^multipart\/.+|application\/x-www-form-urlencoded$/i,S=d=>{let t;try{const r=new URL(d).pathname.split("/").filter(Boolean);t=r[r.length-1]||void 0}catch{return}if(t){try{f.assertSafeId(t)}catch{throw i(400,`Invalid file id: "${t}"`)}return t}};class n extends p{static methods=["delete","download","get","options","post"];multipartBase;maxFileSize;maxHeaderSize;constructor(t){super(t),this.maxFileSize=t.maxFileSize??Math.min(this.storage.maxUploadSize,1024*1024*1024),this.maxHeaderSize=t.maxHeaderSize??64*1024;const r=this;this.multipartBase=new class extends g{get storage(){return r.storage}get maxFileSize(){return r.maxFileSize}get maxHeaderSize(){return r.maxHeaderSize}buildFileUrl(e,s){return r.buildFileUrl({url:e},s)}createStreamFromBytes(e){return e instanceof Uint8Array?a.from(Buffer.from(e)):e instanceof ArrayBuffer?a.from(Buffer.from(e)):a.from(new Uint8Array(0))}createEmptyStream(){return a.from(new Uint8Array(0))}}}async post(t){const r=t.headers.get("content-type")||"";if(!x.test(r.split(";")[0]||""))throw i(400,"Invalid content-type");try{const e=[];for await(const o of m(t,{maxFileSize:this.maxFileSize,maxHeaderSize:this.maxHeaderSize}))e.push(o);const s=e.find(o=>o.isFile);if(!s)throw i(400,"No file found in multipart request");const l=t.url;return this.multipartBase.handlePost(s,e,l)}catch(e){throw e instanceof h?i(413,"File size limit exceeded"):e instanceof c?i(400,"Invalid multipart request"):e instanceof u&&e.statusCode?i(e.statusCode,e.message||e.body||"Validation failed"):e}}async delete(t){const r=S(t.url);if(!r)throw i(404,"File not found");try{return this.multipartBase.handleDelete(r)}catch(e){throw e.code==="ENOENT"?i(404,"File not found"):e}}async options(t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||n.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(t){throw i(500,"GET requests should be handled via fetch() method")}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}}export{n as default};
@@ -0,0 +1 @@
1
+ import{y as s}from"./local-meta-storage-BELb1YwO.js";class o extends s{constructor(r){super(r)}}export{o as default};
@@ -0,0 +1 @@
1
+ import{getStore as u}from"@netlify/blobs";import{a as p}from"./detect-file-type-BA7UBLKA.js";import{B as y,c as h,e as d}from"./storage-DR7qdwBN.js";import{y as w}from"./local-meta-storage-BELb1YwO.js";import f from"./NetlifyBlobFile-DoFhkzaH.js";import{t as m}from"./get-file-status-y3wTtDQs.js";import{t as g}from"./update-size-DuNuLyxj.js";import{i as b}from"./part-match-D-9dGX42.js";import{e as O}from"./has-content-50BsqrWw.js";class C extends y{static name="netlify-blob";checksumTypes=["md5"];get raw(){return this.store}meta;storeName;siteID;token;store;resolvedRetryConfig;constructor(e){super(e),this.storeName=e.storeName||"default",this.siteID=e.siteID||process.env.NETLIFY_SITE_ID,this.token=e.token||process.env.NETLIFY_TOKEN,this.store=u({name:this.storeName,...this.siteID&&{siteID:this.siteID},...this.token&&{token:this.token}});const n={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:r=>{if(r instanceof Error){const i=r.code;if(i==="ECONNRESET"||i==="ETIMEDOUT"||i==="ENOTFOUND"||i==="ECONNREFUSED")return!0}const s=r;if(s.status&&[408,429,500,502,503,504].includes(s.status))return!0},...e.retryConfig};this.resolvedRetryConfig=n;const{metaStorage:t,metaStorageConfig:a}=e;this.meta=t||new w(a),this.isReady=!0}getRetryConfig(){return this.resolvedRetryConfig}async create(e,n){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const r=typeof e.ttl=="string"?h(e.ttl):e.ttl;t.expiredAt=r===void 0?void 0:Date.now()+r}const a=new f(t);a.name=this.namingFunction(a),await this.validate(a);try{const r=await this.getMeta(a.id);if(r.bytesWritten>=0)return r}catch{}return a.bytesWritten=0,a.status=m(a),await this.saveMeta(a),await this.onCreate(a),a})}async write(e,n){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&&g(t,e.size),!b(e,t))throw new Error("File part does not match");const a=await this.lock(e.id);try{if(O(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=[],s=e.body;for await(const o of s)r.push(Buffer.from(o));const i=Buffer.concat(r);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await p(i);o?.mime&&(t.contentType=o.mime)}catch{}await this.runOperation(n,()=>this.store.set(t.name,i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),{metadata:{...t.metadata,contentType:t.contentType}})),t.pathname=t.name,t.url=this.getBlobUrl(t.name),t.bytesWritten=i.length}return t.status=m(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,a)}})}async delete({id:e},n){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.pathname)throw new Error(`File ${e} does not have a valid pathname`);t.status="deleted";try{await this.runOperation(n,()=>this.store.delete(t.pathname))}catch(r){this.logger?.error("Failed to delete blob from Netlify Blob:",r);const s=this.normalizeError(r instanceof Error?r:new Error(String(r)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},n){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);return!t.pathname||t.pathname.length<=0?!1:await this.runOperation(n,()=>this.store.get(t.pathname,{type:"blob"}))!=null}catch{return!1}})}async get({id:e},n){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.pathname||t.pathname.length<=0)throw new Error("File pathname not found");const a=await this.runOperation(n,()=>this.store.get(t.pathname,{type:"blob"}));if(!a)throw new Error("File not found in Netlify Blob");let r;if(typeof a=="string")r=Buffer.from(a,"utf8").buffer;else if(a&&typeof a=="object"&&"arrayBuffer"in a&&typeof a.arrayBuffer=="function")r=await this.runOperation(n,()=>a.arrayBuffer());else throw new Error("Invalid blob type returned from Netlify Blob");const s=Buffer.from(r);let i=null;try{i=await this.store.getMetadata?.(t.pathname)??null}catch{}return{content:s,contentType:i?.contentType||t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:{...t.metadata,...i?.metadata},modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||s.length}})}async copy(e,n,t){return this.instrumentOperation("copy",async()=>{const a=await this.getMeta(e);if(!a.pathname)throw new Error("Source file pathname not found");const r=await this.runOperation(t,()=>this.store.get(a.pathname,{type:"blob"}));if(!r)throw new Error("Source file not found in Netlify Blob");let s=null;try{const l=this.store;l.getMetadata&&a.pathname&&(s=await l.getMetadata(a.pathname))}catch{}let i;if(typeof r=="string")i=Buffer.from(r,"utf8").buffer;else if(r&&typeof r=="object"&&"arrayBuffer"in r){const l=r;i=await this.runOperation(t,()=>l.arrayBuffer())}else throw new Error("Invalid blob type returned from Netlify Blob");const o=Buffer.from(i);await this.runOperation(t,()=>this.store.set(n,o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength),{metadata:s||{contentType:a.contentType,...a.metadata}}));const c={...a,id:n,name:n,pathname:n,url:this.getBlobUrl(n)};return await this.saveMeta(c),c})}async move(e,n,t){return this.instrumentOperation("move",async()=>{const a=await this.copy(e,n,t);return await this.delete({id:e},t),a})}async update({id:e},n,t){return this.instrumentOperation("update",async()=>{const a=await this.getMeta(e),r={...n};if("ttl"in r&&r.ttl!==void 0){const i=r.ttl,o=typeof i=="string"?h(i):i;o!==void 0&&(r.expiredAt=Date.now()+o),delete r.ttl}d(a,r),await this.saveMeta(a);const s={...a,status:"updated"};return await this.onUpdate(s),s})}async list(e=1e3,n){return this.instrumentOperation("list",async()=>{const t=await this.runOperation(n,()=>this.store.list()),a=[];for await(const r of t.blobs){let s=null;try{s=await this.store.getMetadata?.(r.key)??null}catch{}const i=new f({contentType:s?.contentType||"application/octet-stream",metadata:s?.metadata||{},originalName:r.key}),o=r;if(i.createdAt=o.createdAt?.toISOString(),i.id=r.key,i.modifiedAt=o.updatedAt?.toISOString(),i.name=r.key,i.pathname=r.key,i.size=o.size,i.url=this.getBlobUrl(r.key),a.push(i),a.length>=e)break}return a},{limit:e})}internalOnComplete=e=>this.deleteMeta(e.id);getBlobUrl(e){return`/api/blobs/${this.storeName}/${e}`}}export{C as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-BELb1YwO.js";class o extends r{constructor(t){super(t)}}export{o as default};
@@ -1 +1 @@
1
- import{ResponseType as g,Client as U,GraphError as b}from"@microsoft/microsoft-graph-client";import{wrapStorageError as p,ERRORS as m,throwErrorCode as E}from"./ERRORS-BIBxE2oR.js";import{c as D}from"./oauth-refresh-EdGzlcOZ.js";import{B as _}from"./storage-0j5nCAUp.js";import u from"./OneDriveFile-CNNJYI43.js";import A from"./OneDriveMetaStorage-xlHfKwmR.js";import{t as T}from"./get-file-status-y3wTtDQs.js";import{t as N}from"./update-size-DuNuLyxj.js";import{i as S}from"./part-match-D-9dGX42.js";import{e as L}from"./has-content-50BsqrWw.js";const P="https://graph.microsoft.com/.default",M=250*1024*1024,F=16*320*1024,B=1e3,d=o=>{let t=0,i=o.length;for(;t<i&&o[t]==="/";)t+=1;for(;i>t&&o[i-1]==="/";)i-=1;return t===0&&i===o.length?o:o.slice(t,i)},w=(o,t)=>{if(d(o).split("/").filter(Boolean).some(i=>i==="."||i===".."))throw new Error(`OneDrive storage: ${t} must not contain "." or ".." path segments.`)},y=o=>o.split("/").map(t=>encodeURIComponent(t)).join("/"),x=async o=>{const t=[];for await(const i of o)t.push(Buffer.from(i));return Buffer.concat(t)},I=o=>({getAccessToken:()=>Promise.resolve(o)}),$=o=>({getAccessToken:async()=>o()}),O=o=>D({buildBody:()=>new URLSearchParams({client_id:o.clientId,client_secret:o.clientSecret,grant_type:"client_credentials",scope:P}),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(o.tenantId)}/oauth2/v2.0/token`}),v=o=>D({buildBody:()=>new URLSearchParams({client_id:o.clientId,grant_type:"refresh_token",refresh_token:o.refreshToken,scope:P,...o.clientSecret&&{client_secret:o.clientSecret}}),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(o.tenantId??"common")}/oauth2/v2.0/token`}),V=o=>({getAccessToken:()=>o.getAccessToken()}),C=o=>{if(o.client)return o.client;const t=o.accessToken!==void 0,i=o.clientCredentials!==void 0,e=o.oauth!==void 0;if([t,i,e].filter(Boolean).length>1)throw new Error("OneDrive storage: pass exactly one of `accessToken`, `clientCredentials`, or `oauth`.");let n;if(o.accessToken!==void 0?n=typeof o.accessToken=="function"?$(o.accessToken):I(o.accessToken):o.clientCredentials?n=O(o.clientCredentials):o.oauth&&(n=v({clientId:o.oauth.clientId,refreshToken:o.oauth.refreshToken,...o.oauth.clientSecret&&{clientSecret:o.oauth.clientSecret},...o.oauth.tenantId&&{tenantId:o.oauth.tenantId}})),!n){const a=process.env.ONEDRIVE_ACCESS_TOKEN;if(a)n=I(a);else{const r=process.env.ONEDRIVE_CLIENT_ID,s=process.env.ONEDRIVE_CLIENT_SECRET,c=process.env.ONEDRIVE_TENANT_ID,h=process.env.ONEDRIVE_REFRESH_TOKEN;h&&r?n=v({clientId:r,refreshToken:h,...s&&{clientSecret:s},...c&&{tenantId:c}}):r&&s&&c&&(n=O({clientId:r,clientSecret:s,tenantId:c}))}}if(!n)throw new Error("OneDrive storage: missing auth. Pass `client`, `accessToken`, `clientCredentials`, or `oauth`. Env fallbacks: ONEDRIVE_ACCESS_TOKEN; or ONEDRIVE_REFRESH_TOKEN + ONEDRIVE_CLIENT_ID (+ optional ONEDRIVE_CLIENT_SECRET, ONEDRIVE_TENANT_ID); or ONEDRIVE_CLIENT_ID + ONEDRIVE_CLIENT_SECRET + ONEDRIVE_TENANT_ID.");return U.initWithMiddleware({authProvider:V(n)})},z=o=>{if(o instanceof b)return o.statusCode===404||o.code==="itemNotFound";if(o&&typeof o=="object"){const t=o;return t.statusCode===404||t.status===404||t.code==="itemNotFound"}return!1};class Z extends _{static name="onedrive";checksumTypes=[];meta;basePath;client;copyTimeoutMs;publicByDefault;rootFolderPath;constructor(t){if(super(t),[t.driveId,t.siteId,t.userId].filter(i=>i!==void 0).length>1)throw new Error("OneDrive storage: pass at most one of `driveId`, `siteId`, or `userId`.");if(t.driveId)this.basePath=`/drives/${encodeURIComponent(t.driveId)}`;else if(t.siteId)this.basePath=`/sites/${encodeURIComponent(t.siteId)}/drive`;else if(t.userId)this.basePath=`/users/${encodeURIComponent(t.userId)}/drive`;else{if(t.clientCredentials)throw new Error("OneDrive storage: `clientCredentials` (app-only) auth requires `driveId`, `siteId`, or `userId`.");this.basePath="/me/drive"}w(t.rootFolderPath??"","rootFolderPath"),this.rootFolderPath=d(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.copyTimeoutMs=t.copyTimeoutMs??6e4,this.client=C(t),this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,i){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),await this.validate(e);try{const n=await this.getMeta(e.id);if(n.bytesWritten>=0)return n}catch{}return e.bytesWritten=0,e.status=T(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,i){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&&N(e,t.size),!S(t,e))throw new Error("File part does not match");const n=await this.lock(t.id);try{if(L(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await x(t.body),r=e.name||e.id,s=a.byteLength<=M?await this.uploadSimple(r,a,e.contentType,i):await this.uploadSession(r,a,e.contentType,i);e.bytesWritten=a.length,e.size=a.length,e.driveItemId=s.id,e.webUrl=s.webUrl,e.eTag=s.eTag,e.ETag=s.eTag}return e.status=T(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,n)}})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const n=e?.name??t;try{await this.runOperation(i,()=>this.client.api(this.itemApiPath(n)).delete())}catch(a){if(!z(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,status:"deleted"})})}async get({id:t},i){return this.instrumentOperation("get",async()=>{let e,n=t;try{e=await this.checkIfExpired(await this.getMeta(t)),n=e.name??t}catch{}const a=await this.runOperation(i,()=>this.client.api(this.itemApiPath(n)).get()),r=await this.runOperation(i,()=>this.client.api(this.itemActionPath(n,"content")).responseType(g.ARRAYBUFFER).get()),s=Buffer.from(r);return{content:s,contentType:e?.contentType??a.file?.mimeType??"application/octet-stream",ETag:e?.ETag??a.eTag,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??a.lastModifiedDateTime,name:e?.name??a.name,originalName:e?.originalName??a.name,size:e?.size??a.size??s.length}})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{const n=this.parentReferencePath(i),a={name:R(i),parentReference:{path:n}},r=await this.runOperation(e,()=>this.client.api(this.itemActionPath(t,"copy")).responseType(g.RAW).post(a));if(r.status!==202){const f=await r.text().catch(()=>"");throw p(new Error(f||r.statusText),{adapter:"OneDrive",operation:"copy",status:r.status})}const s=r.headers.get("Location");if(!s)throw p(new Error("response missing Location monitor URL"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});const c=await this.pollCopyMonitor(s,e),h=new u({contentType:"application/octet-stream",metadata:{},originalName:i});return h.id=i,h.name=i,h.driveItemId=c,h})}async move(t,i,e){return this.instrumentOperation("move",async()=>{const n=this.parentReferencePath(i),a=R(i),r=await this.runOperation(e,()=>this.client.api(this.itemApiPath(t)).patch({name:a,parentReference:{path:n}})),s=new u({contentType:"application/octet-stream",metadata:{},originalName:i});s.id=i,s.name=i,s.driveItemId=r.id,s.webUrl=r.webUrl,s.eTag=r.eTag,s.ETag=r.eTag;try{await this.deleteMeta(t)}catch{}return s})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>{const e=[];let n=`${this.folderListChildrenPath()}?$top=${Math.min(t,1e3)}`;for(;n&&e.length<t;){const a=await this.runOperation(i,()=>this.client.api(n).get());for(const r of a.value){if(!r.file)continue;const s=this.itemPathToKey(r);if(!s)continue;const c=new u({contentType:r.file.mimeType??"application/octet-stream",metadata:{},originalName:r.name});if(c.id=s,c.name=s,c.driveItemId=r.id,c.webUrl=r.webUrl,c.eTag=r.eTag,c.ETag=r.eTag,c.size=r.size??0,c.modifiedAt=r.lastModifiedDateTime,e.push(c),e.length>=t)break}n=a["@odata.nextLink"]??null}return e},{limit:t})}async getReadUrl(t,i){if(i?.responseContentDisposition||i?.responseContentType)return E(m.METHOD_NOT_ALLOWED,"OneDrive: `responseContentDisposition` / `responseContentType` are not supported — Graph download URLs have no overrides.");if(this.publicByDefault){const n=(await this.client.api(this.itemActionPath(t,"createLink")).post({scope:"anonymous",type:"view"})).link?.webUrl;if(!n)throw new Error("OneDrive: createLink response missing webUrl");return n}const e=(await this.client.api(this.itemApiPath(t)).select("@microsoft.graph.downloadUrl").get())["@microsoft.graph.downloadUrl"];if(!e)throw new Error("OneDrive: item has no `@microsoft.graph.downloadUrl` — it may be a folder or have no content.");return e}async getUploadUrl(t,i){if(i?.contentLength!==void 0)return E(m.BAD_REQUEST,"OneDrive: `contentLength` is not supported for upload URLs. A Graph upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");const e=await this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...i?.contentType&&{file:{mimeType:i.contentType}}}});if(!e.uploadUrl)throw p(new Error("createUploadSession response missing uploadUrl"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"getUploadUrl"});return e.uploadUrl}keyParts(t){w(t,"key");const i=d(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),i&&e.push(i),e}itemApiPath(t){const i=this.keyParts(t);return i.length===0?`${this.basePath}/root`:`${this.basePath}/root:/${y(i.join("/"))}`}itemActionPath(t,i){const e=this.keyParts(t);return e.length===0?`${this.basePath}/root/${i}`:`${this.basePath}/root:/${y(e.join("/"))}:/${i}`}folderListChildrenPath(){return this.itemActionPath("","children")}parentReferencePath(t){w(t,"key");const i=d(t),e=[];this.rootFolderPath&&e.push(this.rootFolderPath);const n=i.lastIndexOf("/");if(n!==-1){const a=i.slice(0,n);a&&e.push(a)}return e.length===0?"/drive/root:":`/drive/root:/${y(e.join("/"))}`}itemPathToKey(t){const i=t.parentReference?.path??"",e="/root:",n=i.indexOf(e);let a=n===-1?"":i.slice(n+e.length);a=d(decodeURIComponent(a));const r=this.rootFolderPath&&a.startsWith(this.rootFolderPath)?a.slice(this.rootFolderPath.length):a,s=d(r);return s?`${s}/${t.name}`:t.name}async uploadSimple(t,i,e,n){return await this.runOperation(n,()=>this.client.api(`${this.itemActionPath(t,"content")}?@microsoft.graph.conflictBehavior=replace`).header("Content-Type",e??"application/octet-stream").put(i))}async uploadSession(t,i,e,n){const a=await this.runOperation(n,()=>this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...e&&{file:{mimeType:e}}}})),r=i.byteLength;let s=0,c;for(;s<r;){const h=Math.min(s+F,r),f=i.subarray(s,h),l=await this.runOperation(n,()=>fetch(a.uploadUrl,{body:new Uint8Array(f),headers:{"Content-Length":String(f.byteLength),"Content-Range":`bytes ${s}-${h-1}/${r}`},method:"PUT"}));if(l.status===200||l.status===201)c=await l.json();else if(l.status!==202){const k=await l.text().catch(()=>"");throw p(new Error(k||l.statusText),{adapter:"OneDrive",operation:"upload-session chunk",status:l.status})}s=h}if(!c)throw p(new Error("upload-session terminated without a final DriveItem response"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"write"});return c}async pollCopyMonitor(t,i){const e=Date.now()+this.copyTimeoutMs;for(;;){const n=await this.runOperation(i,()=>fetch(t));if(!n.ok)throw p(new Error(n.statusText),{adapter:"OneDrive",operation:"copy monitor",status:n.status});const a=await n.json();if(a.status==="completed")return a.resourceId;if(a.status==="failed")throw p(new Error(a.error?.message??"unknown error"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});if(Date.now()>=e)throw new Error(`OneDrive: copy timed out after ${this.copyTimeoutMs}ms (status: ${a.status??"unknown"})`);await new Promise(r=>{setTimeout(r,B)})}}internalOnComplete=t=>this.deleteMeta(t.id)}const R=o=>{const t=d(o),i=t.lastIndexOf("/");return i===-1?t:t.slice(i+1)},tt=o=>C(o);export{tt as buildGraphClient,Z as default};
1
+ import{ResponseType as g,Client as U,GraphError as b}from"@microsoft/microsoft-graph-client";import{wrapStorageError as p,ERRORS as m,throwErrorCode as E}from"./ERRORS-BIBxE2oR.js";import{c as D}from"./oauth-refresh-EdGzlcOZ.js";import{B as _}from"./storage-DR7qdwBN.js";import u from"./OneDriveFile-CNNJYI43.js";import A from"./OneDriveMetaStorage-B0gLF7Io.js";import{t as T}from"./get-file-status-y3wTtDQs.js";import{t as N}from"./update-size-DuNuLyxj.js";import{i as S}from"./part-match-D-9dGX42.js";import{e as L}from"./has-content-50BsqrWw.js";const P="https://graph.microsoft.com/.default",M=250*1024*1024,F=16*320*1024,B=1e3,d=o=>{let t=0,i=o.length;for(;t<i&&o[t]==="/";)t+=1;for(;i>t&&o[i-1]==="/";)i-=1;return t===0&&i===o.length?o:o.slice(t,i)},w=(o,t)=>{if(d(o).split("/").filter(Boolean).some(i=>i==="."||i===".."))throw new Error(`OneDrive storage: ${t} must not contain "." or ".." path segments.`)},y=o=>o.split("/").map(t=>encodeURIComponent(t)).join("/"),x=async o=>{const t=[];for await(const i of o)t.push(Buffer.from(i));return Buffer.concat(t)},I=o=>({getAccessToken:()=>Promise.resolve(o)}),$=o=>({getAccessToken:async()=>o()}),O=o=>D({buildBody:()=>new URLSearchParams({client_id:o.clientId,client_secret:o.clientSecret,grant_type:"client_credentials",scope:P}),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(o.tenantId)}/oauth2/v2.0/token`}),v=o=>D({buildBody:()=>new URLSearchParams({client_id:o.clientId,grant_type:"refresh_token",refresh_token:o.refreshToken,scope:P,...o.clientSecret&&{client_secret:o.clientSecret}}),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(o.tenantId??"common")}/oauth2/v2.0/token`}),V=o=>({getAccessToken:()=>o.getAccessToken()}),C=o=>{if(o.client)return o.client;const t=o.accessToken!==void 0,i=o.clientCredentials!==void 0,e=o.oauth!==void 0;if([t,i,e].filter(Boolean).length>1)throw new Error("OneDrive storage: pass exactly one of `accessToken`, `clientCredentials`, or `oauth`.");let n;if(o.accessToken!==void 0?n=typeof o.accessToken=="function"?$(o.accessToken):I(o.accessToken):o.clientCredentials?n=O(o.clientCredentials):o.oauth&&(n=v({clientId:o.oauth.clientId,refreshToken:o.oauth.refreshToken,...o.oauth.clientSecret&&{clientSecret:o.oauth.clientSecret},...o.oauth.tenantId&&{tenantId:o.oauth.tenantId}})),!n){const a=process.env.ONEDRIVE_ACCESS_TOKEN;if(a)n=I(a);else{const r=process.env.ONEDRIVE_CLIENT_ID,s=process.env.ONEDRIVE_CLIENT_SECRET,c=process.env.ONEDRIVE_TENANT_ID,h=process.env.ONEDRIVE_REFRESH_TOKEN;h&&r?n=v({clientId:r,refreshToken:h,...s&&{clientSecret:s},...c&&{tenantId:c}}):r&&s&&c&&(n=O({clientId:r,clientSecret:s,tenantId:c}))}}if(!n)throw new Error("OneDrive storage: missing auth. Pass `client`, `accessToken`, `clientCredentials`, or `oauth`. Env fallbacks: ONEDRIVE_ACCESS_TOKEN; or ONEDRIVE_REFRESH_TOKEN + ONEDRIVE_CLIENT_ID (+ optional ONEDRIVE_CLIENT_SECRET, ONEDRIVE_TENANT_ID); or ONEDRIVE_CLIENT_ID + ONEDRIVE_CLIENT_SECRET + ONEDRIVE_TENANT_ID.");return U.initWithMiddleware({authProvider:V(n)})},z=o=>{if(o instanceof b)return o.statusCode===404||o.code==="itemNotFound";if(o&&typeof o=="object"){const t=o;return t.statusCode===404||t.status===404||t.code==="itemNotFound"}return!1};class Z extends _{static name="onedrive";checksumTypes=[];meta;basePath;client;copyTimeoutMs;publicByDefault;rootFolderPath;constructor(t){if(super(t),[t.driveId,t.siteId,t.userId].filter(i=>i!==void 0).length>1)throw new Error("OneDrive storage: pass at most one of `driveId`, `siteId`, or `userId`.");if(t.driveId)this.basePath=`/drives/${encodeURIComponent(t.driveId)}`;else if(t.siteId)this.basePath=`/sites/${encodeURIComponent(t.siteId)}/drive`;else if(t.userId)this.basePath=`/users/${encodeURIComponent(t.userId)}/drive`;else{if(t.clientCredentials)throw new Error("OneDrive storage: `clientCredentials` (app-only) auth requires `driveId`, `siteId`, or `userId`.");this.basePath="/me/drive"}w(t.rootFolderPath??"","rootFolderPath"),this.rootFolderPath=d(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.copyTimeoutMs=t.copyTimeoutMs??6e4,this.client=C(t),this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,i){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),await this.validate(e);try{const n=await this.getMeta(e.id);if(n.bytesWritten>=0)return n}catch{}return e.bytesWritten=0,e.status=T(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,i){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&&N(e,t.size),!S(t,e))throw new Error("File part does not match");const n=await this.lock(t.id);try{if(L(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await x(t.body),r=e.name||e.id,s=a.byteLength<=M?await this.uploadSimple(r,a,e.contentType,i):await this.uploadSession(r,a,e.contentType,i);e.bytesWritten=a.length,e.size=a.length,e.driveItemId=s.id,e.webUrl=s.webUrl,e.eTag=s.eTag,e.ETag=s.eTag}return e.status=T(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,n)}})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const n=e?.name??t;try{await this.runOperation(i,()=>this.client.api(this.itemApiPath(n)).delete())}catch(a){if(!z(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,status:"deleted"})})}async get({id:t},i){return this.instrumentOperation("get",async()=>{let e,n=t;try{e=await this.checkIfExpired(await this.getMeta(t)),n=e.name??t}catch{}const a=await this.runOperation(i,()=>this.client.api(this.itemApiPath(n)).get()),r=await this.runOperation(i,()=>this.client.api(this.itemActionPath(n,"content")).responseType(g.ARRAYBUFFER).get()),s=Buffer.from(r);return{content:s,contentType:e?.contentType??a.file?.mimeType??"application/octet-stream",ETag:e?.ETag??a.eTag,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??a.lastModifiedDateTime,name:e?.name??a.name,originalName:e?.originalName??a.name,size:e?.size??a.size??s.length}})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{const n=this.parentReferencePath(i),a={name:R(i),parentReference:{path:n}},r=await this.runOperation(e,()=>this.client.api(this.itemActionPath(t,"copy")).responseType(g.RAW).post(a));if(r.status!==202){const f=await r.text().catch(()=>"");throw p(new Error(f||r.statusText),{adapter:"OneDrive",operation:"copy",status:r.status})}const s=r.headers.get("Location");if(!s)throw p(new Error("response missing Location monitor URL"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});const c=await this.pollCopyMonitor(s,e),h=new u({contentType:"application/octet-stream",metadata:{},originalName:i});return h.id=i,h.name=i,h.driveItemId=c,h})}async move(t,i,e){return this.instrumentOperation("move",async()=>{const n=this.parentReferencePath(i),a=R(i),r=await this.runOperation(e,()=>this.client.api(this.itemApiPath(t)).patch({name:a,parentReference:{path:n}})),s=new u({contentType:"application/octet-stream",metadata:{},originalName:i});s.id=i,s.name=i,s.driveItemId=r.id,s.webUrl=r.webUrl,s.eTag=r.eTag,s.ETag=r.eTag;try{await this.deleteMeta(t)}catch{}return s})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>{const e=[];let n=`${this.folderListChildrenPath()}?$top=${Math.min(t,1e3)}`;for(;n&&e.length<t;){const a=await this.runOperation(i,()=>this.client.api(n).get());for(const r of a.value){if(!r.file)continue;const s=this.itemPathToKey(r);if(!s)continue;const c=new u({contentType:r.file.mimeType??"application/octet-stream",metadata:{},originalName:r.name});if(c.id=s,c.name=s,c.driveItemId=r.id,c.webUrl=r.webUrl,c.eTag=r.eTag,c.ETag=r.eTag,c.size=r.size??0,c.modifiedAt=r.lastModifiedDateTime,e.push(c),e.length>=t)break}n=a["@odata.nextLink"]??null}return e},{limit:t})}async getReadUrl(t,i){if(i?.responseContentDisposition||i?.responseContentType)return E(m.METHOD_NOT_ALLOWED,"OneDrive: `responseContentDisposition` / `responseContentType` are not supported — Graph download URLs have no overrides.");if(this.publicByDefault){const n=(await this.client.api(this.itemActionPath(t,"createLink")).post({scope:"anonymous",type:"view"})).link?.webUrl;if(!n)throw new Error("OneDrive: createLink response missing webUrl");return n}const e=(await this.client.api(this.itemApiPath(t)).select("@microsoft.graph.downloadUrl").get())["@microsoft.graph.downloadUrl"];if(!e)throw new Error("OneDrive: item has no `@microsoft.graph.downloadUrl` — it may be a folder or have no content.");return e}async getUploadUrl(t,i){if(i?.contentLength!==void 0)return E(m.BAD_REQUEST,"OneDrive: `contentLength` is not supported for upload URLs. A Graph upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");const e=await this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...i?.contentType&&{file:{mimeType:i.contentType}}}});if(!e.uploadUrl)throw p(new Error("createUploadSession response missing uploadUrl"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"getUploadUrl"});return e.uploadUrl}keyParts(t){w(t,"key");const i=d(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),i&&e.push(i),e}itemApiPath(t){const i=this.keyParts(t);return i.length===0?`${this.basePath}/root`:`${this.basePath}/root:/${y(i.join("/"))}`}itemActionPath(t,i){const e=this.keyParts(t);return e.length===0?`${this.basePath}/root/${i}`:`${this.basePath}/root:/${y(e.join("/"))}:/${i}`}folderListChildrenPath(){return this.itemActionPath("","children")}parentReferencePath(t){w(t,"key");const i=d(t),e=[];this.rootFolderPath&&e.push(this.rootFolderPath);const n=i.lastIndexOf("/");if(n!==-1){const a=i.slice(0,n);a&&e.push(a)}return e.length===0?"/drive/root:":`/drive/root:/${y(e.join("/"))}`}itemPathToKey(t){const i=t.parentReference?.path??"",e="/root:",n=i.indexOf(e);let a=n===-1?"":i.slice(n+e.length);a=d(decodeURIComponent(a));const r=this.rootFolderPath&&a.startsWith(this.rootFolderPath)?a.slice(this.rootFolderPath.length):a,s=d(r);return s?`${s}/${t.name}`:t.name}async uploadSimple(t,i,e,n){return await this.runOperation(n,()=>this.client.api(`${this.itemActionPath(t,"content")}?@microsoft.graph.conflictBehavior=replace`).header("Content-Type",e??"application/octet-stream").put(i))}async uploadSession(t,i,e,n){const a=await this.runOperation(n,()=>this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...e&&{file:{mimeType:e}}}})),r=i.byteLength;let s=0,c;for(;s<r;){const h=Math.min(s+F,r),f=i.subarray(s,h),l=await this.runOperation(n,()=>fetch(a.uploadUrl,{body:new Uint8Array(f),headers:{"Content-Length":String(f.byteLength),"Content-Range":`bytes ${s}-${h-1}/${r}`},method:"PUT"}));if(l.status===200||l.status===201)c=await l.json();else if(l.status!==202){const k=await l.text().catch(()=>"");throw p(new Error(k||l.statusText),{adapter:"OneDrive",operation:"upload-session chunk",status:l.status})}s=h}if(!c)throw p(new Error("upload-session terminated without a final DriveItem response"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"write"});return c}async pollCopyMonitor(t,i){const e=Date.now()+this.copyTimeoutMs;for(;;){const n=await this.runOperation(i,()=>fetch(t));if(!n.ok)throw p(new Error(n.statusText),{adapter:"OneDrive",operation:"copy monitor",status:n.status});const a=await n.json();if(a.status==="completed")return a.resourceId;if(a.status==="failed")throw p(new Error(a.error?.message??"unknown error"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});if(Date.now()>=e)throw new Error(`OneDrive: copy timed out after ${this.copyTimeoutMs}ms (status: ${a.status??"unknown"})`);await new Promise(r=>{setTimeout(r,B)})}}internalOnComplete=t=>this.deleteMeta(t.id)}const R=o=>{const t=d(o),i=t.lastIndexOf("/");return i===-1?t:t.slice(i+1)},tt=o=>C(o);export{tt as buildGraphClient,Z as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-BELb1YwO.js";class e extends r{constructor(o){super(o)}}export{e as default};
@@ -1 +1 @@
1
- import g,{ClientResponseError as O}from"pocketbase";import{throwErrorCode as p,ERRORS as m}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-0j5nCAUp.js";import u from"./PocketBaseFile-DpJpxl3e.js";import A from"./PocketBaseMetaStorage-DnrxOQhO.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as E}from"./update-size-DuNuLyxj.js";import{i as T}from"./part-match-D-9dGX42.js";import{e as B}from"./has-content-50BsqrWw.js";const N=async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},d=o=>(o instanceof O||!!o&&typeof o=="object")&&o.status===404,f=(o,t,a,e)=>{const i=o.files.getURL??o.files.getUrl;return i?i(t,a,e):p(m.METHOD_NOT_ALLOWED,"PocketBase: client has no files.getURL()")};class P extends k{static name="pocketbase";checksumTypes=[];meta;client;collectionName;defaultUrlExpiresIn;fileField;keyField;publicBaseUrl;ensureAuth;constructor(t){if(super(t),!t.collection)throw new Error("PocketBase storage: `collection` is required.");if(this.collectionName=t.collection,this.keyField=t.keyField??"key",this.fileField=t.fileField??"file",this.publicBaseUrl=t.publicBaseUrl,this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??3600,t.client)this.client=t.client,this.ensureAuth=async()=>{};else{const a=t.url??process.env.POCKETBASE_URL;if(!a)throw new Error("PocketBase storage: `url` is required (or set POCKETBASE_URL).");const e=new g(a);this.client=e;const i=t.authToken??process.env.POCKETBASE_AUTH_TOKEN,n=t.adminEmail??process.env.POCKETBASE_ADMIN_EMAIL,s=t.adminPassword??process.env.POCKETBASE_ADMIN_PASSWORD;i?(e.authStore.save(i,null),this.ensureAuth=async()=>{}):n&&s?this.ensureAuth=async()=>{e.authStore.isValid||await e.collection("_superusers").authWithPassword(n,s)}:this.ensureAuth=async()=>{}}this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),e.bucket=this.collectionName,e.path=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&&E(e,t.size),!T(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(B(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await N(t.body),s=e.path??e.name;await this.putRecord(s,n,e.contentType,a),e.bytesWritten=n.length,e.size=n.length,e.path=s}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?.path??e?.name??t;await this.ensureAuth();try{const n=await this.findRecord(i,a);await this.runOperation(a,()=>this.client.collection(this.collectionName).delete(n.id))}catch(n){if(!d(n))throw n}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.collectionName,id:t,name:t,path:i,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}await this.ensureAuth();try{return await this.findRecord(e,a),!0}catch(i){if(d(i))return!1;throw i}})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,i;try{i=await this.checkIfExpired(await this.getMeta(t)),e=i.path??i.name??t}catch{}await this.ensureAuth();const n=await this.findRecord(e,a),s=String(n[this.fileField]??""),r=f(this.client,n,s),c=await this.runOperation(a,()=>fetch(r));if(!c.ok)return p(m.FILE_NOT_FOUND,`PocketBase: object not found at "${e}"`);const l=Buffer.from(await c.arrayBuffer());return{content:l,contentType:i?.contentType??c.headers.get("content-type")??"application/octet-stream",ETag:i?.ETag,expiredAt:i?.expiredAt,id:t,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt,name:i?.name??e,originalName:i?.originalName??e,size:i?.size??l.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.ensureAuth();const n=await this.findRecord(i,e),s=String(n[this.fileField]??""),r=f(this.client,n,s),c=await this.runOperation(e,()=>fetch(r));if(!c.ok)return p(m.FILE_NOT_FOUND,`PocketBase: object not found at "${i}"`);const l=Buffer.from(await c.arrayBuffer()),w=c.headers.get("content-type")??"application/octet-stream";await this.putRecord(a,l,w,e);const h=new u({contentType:w,metadata:{},originalName:a});return h.id=a,h.name=a,h.path=a,h.bucket=this.collectionName,h.size=l.length,h})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=await this.copy(t,a,e),n=(await this.getMetaSafe(t))?.path??t;await this.ensureAuth();try{const s=await this.findRecord(n,e);await this.runOperation(e,()=>this.client.collection(this.collectionName).delete(s.id))}catch(s){if(!d(s))throw s}try{await this.deleteMeta(t)}catch{}return i})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{await this.ensureAuth();const{items:e}=await this.runOperation(a,()=>this.client.collection(this.collectionName).getList(1,t));return(e??[]).map(i=>{const n=String(i[this.keyField]??i.id),s=String(i[this.fileField]??""),r=new u({contentType:"application/octet-stream",metadata:{},originalName:n});return r.id=n,r.name=n,r.path=n,r.bucket=this.collectionName,r.ETag=s||void 0,r.createdAt=typeof i.created=="string"?i.created:void 0,r.modifiedAt=typeof i.updated=="string"?i.updated:void 0,r})},{limit:t})}async getReadUrl(t,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return p(m.METHOD_NOT_ALLOWED,"PocketBase: `responseContentDisposition`/`responseContentType` are not supported — PocketBase file URLs have no Content-Disposition/Content-Type override.");if(this.publicBaseUrl)return`${this.publicBaseUrl.replace(/\/+$/,"")}/${t}`;await this.ensureAuth();let e=t;const i=await this.getMetaSafe(t);i?.path&&(e=i.path);const n=await this.findRecord(e),s=String(n[this.fileField]??""),r=await this.client.files.getToken();return f(this.client,n,s,{token:r})}async findRecord(t,a){const e=this.client.filter(`${this.keyField} = {:k}`,{k:t});return this.runOperation(a,()=>this.client.collection(this.collectionName).getFirstListItem(e))}async putRecord(t,a,e,i){await this.ensureAuth();const n=new FormData;n.append(this.keyField,t),n.append(this.fileField,new Blob([new Uint8Array(a)],{type:e}),t);try{const s=await this.findRecord(t,i);await this.runOperation(i,()=>this.client.collection(this.collectionName).update(s.id,n))}catch(s){if(!d(s))throw s;await this.runOperation(i,()=>this.client.collection(this.collectionName).create(n))}}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=t=>this.deleteMeta(t.id)}export{P as default};
1
+ import g,{ClientResponseError as O}from"pocketbase";import{throwErrorCode as p,ERRORS as m}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-DR7qdwBN.js";import u from"./PocketBaseFile-DpJpxl3e.js";import A from"./PocketBaseMetaStorage-Cm3v8g1-.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as E}from"./update-size-DuNuLyxj.js";import{i as T}from"./part-match-D-9dGX42.js";import{e as B}from"./has-content-50BsqrWw.js";const N=async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},d=o=>(o instanceof O||!!o&&typeof o=="object")&&o.status===404,f=(o,t,a,e)=>{const i=o.files.getURL??o.files.getUrl;return i?i(t,a,e):p(m.METHOD_NOT_ALLOWED,"PocketBase: client has no files.getURL()")};class P extends k{static name="pocketbase";checksumTypes=[];meta;client;collectionName;defaultUrlExpiresIn;fileField;keyField;publicBaseUrl;ensureAuth;constructor(t){if(super(t),!t.collection)throw new Error("PocketBase storage: `collection` is required.");if(this.collectionName=t.collection,this.keyField=t.keyField??"key",this.fileField=t.fileField??"file",this.publicBaseUrl=t.publicBaseUrl,this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??3600,t.client)this.client=t.client,this.ensureAuth=async()=>{};else{const a=t.url??process.env.POCKETBASE_URL;if(!a)throw new Error("PocketBase storage: `url` is required (or set POCKETBASE_URL).");const e=new g(a);this.client=e;const i=t.authToken??process.env.POCKETBASE_AUTH_TOKEN,n=t.adminEmail??process.env.POCKETBASE_ADMIN_EMAIL,s=t.adminPassword??process.env.POCKETBASE_ADMIN_PASSWORD;i?(e.authStore.save(i,null),this.ensureAuth=async()=>{}):n&&s?this.ensureAuth=async()=>{e.authStore.isValid||await e.collection("_superusers").authWithPassword(n,s)}:this.ensureAuth=async()=>{}}this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),e.bucket=this.collectionName,e.path=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&&E(e,t.size),!T(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(B(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await N(t.body),s=e.path??e.name;await this.putRecord(s,n,e.contentType,a),e.bytesWritten=n.length,e.size=n.length,e.path=s}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?.path??e?.name??t;await this.ensureAuth();try{const n=await this.findRecord(i,a);await this.runOperation(a,()=>this.client.collection(this.collectionName).delete(n.id))}catch(n){if(!d(n))throw n}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.collectionName,id:t,name:t,path:i,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}await this.ensureAuth();try{return await this.findRecord(e,a),!0}catch(i){if(d(i))return!1;throw i}})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,i;try{i=await this.checkIfExpired(await this.getMeta(t)),e=i.path??i.name??t}catch{}await this.ensureAuth();const n=await this.findRecord(e,a),s=String(n[this.fileField]??""),r=f(this.client,n,s),c=await this.runOperation(a,()=>fetch(r));if(!c.ok)return p(m.FILE_NOT_FOUND,`PocketBase: object not found at "${e}"`);const l=Buffer.from(await c.arrayBuffer());return{content:l,contentType:i?.contentType??c.headers.get("content-type")??"application/octet-stream",ETag:i?.ETag,expiredAt:i?.expiredAt,id:t,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt,name:i?.name??e,originalName:i?.originalName??e,size:i?.size??l.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.ensureAuth();const n=await this.findRecord(i,e),s=String(n[this.fileField]??""),r=f(this.client,n,s),c=await this.runOperation(e,()=>fetch(r));if(!c.ok)return p(m.FILE_NOT_FOUND,`PocketBase: object not found at "${i}"`);const l=Buffer.from(await c.arrayBuffer()),w=c.headers.get("content-type")??"application/octet-stream";await this.putRecord(a,l,w,e);const h=new u({contentType:w,metadata:{},originalName:a});return h.id=a,h.name=a,h.path=a,h.bucket=this.collectionName,h.size=l.length,h})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=await this.copy(t,a,e),n=(await this.getMetaSafe(t))?.path??t;await this.ensureAuth();try{const s=await this.findRecord(n,e);await this.runOperation(e,()=>this.client.collection(this.collectionName).delete(s.id))}catch(s){if(!d(s))throw s}try{await this.deleteMeta(t)}catch{}return i})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{await this.ensureAuth();const{items:e}=await this.runOperation(a,()=>this.client.collection(this.collectionName).getList(1,t));return(e??[]).map(i=>{const n=String(i[this.keyField]??i.id),s=String(i[this.fileField]??""),r=new u({contentType:"application/octet-stream",metadata:{},originalName:n});return r.id=n,r.name=n,r.path=n,r.bucket=this.collectionName,r.ETag=s||void 0,r.createdAt=typeof i.created=="string"?i.created:void 0,r.modifiedAt=typeof i.updated=="string"?i.updated:void 0,r})},{limit:t})}async getReadUrl(t,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return p(m.METHOD_NOT_ALLOWED,"PocketBase: `responseContentDisposition`/`responseContentType` are not supported — PocketBase file URLs have no Content-Disposition/Content-Type override.");if(this.publicBaseUrl)return`${this.publicBaseUrl.replace(/\/+$/,"")}/${t}`;await this.ensureAuth();let e=t;const i=await this.getMetaSafe(t);i?.path&&(e=i.path);const n=await this.findRecord(e),s=String(n[this.fileField]??""),r=await this.client.files.getToken();return f(this.client,n,s,{token:r})}async findRecord(t,a){const e=this.client.filter(`${this.keyField} = {:k}`,{k:t});return this.runOperation(a,()=>this.client.collection(this.collectionName).getFirstListItem(e))}async putRecord(t,a,e,i){await this.ensureAuth();const n=new FormData;n.append(this.keyField,t),n.append(this.fileField,new Blob([new Uint8Array(a)],{type:e}),t);try{const s=await this.findRecord(t,i);await this.runOperation(i,()=>this.client.collection(this.collectionName).update(s.id,n))}catch(s){if(!d(s))throw s;await this.runOperation(i,()=>this.client.collection(this.collectionName).create(n))}}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=t=>this.deleteMeta(t.id)}export{P as default};