@visulima/storage 1.0.0 → 1.0.1

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 (109) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/handler/http/fetch/index.js +1 -1
  3. package/dist/handler/http/hono/index.js +1 -1
  4. package/dist/handler/http/nextjs/index.js +1 -1
  5. package/dist/handler/http/node/index.js +1 -1
  6. package/dist/handler/http/solid-start/index.js +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/packem_shared/{AbstractBaseStorage-Ba7cLu-t.js → AbstractBaseStorage-CiPEMcuo.js} +1 -1
  9. package/dist/packem_shared/{AwsLightStorage-DTBVxHXO.js → AwsLightStorage-BK-WPL0h.js} +1 -1
  10. package/dist/packem_shared/{AzureStorage-BFsD4qbF.js → AzureStorage-1UvDIQZd.js} +1 -1
  11. package/dist/packem_shared/BoxMetaStorage-BSn6Qfnf.js +1 -0
  12. package/dist/packem_shared/{BoxStorage-B_t-OVzf.js → BoxStorage-DbGqBLux.js} +1 -1
  13. package/dist/packem_shared/BunS3MetaStorage-BSn6Qfnf.js +1 -0
  14. package/dist/packem_shared/{BunS3Storage-CB_pZWlV.js → BunS3Storage-DNvimm9e.js} +1 -1
  15. package/dist/packem_shared/BunnyMetaStorage-BSn6Qfnf.js +1 -0
  16. package/dist/packem_shared/{BunnyStorage-CILSK4_Z.js → BunnyStorage-C7d0opLL.js} +1 -1
  17. package/dist/packem_shared/CloudinaryMetaStorage-DPVnmNe5.js +1 -0
  18. package/dist/packem_shared/{CloudinaryStorage-DiCbdAi_.js → CloudinaryStorage-Dc3XA2lP.js} +1 -1
  19. package/dist/packem_shared/{DiskStorage-Kp5t3vnF.js → DiskStorage-CI07TVNu.js} +1 -1
  20. package/dist/packem_shared/{DiskStorageWithChecksum-Bh6w-Iu8.js → DiskStorageWithChecksum-vFCubS6K.js} +1 -1
  21. package/dist/packem_shared/DropboxMetaStorage-BSn6Qfnf.js +1 -0
  22. package/dist/packem_shared/{DropboxStorage-H8bd8hEz.js → DropboxStorage-CY9Ggu3m.js} +1 -1
  23. package/dist/packem_shared/{Files-BA3mpDwz.js → Files-CpIcMjP0.js} +1 -1
  24. package/dist/packem_shared/FirebaseMetaStorage-DPVnmNe5.js +1 -0
  25. package/dist/packem_shared/{FirebaseStorage-Dgk4XyMr.js → FirebaseStorage-D6O9CJXN.js} +1 -1
  26. package/dist/packem_shared/FtpMetaStorage-BSn6Qfnf.js +1 -0
  27. package/dist/packem_shared/{FtpStorage-g_DjiR-C.js → FtpStorage-DbEjbq8z.js} +1 -1
  28. package/dist/packem_shared/{GCSMetaStorage-3fLTlRd4.js → GCSMetaStorage-BuPA0DDW.js} +1 -1
  29. package/dist/packem_shared/{GCStorage-DUfwVFd3.js → GCStorage-i9t5TQc1.js} +1 -1
  30. package/dist/packem_shared/GoogleDriveMetaStorage-Cbwa1CHV.js +1 -0
  31. package/dist/packem_shared/{GoogleDriveStorage-D0-5egHE.js → GoogleDriveStorage-Bklsz7Bh.js} +1 -1
  32. package/dist/packem_shared/{LocalMetaStorage-Bp5mVc76.js → LocalMetaStorage-BhicZnNl.js} +1 -1
  33. package/dist/packem_shared/{MemoryStorage-DzSTdlAq.js → MemoryStorage-9gbWd09l.js} +1 -1
  34. package/dist/packem_shared/{Multipart-C4GpuHMU.js → Multipart-CQjYqU--.js} +1 -1
  35. package/dist/packem_shared/{Multipart-Btj2mo9r.js → Multipart-D0ok6BBy.js} +1 -1
  36. package/dist/packem_shared/NetlifyBlobMetaStorage-DPVnmNe5.js +1 -0
  37. package/dist/packem_shared/{NetlifyBlobStorage-DZdCmOVW.js → NetlifyBlobStorage-CkpCCoN1.js} +1 -1
  38. package/dist/packem_shared/OneDriveMetaStorage-Cbwa1CHV.js +1 -0
  39. package/dist/packem_shared/{OneDriveStorage-CvJetV7_.js → OneDriveStorage-CP6MvGAa.js} +1 -1
  40. package/dist/packem_shared/PocketBaseMetaStorage-DOTLwVE7.js +1 -0
  41. package/dist/packem_shared/{PocketBaseStorage-BPil-koe.js → PocketBaseStorage-2qhbI2PW.js} +1 -1
  42. package/dist/packem_shared/{Rest-ymPCZkKR.js → Rest-CI_BiZPv.js} +1 -1
  43. package/dist/packem_shared/{Rest-BehVaxbl.js → Rest-DvfN4-kf.js} +1 -1
  44. package/dist/packem_shared/{S3Storage-wslqssvr.js → S3Storage-YGeNk3Tt.js} +1 -1
  45. package/dist/packem_shared/SftpMetaStorage-BSn6Qfnf.js +1 -0
  46. package/dist/packem_shared/{SftpStorage-BVbMtS2b.js → SftpStorage-2Hz396Xr.js} +1 -1
  47. package/dist/packem_shared/SharePointMetaStorage-BSn6Qfnf.js +1 -0
  48. package/dist/packem_shared/{SharePointStorage-DWjvR5oZ.js → SharePointStorage-CrX2Pk6C.js} +1 -1
  49. package/dist/packem_shared/SupabaseMetaStorage-Cbwa1CHV.js +1 -0
  50. package/dist/packem_shared/{SupabaseStorage-BiKmYKb6.js → SupabaseStorage-Dc_DBX29.js} +1 -1
  51. package/dist/packem_shared/{Tus-v6jzkaIO.js → Tus-BBVt2ky3.js} +1 -1
  52. package/dist/packem_shared/{Tus-BgbON_wQ.js → Tus-BlBZykIL.js} +1 -1
  53. package/dist/packem_shared/UploadThingMetaStorage-DPVnmNe5.js +1 -0
  54. package/dist/packem_shared/{UploadThingStorage-jrEnANC5.js → UploadThingStorage-BChykYSe.js} +1 -1
  55. package/dist/packem_shared/VercelBlobMetaStorage-BSn6Qfnf.js +1 -0
  56. package/dist/packem_shared/{VercelBlobStorage-Y-cDgH30.js → VercelBlobStorage-CsRyPfw3.js} +1 -1
  57. package/dist/packem_shared/{base-handler-core-EeV8gZck.js → base-handler-core-D-9Ku1h-.js} +1 -1
  58. package/dist/packem_shared/{base-handler-fetch-CHzsgb7C.js → base-handler-fetch-CfkNakv8.js} +1 -1
  59. package/dist/packem_shared/{base-handler-node-BjpW8pGi.js → base-handler-node-BF1v1qDa.js} +1 -1
  60. package/dist/packem_shared/{disk-storage-DIn-VnCh.js → disk-storage-CsQcYW3s.js} +1 -1
  61. package/dist/packem_shared/gcs-meta-storage-B1RrMqH3.js +1 -0
  62. package/dist/packem_shared/local-meta-storage-iuJnu90B.js +11 -0
  63. package/dist/packem_shared/path-0oTTdkvl-DvWvbDbh.js +1 -0
  64. package/dist/packem_shared/{rest-base-CynUg0mH.js → rest-base-e0reNDE_.js} +1 -1
  65. package/dist/packem_shared/{s3-base-storage-DXZYN24h.js → s3-base-storage-BoTyhuzO.js} +1 -1
  66. package/dist/packem_shared/{storage-Cyy73Y6r.js → storage-0j5nCAUp.js} +1 -1
  67. package/dist/storage/aws/index.js +1 -1
  68. package/dist/storage/aws-light/index.js +1 -1
  69. package/dist/storage/azure/index.js +1 -1
  70. package/dist/storage/box/index.js +1 -1
  71. package/dist/storage/bun-s3/index.js +1 -1
  72. package/dist/storage/bunny/index.js +1 -1
  73. package/dist/storage/cloudinary/index.js +1 -1
  74. package/dist/storage/dropbox/index.js +1 -1
  75. package/dist/storage/firebase/index.js +1 -1
  76. package/dist/storage/ftp/index.js +1 -1
  77. package/dist/storage/gcs/index.js +1 -1
  78. package/dist/storage/google-drive/index.js +1 -1
  79. package/dist/storage/local/index.js +1 -1
  80. package/dist/storage/memory/index.js +1 -1
  81. package/dist/storage/netlify-blob/index.js +1 -1
  82. package/dist/storage/onedrive/index.js +1 -1
  83. package/dist/storage/pocketbase/index.js +1 -1
  84. package/dist/storage/sftp/index.js +1 -1
  85. package/dist/storage/sharepoint/index.js +1 -1
  86. package/dist/storage/supabase/index.js +1 -1
  87. package/dist/storage/uploadthing/index.js +1 -1
  88. package/dist/storage/vercel-blob/index.js +1 -1
  89. package/dist/transformer/image-transformer.js +1 -1
  90. package/package.json +18 -18
  91. package/dist/packem_shared/BoxMetaStorage-DFwhEI9C.js +0 -1
  92. package/dist/packem_shared/BunS3MetaStorage-DFwhEI9C.js +0 -1
  93. package/dist/packem_shared/BunnyMetaStorage-DFwhEI9C.js +0 -1
  94. package/dist/packem_shared/CloudinaryMetaStorage-D_vNzewL.js +0 -1
  95. package/dist/packem_shared/DropboxMetaStorage-DFwhEI9C.js +0 -1
  96. package/dist/packem_shared/FirebaseMetaStorage-D_vNzewL.js +0 -1
  97. package/dist/packem_shared/FtpMetaStorage-DFwhEI9C.js +0 -1
  98. package/dist/packem_shared/GoogleDriveMetaStorage-DqkgoE46.js +0 -1
  99. package/dist/packem_shared/NetlifyBlobMetaStorage-D_vNzewL.js +0 -1
  100. package/dist/packem_shared/OneDriveMetaStorage-DqkgoE46.js +0 -1
  101. package/dist/packem_shared/PocketBaseMetaStorage-CpvDRnSu.js +0 -1
  102. package/dist/packem_shared/SftpMetaStorage-DFwhEI9C.js +0 -1
  103. package/dist/packem_shared/SharePointMetaStorage-DFwhEI9C.js +0 -1
  104. package/dist/packem_shared/SupabaseMetaStorage-DqkgoE46.js +0 -1
  105. package/dist/packem_shared/UploadThingMetaStorage-D_vNzewL.js +0 -1
  106. package/dist/packem_shared/VercelBlobMetaStorage-DFwhEI9C.js +0 -1
  107. package/dist/packem_shared/gcs-meta-storage-Dy37wCjI.js +0 -1
  108. package/dist/packem_shared/local-meta-storage-C2T92TYb.js +0 -11
  109. package/dist/packem_shared/path-0oTTdkvl-BVg7lYf5.js +0 -1
@@ -1 +1 @@
1
- import{format as b}from"node:url";import{n as d}from"./headers-BAiAKekR.js";import{b as a,a as c,g as n}from"./base-handler-core-EeV8gZck.js";import{T as f}from"./base-handler-node-BjpW8pGi.js";import{TusBase as U,TUS_RESUMABLE as T}from"./TUS_RESUMABLE-CyTSRvPU.js";import{TUS_VERSION as R}from"./TUS_RESUMABLE-CyTSRvPU.js";class p extends f{static methods=["delete","download","get","head","options","patch","post"];disableTerminationForFinishedUploads=!1;tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends U{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(p.methods)}async post(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));const t=e.headers["upload-length"],s=e.headers["upload-defer-length"],r=e.headers["upload-concat"],o=a(e,"upload-metadata",!0),i=a(e,"content-type")||"",h=Number.parseInt(a(e,"content-length")||"0",10),l=e.originalUrl||e.url||"",u=c(e);return this.tusBase.handlePost(t,s,r,o,l,u,h,i)}async patch(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);if(e.headers["upload-offset"]===void 0)throw d(412,"Missing Upload-Offset header");if(e.headers["content-type"]===void 0)throw d(412,"Content-Type header required");if(e.headers["content-type"]!=="application/offset+octet-stream")throw d(415,"Unsupported Media Type");const s=Number.parseInt(a(e,"upload-offset"),10),r=e.headers["upload-length"],o=a(e,"upload-metadata",!0),i=Number(a(e,"content-length")),h=a(e,"upload-checksum"),{checksum:l,checksumAlgorithm:u}=this.tusBase.extractChecksum(h),m=e.originalUrl||e.url||"",g=c(e);return this.tusBase.handlePatch(t,s,r,o,l,u,m,g,i)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async head(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleHead(t)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async get(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleGet(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.UploadErrorCode==="GONE"?d(410,"Upload expired"):t}}async delete(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleDelete(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.code==="ENOENT"?d(404,"File not found"):t}}send(e,{body:t="",headers:s={},statusCode:r=200}){const o={body:t,headers:{...s,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control","Tus-Resumable":T},statusCode:r||200};super.send(e,o)}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}buildFileUrlForTus(e,t){const s=new URL(e,"http://localhost"),{pathname:r}=s,o=Object.fromEntries(s.searchParams.entries()),i=b({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:(/^https?:\/\//iu.test(e)?s.origin:"")+i}}export{T as TUS_RESUMABLE,R as TUS_VERSION,p as Tus};
1
+ import{format as b}from"node:url";import{n as d}from"./headers-BAiAKekR.js";import{b as a,a as c,g as n}from"./base-handler-core-D-9Ku1h-.js";import{T as f}from"./base-handler-node-BF1v1qDa.js";import{TusBase as U,TUS_RESUMABLE as T}from"./TUS_RESUMABLE-CyTSRvPU.js";import{TUS_VERSION as R}from"./TUS_RESUMABLE-CyTSRvPU.js";class p extends f{static methods=["delete","download","get","head","options","patch","post"];disableTerminationForFinishedUploads=!1;tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends U{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(p.methods)}async post(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));const t=e.headers["upload-length"],s=e.headers["upload-defer-length"],r=e.headers["upload-concat"],o=a(e,"upload-metadata",!0),i=a(e,"content-type")||"",h=Number.parseInt(a(e,"content-length")||"0",10),l=e.originalUrl||e.url||"",u=c(e);return this.tusBase.handlePost(t,s,r,o,l,u,h,i)}async patch(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);if(e.headers["upload-offset"]===void 0)throw d(412,"Missing Upload-Offset header");if(e.headers["content-type"]===void 0)throw d(412,"Content-Type header required");if(e.headers["content-type"]!=="application/offset+octet-stream")throw d(415,"Unsupported Media Type");const s=Number.parseInt(a(e,"upload-offset"),10),r=e.headers["upload-length"],o=a(e,"upload-metadata",!0),i=Number(a(e,"content-length")),h=a(e,"upload-checksum"),{checksum:l,checksumAlgorithm:u}=this.tusBase.extractChecksum(h),m=e.originalUrl||e.url||"",g=c(e);return this.tusBase.handlePatch(t,s,r,o,l,u,m,g,i)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async head(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleHead(t)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async get(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleGet(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.UploadErrorCode==="GONE"?d(410,"Upload expired"):t}}async delete(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleDelete(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.code==="ENOENT"?d(404,"File not found"):t}}send(e,{body:t="",headers:s={},statusCode:r=200}){const o={body:t,headers:{...s,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control","Tus-Resumable":T},statusCode:r||200};super.send(e,o)}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}buildFileUrlForTus(e,t){const s=new URL(e,"http://localhost"),{pathname:r}=s,o=Object.fromEntries(s.searchParams.entries()),i=b({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:(/^https?:\/\//iu.test(e)?s.origin:"")+i}}export{T as TUS_RESUMABLE,R as TUS_VERSION,p as Tus};
@@ -0,0 +1 @@
1
+ import{y as s}from"./local-meta-storage-iuJnu90B.js";class o extends s{constructor(r){super(r)}}export{o as default};
@@ -1 +1 @@
1
- import{UTApi as w,UTFile as u}from"uploadthing/server";import{throwErrorCode as l,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as g}from"./storage-Cyy73Y6r.js";import d from"./UploadThingFile-BTFMpcIA.js";import T from"./UploadThingMetaStorage-D_vNzewL.js";import{t as m}from"./get-file-status-y3wTtDQs.js";import{t as U}from"./update-size-DuNuLyxj.js";import{i as I}from"./part-match-D-9dGX42.js";import{e as O}from"./has-content-50BsqrWw.js";const f=3600*24*7,E=p=>{let e;try{e=typeof atob=="function"?atob(p):Buffer.from(p,"base64").toString("utf8")}catch(t){throw new Error(`UploadThing: token is not valid base64: ${t.message}`)}let a;try{a=JSON.parse(e)}catch(t){throw new Error(`UploadThing: token does not decode to JSON: ${t.message}`)}if(!a||typeof a!="object"||typeof a.apiKey!="string"||typeof a.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return a},k=async p=>{const e=[];for await(const a of p)e.push(Buffer.from(a));return Buffer.concat(e)},y=p=>{const e=p.lastIndexOf("/");return e===-1?p:p.slice(e+1)};class S extends g{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(e){super(e);const a=e.token??process.env.UPLOADTHING_TOKEN;if(e.client)this.utapi=e.client;else{if(!a)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new w({defaultKeyType:"customId",token:a})}if(!a)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=E(a).appId,this.acl=e.acl??"public-read",this.defaultUrlExpiresIn=Math.min(e.defaultUrlExpiresIn??3600,f),this.meta=e.metaStorage??new T(e.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new d(e);t.name=this.namingFunction(t),t.customId=t.name,await this.validate(t);try{const i=await this.getMeta(t.id);if(i.bytesWritten>=0)return i}catch{}return t.bytesWritten=0,t.status=m(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&&U(t,e.size),!I(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(O(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await k(e.body),o=new Blob([new Uint8Array(n)],{type:t.contentType}),s=new u([o],y(t.name||t.id),{customId:t.name||t.id,type:t.contentType}),r=await this.runOperation(a,()=>this.utapi.uploadFiles(s,{acl:this.acl}));if(r.error)throw new Error(r.error.message);const{data:c}=r;t.bytesWritten=n.length,t.size=n.length,t.ufsKey=c.key,t.url=c.ufsUrl??c.url,t.ETag=c.fileHash,t.fileHash=c.fileHash}return t.status=m(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const i=t?.customId??t?.name??e;return await this.runOperation(a,()=>this.utapi.deleteFiles(i)),t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:e}),{customId:i,id:e,name:e,status:"deleted"})})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t,i=e;try{t=await this.checkIfExpired(await this.getMeta(e)),i=t.customId??t.name??e}catch{}const n=await this.resolveFetchUrl(i,a),o=await this.runOperation(a,()=>fetch(n));if(!o.ok)throw new Error(`UploadThing: fetch failed: ${o.status} ${o.statusText} for ${i}`);const s=Buffer.from(await o.arrayBuffer());return{content:s,contentType:t?.contentType??o.headers.get("content-type")??"application/octet-stream",ETag:t?.ETag??o.headers.get("etag")??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt,name:t?.name??i,originalName:t?.originalName??i,size:t?.size??s.length}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const i=await this.get({id:e},t),n=new Blob([new Uint8Array(i.content)],{type:i.contentType}),o=new u([n],y(a),{customId:a,type:i.contentType}),s=await this.runOperation(t,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const r=new d({contentType:i.contentType,metadata:{},originalName:a});return r.id=a,r.name=a,r.customId=a,r.size=typeof i.size=="string"?Number(i.size):i.size,r.ufsKey=s.data.key,r.url=s.data.ufsUrl??s.data.url,r.ETag=s.data.fileHash,r})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,a,t);return await this.delete({id:e},t),i})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>(await this.runOperation(a,()=>this.utapi.listFiles({limit:e}))).files.map(t=>{const i=t.customId??t.key,n=new d({contentType:"application/octet-stream",metadata:{},originalName:i});return n.id=i,n.name=i,n.customId=t.customId??void 0,n.ufsKey=t.key,n.size=t.size,n.modifiedAt=t.uploadedAt?new Date(t.uploadedAt).toISOString():void 0,n}),{limit:e})}async getReadUrl(e,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return l(h.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition`/`responseContentType` are not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(e)}`;const t=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{ufsUrl:i}=await this.utapi.generateSignedURL(e,{expiresIn:t,keyType:"customId"});return i}async getUploadUrl(e,a){return l(h.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(e,a){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(e)}`;const{ufsUrl:t}=await this.runOperation(a,()=>this.utapi.generateSignedURL(e,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return t}internalOnComplete=e=>this.deleteMeta(e.id)}export{S as default};
1
+ import{UTApi as w,UTFile as u}from"uploadthing/server";import{throwErrorCode as l,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as g}from"./storage-0j5nCAUp.js";import d from"./UploadThingFile-BTFMpcIA.js";import T from"./UploadThingMetaStorage-DPVnmNe5.js";import{t as m}from"./get-file-status-y3wTtDQs.js";import{t as U}from"./update-size-DuNuLyxj.js";import{i as I}from"./part-match-D-9dGX42.js";import{e as O}from"./has-content-50BsqrWw.js";const f=3600*24*7,E=p=>{let e;try{e=typeof atob=="function"?atob(p):Buffer.from(p,"base64").toString("utf8")}catch(t){throw new Error(`UploadThing: token is not valid base64: ${t.message}`)}let a;try{a=JSON.parse(e)}catch(t){throw new Error(`UploadThing: token does not decode to JSON: ${t.message}`)}if(!a||typeof a!="object"||typeof a.apiKey!="string"||typeof a.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return a},k=async p=>{const e=[];for await(const a of p)e.push(Buffer.from(a));return Buffer.concat(e)},y=p=>{const e=p.lastIndexOf("/");return e===-1?p:p.slice(e+1)};class S extends g{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(e){super(e);const a=e.token??process.env.UPLOADTHING_TOKEN;if(e.client)this.utapi=e.client;else{if(!a)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new w({defaultKeyType:"customId",token:a})}if(!a)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=E(a).appId,this.acl=e.acl??"public-read",this.defaultUrlExpiresIn=Math.min(e.defaultUrlExpiresIn??3600,f),this.meta=e.metaStorage??new T(e.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new d(e);t.name=this.namingFunction(t),t.customId=t.name,await this.validate(t);try{const i=await this.getMeta(t.id);if(i.bytesWritten>=0)return i}catch{}return t.bytesWritten=0,t.status=m(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&&U(t,e.size),!I(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(O(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await k(e.body),o=new Blob([new Uint8Array(n)],{type:t.contentType}),s=new u([o],y(t.name||t.id),{customId:t.name||t.id,type:t.contentType}),r=await this.runOperation(a,()=>this.utapi.uploadFiles(s,{acl:this.acl}));if(r.error)throw new Error(r.error.message);const{data:c}=r;t.bytesWritten=n.length,t.size=n.length,t.ufsKey=c.key,t.url=c.ufsUrl??c.url,t.ETag=c.fileHash,t.fileHash=c.fileHash}return t.status=m(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const i=t?.customId??t?.name??e;return await this.runOperation(a,()=>this.utapi.deleteFiles(i)),t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:e}),{customId:i,id:e,name:e,status:"deleted"})})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t,i=e;try{t=await this.checkIfExpired(await this.getMeta(e)),i=t.customId??t.name??e}catch{}const n=await this.resolveFetchUrl(i,a),o=await this.runOperation(a,()=>fetch(n));if(!o.ok)throw new Error(`UploadThing: fetch failed: ${o.status} ${o.statusText} for ${i}`);const s=Buffer.from(await o.arrayBuffer());return{content:s,contentType:t?.contentType??o.headers.get("content-type")??"application/octet-stream",ETag:t?.ETag??o.headers.get("etag")??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt,name:t?.name??i,originalName:t?.originalName??i,size:t?.size??s.length}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const i=await this.get({id:e},t),n=new Blob([new Uint8Array(i.content)],{type:i.contentType}),o=new u([n],y(a),{customId:a,type:i.contentType}),s=await this.runOperation(t,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const r=new d({contentType:i.contentType,metadata:{},originalName:a});return r.id=a,r.name=a,r.customId=a,r.size=typeof i.size=="string"?Number(i.size):i.size,r.ufsKey=s.data.key,r.url=s.data.ufsUrl??s.data.url,r.ETag=s.data.fileHash,r})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,a,t);return await this.delete({id:e},t),i})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>(await this.runOperation(a,()=>this.utapi.listFiles({limit:e}))).files.map(t=>{const i=t.customId??t.key,n=new d({contentType:"application/octet-stream",metadata:{},originalName:i});return n.id=i,n.name=i,n.customId=t.customId??void 0,n.ufsKey=t.key,n.size=t.size,n.modifiedAt=t.uploadedAt?new Date(t.uploadedAt).toISOString():void 0,n}),{limit:e})}async getReadUrl(e,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return l(h.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition`/`responseContentType` are not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(e)}`;const t=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{ufsUrl:i}=await this.utapi.generateSignedURL(e,{expiresIn:t,keyType:"customId"});return i}async getUploadUrl(e,a){return l(h.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(e,a){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(e)}`;const{ufsUrl:t}=await this.runOperation(a,()=>this.utapi.generateSignedURL(e,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return t}internalOnComplete=e=>this.deleteMeta(e.id)}export{S as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-iuJnu90B.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -1 +1 @@
1
- import{put as l,list as u,del as d,copy as h}from"@vercel/blob";import{a as y}from"./detect-file-type-BA7UBLKA.js";import{B as O,c as E}from"./storage-Cyy73Y6r.js";import{y as g}from"./local-meta-storage-C2T92TYb.js";import m from"./VercelBlobFile-CVQwKlZk.js";import{t as p}from"./get-file-status-y3wTtDQs.js";import{t as T}from"./update-size-DuNuLyxj.js";import{i as b}from"./part-match-D-9dGX42.js";import{e as v}from"./has-content-50BsqrWw.js";class f extends O{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:h,credentials:this.credentials,del:d,list:u,put:l}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=f.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:r,metaStorageConfig:t}=e;this.meta=r||new g(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const r=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,i=t?.startsWith("store_")?t.slice(6):t;if(r&&i)return{oidcToken:r,storeId:i};if(r||i)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${r?"set":"missing"}, storeId=${i?"set":"missing"}.`);const a=process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN;if(a)return{token:a};throw new Error("Vercel Blob credentials are required. Provide `token`, an `oidcToken`+`storeId` pair, or set BLOB_READ_WRITE_TOKEN / (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) env vars.")}async create(e,r){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?E(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const i=new m(t);i.name=this.namingFunction(i),await this.validate(i);try{const a=await this.getMeta(i.id);if(a.bytesWritten>=0)return a}catch{}return i.bytesWritten=0,i.status=p(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(e,r){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(t,e.size),!b(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(v(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],n=e.body;for await(const o of n)a.push(Buffer.from(o));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await y(s);o?.mime&&(t.contentType=o.mime)}catch{}const w=new Blob([s],{type:t.contentType}),c=await this.runOperation(r,()=>l(t.name,w,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=c.url,t.pathname=c.pathname,t.downloadUrl=c.downloadUrl,t.bytesWritten=s.length}return t.status=p(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},r){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);const{url:i}=t;t.status="deleted";try{await this.runOperation(r,()=>d(i,{...this.credentials}))}catch(n){this.logger?.error("Failed to delete blob from Vercel Blob:",n);const s=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},r){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:i}=t;return(await this.runOperation(r,()=>fetch(i,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},r){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.url||t.url.length===0)throw new Error("File URL not found");const{url:i}=t,a=await this.runOperation(r,()=>fetch(i)),n=Buffer.from(await this.runOperation(r,()=>a.arrayBuffer()));return{content:n,contentType:t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||n.length}})}async copy(e,r,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(e);if(!i.url)throw new Error("Source file URL not found");const a=i.url,n=await this.runOperation(t,()=>h(a,r,{access:"public",...this.credentials}));return{...i,id:r,name:r,pathname:n.pathname,url:n.url}})}async move(e,r,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,r,t);return await this.delete({id:e},t),i})}async list(e=1e3,r){return this.instrumentOperation("list",async()=>(await this.runOperation(r,()=>u({limit:e,...this.credentials}))).blobs.map(t=>{const i=new m({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return i.createdAt=t.uploadedAt?.toISOString(),i.id=t.pathname,i.modifiedAt=t.uploadedAt?.toISOString(),i.name=t.pathname,i.pathname=t.pathname,i.size=t.size,i.url=t.url,i.downloadUrl=t.downloadUrl,i}),{limit:e})}internalOnComplete=e=>this.deleteMeta(e.id);shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{f as default};
1
+ import{put as l,list as u,del as d,copy as h}from"@vercel/blob";import{a as y}from"./detect-file-type-BA7UBLKA.js";import{B as O,c as E}from"./storage-0j5nCAUp.js";import{y as g}from"./local-meta-storage-iuJnu90B.js";import m from"./VercelBlobFile-CVQwKlZk.js";import{t as p}from"./get-file-status-y3wTtDQs.js";import{t as T}from"./update-size-DuNuLyxj.js";import{i as b}from"./part-match-D-9dGX42.js";import{e as v}from"./has-content-50BsqrWw.js";class f extends O{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:h,credentials:this.credentials,del:d,list:u,put:l}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=f.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:r,metaStorageConfig:t}=e;this.meta=r||new g(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const r=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,i=t?.startsWith("store_")?t.slice(6):t;if(r&&i)return{oidcToken:r,storeId:i};if(r||i)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${r?"set":"missing"}, storeId=${i?"set":"missing"}.`);const a=process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN;if(a)return{token:a};throw new Error("Vercel Blob credentials are required. Provide `token`, an `oidcToken`+`storeId` pair, or set BLOB_READ_WRITE_TOKEN / (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) env vars.")}async create(e,r){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?E(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const i=new m(t);i.name=this.namingFunction(i),await this.validate(i);try{const a=await this.getMeta(i.id);if(a.bytesWritten>=0)return a}catch{}return i.bytesWritten=0,i.status=p(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(e,r){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(t,e.size),!b(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(v(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],n=e.body;for await(const o of n)a.push(Buffer.from(o));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await y(s);o?.mime&&(t.contentType=o.mime)}catch{}const w=new Blob([s],{type:t.contentType}),c=await this.runOperation(r,()=>l(t.name,w,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=c.url,t.pathname=c.pathname,t.downloadUrl=c.downloadUrl,t.bytesWritten=s.length}return t.status=p(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},r){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);const{url:i}=t;t.status="deleted";try{await this.runOperation(r,()=>d(i,{...this.credentials}))}catch(n){this.logger?.error("Failed to delete blob from Vercel Blob:",n);const s=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},r){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:i}=t;return(await this.runOperation(r,()=>fetch(i,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},r){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.url||t.url.length===0)throw new Error("File URL not found");const{url:i}=t,a=await this.runOperation(r,()=>fetch(i)),n=Buffer.from(await this.runOperation(r,()=>a.arrayBuffer()));return{content:n,contentType:t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||n.length}})}async copy(e,r,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(e);if(!i.url)throw new Error("Source file URL not found");const a=i.url,n=await this.runOperation(t,()=>h(a,r,{access:"public",...this.credentials}));return{...i,id:r,name:r,pathname:n.pathname,url:n.url}})}async move(e,r,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,r,t);return await this.delete({id:e},t),i})}async list(e=1e3,r){return this.instrumentOperation("list",async()=>(await this.runOperation(r,()=>u({limit:e,...this.credentials}))).blobs.map(t=>{const i=new m({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return i.createdAt=t.uploadedAt?.toISOString(),i.id=t.pathname,i.modifiedAt=t.uploadedAt?.toISOString(),i.name=t.pathname,i.pathname=t.pathname,i.size=t.size,i.url=t.url,i.downloadUrl=t.downloadUrl,i}),{limit:e})}internalOnComplete=e=>this.deleteMeta(e.id);shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{f as default};
@@ -1 +1 @@
1
- import{EventEmitter as u}from"node:events";import{format as m}from"node:url";import g from"mime";import{ErrorMap as b}from"./ERRORS-BIBxE2oR.js";import{H as w}from"./headers-BAiAKekR.js";import{Readable as f}from"node:stream";import"type-is";import{B as h}from"./storage-Cyy73Y6r.js";const C=(r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},R=r=>r.at(-1),y=r=>{let e="",t="";const s=c(r,"forwarded");return s&&s.split(";").forEach(o=>{const[i,n]=o.split("=");i==="proto"&&(e=n),i==="host"&&(t=n)}),{host:t,proto:e}},P=(r,e="utf8",t)=>new Promise((s,o)=>{const i=[];let n=0;r.on("data",d=>{const a=Buffer.isBuffer(d)?d:Buffer.from(d,e);if(n+=a.length,n>t){o(new Error("Request body length limit exceeded")),r.destroy();return}i.push(a)}),r.once("end",()=>{s(Buffer.concat(i).toString(e))}),r.once("error",o)}),c=(r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const o=Array.isArray(s)?s:s.split(",");return R(o).trim()},E=(r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},A=(r,e={})=>{const t=Object.keys(e);t.length>0&&E(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{if(["link","location"].includes(s.toLowerCase())){const o=encodeURI(e[s].toString()).replaceAll("#","%23");r.setHeader(s,o)}else r.setHeader(s,e[s])})},U=r=>c(r,"host")||c(r,"x-forwarded-host"),I=r=>c(r,"x-forwarded-proto").toLowerCase(),L=r=>{let{host:e,proto:t}=y(r);return e||=U(r),t||=I(r),e?t?`${t}://${e}`:`//${e}`:""},H=r=>{let e=(r.originalUrl||r.url||"").split("?")[0];if(!e)throw new TypeError("Invalid request URL");return e.startsWith("/")||(e=`/${e}`),e.startsWith("http")&&(e=new URL(e).pathname),e},$=/^[\da-z]{4,}(?:-[\da-z]{4,}){2,}$/i,k=r=>{const e=H(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let o=e.length-1;o>=0;o-=1){const i=e[o];if(!i)continue;const n=i.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(n.toLowerCase())&&$.test(n))return h.assertSafeId(n),n}const t=e[e.length-1];if(!t)throw new Error("Invalid request URL");const s=t.replace(/\.[^/.]+$/,"");if(["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(s.toLowerCase()))throw new Error("Invalid request URL");if(s.length<8)throw new Error("Invalid request URL");if(e.length>1)return h.assertSafeId(s),s;throw new Error("Invalid request URL")},W=r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?f.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?f.from(Buffer.from(r.body)):r instanceof f?r:f.from(new Uint8Array(0));class j extends u{responseType="json";storage;mediaTransformer;disableTerminationForFinishedUploads;logger;get loggerInstance(){return this.logger}internalErrorResponses={};get errorResponses(){return this.internalErrorResponses}constructor({disableTerminationForFinishedUploads:e,mediaTransformer:t,storage:s}){super(),this.storage=s,this.mediaTransformer=t,this.disableTerminationForFinishedUploads=e,this.logger=this.storage?.logger,this.assembleErrors()}set errorResponses(e){this.assembleErrors(e)}assembleErrors=(e={})=>{this.internalErrorResponses={...b,...this.internalErrorResponses,...this.storage.errorResponses,...e}};parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const o=s[0]?.trim();if(!o)return;const i=o.split("-");if(i.length!==2)return;const[n,d]=i;let a,l;if(n&&d)a=Number.parseInt(n,10),l=Number.parseInt(d,10);else if(n&&!d)a=Number.parseInt(n,10),l=t-1;else if(!n&&d){const p=Number.parseInt(d,10);a=Math.max(0,t-p),l=t-1}else return;if(!(Number.isNaN(a)||Number.isNaN(l)||a>=t||l>=t||a>l))return{end:l,start:a}}buildFileUrlFromString(e,t,s){const o=new URL(e,"http://localhost"),{pathname:i}=o,n=Object.fromEntries(o.searchParams.entries()),d=m({pathname:`${i}/${t.id}`,query:n});let a="";return this.storage.config.useRelativeLocation||(/^https?:\/\//iu.test(e)?a=o.origin:s&&(a=L({headers:s}))),`${a}${d}.${g.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return w.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{W as a,c as b,j as c,C as d,H as e,k as g,P as r,A as s,$ as u};
1
+ import{EventEmitter as u}from"node:events";import{format as m}from"node:url";import g from"mime";import{ErrorMap as b}from"./ERRORS-BIBxE2oR.js";import{H as w}from"./headers-BAiAKekR.js";import{Readable as f}from"node:stream";import"type-is";import{B as h}from"./storage-0j5nCAUp.js";const C=(r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},R=r=>r.at(-1),y=r=>{let e="",t="";const s=c(r,"forwarded");return s&&s.split(";").forEach(o=>{const[i,n]=o.split("=");i==="proto"&&(e=n),i==="host"&&(t=n)}),{host:t,proto:e}},P=(r,e="utf8",t)=>new Promise((s,o)=>{const i=[];let n=0;r.on("data",d=>{const a=Buffer.isBuffer(d)?d:Buffer.from(d,e);if(n+=a.length,n>t){o(new Error("Request body length limit exceeded")),r.destroy();return}i.push(a)}),r.once("end",()=>{s(Buffer.concat(i).toString(e))}),r.once("error",o)}),c=(r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const o=Array.isArray(s)?s:s.split(",");return R(o).trim()},E=(r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},A=(r,e={})=>{const t=Object.keys(e);t.length>0&&E(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{if(["link","location"].includes(s.toLowerCase())){const o=encodeURI(e[s].toString()).replaceAll("#","%23");r.setHeader(s,o)}else r.setHeader(s,e[s])})},U=r=>c(r,"host")||c(r,"x-forwarded-host"),I=r=>c(r,"x-forwarded-proto").toLowerCase(),L=r=>{let{host:e,proto:t}=y(r);return e||=U(r),t||=I(r),e?t?`${t}://${e}`:`//${e}`:""},H=r=>{let e=(r.originalUrl||r.url||"").split("?")[0];if(!e)throw new TypeError("Invalid request URL");return e.startsWith("/")||(e=`/${e}`),e.startsWith("http")&&(e=new URL(e).pathname),e},$=/^[\da-z]{4,}(?:-[\da-z]{4,}){2,}$/i,k=r=>{const e=H(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let o=e.length-1;o>=0;o-=1){const i=e[o];if(!i)continue;const n=i.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(n.toLowerCase())&&$.test(n))return h.assertSafeId(n),n}const t=e[e.length-1];if(!t)throw new Error("Invalid request URL");const s=t.replace(/\.[^/.]+$/,"");if(["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(s.toLowerCase()))throw new Error("Invalid request URL");if(s.length<8)throw new Error("Invalid request URL");if(e.length>1)return h.assertSafeId(s),s;throw new Error("Invalid request URL")},W=r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?f.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?f.from(Buffer.from(r.body)):r instanceof f?r:f.from(new Uint8Array(0));class j extends u{responseType="json";storage;mediaTransformer;disableTerminationForFinishedUploads;logger;get loggerInstance(){return this.logger}internalErrorResponses={};get errorResponses(){return this.internalErrorResponses}constructor({disableTerminationForFinishedUploads:e,mediaTransformer:t,storage:s}){super(),this.storage=s,this.mediaTransformer=t,this.disableTerminationForFinishedUploads=e,this.logger=this.storage?.logger,this.assembleErrors()}set errorResponses(e){this.assembleErrors(e)}assembleErrors=(e={})=>{this.internalErrorResponses={...b,...this.internalErrorResponses,...this.storage.errorResponses,...e}};parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const o=s[0]?.trim();if(!o)return;const i=o.split("-");if(i.length!==2)return;const[n,d]=i;let a,l;if(n&&d)a=Number.parseInt(n,10),l=Number.parseInt(d,10);else if(n&&!d)a=Number.parseInt(n,10),l=t-1;else if(!n&&d){const p=Number.parseInt(d,10);a=Math.max(0,t-p),l=t-1}else return;if(!(Number.isNaN(a)||Number.isNaN(l)||a>=t||l>=t||a>l))return{end:l,start:a}}buildFileUrlFromString(e,t,s){const o=new URL(e,"http://localhost"),{pathname:i}=o,n=Object.fromEntries(o.searchParams.entries()),d=m({pathname:`${i}/${t.id}`,query:n});let a="";return this.storage.config.useRelativeLocation||(/^https?:\/\//iu.test(e)?a=o.origin:s&&(a=L({headers:s}))),`${a}${d}.${g.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return w.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{W as a,c as b,j as c,C as d,H as e,k as g,P as r,A as s,$ as u};
@@ -1 +1 @@
1
- import{H as u,h as f}from"./headers-BAiAKekR.js";import{ERRORS as p,isUploadError as C}from"./ERRORS-BIBxE2oR.js";import{c as E,d as b}from"./base-handler-core-EeV8gZck.js";import{i as R}from"./storage-Cyy73Y6r.js";import{waitForStorage as O}from"./waitForStorage-ByQmG4xF.js";class A extends E{static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(t){super(t),this.compose()}get handlers(){return this.registeredHandlers}async fetch(t){this.logger?.debug("[fetch request]: %s %s",t.method,t.url);const e=this.registeredHandlers.get(t.method||"GET");if(!e)return this.createErrorResponse({UploadErrorCode:p.METHOD_NOT_ALLOWED});try{await O(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:p.STORAGE_ERROR})}try{const o=await e.call(this,t);return this.handleFetchResponse(t,o)}catch(o){const s=o instanceof Error?o:new Error(String(o)),r={...b(s,["name",...Object.getOwnPropertyNames(s)]),request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}};return this.listenerCount("error")>0&&this.emit("error",r),this.logger?.error("[fetch error]: %O",r),this.createErrorResponse(s)}}async handleFetchResponse(t,e){if(t.method==="HEAD"||t.method==="OPTIONS"){const{headers:n,statusCode:d}=e;return new Response(void 0,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}if(t.method==="GET"){const{headers:n,statusCode:d}=e;let c="";return e.content!==void 0?c=new Uint8Array(e.content):typeof e=="object"&&"data"in e&&(c=JSON.stringify(e.data)),new Response(c,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}const{headers:o,statusCode:s,...r}=e;if(r.status!==void 0&&this.listenerCount(r.status)>0&&this.emit(r.status,{...r,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),r.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(r,n)}catch(l){throw this.logger?.error("[onComplete error]: %O",l),l}const{headers:d,statusCode:c,...g}=n,{content:H,stream:w,...y}=g;return this.createResponse({body:y,headers:d||o,statusCode:c||s||200})}const m={...o,...e.headers},a=this.convertHeaders({...m,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control",...r.hash===void 0?{}:{[`X-Range-${r.hash?.algorithm.toUpperCase()}`]:r.hash?.value}}),h=e.headers||{};h.Location&&!a.location&&!a.Location?a.location=String(h.Location):h.location&&!a.location&&!a.Location?a.location=String(h.location):o.Location&&!a.location&&!a.Location?a.location=String(o.Location):o.location&&!a.location&&!a.Location&&(a.location=String(o.location));let i;return s>=200&&s<300&&(i=Object.keys(r).length>0?{...r}:{},"content"in i&&delete i.content,"stream"in i&&delete i.stream,Object.keys(i).length===0&&(i={})),this.createResponse({body:i,headers:a,statusCode:s||200})}convertHeaders(t){const e={};for(const[o,s]of Object.entries(t))e[o]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:o={},statusCode:s}=t;let r;return s===204?r=null:typeof e=="string"?r=e:e instanceof Buffer?r=new Uint8Array(e):e&&typeof e=="object"?(r=JSON.stringify(e),o["Content-Type"]||(o["Content-Type"]=u.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(r="{}",o["Content-Type"]||(o["Content-Type"]=u.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(r,{headers:this.convertHeaders(o),status:s})}async createErrorResponse(t){let e;C(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!R(t)&&!f.isHttpError(t)?e=this.storage.normalizeError(t):e={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(e);let o;return e.body?typeof e.body=="object"&&e.body!==null?o={body:e.body,headers:e.headers,statusCode:e.statusCode}:o={body:{error:{code:e.code||e.name||"Error",message:e.body||e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500}:o={body:{error:{code:e.code||e.name||"Error",message:e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500},this.createResponse(o)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{A as C};
1
+ import{H as u,h as f}from"./headers-BAiAKekR.js";import{ERRORS as p,isUploadError as C}from"./ERRORS-BIBxE2oR.js";import{c as E,d as b}from"./base-handler-core-D-9Ku1h-.js";import{i as R}from"./storage-0j5nCAUp.js";import{waitForStorage as O}from"./waitForStorage-ByQmG4xF.js";class A extends E{static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(t){super(t),this.compose()}get handlers(){return this.registeredHandlers}async fetch(t){this.logger?.debug("[fetch request]: %s %s",t.method,t.url);const e=this.registeredHandlers.get(t.method||"GET");if(!e)return this.createErrorResponse({UploadErrorCode:p.METHOD_NOT_ALLOWED});try{await O(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:p.STORAGE_ERROR})}try{const o=await e.call(this,t);return this.handleFetchResponse(t,o)}catch(o){const s=o instanceof Error?o:new Error(String(o)),r={...b(s,["name",...Object.getOwnPropertyNames(s)]),request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}};return this.listenerCount("error")>0&&this.emit("error",r),this.logger?.error("[fetch error]: %O",r),this.createErrorResponse(s)}}async handleFetchResponse(t,e){if(t.method==="HEAD"||t.method==="OPTIONS"){const{headers:n,statusCode:d}=e;return new Response(void 0,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}if(t.method==="GET"){const{headers:n,statusCode:d}=e;let c="";return e.content!==void 0?c=new Uint8Array(e.content):typeof e=="object"&&"data"in e&&(c=JSON.stringify(e.data)),new Response(c,{headers:this.convertHeaders({...n,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control"}),status:d})}const{headers:o,statusCode:s,...r}=e;if(r.status!==void 0&&this.listenerCount(r.status)>0&&this.emit(r.status,{...r,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),r.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(r,n)}catch(l){throw this.logger?.error("[onComplete error]: %O",l),l}const{headers:d,statusCode:c,...g}=n,{content:H,stream:w,...y}=g;return this.createResponse({body:y,headers:d||o,statusCode:c||s||200})}const m={...o,...e.headers},a=this.convertHeaders({...m,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control",...r.hash===void 0?{}:{[`X-Range-${r.hash?.algorithm.toUpperCase()}`]:r.hash?.value}}),h=e.headers||{};h.Location&&!a.location&&!a.Location?a.location=String(h.Location):h.location&&!a.location&&!a.Location?a.location=String(h.location):o.Location&&!a.location&&!a.Location?a.location=String(o.Location):o.location&&!a.location&&!a.Location&&(a.location=String(o.location));let i;return s>=200&&s<300&&(i=Object.keys(r).length>0?{...r}:{},"content"in i&&delete i.content,"stream"in i&&delete i.stream,Object.keys(i).length===0&&(i={})),this.createResponse({body:i,headers:a,statusCode:s||200})}convertHeaders(t){const e={};for(const[o,s]of Object.entries(t))e[o]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:o={},statusCode:s}=t;let r;return s===204?r=null:typeof e=="string"?r=e:e instanceof Buffer?r=new Uint8Array(e):e&&typeof e=="object"?(r=JSON.stringify(e),o["Content-Type"]||(o["Content-Type"]=u.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(r="{}",o["Content-Type"]||(o["Content-Type"]=u.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(r,{headers:this.convertHeaders(o),status:s})}async createErrorResponse(t){let e;C(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!R(t)&&!f.isHttpError(t)?e=this.storage.normalizeError(t):e={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(e);let o;return e.body?typeof e.body=="object"&&e.body!==null?o={body:e.body,headers:e.headers,statusCode:e.statusCode}:o={body:{error:{code:e.code||e.name||"Error",message:e.body||e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500}:o={body:{error:{code:e.code||e.name||"Error",message:e.message||"Unknown error",name:e.name||"Error"}},headers:e.headers,statusCode:e.statusCode||500},this.createResponse(o)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{A as C};
@@ -1 +1 @@
1
- import{paginate as H}from"@visulima/pagination";import{H as b,h as N,n as f}from"./headers-BAiAKekR.js";import T from"mime";import{ERRORS as g,isUploadError as L}from"./ERRORS-BIBxE2oR.js";import{match as z}from"path-to-regexp";import{d as O,c as M,s as S,e as w,u as R}from"./base-handler-core-EeV8gZck.js";import{i as j}from"./storage-Cyy73Y6r.js";import{waitForStorage as k}from"./waitForStorage-ByQmG4xF.js";import{PassThrough as $}from"node:stream";import{e as v}from"./response-builder-CbSA8qPa.js";const P=z(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),F=c=>{const e=P(c);if(!e)return;const{params:t}=e;if(!t.uuid)return;const s={uuid:t.uuid};return t.metadata!==void 0&&(s.metadata=t.metadata),t.path!==void 0&&(s.path=t.path),t.ext!==void 0&&(s.ext=t.ext),{params:s,path:e.path}},D=(c,e,t)=>{let s=0,r=0;const o=t-e+1;return new $({highWaterMark:Math.min(64*1024,o),transform(n,d,a){const h=n.length,i=s,p=i+h-1;if(s+=h,p<e){a();return}if(i>t){this.end(),a();return}const u=Math.max(0,e-i),y=Math.min(h,t-i+1);if(u<y){const C=n.subarray(u,y);r+=C.length,this.push(C)||c.pause()}r>=o&&(this.end(),c.destroy()),a()}})},_=(c,e,t)=>{let s=!1;const r=()=>{s||(s=!0,c.destroy())};e.on("drain",()=>{c.resume()}),e.on("close",r),e.on("finish",r),e.on("error",r),c.on("end",()=>{e.end()}),c.on("error",async o=>{s||(await t(e,o),r())}),c.on("data",o=>{e.write(o)||c.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",r)},I=(c,e,t)=>{const{headers:s,statusCode:r}=c;e(t,{headers:s,statusCode:r})},X=(c,e,t,s,r,o,n)=>{e.body=c?.data===void 0?c:c.data;const{headers:d,statusCode:a}=c,h=c;if(h.stream)if(typeof s=="function")s();else{const i=n(e.headers.range,h.size||0);o(t,h.stream,{headers:d,range:i||void 0,size:h.size,statusCode:a})}else{let i="";c.content!==void 0?i=c.content:typeof c=="object"&&"data"in c&&(i=c.data),typeof s=="function"?s():r(t,{body:i,headers:d,statusCode:a})}},q=async(c,e,t,s,r,o,n)=>{const{headers:d,statusCode:a,...h}=c;if(typeof s=="function")e._body=!0,e.body=h,s();else{const i=c,p=i.headers?{...i.headers}:{};i.headers===void 0&&(i.headers={}),i.statusCode===void 0&&(i.statusCode=200);try{const u=r.onComplete(h,i,e);u instanceof Promise&&await u}catch(u){throw o?.error&&o.error("[onComplete error]: %O",u),u}Object.keys(i.headers||{}).length===0&&Object.keys(p).length>0?i.headers=p:i.headers&&Object.keys(p).length>0&&(i.headers={...p,...i.headers}),n(e,t,i)}},G=(c,e,t,s)=>{const{headers:r,statusCode:o,...n}=c,d=r||{},a=d["X-Chunked-Upload"]==="true"||d["x-chunked-upload"]==="true";let h;const i={...v(d),...r?v(r):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};a&&(h=JSON.stringify(n),!i["Content-Type"]&&!i["content-type"]&&(i["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(h=""),s(t,{body:h,headers:i,statusCode:o||200})},W=async(c,e,t,s,r,o,n)=>{const d=c instanceof Error?c:new Error(String(c)),a={...O(d,["name",...Object.getOwnPropertyNames(d)]),request:O(e,["headers","method","url"])};s("error")>0&&t("error",a),r?.error&&r.error("[error]: %O",a),await o(n,d)},m="Content-Type";class x extends M{static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=async(e,t)=>this.upload(e,t);upload=async(e,t,s)=>{e.on("error",o=>this.logger?.error("[request error]: %O",o)),this.logger?.debug("[request]: %s %s",e.method,e.url);const r=this.registeredHandlers.get(e.method);if(!r){await this.sendError(t,{UploadErrorCode:g.METHOD_NOT_ALLOWED});return}try{await k(this.storage)}catch{await this.sendError(t,{UploadErrorCode:g.STORAGE_ERROR});return}try{const o=await r.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))I(o,this.send.bind(this),t);else if(e.method==="GET"){const n=o;n&&X(n,e,t,s,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:d,...a}=o;this.logger?.debug("[%s]: %s: %d/%d",a.status,a.name,a.bytesWritten,a.size),a.status!==void 0&&this.listenerCount(a.status)>0&&this.emit(a.status,{...a,request:O(e,["headers","method","url"])}),a.status==="completed"?await q(o,e,t,s,this.storage,this.logger,(h,i,p)=>{this.finish(h,i,p)}):G(o,e,t,(h,i)=>{this.send(h,{body:i.body,headers:i.headers,statusCode:i.statusCode})})}}catch(o){await W(o,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}};send(e,{body:t="",headers:s={},statusCode:r=200}){let o;const n={...s};if(typeof t=="string"){if(o=t,n[m]===void 0)n[m]=b.createContentType({mediaType:"text/plain"});else{const d=Array.isArray(n[m])?n[m].join(", "):String(n[m]);n[m]=b.ensureCharset(d)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?o=t:(o=JSON.stringify(t),n[m]||(n[m]=b.createContentType({charset:"utf8",mediaType:"application/json"})));S(e,n),e.statusCode=r,e.end(o)}async sendError(e,t){let s;L(t)?s=this.internalErrorResponses[t.UploadErrorCode]:!j(t)&&!N.isHttpError(t)?s=this.storage.normalizeError(t):s={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(s);let r;s.body?typeof s.body=="object"&&s.body!==null?r={body:s.body,headers:s.headers,statusCode:s.statusCode}:r={body:{error:{code:s.code||s.name||"Error",message:s.body||s.message||"Unknown error",name:s.name||"Error"}},headers:s.headers,statusCode:s.statusCode||500}:r={body:{error:{code:s.code||s.name||"Error",message:s.message||"Unknown error",name:s.name||"Error"}},headers:s.headers,statusCode:s.statusCode||500},this.send(e,r)}sendStream(e,t,{headers:s={},range:r,size:o,statusCode:n=200}){S(e,s),e.statusCode=n;let d=t;r&&o?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${r.start}-${r.end}/${o}`),e.setHeader("Content-Length",r.end-r.start+1),e.setHeader("Accept-Ranges","bytes"),d=D(t,r.start,r.end)):(o&&e.setHeader("Content-Length",o),e.setHeader("Accept-Ranges","bytes")),_(d,e,(a,h)=>this.sendError(a,h))}finish(e,t,s){const r="id"in s&&"headers"in s&&!("body"in s);let o,n,d;if(r){const a=s,h=a.headers||{},i=a.statusCode||200,{headers:p,statusCode:u,...y}=a;o=y,n={...h},d=i}else{const a=s;o=a.body,n=a.headers||{},d=a.statusCode||200}if(o&&typeof o=="object"&&o.content!==void 0){const{content:a,contentType:h}=o;o=a,n={...n,"Content-Type":h}}this.send(t,{body:o||s,headers:n,statusCode:d})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t,e.headers)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||x.methods).map(s=>s.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const s=F(w(e));if(s?.params.uuid){const{ext:r,metadata:o,uuid:n}=s.params,d=r?n.replace(new RegExp(String.raw`\.${r}$`),""):n;if(o==="metadata"&&w(e).endsWith("/metadata"))try{const a=await this.storage.getMeta(d);return{...a,content:JSON.stringify(a),headers:{"Content-Type":b.createContentType({charset:"utf8",mediaType:"application/json"}),...a.expiredAt===void 0?{}:{"X-Upload-Expires":a.expiredAt.toString()},...a.modifiedAt===void 0?{}:{"Last-Modified":a.modifiedAt.toString()}},statusCode:200}}catch(a){const h=a;throw h.UploadErrorCode===g.FILE_NOT_FOUND||h.UploadErrorCode===g.GONE?f(404,"File metadata not found"):a}if(!R.test(d))return this.list(e,t);try{const a=new URL(e.url||"","http://localhost"),h=Object.fromEntries(a.searchParams.entries());if(Object.keys(h).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const l=await this.mediaTransformer.handle(d,h);return{content:l.buffer,headers:{"Content-Length":String(l.size),"Content-Type":`${l.mediaType}/${l.format}`,"X-Media-Type":l.mediaType,"X-Original-Format":l.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":l.format,...l.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":l.originalFile.expiredAt.toString()},...l.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":l.originalFile.modifiedAt.toString()},...l.originalFile?.ETag===void 0?{}:{ETag:l.originalFile.ETag}},statusCode:200}}catch(l){if(l.name==="ValidationError")throw f(400,l.message);this.logger?.warn(`Media transformation failed: ${l.message}`)}const i=await this.storage.getMeta(d);if((e.headers.range||i.size&&i.size>1024*1024)&&this.storage.getStream)try{const l=await this.storage.getStream({id:d});let E=l.headers?.["Content-Type"]||i.contentType;return E.includes("image")&&typeof r=="string"&&(E=T.getType(r)||E),{headers:{...l.headers,"Accept-Ranges":"bytes","Content-Type":E},size:l.size,statusCode:200,stream:l.stream,...i,contentType:E}}catch(l){this.logger?.warn(`Streaming failed, falling back to buffer: ${l}`)}const p=await this.storage.get({id:d});let{contentType:u}=p;u.includes("image")&&typeof r=="string"&&(u=T.getType(r)||u);const{ETag:y,expiredAt:C,modifiedAt:U,size:A}=p;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(A),"Content-Type":u,...C===void 0?{}:{"X-Upload-Expires":C.toString()},...U===void 0?{}:{"Last-Modified":U.toString()},...y===void 0?{}:{ETag:y}},statusCode:200,...p,contentType:u}}catch(a){const h=a;throw h.UploadErrorCode===g.FILE_NOT_FOUND||h.UploadErrorCode===g.GONE?f(404,"File not found"):a}}return this.list(e,t)}async list(e,t){const s=new URL(e.url||"","http://localhost"),r=s.searchParams.get("limit"),o=s.searchParams.get("page"),n=await this.storage.list(Number(r||1e3));return n.length===0?{data:[],headers:{},statusCode:200}:o!==void 0&&r!==void 0?{data:H(Number(o),Number(r),n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const s=F(w(e));if(!s?.params.uuid||!R.test(s.params.uuid))throw f(404,"File not found");const{ext:r,uuid:o}=s.params;try{const n=await this.storage.getMeta(o);if(!this.storage.getStream){await this.sendError(t,f(501,"Streaming download not supported"));return}const d=await this.storage.getStream({id:o});let a=d.headers?.["Content-Type"]||n.contentType;a.includes("image")&&typeof r=="string"&&(a=T.getType(r)||a);const h=this.parseRangeHeader(e.headers.range,d.size||0),i={...d.headers,"Accept-Ranges":"bytes","Content-Disposition":b.createContentDisposition({filename:n.originalName||o,type:"attachment"}),"Content-Type":a};this.sendStream(t,d.stream,{headers:i,range:h||void 0,size:d.size,statusCode:h?206:200})}catch(n){const d=n;if(d.UploadErrorCode===g.FILE_NOT_FOUND||d.UploadErrorCode===g.GONE){await this.sendError(t,f(404,"File not found"));return}await this.sendError(t,n)}}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw f(404,"File not found")}}export{x as T};
1
+ import{paginate as H}from"@visulima/pagination";import{H as b,h as N,n as f}from"./headers-BAiAKekR.js";import T from"mime";import{ERRORS as g,isUploadError as L}from"./ERRORS-BIBxE2oR.js";import{match as z}from"path-to-regexp";import{d as O,c as M,s as S,e as w,u as R}from"./base-handler-core-D-9Ku1h-.js";import{i as j}from"./storage-0j5nCAUp.js";import{waitForStorage as k}from"./waitForStorage-ByQmG4xF.js";import{PassThrough as $}from"node:stream";import{e as v}from"./response-builder-CbSA8qPa.js";const P=z(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),F=c=>{const e=P(c);if(!e)return;const{params:t}=e;if(!t.uuid)return;const s={uuid:t.uuid};return t.metadata!==void 0&&(s.metadata=t.metadata),t.path!==void 0&&(s.path=t.path),t.ext!==void 0&&(s.ext=t.ext),{params:s,path:e.path}},D=(c,e,t)=>{let s=0,r=0;const o=t-e+1;return new $({highWaterMark:Math.min(64*1024,o),transform(n,d,a){const h=n.length,i=s,p=i+h-1;if(s+=h,p<e){a();return}if(i>t){this.end(),a();return}const u=Math.max(0,e-i),y=Math.min(h,t-i+1);if(u<y){const C=n.subarray(u,y);r+=C.length,this.push(C)||c.pause()}r>=o&&(this.end(),c.destroy()),a()}})},_=(c,e,t)=>{let s=!1;const r=()=>{s||(s=!0,c.destroy())};e.on("drain",()=>{c.resume()}),e.on("close",r),e.on("finish",r),e.on("error",r),c.on("end",()=>{e.end()}),c.on("error",async o=>{s||(await t(e,o),r())}),c.on("data",o=>{e.write(o)||c.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",r)},I=(c,e,t)=>{const{headers:s,statusCode:r}=c;e(t,{headers:s,statusCode:r})},X=(c,e,t,s,r,o,n)=>{e.body=c?.data===void 0?c:c.data;const{headers:d,statusCode:a}=c,h=c;if(h.stream)if(typeof s=="function")s();else{const i=n(e.headers.range,h.size||0);o(t,h.stream,{headers:d,range:i||void 0,size:h.size,statusCode:a})}else{let i="";c.content!==void 0?i=c.content:typeof c=="object"&&"data"in c&&(i=c.data),typeof s=="function"?s():r(t,{body:i,headers:d,statusCode:a})}},q=async(c,e,t,s,r,o,n)=>{const{headers:d,statusCode:a,...h}=c;if(typeof s=="function")e._body=!0,e.body=h,s();else{const i=c,p=i.headers?{...i.headers}:{};i.headers===void 0&&(i.headers={}),i.statusCode===void 0&&(i.statusCode=200);try{const u=r.onComplete(h,i,e);u instanceof Promise&&await u}catch(u){throw o?.error&&o.error("[onComplete error]: %O",u),u}Object.keys(i.headers||{}).length===0&&Object.keys(p).length>0?i.headers=p:i.headers&&Object.keys(p).length>0&&(i.headers={...p,...i.headers}),n(e,t,i)}},G=(c,e,t,s)=>{const{headers:r,statusCode:o,...n}=c,d=r||{},a=d["X-Chunked-Upload"]==="true"||d["x-chunked-upload"]==="true";let h;const i={...v(d),...r?v(r):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};a&&(h=JSON.stringify(n),!i["Content-Type"]&&!i["content-type"]&&(i["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(h=""),s(t,{body:h,headers:i,statusCode:o||200})},W=async(c,e,t,s,r,o,n)=>{const d=c instanceof Error?c:new Error(String(c)),a={...O(d,["name",...Object.getOwnPropertyNames(d)]),request:O(e,["headers","method","url"])};s("error")>0&&t("error",a),r?.error&&r.error("[error]: %O",a),await o(n,d)},m="Content-Type";class x extends M{static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=async(e,t)=>this.upload(e,t);upload=async(e,t,s)=>{e.on("error",o=>this.logger?.error("[request error]: %O",o)),this.logger?.debug("[request]: %s %s",e.method,e.url);const r=this.registeredHandlers.get(e.method);if(!r){await this.sendError(t,{UploadErrorCode:g.METHOD_NOT_ALLOWED});return}try{await k(this.storage)}catch{await this.sendError(t,{UploadErrorCode:g.STORAGE_ERROR});return}try{const o=await r.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))I(o,this.send.bind(this),t);else if(e.method==="GET"){const n=o;n&&X(n,e,t,s,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:d,...a}=o;this.logger?.debug("[%s]: %s: %d/%d",a.status,a.name,a.bytesWritten,a.size),a.status!==void 0&&this.listenerCount(a.status)>0&&this.emit(a.status,{...a,request:O(e,["headers","method","url"])}),a.status==="completed"?await q(o,e,t,s,this.storage,this.logger,(h,i,p)=>{this.finish(h,i,p)}):G(o,e,t,(h,i)=>{this.send(h,{body:i.body,headers:i.headers,statusCode:i.statusCode})})}}catch(o){await W(o,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}};send(e,{body:t="",headers:s={},statusCode:r=200}){let o;const n={...s};if(typeof t=="string"){if(o=t,n[m]===void 0)n[m]=b.createContentType({mediaType:"text/plain"});else{const d=Array.isArray(n[m])?n[m].join(", "):String(n[m]);n[m]=b.ensureCharset(d)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?o=t:(o=JSON.stringify(t),n[m]||(n[m]=b.createContentType({charset:"utf8",mediaType:"application/json"})));S(e,n),e.statusCode=r,e.end(o)}async sendError(e,t){let s;L(t)?s=this.internalErrorResponses[t.UploadErrorCode]:!j(t)&&!N.isHttpError(t)?s=this.storage.normalizeError(t):s={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(s);let r;s.body?typeof s.body=="object"&&s.body!==null?r={body:s.body,headers:s.headers,statusCode:s.statusCode}:r={body:{error:{code:s.code||s.name||"Error",message:s.body||s.message||"Unknown error",name:s.name||"Error"}},headers:s.headers,statusCode:s.statusCode||500}:r={body:{error:{code:s.code||s.name||"Error",message:s.message||"Unknown error",name:s.name||"Error"}},headers:s.headers,statusCode:s.statusCode||500},this.send(e,r)}sendStream(e,t,{headers:s={},range:r,size:o,statusCode:n=200}){S(e,s),e.statusCode=n;let d=t;r&&o?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${r.start}-${r.end}/${o}`),e.setHeader("Content-Length",r.end-r.start+1),e.setHeader("Accept-Ranges","bytes"),d=D(t,r.start,r.end)):(o&&e.setHeader("Content-Length",o),e.setHeader("Accept-Ranges","bytes")),_(d,e,(a,h)=>this.sendError(a,h))}finish(e,t,s){const r="id"in s&&"headers"in s&&!("body"in s);let o,n,d;if(r){const a=s,h=a.headers||{},i=a.statusCode||200,{headers:p,statusCode:u,...y}=a;o=y,n={...h},d=i}else{const a=s;o=a.body,n=a.headers||{},d=a.statusCode||200}if(o&&typeof o=="object"&&o.content!==void 0){const{content:a,contentType:h}=o;o=a,n={...n,"Content-Type":h}}this.send(t,{body:o||s,headers:n,statusCode:d})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t,e.headers)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||x.methods).map(s=>s.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const s=F(w(e));if(s?.params.uuid){const{ext:r,metadata:o,uuid:n}=s.params,d=r?n.replace(new RegExp(String.raw`\.${r}$`),""):n;if(o==="metadata"&&w(e).endsWith("/metadata"))try{const a=await this.storage.getMeta(d);return{...a,content:JSON.stringify(a),headers:{"Content-Type":b.createContentType({charset:"utf8",mediaType:"application/json"}),...a.expiredAt===void 0?{}:{"X-Upload-Expires":a.expiredAt.toString()},...a.modifiedAt===void 0?{}:{"Last-Modified":a.modifiedAt.toString()}},statusCode:200}}catch(a){const h=a;throw h.UploadErrorCode===g.FILE_NOT_FOUND||h.UploadErrorCode===g.GONE?f(404,"File metadata not found"):a}if(!R.test(d))return this.list(e,t);try{const a=new URL(e.url||"","http://localhost"),h=Object.fromEntries(a.searchParams.entries());if(Object.keys(h).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const l=await this.mediaTransformer.handle(d,h);return{content:l.buffer,headers:{"Content-Length":String(l.size),"Content-Type":`${l.mediaType}/${l.format}`,"X-Media-Type":l.mediaType,"X-Original-Format":l.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":l.format,...l.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":l.originalFile.expiredAt.toString()},...l.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":l.originalFile.modifiedAt.toString()},...l.originalFile?.ETag===void 0?{}:{ETag:l.originalFile.ETag}},statusCode:200}}catch(l){if(l.name==="ValidationError")throw f(400,l.message);this.logger?.warn(`Media transformation failed: ${l.message}`)}const i=await this.storage.getMeta(d);if((e.headers.range||i.size&&i.size>1024*1024)&&this.storage.getStream)try{const l=await this.storage.getStream({id:d});let E=l.headers?.["Content-Type"]||i.contentType;return E.includes("image")&&typeof r=="string"&&(E=T.getType(r)||E),{headers:{...l.headers,"Accept-Ranges":"bytes","Content-Type":E},size:l.size,statusCode:200,stream:l.stream,...i,contentType:E}}catch(l){this.logger?.warn(`Streaming failed, falling back to buffer: ${l}`)}const p=await this.storage.get({id:d});let{contentType:u}=p;u.includes("image")&&typeof r=="string"&&(u=T.getType(r)||u);const{ETag:y,expiredAt:C,modifiedAt:U,size:A}=p;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(A),"Content-Type":u,...C===void 0?{}:{"X-Upload-Expires":C.toString()},...U===void 0?{}:{"Last-Modified":U.toString()},...y===void 0?{}:{ETag:y}},statusCode:200,...p,contentType:u}}catch(a){const h=a;throw h.UploadErrorCode===g.FILE_NOT_FOUND||h.UploadErrorCode===g.GONE?f(404,"File not found"):a}}return this.list(e,t)}async list(e,t){const s=new URL(e.url||"","http://localhost"),r=s.searchParams.get("limit"),o=s.searchParams.get("page"),n=await this.storage.list(Number(r||1e3));return n.length===0?{data:[],headers:{},statusCode:200}:o!==void 0&&r!==void 0?{data:H(Number(o),Number(r),n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const s=F(w(e));if(!s?.params.uuid||!R.test(s.params.uuid))throw f(404,"File not found");const{ext:r,uuid:o}=s.params;try{const n=await this.storage.getMeta(o);if(!this.storage.getStream){await this.sendError(t,f(501,"Streaming download not supported"));return}const d=await this.storage.getStream({id:o});let a=d.headers?.["Content-Type"]||n.contentType;a.includes("image")&&typeof r=="string"&&(a=T.getType(r)||a);const h=this.parseRangeHeader(e.headers.range,d.size||0),i={...d.headers,"Accept-Ranges":"bytes","Content-Disposition":b.createContentDisposition({filename:n.originalName||o,type:"attachment"}),"Content-Type":a};this.sendStream(t,d.stream,{headers:i,range:h||void 0,size:d.size,statusCode:h?206:200})}catch(n){const d=n;if(d.UploadErrorCode===g.FILE_NOT_FOUND||d.UploadErrorCode===g.GONE){await this.sendError(t,f(404,"File not found"));return}await this.sendError(t,n)}}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw f(404,"File not found")}}export{x as T};
@@ -1 +1 @@
1
- import{createReadStream as _,createWriteStream as C}from"node:fs";import{truncate as P,stat as F,open as L,copyFile as A}from"node:fs/promises";import{PassThrough as W,Transform as x,pipeline as U}from"node:stream";import{y as D,d as I,z as B,l as M,V,x as Q,f as H}from"./local-meta-storage-C2T92TYb.js";import{A as G,m as K}from"./path-0oTTdkvl-BVg7lYf5.js";import{F as X}from"./index-nZWCQrSe.js";import{d as Y}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as g,ERRORS as h,isUploadError as q}from"./ERRORS-BIBxE2oR.js";import{createHash as j}from"node:crypto";import{B as J,a as Z,c as $}from"./storage-Cyy73Y6r.js";import tt from"./File-W8aOo15X.js";import{t as k}from"./get-file-status-y3wTtDQs.js";import{t as et}from"./update-size-DuNuLyxj.js";import{i as rt}from"./part-match-D-9dGX42.js";import{e as it}from"./has-content-50BsqrWw.js";class st extends x{constructor(t,e,r="base64"){super(),this.checksum=t,this.algorithm=e,this.encoding=r,this.hash=j(e)}checksum;algorithm;encoding;length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(t,e,r){this.push(t),this.hash.update(t),this.length+=t.length,r()}_flush(t){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?t(new Error("Checksum mismatch")):t()}}const at=(S,t,e="base64")=>t?new st(S,t,e):new W;class nt extends x{constructor(t=Number.POSITIVE_INFINITY){super(),this.limit=t}limit;length=0;_transform(t,e,r){const a=this.length+t.length;this.limit>=a?(this.push(t),this.length=a,r()):r(new Error("Stream length limit exceeded"))}}class w extends J{static name="disk";checksumTypes=["md5","sha1"];supportsRange=!0;get raw(){return{directory:this.directory}}directory;meta;constructor(t){const e={...t,fileNameValidation:t.fileNameValidation??Z};if(super(e),this.directory=e.directory,e.metaStorage)this.meta=e.metaStorage;else{const r={...e,...e.metaStorageConfig,logger:this.logger};this.meta=new D(r)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(r=>{this.logger?.error("Storage access check failed: %O",r)})}normalizeError(t){return super.normalizeError(t)}async create(t){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const i=typeof t.ttl=="string"?$(t.ttl):t.ttl;i!==void 0&&(e.expiredAt=Date.now()+i)}e.size!==void 0&&Number(e.size)<0&&g(h.REQUEST_ENTITY_TOO_LARGE,"Request entity too large");const r=new tt(e);try{const i=await this.getMeta(r.id);if(i.status==="completed")return i}catch{}r.name=this.namingFunction(r),(r.size===void 0||Number.isNaN(r.size))&&(r.size===void 0||(r.size=this.maxUploadSize)),await this.validate(r);const a=this.getFilePath(r.name);try{await I(a),r.bytesWritten=0}catch(i){const s=this.normalizeError(i instanceof Error?i:new Error(String(i)));await this.onError(s),g(h.FILE_ERROR,s.message)}return r.status=k(r),await this.saveMeta(r),await this.onCreate(r),r})}async write(t){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&&et(e,t.size),!rt(t,e))return g(h.FILE_CONFLICT);const r=this.getFilePath(e.name),a=await this.lock(r);try{const i=t.start||0;if(await I(r),e.bytesWritten===0&&(e.bytesWritten=i),it(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return g(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:u,stream:d}=await Y(t.body);u?.mime&&(e.contentType=u.mime),t.body=d}catch{}const s=t.signal,o={...e,...t,body:t.body};s&&(o.signal=s);const[n,m]=await this.lazyWrite(o);if(m)return await P(r,e.bytesWritten),g(m);const l=i+(t.contentLength||0);e.bytesWritten=Math.max(e.bytesWritten||0,l),e.bytesWritten=Math.max(e.bytesWritten||0,n),e.status=k(e),await this.saveMeta(e)}else await I(r),e.bytesWritten=0;return e}catch(i){if(q(i))throw i;const s=this.normalizeError(i instanceof Error?i:new Error(String(i)));return await this.onError(s),g(h.FILE_ERROR,(typeof s.message=="string"?s.message:String(i))||String(i))}finally{await this.unlock(r,a)}})}async get({id:t},e){return this.instrumentOperation("get",async()=>{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:a,contentType:i,expiredAt:s,metadata:o,modifiedAt:n,name:m,originalName:l,size:u}=r,d=this.getFilePath(m),E=e?.range,b=async c=>{const y=c;if(y.code==="ENOENT"||y.code==="EPERM"){const p=this.normalizeError(c instanceof Error?c:new Error(y.message||String(c)));return await this.onError(p),g(h.FILE_NOT_FOUND,(typeof p.message=="string"?p.message:String(c))||String(c))}const f=this.normalizeError(c instanceof Error?c:new Error(String(c)));throw await this.onError(f),c};if(E){let c;try{c=await F(d)}catch(R){return b(R)}const y=c.size,f=Math.max(0,E.start),p=E.end===void 0?y-1:Math.min(y-1,E.end);if(f>p||f>=y)return g(h.BAD_REQUEST,`Invalid range ${f}-${E.end??""}`);const N=p-f+1,z=Buffer.allocUnsafe(N);let O;try{O=await L(d,"r"),await O.read(z,0,N,f)}catch(R){return b(R)}finally{await O?.close()}const v=`W/"${y.toString(16)}-${Math.trunc(c.mtimeMs).toString(16)}-${f}-${p}"`;return{content:z,contentType:i,ETag:v,expiredAt:s,id:t,metadata:o,modifiedAt:n,name:m,originalName:l,size:N}}let T;try{T=await B(d,{buffer:!0})}catch(c){return b(c)}return{content:T,contentType:i,ETag:X(T),expiredAt:s,id:t,metadata:o,modifiedAt:n,name:m,originalName:l,size:u||a}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{const e=await this.getMeta(t),r=this.getFilePath(e.name);return await F(r),!0}catch{return!1}})}async getStream({id:t}){return this.instrumentOperation("getStream",async()=>{try{const e=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:r,contentType:a,expiredAt:i,modifiedAt:s,name:o,size:n}=e,m=_(this.getFilePath(o));return{headers:{"Content-Length":String(n||r),"Content-Type":a,...i&&{"X-Upload-Expires":i.toString()},...s&&{"Last-Modified":s.toString()}},size:n||r,stream:m}}catch(e){const r=this.normalizeError(e instanceof Error?e:new Error(String(e)));throw await this.onError(r),g(h.FILE_NOT_FOUND,(typeof r.message=="string"?r.message:String(e))||String(e))}})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);await M(this.getFilePath(e.name)),await this.deleteMeta(t);const r={...e,status:"deleted"};return await this.onDelete(r),r})}async copy(t,e){return this.instrumentOperation("copy",async()=>{w.assertSafeId(t),w.assertSafeId(e);const r=await this.getMeta(t);return await A(this.getFilePath(r.name),this.getFilePath(e)),{...r,name:e}})}async move(t,e){return this.instrumentOperation("move",async()=>{w.assertSafeId(t),w.assertSafeId(e);const r=await this.getMeta(t),a=this.getFilePath(r.name),i=this.getFilePath(e);try{await V(a,i)}catch(s){if(s?.code==="EXDEV")await A(a,i),await M(a);else{const o=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(o),s}}return{...r,id:r.id,name:e}})}async list(){return this.instrumentOperation("list",async()=>{const t={followSymlinks:!1,includeDirs:!1,includeFiles:!0,skip:["*.META$"]},e=[],{directory:r}=this,a=s=>s.replaceAll("\\","/"),i=a(r);for await(const s of Q(r,t)){const{suffix:o}=this.meta,{path:n}=s;if(!n.includes(o)){const{birthtime:m,ctime:l,mtime:u}=await F(n),d=a(n),E=d.startsWith(i)?d.slice(i.length):d;e.push({createdAt:m||l,id:E,modifiedAt:u})}}return e})}getFilePath(t){return w.assertSafeId(t),G(t)&&g(h.INVALID_FILE_NAME,`Invalid file id: "${t}"`),K(this.directory,t)}lazyWrite(t){return new Promise((e,r)=>{const a=C(this.getFilePath(t.name),{flags:"r+",start:t.start}),i=new nt(t.contentLength||t.size-t.start),s=at(t.checksum,t.checksumAlgorithm),o=!t.checksum,{signal:n}=t,m=()=>{a.close(),i.destroy(),s.destroy()},l=d=>{m(),e([Number.NaN,d])};if(i.on("error",()=>{l(h.FILE_CONFLICT)}),s.on("error",()=>{l(h.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{l(o?void 0:h.REQUEST_ABORTED)}),t.body.on("error",d=>{m(),r(d)}),n?.aborted){l(o?void 0:h.REQUEST_ABORTED);return}let u;n&&(u=()=>{m(),a.destroy(),i.destroy(),s.destroy(),t.body.destroy(),e([Number.NaN,o?void 0:h.REQUEST_ABORTED])},n.addEventListener("abort",u,{once:!0})),U(t.body,i,s,a,d=>{if(n&&u&&n.removeEventListener("abort",u),d){if(m(),n?.aborted){e([Number.NaN,o?void 0:h.REQUEST_ABORTED]);return}e([Number.NaN,h.FILE_ERROR]);return}e([t.start+a.bytesWritten])})})}async accessCheck(){await H(this.directory)}}export{w as F,nt as n,at as s};
1
+ import{createReadStream as _,createWriteStream as C}from"node:fs";import{truncate as P,stat as F,open as L,copyFile as A}from"node:fs/promises";import{PassThrough as W,Transform as x,pipeline as U}from"node:stream";import{y as D,d as I,z as B,l as M,V,x as Q,f as H}from"./local-meta-storage-iuJnu90B.js";import{A as G,m as K}from"./path-0oTTdkvl-DvWvbDbh.js";import{F as X}from"./index-nZWCQrSe.js";import{d as Y}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as g,ERRORS as h,isUploadError as q}from"./ERRORS-BIBxE2oR.js";import{createHash as j}from"node:crypto";import{B as J,a as Z,c as $}from"./storage-0j5nCAUp.js";import tt from"./File-W8aOo15X.js";import{t as k}from"./get-file-status-y3wTtDQs.js";import{t as et}from"./update-size-DuNuLyxj.js";import{i as rt}from"./part-match-D-9dGX42.js";import{e as it}from"./has-content-50BsqrWw.js";class st extends x{constructor(t,e,r="base64"){super(),this.checksum=t,this.algorithm=e,this.encoding=r,this.hash=j(e)}checksum;algorithm;encoding;length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(t,e,r){this.push(t),this.hash.update(t),this.length+=t.length,r()}_flush(t){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?t(new Error("Checksum mismatch")):t()}}const at=(S,t,e="base64")=>t?new st(S,t,e):new W;class nt extends x{constructor(t=Number.POSITIVE_INFINITY){super(),this.limit=t}limit;length=0;_transform(t,e,r){const a=this.length+t.length;this.limit>=a?(this.push(t),this.length=a,r()):r(new Error("Stream length limit exceeded"))}}class w extends J{static name="disk";checksumTypes=["md5","sha1"];supportsRange=!0;get raw(){return{directory:this.directory}}directory;meta;constructor(t){const e={...t,fileNameValidation:t.fileNameValidation??Z};if(super(e),this.directory=e.directory,e.metaStorage)this.meta=e.metaStorage;else{const r={...e,...e.metaStorageConfig,logger:this.logger};this.meta=new D(r)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(r=>{this.logger?.error("Storage access check failed: %O",r)})}normalizeError(t){return super.normalizeError(t)}async create(t){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const i=typeof t.ttl=="string"?$(t.ttl):t.ttl;i!==void 0&&(e.expiredAt=Date.now()+i)}e.size!==void 0&&Number(e.size)<0&&g(h.REQUEST_ENTITY_TOO_LARGE,"Request entity too large");const r=new tt(e);try{const i=await this.getMeta(r.id);if(i.status==="completed")return i}catch{}r.name=this.namingFunction(r),(r.size===void 0||Number.isNaN(r.size))&&(r.size===void 0||(r.size=this.maxUploadSize)),await this.validate(r);const a=this.getFilePath(r.name);try{await I(a),r.bytesWritten=0}catch(i){const s=this.normalizeError(i instanceof Error?i:new Error(String(i)));await this.onError(s),g(h.FILE_ERROR,s.message)}return r.status=k(r),await this.saveMeta(r),await this.onCreate(r),r})}async write(t){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&&et(e,t.size),!rt(t,e))return g(h.FILE_CONFLICT);const r=this.getFilePath(e.name),a=await this.lock(r);try{const i=t.start||0;if(await I(r),e.bytesWritten===0&&(e.bytesWritten=i),it(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return g(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:u,stream:d}=await Y(t.body);u?.mime&&(e.contentType=u.mime),t.body=d}catch{}const s=t.signal,o={...e,...t,body:t.body};s&&(o.signal=s);const[n,m]=await this.lazyWrite(o);if(m)return await P(r,e.bytesWritten),g(m);const l=i+(t.contentLength||0);e.bytesWritten=Math.max(e.bytesWritten||0,l),e.bytesWritten=Math.max(e.bytesWritten||0,n),e.status=k(e),await this.saveMeta(e)}else await I(r),e.bytesWritten=0;return e}catch(i){if(q(i))throw i;const s=this.normalizeError(i instanceof Error?i:new Error(String(i)));return await this.onError(s),g(h.FILE_ERROR,(typeof s.message=="string"?s.message:String(i))||String(i))}finally{await this.unlock(r,a)}})}async get({id:t},e){return this.instrumentOperation("get",async()=>{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:a,contentType:i,expiredAt:s,metadata:o,modifiedAt:n,name:m,originalName:l,size:u}=r,d=this.getFilePath(m),E=e?.range,b=async c=>{const y=c;if(y.code==="ENOENT"||y.code==="EPERM"){const p=this.normalizeError(c instanceof Error?c:new Error(y.message||String(c)));return await this.onError(p),g(h.FILE_NOT_FOUND,(typeof p.message=="string"?p.message:String(c))||String(c))}const f=this.normalizeError(c instanceof Error?c:new Error(String(c)));throw await this.onError(f),c};if(E){let c;try{c=await F(d)}catch(R){return b(R)}const y=c.size,f=Math.max(0,E.start),p=E.end===void 0?y-1:Math.min(y-1,E.end);if(f>p||f>=y)return g(h.BAD_REQUEST,`Invalid range ${f}-${E.end??""}`);const N=p-f+1,z=Buffer.allocUnsafe(N);let O;try{O=await L(d,"r"),await O.read(z,0,N,f)}catch(R){return b(R)}finally{await O?.close()}const v=`W/"${y.toString(16)}-${Math.trunc(c.mtimeMs).toString(16)}-${f}-${p}"`;return{content:z,contentType:i,ETag:v,expiredAt:s,id:t,metadata:o,modifiedAt:n,name:m,originalName:l,size:N}}let T;try{T=await B(d,{buffer:!0})}catch(c){return b(c)}return{content:T,contentType:i,ETag:X(T),expiredAt:s,id:t,metadata:o,modifiedAt:n,name:m,originalName:l,size:u||a}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{const e=await this.getMeta(t),r=this.getFilePath(e.name);return await F(r),!0}catch{return!1}})}async getStream({id:t}){return this.instrumentOperation("getStream",async()=>{try{const e=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:r,contentType:a,expiredAt:i,modifiedAt:s,name:o,size:n}=e,m=_(this.getFilePath(o));return{headers:{"Content-Length":String(n||r),"Content-Type":a,...i&&{"X-Upload-Expires":i.toString()},...s&&{"Last-Modified":s.toString()}},size:n||r,stream:m}}catch(e){const r=this.normalizeError(e instanceof Error?e:new Error(String(e)));throw await this.onError(r),g(h.FILE_NOT_FOUND,(typeof r.message=="string"?r.message:String(e))||String(e))}})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);await M(this.getFilePath(e.name)),await this.deleteMeta(t);const r={...e,status:"deleted"};return await this.onDelete(r),r})}async copy(t,e){return this.instrumentOperation("copy",async()=>{w.assertSafeId(t),w.assertSafeId(e);const r=await this.getMeta(t);return await A(this.getFilePath(r.name),this.getFilePath(e)),{...r,name:e}})}async move(t,e){return this.instrumentOperation("move",async()=>{w.assertSafeId(t),w.assertSafeId(e);const r=await this.getMeta(t),a=this.getFilePath(r.name),i=this.getFilePath(e);try{await V(a,i)}catch(s){if(s?.code==="EXDEV")await A(a,i),await M(a);else{const o=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(o),s}}return{...r,id:r.id,name:e}})}async list(){return this.instrumentOperation("list",async()=>{const t={followSymlinks:!1,includeDirs:!1,includeFiles:!0,skip:["*.META$"]},e=[],{directory:r}=this,a=s=>s.replaceAll("\\","/"),i=a(r);for await(const s of Q(r,t)){const{suffix:o}=this.meta,{path:n}=s;if(!n.includes(o)){const{birthtime:m,ctime:l,mtime:u}=await F(n),d=a(n),E=d.startsWith(i)?d.slice(i.length):d;e.push({createdAt:m||l,id:E,modifiedAt:u})}}return e})}getFilePath(t){return w.assertSafeId(t),G(t)&&g(h.INVALID_FILE_NAME,`Invalid file id: "${t}"`),K(this.directory,t)}lazyWrite(t){return new Promise((e,r)=>{const a=C(this.getFilePath(t.name),{flags:"r+",start:t.start}),i=new nt(t.contentLength||t.size-t.start),s=at(t.checksum,t.checksumAlgorithm),o=!t.checksum,{signal:n}=t,m=()=>{a.close(),i.destroy(),s.destroy()},l=d=>{m(),e([Number.NaN,d])};if(i.on("error",()=>{l(h.FILE_CONFLICT)}),s.on("error",()=>{l(h.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{l(o?void 0:h.REQUEST_ABORTED)}),t.body.on("error",d=>{m(),r(d)}),n?.aborted){l(o?void 0:h.REQUEST_ABORTED);return}let u;n&&(u=()=>{m(),a.destroy(),i.destroy(),s.destroy(),t.body.destroy(),e([Number.NaN,o?void 0:h.REQUEST_ABORTED])},n.addEventListener("abort",u,{once:!0})),U(t.body,i,s,a,d=>{if(n&&u&&n.removeEventListener("abort",u),d){if(m(),n?.aborted){e([Number.NaN,o?void 0:h.REQUEST_ABORTED]);return}e([Number.NaN,h.FILE_ERROR]);return}e([t.start+a.bytesWritten])})})}async accessCheck(){await H(this.directory)}}export{w as F,nt as n,at as s};
@@ -0,0 +1 @@
1
+ import{randomUUID as p}from"node:crypto";import{request as l}from"gaxios";import{GoogleAuth as g}from"google-auth-library";import y from"./MetaStorage-DPEUyWgN.js";import{stringifyMetadata as f,parseMetadata as C}from"./Metadata-B7CcBueg.js";import a from"./GCSConfig-BQ0OpVhe.js";import{e as R}from"./has-content-50BsqrWw.js";var v="@visulima/storage",E="1.0.0";const n={name:v,version:E},b=r=>{const t=r.match(/(\d+)-(\d+)/),e=t?.[2]?+t[2]:0;return e>0?e+1:0},q=r=>{if(R(r)){const t=r.contentLength?r.start+r.contentLength-1:"*";return`bytes ${r.start}-${t}/${r.size??"*"}`}return`bytes */${r.size??"*"}`},I=r=>{if(r.response!==void 0){const{response:t}=r;return t?.data?.error?.errors?.map(({reason:e=""})=>e==="rateLimitExceeded"||e==="userRateLimitExceeded"?!0:!!(e&&e.includes("EAI_AGAIN"))).includes(!0)}return!1},A={retry:3,shouldRetry:I,statusCodesToRetry:[[408,429,500,502,503,504],[100,199],[429],[500,599]]};class M extends y{constructor(t){super(t),this.config=t;const{authClient:e,...s}=t,o=s.bucket||process.env.GCS_BUCKET;if(e===void 0){if(!o)throw new Error("GCS bucket is not defined");if(!s.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");s.scopes||=a.authScopes,this.authClient=new g(s)}else this.authClient=e;this.storageBaseURI=`${s.storageAPI||a.storageAPI}/${o}/o`,this.uploadBaseURI=`${s.uploadAPI||a.uploadAPI}/${o}/o`;const u=["storage.googleapis.com"],c=new URL(this.storageBaseURI).hostname;this.isCustomEndpoint=!u.includes(c);const{retryOptions:h,useAuthWithCustomEndpoint:d,userProject:m}=t;this.userProject=m,this.useAuthWithCustomEndpoint=d||!1,this.retryOptions={...A,...h},e===void 0&&this.accessCheck().catch(i=>{throw i.code==="404"?new Error(`Bucket ${o} does not exist`):i})}config;authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;async save(t,e){const s={...e};return s.metadata&&(s.metadata=f(e.metadata)),await this.makeRequest({body:JSON.stringify(s),headers:{"Content-Type":"application/json; charset=utf-8"},method:"POST",params:{name:encodeURIComponent(this.getMetaName(t)),uploadType:"media"},url:this.uploadBaseURI}),e}async delete(t){const e=this.getMetaPath(t);await this.makeRequest({method:"DELETE",url:e})}async get(t){const e=this.getMetaPath(t),{data:s}=await this.makeRequest({params:{alt:"media"},url:e});return s.metadata&&typeof s.metadata=="string"&&(s.metadata=C(s.metadata)),s}async touch(t,e){return this.save(t,e)}async accessCheck(){return this.makeRequest({url:this.storageBaseURI.replace("/o","")})}getMetaPath(t){return`${this.storageBaseURI}/${this.getMetaName(t)}`}async makeRequest(t){return typeof t.url=="string"&&(t.url=t.url.replaceAll("/:",":")),t={...t,headers:{"User-Agent":`${n.name}/${n.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${n.version} gccl-invocation-id/${p()}`},params:{...this.userProject===void 0?{}:{userProject:this.userProject}},retry:!0,retryConfig:this.retryOptions,timeout:6e4},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?l(t):this.authClient.request(t)}}export{q as b,b as g,n as m,A as r,M as v};
@@ -0,0 +1,11 @@
1
+ import{utimes as tr}from"node:fs/promises";import{tmpdir as rr}from"node:os";import{createRequire as C}from"node:module";import{v as or,H as ge,B as mt,m as Ut,W as yt,J as sr}from"./path-0oTTdkvl-DvWvbDbh.js";import{throwErrorCode as nt,ERRORS as it}from"./ERRORS-BIBxE2oR.js";import nr from"./MetaStorage-DPEUyWgN.js";import{stringifyMetadata as ir,parseMetadata as ur}from"./Metadata-B7CcBueg.js";const Xt=0,ar=C(import.meta.url),be=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,lr=t=>{if(typeof be<"u"&&be.versions&&be.versions.node){const[e,r]=be.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return be.getBuiltinModule(t)}return ar(t)},{fileURLToPath:pr}=lr("node:url");function cr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Tt,xt;function fr(){return xt||(xt=1,Tt=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cr3","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Tt}var dr=fr();const gr=cr(dr);new Set(gr);const ye=t=>or(t instanceof URL?pr(t):t);let hr=class extends Error{constructor(e){super(`EEXIST: ${e}`)}get code(){return"EEXIST"}set code(e){throw new Error("Cannot overwrite code EEXIST")}get name(){return"AlreadyExistsError"}set name(e){throw new Error("Cannot overwrite name of AlreadyExistsError")}};const he=t=>{if(!t||!(t instanceof URL)&&typeof t!="string")throw new TypeError("Path must be a non-empty string or URL.")},mr=C(import.meta.url),$e=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,yr=t=>{if(typeof $e<"u"&&$e.versions&&$e.versions.node){const[e,r]=$e.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return $e.getBuiltinModule(t)}return mr(t)};yr("node:fs/promises");const br=C(import.meta.url),ve=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,$r=t=>{if(typeof ve<"u"&&ve.versions&&ve.versions.node){const[e,r]=ve.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return ve.getBuiltinModule(t)}return br(t)};$r("node:fs");const bt=t=>{if(t.isFile())return"file";if(t.isDirectory())return"dir";if(t.isSymbolicLink())return"symlink"},vr=C(import.meta.url),Ee=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Er=t=>{if(typeof Ee<"u"&&Ee.versions&&Ee.versions.node){const[e,r]=Ee.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Ee.getBuiltinModule(t)}return vr(t)},{lstat:wt,mkdir:Ar}=Er("node:fs/promises"),zt=async t=>{he(t);try{const e=await wt(t);if(!e.isDirectory())throw new Error(`Ensure path exists, expected 'dir', got '${String(bt(e))}'`);return}catch(e){if(e.code!=="ENOENT")throw e}try{await Ar(t,{recursive:!0})}catch(e){if(e.code!=="EEXIST")throw e;const r=await wt(t);if(!r.isDirectory())throw new Error(`Ensure path exists, expected 'dir', got '${String(bt(r))}'`,{cause:e})}},Rr=C(import.meta.url),Ae=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Tr=t=>{if(typeof Ae<"u"&&Ae.versions&&Ae.versions.node){const[e,r]=Ae.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Ae.getBuiltinModule(t)}return Rr(t)};Tr("node:fs");const xr=C(import.meta.url),Re=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,wr=t=>{if(typeof Re<"u"&&Re.versions&&Re.versions.node){const[e,r]=Re.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Re.getBuiltinModule(t)}return xr(t)},{lstat:_r,writeFile:Sr}=wr("node:fs/promises"),Hs=async t=>{he(t);try{const e=await _r(t);if(!e.isFile())throw new Error(`Ensure path exists, expected 'file', got '${String(bt(e))}'`)}catch(e){if(e.code==="ENOENT"){await zt(ge(ye(t))),await Sr(t,new Uint8Array);return}throw e}},Cr=C(import.meta.url),Te=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,kr=t=>{if(typeof Te<"u"&&Te.versions&&Te.versions.node){const[e,r]=Te.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Te.getBuiltinModule(t)}return Cr(t)};kr("node:fs");const Or=C(import.meta.url),xe=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Nr=t=>{if(typeof xe<"u"&&xe.versions&&xe.versions.node){const[e,r]=xe.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return xe.getBuiltinModule(t)}return Or(t)};Nr("node:fs/promises");const Lr=C(import.meta.url),we=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Hr=t=>{if(typeof we<"u"&&we.versions&&we.versions.node){const[e,r]=we.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return we.getBuiltinModule(t)}return Lr(t)};Hr("node:fs");const Mr=C(import.meta.url),_e=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Br=t=>{if(typeof _e<"u"&&_e.versions&&_e.versions.node){const[e,r]=_e.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return _e.getBuiltinModule(t)}return Mr(t)};Br("node:fs/promises");const Ir=C(import.meta.url),Se=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Dr=t=>{if(typeof Se<"u"&&Se.versions&&Se.versions.node){const[e,r]=Se.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Se.getBuiltinModule(t)}return Ir(t)};Dr("node:fs");C(import.meta.url);let _t=class extends Error{root;constructor(e,r){super(`${e instanceof Error?e.message:String(e)} for path "${r}"`),this.cause=e,this.root=r}get name(){return"WalkError"}set name(e){throw new Error("Cannot overwrite name of WalkError")}};const St=t=>{const e=t.replace(/[$()+\\^]/g,String.raw`\$&`).replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,String.raw`\.`).replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");try{return new RegExp(`^${e}$`)}catch(r){throw new Error(`Invalid glob pattern: ${t}`,{cause:r})}};let Pr=class{name;path;#e;constructor(e,r,y){this.#e=e,this.name=r,this.path=y}isDirectory(){return this.#e.isDirectory()}isFile(){return this.#e.isFile()}isSymbolicLink(){return this.#e.isSymbolicLink()}};const $t=(t,e,r)=>new Pr(t,e,r),rt=(t,e,r,y)=>{if(Array.isArray(e)&&e.length>0&&!e.some(o=>t.endsWith(o)))return!1;const p=t.includes("\\")?t.replaceAll("\\","/"):t;return r&&!r.some(o=>o.test(p))?!1:!y?.some(o=>o.test(p))},Fr=C(import.meta.url),Ce=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Gr=t=>{if(typeof Ce<"u"&&Ce.versions&&Ce.versions.node){const[e,r]=Ce.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Ce.getBuiltinModule(t)}return Fr(t)},{readdir:Ur,realpath:Xr,stat:Kt}=Gr("node:fs/promises"),zr=async t=>{const e=yt(t),r=sr(e),y=await Kt(e);return $t(y,r,e)};async function*Kr(t,e={}){const{extensions:r,followSymlinks:y=!1,includeDirs:p=!0,includeFiles:o=!0,includeSymlinks:a=!0,match:f,maxDepth:l=Number.POSITIVE_INFINITY,skip:A}=e;if(he(t),l<0)return;const g=e.visited??new Set,T=f?f.map(b=>typeof b=="string"?St(b):b):void 0,w=A?A.map(b=>typeof b=="string"?St(b):b):void 0;if(t=mt(ye(t)),p&&rt(t,r,T,w)&&(yield await zr(t)),!(l<1||!rt(t,void 0,void 0,w)))try{const b=await Ur(t,{withFileTypes:!0});for(const k of b){let X=Ut(t,k.name),K=k.isDirectory(),W=k.isFile();if(k.isSymbolicLink())if(y){const L=await Xr(X);if(g.has(L))continue;X=L;const h=await Kt(L);K=h.isDirectory(),W=h.isFile()}else if(a&&rt(X,r,T,w)){yield $t(k,k.name,X);continue}else continue;K?(y&&g.add(X),yield*Kr(X,{extensions:r,followSymlinks:y,includeDirs:p,includeFiles:o,includeSymlinks:a,match:T,maxDepth:l-1,skip:w,visited:g})):W&&o&&rt(X,r,T,w)&&(yield $t(k,k.name,X))}}catch(b){throw b instanceof _t?b:new _t(b,t)}}const Wr=C(import.meta.url),ke=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,jr=t=>{if(typeof ke<"u"&&ke.versions&&ke.versions.node){const[e,r]=ke.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return ke.getBuiltinModule(t)}return Wr(t)};jr("node:fs");const Qr=C(import.meta.url),Oe=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,qr=t=>{if(typeof Oe<"u"&&Oe.versions&&Oe.versions.node){const[e,r]=Oe.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Oe.getBuiltinModule(t)}return Qr(t)};qr("node:fs/promises");const Vr=C(import.meta.url),Ne=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Yr=t=>{if(typeof Ne<"u"&&Ne.versions&&Ne.versions.node){const[e,r]=Ne.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Ne.getBuiltinModule(t)}return Vr(t)};Yr("node:fs");function Et(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Ct={},ut,kt;function ot(){if(kt)return ut;kt=1;const t="[^\\\\/]",e=Symbol("unignore"),r="\\.",y="\\+",p="\\?",o="\\/",a="(?=.)",f="[^/]",l=`(?:${o}|$)`,A=`(?:^|${o})`,g=`${r}{1,2}${l}`,T=`(?!${r})`,w=`(?!${A}${g})`,b=`(?!${r}{0,1}${l})`,k=`(?!${g})`,X=`[^.${o}]`,K=`${f}*?`,W="/",L={DOT_LITERAL:r,PLUS_LITERAL:y,QMARK_LITERAL:p,SLASH_LITERAL:o,ONE_CHAR:a,QMARK:f,END_ANCHOR:l,DOTS_SLASH:g,NO_DOT:T,NO_DOTS:w,NO_DOT_SLASH:b,NO_DOTS_SLASH:k,QMARK_NO_DOT:X,STAR:K,START_ANCHOR:A,SEP:W},h={...L,SLASH_LITERAL:"[\\\\/]",QMARK:t,STAR:`${t}*?`,DOTS_SLASH:`${r}{1,2}(?:[\\\\/]|$)`,NO_DOT:`(?!${r})`,NO_DOTS:`(?!(?:^|[\\\\/])${r}{1,2}(?:[\\\\/]|$))`,NO_DOT_SLASH:`(?!${r}{0,1}(?:[\\\\/]|$))`,NO_DOTS_SLASH:`(?!${r}{1,2}(?:[\\\\/]|$))`,QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},m={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};return ut={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:m,UNIGNORE:e,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(s){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${s.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(s){return s===!0?h:L}},ut}var Ot;function st(){return Ot||(Ot=1,(function(t){const{REGEX_BACKSLASH:e,REGEX_REMOVE_BACKSLASH:r,REGEX_SPECIAL_CHARS:y,REGEX_SPECIAL_CHARS_GLOBAL:p}=ot();t.isObject=o=>o!==null&&typeof o=="object"&&!Array.isArray(o),t.hasRegexChars=o=>y.test(o),t.isRegexChar=o=>o.length===1&&t.hasRegexChars(o),t.escapeRegex=o=>o.replace(p,"\\$1"),t.toPosixSlashes=o=>o.replace(e,"/"),t.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){const o=navigator.platform.toLowerCase();return o==="win32"||o==="windows"}return process.platform?process.platform==="win32":!1},t.removeBackslashes=o=>o.replace(r,a=>a==="\\"?"":a),t.escapeLast=(o,a,f)=>{const l=o.lastIndexOf(a,f);return l===-1?o:o[l-1]==="\\"?t.escapeLast(o,a,l-1):`${o.slice(0,l)}\\${o.slice(l)}`},t.removePrefix=(o,a={})=>{let f=o;return f.startsWith("./")&&(f=f.slice(2),a.prefix="./"),f},t.wrapOutput=(o,a={},f={})=>{const l=f.contains?"":"^",A=f.contains?"":"$";let g=`${l}(?:${o})${A}`;return a.negated===!0&&(g=`(?:^(?!${g}).*$)`),g},t.basename=(o,{windows:a}={})=>{const f=o.split(a?/[\\/]/:"/"),l=f[f.length-1];return l===""?f[f.length-2]:l}})(Ct)),Ct}var at,Nt;function Zr(){if(Nt)return at;Nt=1;const t=st(),{CHAR_ASTERISK:e,CHAR_AT:r,CHAR_BACKWARD_SLASH:y,CHAR_COMMA:p,CHAR_DOT:o,CHAR_EXCLAMATION_MARK:a,CHAR_FORWARD_SLASH:f,CHAR_LEFT_CURLY_BRACE:l,CHAR_LEFT_PARENTHESES:A,CHAR_LEFT_SQUARE_BRACKET:g,CHAR_PLUS:T,CHAR_QUESTION_MARK:w,CHAR_RIGHT_CURLY_BRACE:b,CHAR_RIGHT_PARENTHESES:k,CHAR_RIGHT_SQUARE_BRACKET:X}=ot(),K=L=>L===f||L===y,W=L=>{L.isPrefix!==!0&&(L.depth=L.isGlobstar?1/0:1)};return at=(L,h)=>{const m=h||{},s=L.length-1,R=m.parts===!0||m.scanToEnd===!0,O=[],$=[],x=[];let v=L,j=-1,G=0,J=0,le=!1,ee=!1,U=!1,te=!1,pe=!1,se=!1,re=!1,P=!1,ne=!1,q=!1,ce=0,V,E,H={value:"",depth:0,isGlob:!1};const Q=()=>j>=s,u=()=>v.charCodeAt(j+1),I=()=>(V=E,v.charCodeAt(++j));for(;j<s;){E=I();let Y;if(E===y){re=H.backslashes=!0,E=I(),E===l&&(se=!0);continue}if(se===!0||E===l){for(ce++;Q()!==!0&&(E=I());){if(E===y){re=H.backslashes=!0,I();continue}if(E===l){ce++;continue}if(se!==!0&&E===o&&(E=I())===o){if(le=H.isBrace=!0,U=H.isGlob=!0,q=!0,R===!0)continue;break}if(se!==!0&&E===p){if(le=H.isBrace=!0,U=H.isGlob=!0,q=!0,R===!0)continue;break}if(E===b&&(ce--,ce===0)){se=!1,le=H.isBrace=!0,q=!0;break}}if(R===!0)continue;break}if(E===f){if(O.push(j),$.push(H),H={value:"",depth:0,isGlob:!1},q===!0)continue;if(V===o&&j===G+1){G+=2;continue}J=j+1;continue}if(m.noext!==!0&&(E===T||E===r||E===e||E===w||E===a)&&u()===A){if(U=H.isGlob=!0,te=H.isExtglob=!0,q=!0,E===a&&j===G&&(ne=!0),R===!0){for(;Q()!==!0&&(E=I());){if(E===y){re=H.backslashes=!0,E=I();continue}if(E===k){U=H.isGlob=!0,q=!0;break}}continue}break}if(E===e){if(V===e&&(pe=H.isGlobstar=!0),U=H.isGlob=!0,q=!0,R===!0)continue;break}if(E===w){if(U=H.isGlob=!0,q=!0,R===!0)continue;break}if(E===g){for(;Q()!==!0&&(Y=I());){if(Y===y){re=H.backslashes=!0,I();continue}if(Y===X){ee=H.isBracket=!0,U=H.isGlob=!0,q=!0;break}}if(R===!0)continue;break}if(m.nonegate!==!0&&E===a&&j===G){P=H.negated=!0,G++;continue}if(m.noparen!==!0&&E===A){if(U=H.isGlob=!0,R===!0){for(;Q()!==!0&&(E=I());){if(E===A){re=H.backslashes=!0,E=I();continue}if(E===k){q=!0;break}}continue}break}if(U===!0){if(q=!0,R===!0)continue;break}}m.noext===!0&&(te=!1,U=!1);let B=v,fe="",n="";G>0&&(fe=v.slice(0,G),v=v.slice(G),J-=G),B&&U===!0&&J>0?(B=v.slice(0,J),n=v.slice(J)):U===!0?(B="",n=v):B=v,B&&B!==""&&B!=="/"&&B!==v&&K(B.charCodeAt(B.length-1))&&(B=B.slice(0,-1)),m.unescape===!0&&(n&&(n=t.removeBackslashes(n)),B&&re===!0&&(B=t.removeBackslashes(B)));const i={prefix:fe,input:L,start:G,base:B,glob:n,isBrace:le,isBracket:ee,isGlob:U,isExtglob:te,isGlobstar:pe,negated:P,negatedExtglob:ne};if(m.tokens===!0&&(i.maxDepth=0,K(E)||$.push(H),i.tokens=$),m.parts===!0||m.tokens===!0){let Y;for(let N=0;N<O.length;N++){const oe=Y?Y+1:G,ie=O[N],Z=L.slice(oe,ie);m.tokens&&(N===0&&G!==0?($[N].isPrefix=!0,$[N].value=fe):$[N].value=Z,W($[N]),i.maxDepth+=$[N].depth),(N!==0||Z!=="")&&x.push(Z),Y=ie}if(Y&&Y+1<L.length){const N=L.slice(Y+1);x.push(N),m.tokens&&($[$.length-1].value=N,W($[$.length-1]),i.maxDepth+=$[$.length-1].depth)}i.slashes=O,i.parts=x}return i},at}var lt,Lt;function Jr(){if(Lt)return lt;Lt=1;const t=ot(),e=st(),{MAX_LENGTH:r,POSIX_REGEX_SOURCE:y,REGEX_NON_SPECIAL_CHARS:p,REGEX_SPECIAL_CHARS_BACKREF:o,REPLACEMENTS:a}=t,f=(h,m)=>typeof m.expandRange=="function"?m.expandRange(...h,m):(h.sort(),`[${h.join("-")}]`),l=(h,m)=>`Missing ${h}: "${m}" - use "\\\\${m}" to match literal characters`,A=h=>{const m=[];let s=0,R=0,O=0,$="",x=!1;for(const v of h){if(x===!0){$+=v,x=!1;continue}if(v==="\\"){$+=v,x=!0;continue}if(v==='"'){O=O===1?0:1,$+=v;continue}if(O===0){if(v==="[")s++;else if(v==="]"&&s>0)s--;else if(s===0){if(v==="(")R++;else if(v===")"&&R>0)R--;else if(v==="|"&&R===0){m.push($),$="";continue}}}$+=v}return m.push($),m},g=h=>{let m=!1;for(const s of h){if(m===!0){m=!1;continue}if(s==="\\"){m=!0;continue}if(/[?*+@!()[\]{}]/.test(s))return!1}return!0},T=h=>{let m=h.trim(),s=!0;for(;s===!0;)s=!1,/^@\([^\\()[\]{}|]+\)$/.test(m)&&(m=m.slice(2,-1),s=!0);if(g(m))return m.replace(/\\(.)/g,"$1")},w=h=>{const m=h.map(T).filter(Boolean);for(let s=0;s<m.length;s++)for(let R=s+1;R<m.length;R++){const O=m[s],$=m[R],x=O[0];if(!(!x||O!==x.repeat(O.length)||$!==x.repeat($.length))&&(O===$||O.startsWith($)||$.startsWith(O)))return!0}return!1},b=(h,m=!0)=>{if(h[0]!=="+"&&h[0]!=="*"||h[1]!=="(")return;let s=0,R=0,O=0,$=!1;for(let x=1;x<h.length;x++){const v=h[x];if($===!0){$=!1;continue}if(v==="\\"){$=!0;continue}if(v==='"'){O=O===1?0:1;continue}if(O!==1){if(v==="["){s++;continue}if(v==="]"&&s>0){s--;continue}if(!(s>0)){if(v==="("){R++;continue}if(v===")"&&(R--,R===0))return m===!0&&x!==h.length-1?void 0:{type:h[0],body:h.slice(2,x),end:x}}}}},k=h=>`${h.length===1?e.escapeRegex(h[0]):`[${h.map(m=>e.escapeRegex(m)).join("")}]`}*`,X=h=>{let m=0;const s=[];for(;m<h.length;){const R=b(h.slice(m),!1);if(!R||R.type!=="*")return;const O=A(R.body).map(x=>x.trim());if(O.length!==1)return;const $=T(O[0]);if(!$||$.length!==1)return;s.push($),m+=R.end+1}if(!(s.length<1))return s},K=h=>{let m=0,s=h.trim(),R=b(s);for(;R;)m++,s=R.body.trim(),R=b(s);return m},W=(h,m)=>{if(m.maxExtglobRecursion===!1)return{risky:!1};const s=typeof m.maxExtglobRecursion=="number"?m.maxExtglobRecursion:t.DEFAULT_MAX_EXTGLOB_RECURSION,R=A(h).map(v=>v.trim());if(R.length>1&&(R.some(v=>v==="")||R.some(v=>/^[*?]+$/.test(v))||w(R)))return{risky:!0};const O=[];let $=!1,x=!0;for(const v of R){const j=X(v);if(j){$=!0,O.push(...j);continue}const G=T(v);if(G&&G.length===1){O.push(G);continue}if(x=!1,K(v)>s)return{risky:!0}}return $?x?{risky:!0,safeOutput:k([...new Set(O)])}:{risky:!0}:{risky:!1}},L=(h,m)=>{if(typeof h!="string")throw new TypeError("Expected a string");h=a[h]||h;const s={...m},R=typeof s.maxLength=="number"?Math.min(r,s.maxLength):r;let O=h.length;if(O>R)throw new SyntaxError(`Input length: ${O}, exceeds maximum allowed length: ${R}`);const $={type:"bos",value:"",output:s.prepend||""},x=[$],v=s.capture?"":"?:",j=t.globChars(s.windows),G=t.extglobChars(j),{DOT_LITERAL:J,PLUS_LITERAL:le,SLASH_LITERAL:ee,ONE_CHAR:U,DOTS_SLASH:te,NO_DOT:pe,NO_DOT_SLASH:se,NO_DOTS_SLASH:re,QMARK:P,QMARK_NO_DOT:ne,STAR:q,START_ANCHOR:ce}=j,V=d=>`(${v}(?:(?!${ce}${d.dot?te:J}).)*?)`,E=s.dot?"":pe,H=s.dot?P:ne;let Q=s.bash===!0?V(s):q;s.capture&&(Q=`(${Q})`),typeof s.noext=="boolean"&&(s.noextglob=s.noext);const u={input:h,index:-1,start:0,dot:s.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:x};h=e.removePrefix(h,u),O=h.length;const I=[],B=[],fe=[];let n=$,i;const Y=()=>u.index===O-1,N=u.peek=(d=1)=>h[u.index+d],oe=u.advance=()=>h[++u.index]||"",ie=()=>h.slice(u.index+1),Z=(d="",D=0)=>{u.consumed+=d,u.index+=D},Je=d=>{u.output+=d.output!=null?d.output:d.value,Z(d.value)},Jt=()=>{let d=1;for(;N()==="!"&&(N(2)!=="("||N(3)==="?");)oe(),u.start++,d++;return d%2===0?!1:(u.negated=!0,u.start++,!0)},et=d=>{u[d]++,fe.push(d)},de=d=>{u[d]--,fe.pop()},_=d=>{if(n.type==="globstar"){const D=u.braces>0&&(d.type==="comma"||d.type==="brace"),c=d.extglob===!0||I.length&&(d.type==="pipe"||d.type==="paren");d.type!=="slash"&&d.type!=="paren"&&!D&&!c&&(u.output=u.output.slice(0,-n.output.length),n.type="star",n.value="*",n.output=Q,u.output+=n.output)}if(I.length&&d.type!=="paren"&&(I[I.length-1].inner+=d.value),(d.value||d.output)&&Je(d),n&&n.type==="text"&&d.type==="text"){n.output=(n.output||n.value)+d.value,n.value+=d.value;return}d.prev=n,x.push(d),n=d},tt=(d,D)=>{const c={...G[D],conditions:1,inner:""};c.prev=n,c.parens=u.parens,c.output=u.output,c.startIndex=u.index,c.tokensIndex=x.length;const S=(s.capture?"(":"")+c.open;et("parens"),_({type:d,value:D,output:u.output?"":U}),_({type:"paren",extglob:!0,value:oe(),output:S}),I.push(c)},er=d=>{const D=h.slice(d.startIndex,u.index+1),c=h.slice(d.startIndex+2,u.index),S=W(c,s);if((d.type==="plus"||d.type==="star")&&S.risky){const M=S.safeOutput?(d.output?"":U)+(s.capture?`(${S.safeOutput})`:S.safeOutput):void 0,ue=x[d.tokensIndex];ue.type="text",ue.value=D,ue.output=M||e.escapeRegex(D);for(let ae=d.tokensIndex+1;ae<x.length;ae++)x[ae].value="",x[ae].output="",delete x[ae].suffix;u.output=d.output+ue.output,u.backtrack=!0,_({type:"paren",extglob:!0,value:i,output:""}),de("parens");return}let F=d.close+(s.capture?")":""),z;if(d.type==="negate"){let M=Q;if(d.inner&&d.inner.length>1&&d.inner.includes("/")&&(M=V(s)),(M!==Q||Y()||/^\)+$/.test(ie()))&&(F=d.close=`)$))${M}`),d.inner.includes("*")&&(z=ie())&&/^\.[^\\/.]+$/.test(z)){const ue=L(z,{...m,fastpaths:!1}).output;F=d.close=`)${ue})${M})`}d.prev.type==="bos"&&(u.negatedExtglob=!0)}_({type:"paren",extglob:!0,value:i,output:F}),de("parens")};if(s.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(h)){let d=!1,D=h.replace(o,(c,S,F,z,M,ue)=>z==="\\"?(d=!0,c):z==="?"?S?S+z+(M?P.repeat(M.length):""):ue===0?H+(M?P.repeat(M.length):""):P.repeat(F.length):z==="."?J.repeat(F.length):z==="*"?S?S+z+(M?Q:""):Q:S?c:`\\${c}`);return d===!0&&(s.unescape===!0?D=D.replace(/\\/g,""):D=D.replace(/\\+/g,c=>c.length%2===0?"\\\\":c?"\\":"")),D===h&&s.contains===!0?(u.output=h,u):(u.output=e.wrapOutput(D,u,m),u)}for(;!Y();){if(i=oe(),i==="\0")continue;if(i==="\\"){const c=N();if(c==="/"&&s.bash!==!0||c==="."||c===";")continue;if(!c){i+="\\",_({type:"text",value:i});continue}const S=/^\\+/.exec(ie());let F=0;if(S&&S[0].length>2&&(F=S[0].length,u.index+=F,F%2!==0&&(i+="\\")),s.unescape===!0?i=oe():i+=oe(),u.brackets===0){_({type:"text",value:i});continue}}if(u.brackets>0&&(i!=="]"||n.value==="["||n.value==="[^")){if(s.posix!==!1&&i===":"){const c=n.value.slice(1);if(c.includes("[")&&(n.posix=!0,c.includes(":"))){const S=n.value.lastIndexOf("["),F=n.value.slice(0,S),z=n.value.slice(S+2),M=y[z];if(M){n.value=F+M,u.backtrack=!0,oe(),!$.output&&x.indexOf(n)===1&&($.output=U);continue}}}(i==="["&&N()!==":"||i==="-"&&N()==="]")&&(i=`\\${i}`),i==="]"&&(n.value==="["||n.value==="[^")&&(i=`\\${i}`),s.posix===!0&&i==="!"&&n.value==="["&&(i="^"),n.value+=i,Je({value:i});continue}if(u.quotes===1&&i!=='"'){i=e.escapeRegex(i),n.value+=i,Je({value:i});continue}if(i==='"'){u.quotes=u.quotes===1?0:1,s.keepQuotes===!0&&_({type:"text",value:i});continue}if(i==="("){et("parens"),_({type:"paren",value:i});continue}if(i===")"){if(u.parens===0&&s.strictBrackets===!0)throw new SyntaxError(l("opening","("));const c=I[I.length-1];if(c&&u.parens===c.parens+1){er(I.pop());continue}_({type:"paren",value:i,output:u.parens?")":"\\)"}),de("parens");continue}if(i==="["){if(s.nobracket===!0||!ie().includes("]")){if(s.nobracket!==!0&&s.strictBrackets===!0)throw new SyntaxError(l("closing","]"));i=`\\${i}`}else et("brackets");_({type:"bracket",value:i});continue}if(i==="]"){if(s.nobracket===!0||n&&n.type==="bracket"&&n.value.length===1){_({type:"text",value:i,output:`\\${i}`});continue}if(u.brackets===0){if(s.strictBrackets===!0)throw new SyntaxError(l("opening","["));_({type:"text",value:i,output:`\\${i}`});continue}de("brackets");const c=n.value.slice(1);if(n.posix!==!0&&c[0]==="^"&&!c.includes("/")&&(i=`/${i}`),n.value+=i,Je({value:i}),s.literalBrackets===!1||e.hasRegexChars(c))continue;const S=e.escapeRegex(n.value);if(u.output=u.output.slice(0,-n.value.length),s.literalBrackets===!0){u.output+=S,n.value=S;continue}n.value=`(${v}${S}|${n.value})`,u.output+=n.value;continue}if(i==="{"&&s.nobrace!==!0){et("braces");const c={type:"brace",value:i,output:"(",outputIndex:u.output.length,tokensIndex:u.tokens.length};B.push(c),_(c);continue}if(i==="}"){const c=B[B.length-1];if(s.nobrace===!0||!c){_({type:"text",value:i,output:i});continue}let S=")";if(c.dots===!0){const F=x.slice(),z=[];for(let M=F.length-1;M>=0&&(x.pop(),F[M].type!=="brace");M--)F[M].type!=="dots"&&z.unshift(F[M].value);S=f(z,s),u.backtrack=!0}if(c.comma!==!0&&c.dots!==!0){const F=u.output.slice(0,c.outputIndex),z=u.tokens.slice(c.tokensIndex);c.value=c.output="\\{",i=S="\\}",u.output=F;for(const M of z)u.output+=M.output||M.value}_({type:"brace",value:i,output:S}),de("braces"),B.pop();continue}if(i==="|"){I.length>0&&I[I.length-1].conditions++,_({type:"text",value:i});continue}if(i===","){let c=i;const S=B[B.length-1];S&&fe[fe.length-1]==="braces"&&(S.comma=!0,c="|"),_({type:"comma",value:i,output:c});continue}if(i==="/"){if(n.type==="dot"&&u.index===u.start+1){u.start=u.index+1,u.consumed="",u.output="",x.pop(),n=$;continue}_({type:"slash",value:i,output:ee});continue}if(i==="."){if(u.braces>0&&n.type==="dot"){n.value==="."&&(n.output=J);const c=B[B.length-1];n.type="dots",n.output+=i,n.value+=i,c.dots=!0;continue}if(u.braces+u.parens===0&&n.type!=="bos"&&n.type!=="slash"){_({type:"text",value:i,output:J});continue}_({type:"dot",value:i,output:J});continue}if(i==="?"){if(!(n&&n.value==="(")&&s.noextglob!==!0&&N()==="("&&N(2)!=="?"){tt("qmark",i);continue}if(n&&n.type==="paren"){const c=N();let S=i;(n.value==="("&&!/[!=<:]/.test(c)||c==="<"&&!/<([!=]|\w+>)/.test(ie()))&&(S=`\\${i}`),_({type:"text",value:i,output:S});continue}if(s.dot!==!0&&(n.type==="slash"||n.type==="bos")){_({type:"qmark",value:i,output:ne});continue}_({type:"qmark",value:i,output:P});continue}if(i==="!"){if(s.noextglob!==!0&&N()==="("&&(N(2)!=="?"||!/[!=<:]/.test(N(3)))){tt("negate",i);continue}if(s.nonegate!==!0&&u.index===0){Jt();continue}}if(i==="+"){if(s.noextglob!==!0&&N()==="("&&N(2)!=="?"){tt("plus",i);continue}if(n&&n.value==="("||s.regex===!1){_({type:"plus",value:i,output:le});continue}if(n&&(n.type==="bracket"||n.type==="paren"||n.type==="brace")||u.parens>0){_({type:"plus",value:i});continue}_({type:"plus",value:le});continue}if(i==="@"){if(s.noextglob!==!0&&N()==="("&&N(2)!=="?"){_({type:"at",extglob:!0,value:i,output:""});continue}_({type:"text",value:i});continue}if(i!=="*"){(i==="$"||i==="^")&&(i=`\\${i}`);const c=p.exec(ie());c&&(i+=c[0],u.index+=c[0].length),_({type:"text",value:i});continue}if(n&&(n.type==="globstar"||n.star===!0)){n.type="star",n.star=!0,n.value+=i,n.output=Q,u.backtrack=!0,u.globstar=!0,Z(i);continue}let d=ie();if(s.noextglob!==!0&&/^\([^?]/.test(d)){tt("star",i);continue}if(n.type==="star"){if(s.noglobstar===!0){Z(i);continue}const c=n.prev,S=c.prev,F=c.type==="slash"||c.type==="bos",z=S&&(S.type==="star"||S.type==="globstar");if(s.bash===!0&&(!F||d[0]&&d[0]!=="/")){_({type:"star",value:i,output:""});continue}const M=u.braces>0&&(c.type==="comma"||c.type==="brace"),ue=I.length&&(c.type==="pipe"||c.type==="paren");if(!F&&c.type!=="paren"&&!M&&!ue){_({type:"star",value:i,output:""});continue}for(;d.slice(0,3)==="/**";){const ae=h[u.index+4];if(ae&&ae!=="/")break;d=d.slice(3),Z("/**",3)}if(c.type==="bos"&&Y()){n.type="globstar",n.value+=i,n.output=V(s),u.output=n.output,u.globstar=!0,Z(i);continue}if(c.type==="slash"&&c.prev.type!=="bos"&&!z&&Y()){u.output=u.output.slice(0,-(c.output+n.output).length),c.output=`(?:${c.output}`,n.type="globstar",n.output=V(s)+(s.strictSlashes?")":"|$)"),n.value+=i,u.globstar=!0,u.output+=c.output+n.output,Z(i);continue}if(c.type==="slash"&&c.prev.type!=="bos"&&d[0]==="/"){const ae=d[1]!==void 0?"|$":"";u.output=u.output.slice(0,-(c.output+n.output).length),c.output=`(?:${c.output}`,n.type="globstar",n.output=`${V(s)}${ee}|${ee}${ae})`,n.value+=i,u.output+=c.output+n.output,u.globstar=!0,Z(i+oe()),_({type:"slash",value:"/",output:""});continue}if(c.type==="bos"&&d[0]==="/"){n.type="globstar",n.value+=i,n.output=`(?:^|${ee}|${V(s)}${ee})`,u.output=n.output,u.globstar=!0,Z(i+oe()),_({type:"slash",value:"/",output:""});continue}if(M&&d[0]==="/"){n.type="globstar",n.value+=i,n.output=`(?:^|${ee}|${V(s)}${ee})`,u.output+=n.output,u.globstar=!0,Z(i+oe()),_({type:"slash",value:"/",output:""});continue}u.output=u.output.slice(0,-n.output.length),n.type="globstar",n.output=V(s),n.value+=i,u.output+=n.output,u.globstar=!0,Z(i);continue}const D={type:"star",value:i,output:Q};if(s.bash===!0){D.output=".*?",(n.type==="bos"||n.type==="slash")&&(D.output=E+D.output),_(D);continue}if(n&&(n.type==="bracket"||n.type==="paren")&&s.regex===!0){D.output=i,_(D);continue}(u.index===u.start||n.type==="slash"||n.type==="dot")&&(n.type==="dot"?(u.output+=se,n.output+=se):s.dot===!0?(u.output+=re,n.output+=re):(u.output+=E,n.output+=E),N()!=="*"&&(u.output+=U,n.output+=U)),_(D)}for(;u.brackets>0;){if(s.strictBrackets===!0)throw new SyntaxError(l("closing","]"));u.output=e.escapeLast(u.output,"["),de("brackets")}for(;u.parens>0;){if(s.strictBrackets===!0)throw new SyntaxError(l("closing",")"));u.output=e.escapeLast(u.output,"("),de("parens")}for(;u.braces>0;){if(s.strictBrackets===!0)throw new SyntaxError(l("closing","}"));u.output=e.escapeLast(u.output,"{"),de("braces")}if(s.strictSlashes!==!0&&(n.type==="star"||n.type==="bracket")&&_({type:"maybe_slash",value:"",output:`${ee}?`}),u.backtrack===!0){u.output="";for(const d of u.tokens)u.output+=d.output!=null?d.output:d.value,d.suffix&&(u.output+=d.suffix)}return u};return L.fastpaths=(h,m)=>{const s={...m},R=typeof s.maxLength=="number"?Math.min(r,s.maxLength):r,O=h.length;if(O>R)throw new SyntaxError(`Input length: ${O}, exceeds maximum allowed length: ${R}`);h=a[h]||h;const{DOT_LITERAL:$,SLASH_LITERAL:x,ONE_CHAR:v,DOTS_SLASH:j,NO_DOT:G,NO_DOTS:J,NO_DOTS_SLASH:le,STAR:ee,START_ANCHOR:U}=t.globChars(s.windows),te=s.dot?J:G,pe=s.dot?le:G,se=s.capture?"":"?:",re={negated:!1,prefix:""};let P=s.bash===!0?".*?":ee;s.capture&&(P=`(${P})`);const ne=E=>E.noglobstar===!0?P:`(${se}(?:(?!${U}${E.dot?j:$}).)*?)`,q=E=>{switch(E){case"*":return`${te}${v}${P}`;case".*":return`${$}${v}${P}`;case"*.*":return`${te}${P}${$}${v}${P}`;case"*/*":return`${te}${P}${x}${v}${pe}${P}`;case"**":return te+ne(s);case"**/*":return`(?:${te}${ne(s)}${x})?${pe}${v}${P}`;case"**/*.*":return`(?:${te}${ne(s)}${x})?${pe}${P}${$}${v}${P}`;case"**/.*":return`(?:${te}${ne(s)}${x})?${$}${v}${P}`;default:{const H=/^(.*?)\.(\w+)$/.exec(E);if(!H)return;const Q=q(H[1]);return Q?Q+$+H[2]:void 0}}},ce=e.removePrefix(h,re);let V=q(ce);return V&&s.strictSlashes!==!0&&(V+=`${x}?`),V},lt=L,lt}var pt,Ht;function eo(){if(Ht)return pt;Ht=1;const t=Zr(),e=Jr(),r=st(),y=ot(),p=a=>a&&typeof a=="object"&&!Array.isArray(a),o=(a,f,l=!1)=>{if(Array.isArray(a)){const K=a.map(W=>o(W,f,l));return W=>{for(const L of K){const h=L(W);if(h)return h}return!1}}const A=p(a)&&a.tokens&&a.input;if(a===""||typeof a!="string"&&!A)throw new TypeError("Expected pattern to be a non-empty string");const g=f||{},T=g.windows,w=A?o.compileRe(a,f):o.makeRe(a,f,!1,!0),b=w.state;delete w.state;let k=()=>!1;if(g.ignore){const K={...f,ignore:null,onMatch:null,onResult:null};k=o(g.ignore,K,l)}const X=(K,W=!1)=>{const{isMatch:L,match:h,output:m}=o.test(K,w,f,{glob:a,posix:T}),s={glob:a,state:b,regex:w,posix:T,input:K,output:m,match:h,isMatch:L};if(typeof g.onResult=="function"&&g.onResult(s),L===!1)return s.isMatch=!1,W?s:!1;e:if(k(K)){if(typeof g.onIgnore=="function"&&g.onIgnore(s)===y.UNIGNORE){s.isMatch=!0;break e}return s.isMatch=!1,W?s:!1}return typeof g.onMatch=="function"&&g.onMatch(s),W?s:!0};return l&&(X.state=b),X};return o.test=(a,f,l,{glob:A,posix:g}={})=>{if(typeof a!="string")throw new TypeError("Expected input to be a string");if(a==="")return{isMatch:!1,output:""};const T=l||{},w=T.format||(g?r.toPosixSlashes:null);let b=a===A,k=b&&w?w(a):a;return b===!1&&(k=w?w(a):a,b=k===A),(b===!1||T.capture===!0)&&(T.matchBase===!0||T.basename===!0?b=o.matchBase(a,f,l,g):b=f.exec(k)),{isMatch:!!b,match:b,output:k}},o.matchBase=(a,f,l,A=l&&l.windows)=>(f instanceof RegExp?f:o.makeRe(f,l)).test(r.basename(a,{windows:A})),o.isMatch=(a,f,l)=>o(f,l)(a),o.parse=(a,f)=>Array.isArray(a)?a.map(l=>o.parse(l,f)):e(a,{...f,fastpaths:!1}),o.scan=(a,f)=>t(a,f),o.compileRe=(a,f,l=!1,A=!1)=>{if(l===!0)return a.output;const g=f||{},T=g.contains?"":"^",w=g.contains?"":"$";let b=`${T}(?:${a.output})${w}`;a&&a.negated===!0&&(b=`^(?!${b}).*$`);const k=o.toRegex(b,f);return A===!0&&(k.state=a),k},o.makeRe=(a,f={},l=!1,A=!1)=>{if(!a||typeof a!="string")throw new TypeError("Expected a non-empty string");let g={negated:!1,fastpaths:!0};return f.fastpaths!==!1&&(a[0]==="."||a[0]==="*")&&(g.output=e.fastpaths(a,f)),g.output||(g=e(a,f)),o.compileRe(g,f,l,A)},o.toRegex=(a,f)=>{try{const l=f||{};return new RegExp(a,l.flags||(l.nocase?"i":""))}catch(l){if(f&&f.debug===!0)throw l;return/$^/}},o.constants=y,pt=o,pt}var ct,Mt;function to(){if(Mt)return ct;Mt=1;const t=eo(),e=st();function r(y,p,o=!1){return p&&(p.windows===null||p.windows===void 0)&&(p={...p,windows:e.isWindows()}),t(y,p,o)}return Object.assign(r,t),ct=r,ct}var ro=to();Et(ro);const oo=C(import.meta.url),Le=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Ze=t=>{if(typeof Le<"u"&&Le.versions&&Le.versions.node){const[e,r]=Le.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Le.getBuiltinModule(t)}return oo(t)};Ze("fs");Ze("fs");Ze("path");Ze("url");const{createRequire:so}=Ze("module");var Bt=so(import.meta.url);try{Bt.resolve("picomatch"),Bt("picomatch")}catch{}var ft,It;function no(){if(It)return ft;It=1;/*!
2
+ * is-extglob <https://github.com/jonschlinkert/is-extglob>
3
+ *
4
+ * Copyright (c) 2014-2016, Jon Schlinkert.
5
+ * Licensed under the MIT License.
6
+ */return ft=function(t){if(typeof t!="string"||t==="")return!1;for(var e;e=/(\\).|([@?!+*]\(.*\))/g.exec(t);){if(e[2])return!0;t=t.slice(e.index+e[0].length)}return!1},ft}var dt,Dt;function Wt(){if(Dt)return dt;Dt=1;/*!
7
+ * is-glob <https://github.com/jonschlinkert/is-glob>
8
+ *
9
+ * Copyright (c) 2014-2017, Jon Schlinkert.
10
+ * Released under the MIT License.
11
+ */var t=no(),e={"{":"}","(":")","[":"]"},r=function(p){if(p[0]==="!")return!0;for(var o=0,a=-2,f=-2,l=-2,A=-2,g=-2;o<p.length;){if(p[o]==="*"||p[o+1]==="?"&&/[\].+)]/.test(p[o])||f!==-1&&p[o]==="["&&p[o+1]!=="]"&&(f<o&&(f=p.indexOf("]",o)),f>o&&(g===-1||g>f||(g=p.indexOf("\\",o),g===-1||g>f)))||l!==-1&&p[o]==="{"&&p[o+1]!=="}"&&(l=p.indexOf("}",o),l>o&&(g=p.indexOf("\\",o),g===-1||g>l))||A!==-1&&p[o]==="("&&p[o+1]==="?"&&/[:!=]/.test(p[o+2])&&p[o+3]!==")"&&(A=p.indexOf(")",o),A>o&&(g=p.indexOf("\\",o),g===-1||g>A))||a!==-1&&p[o]==="("&&p[o+1]!=="|"&&(a<o&&(a=p.indexOf("|",o)),a!==-1&&p[a+1]!==")"&&(A=p.indexOf(")",a),A>a&&(g=p.indexOf("\\",a),g===-1||g>A))))return!0;if(p[o]==="\\"){var T=p[o+1];o+=2;var w=e[T];if(w){var b=p.indexOf(w,o);b!==-1&&(o=b+1)}if(p[o]==="!")return!0}else o++}return!1},y=function(p){if(p[0]==="!")return!0;for(var o=0;o<p.length;){if(/[*?{}()[\]]/.test(p[o]))return!0;if(p[o]==="\\"){var a=p[o+1];o+=2;var f=e[a];if(f){var l=p.indexOf(f,o);l!==-1&&(o=l+1)}if(p[o]==="!")return!0}else o++}return!1};return dt=function(p,o){if(typeof p!="string"||p==="")return!1;if(t(p))return!0;var a=r;return o&&o.strict===!1&&(a=y),a(p)},dt}const io=C(import.meta.url),He=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,jt=t=>{if(typeof He<"u"&&He.versions&&He.versions.node){const[e,r]=He.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return He.getBuiltinModule(t)}return io(t)},uo=jt("path"),ao=jt("os");var gt,Pt;function lo(){if(Pt)return gt;Pt=1;var t=Wt(),e=uo.posix.dirname,r=ao.platform()==="win32",y="/",p=/\\/g,o=/\\([!*?|[\](){}])/g;gt=function(l,A){var g=Object.assign({flipBackslashes:!0},A);g.flipBackslashes&&r&&l.indexOf(y)<0&&(l=l.replace(p,y)),a(l)&&(l+=y),l+="a";do l=e(l);while(f(l));return l.replace(o,"$1")};function a(l){var A=l.slice(-1),g;switch(A){case"}":g="{";break;case"]":g="[";break;default:return!1}var T=l.indexOf(g);return T<0?!1:l.slice(T+1,-1).includes(y)}function f(l){return/\([^()]+$/.test(l)||l[0]==="{"||l[0]==="["||/[^\\][{[]/.test(l)?!0:t(l)}return gt}var po=lo();Et(po);const co=C(import.meta.url),Me=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,fo=t=>{if(typeof Me<"u"&&Me.versions&&Me.versions.node){const[e,r]=Me.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Me.getBuiltinModule(t)}return co(t)},{access:go}=fo("node:fs/promises");async function vt(t,e=Xt){he(t),t=ye(t);try{return await go(t,e),!0}catch{return!1}}const ho=C(import.meta.url),Be=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,mo=t=>{if(typeof Be<"u"&&Be.versions&&Be.versions.node){const[e,r]=Be.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Be.getBuiltinModule(t)}return ho(t)};mo("node:fs");var yo=Wt();Et(yo);const bo=C(import.meta.url),me=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Qt=t=>{if(typeof me<"u"&&me.versions&&me.versions.node){const[e,r]=me.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return me.getBuiltinModule(t)}return bo(t)},{cwd:$o}=me,{mkdir:vo,rename:Eo,copyFile:Ao,unlink:Ro}=Qt("node:fs/promises");Qt("node:fs");class To extends Error{constructor(e,r){super(`Source directory "${ge(e)}" does not match destination directory "${ge(r)}"`),this.name="SameDirectoryError"}}const xo=(t,e)=>{if(!t||!e)throw new Error("Source and destination paths must not be empty");if(ge(t)!==ge(e))throw new To(t,e)},wo=async(t,e,{cwd:r,directoryMode:y,overwrite:p,validateDirectory:o})=>{if(r&&(t=mt(r,t),e=mt(r,e)),o&&xo(t,e),!p&&await vt(e))throw new Error(`The destination file exists: ${e}`);await vo(ge(e),{mode:y,recursive:!0});try{await Eo(t,e)}catch(a){if(a.code==="EXDEV")await Ao(t,e),await Ro(t);else throw a}},Is=async(t,e,r={})=>{const y={overwrite:!0,validateDirectory:!1,...r,cwd:r.cwd?ye(r.cwd):$o()};await wo(t,e,y)};let _o=class extends Error{constructor(e){super(`ENOENT: ${e}`)}get code(){return"ENOENT"}set code(e){throw new Error("Cannot overwrite code ENOENT")}get name(){return"NotFoundError"}set name(e){throw new Error("Cannot overwrite name of NotFoundError")}},So=class extends Error{constructor(e){super(`EPERM: Operation not permitted, ${e}`)}get code(){return"EPERM"}set code(e){throw new Error("Cannot overwrite code EPERM")}get name(){return"PermissionError"}set name(e){throw new Error("Cannot overwrite name of PermissionError")}};const Co=(t,e)=>{const r=t?.code;return r==="ENOENT"?new _o(`no such file or directory, open '${e}'`):r==="EACCES"||r==="EPERM"?new So(`unable to read the non-readable file: ${e}`):t},ko=C(import.meta.url),Ie=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,qt=t=>{if(typeof Ie<"u"&&Ie.versions&&Ie.versions.node){const[e,r]=Ie.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Ie.getBuiltinModule(t)}return ko(t)},{readFile:Oo}=qt("node:fs/promises"),{unzip:No,brotliDecompress:Lo}=qt("node:zlib"),Ho={brotli:Lo,gzip:No,none:(t,e)=>{e(null,t)}},Mo=async(t,e)=>{he(t),t=ye(t);const{buffer:r,compression:y,encoding:p,flag:o}=e??{};let a;try{a=await Oo(t,o?{flag:o}:{})}catch(f){throw Co(f,t)}return await new Promise((f,l)=>{Ho[y??"none"](a,(A,g)=>{A?l(A):f(r?g:g.toString(p??"utf8"))})})},Bo=C(import.meta.url),De=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Vt=t=>{if(typeof De<"u"&&De.versions&&De.versions.node){const[e,r]=De.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return De.getBuiltinModule(t)}return Bo(t)};Vt("node:fs");Vt("node:zlib");const Io=C(import.meta.url),Pe=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Do=t=>{if(typeof Pe<"u"&&Pe.versions&&Pe.versions.node){const[e,r]=Pe.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Pe.getBuiltinModule(t)}return Io(t)},{createRequire:Yt}=Do("node:module"),Po=new Map([["Error",Error],["EvalError",EvalError],["RangeError",RangeError],["ReferenceError",ReferenceError],["SyntaxError",SyntaxError],["TypeError",TypeError],["URIError",URIError]]);typeof AggregateError<"u"&&Po.set("AggregateError",AggregateError);const Fo=Yt(import.meta.url),Fe=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Go=t=>{if(typeof Fe<"u"&&Fe.versions&&Fe.versions.node){const[e,r]=Fe.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Fe.getBuiltinModule(t)}return Fo(t)};Go("node:util");const Uo=Yt(import.meta.url),Ge=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,At=t=>{if(typeof Ge<"u"&&Ge.versions&&Ge.versions.node){const[e,r]=Ge.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Ge.getBuiltinModule(t)}return Uo(t)};At("node:fs");At("node:path");At("node:url");const Xo=t=>{const e={force:!0,recursive:!0};return t?.maxRetries!==void 0&&(e.maxRetries=t.maxRetries),t?.retryDelay!==void 0&&(e.retryDelay=t.retryDelay),e},zo=C(import.meta.url),Ue=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Zt=t=>{if(typeof Ue<"u"&&Ue.versions&&Ue.versions.node){const[e,r]=Ue.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Ue.getBuiltinModule(t)}return zo(t)};Zt("node:fs");Zt("node:fs/promises");const Ko=C(import.meta.url),Xe=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Wo=t=>{if(typeof Xe<"u"&&Xe.versions&&Xe.versions.node){const[e,r]=Xe.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Xe.getBuiltinModule(t)}return Ko(t)};Wo("node:fs");const jo=C(import.meta.url),ze=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Qo=t=>{if(typeof ze<"u"&&ze.versions&&ze.versions.node){const[e,r]=ze.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return ze.getBuiltinModule(t)}return jo(t)},{rm:qo}=Qo("node:fs/promises"),Vo=async(t,e={})=>{he(t),await qo(t,Xo(e))},Yo=C(import.meta.url),Ke=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Zo=t=>{if(typeof Ke<"u"&&Ke.versions&&Ke.versions.node){const[e,r]=Ke.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Ke.getBuiltinModule(t)}return Yo(t)};Zo("node:fs");C(import.meta.url);const Jo=t=>{if(typeof t!="string"&&!(t instanceof ArrayBuffer)&&!ArrayBuffer.isView(t))throw new TypeError("File contents must be a string, ArrayBuffer, or ArrayBuffer view.")},es=C(import.meta.url),We=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ts=t=>{if(typeof We<"u"&&We.versions&&We.versions.node){const[e,r]=We.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return We.getBuiltinModule(t)}return es(t)},{randomBytes:rs}=ts("node:crypto"),os=t=>`${t}.${process.pid.toString(36)}.${rs(6).toString("hex")}.tmp`,ss=new TextEncoder,ns=t=>{if(t instanceof Uint8Array)return t;if(typeof t=="string")return ss.encode(t);if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t)){const e=t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength);return new Uint8Array(e)}throw new TypeError("Invalid contents type. Expected string or ArrayBuffer.")},is=C(import.meta.url),je=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,us=t=>{if(typeof je<"u"&&je.versions&&je.versions.node){const[e,r]=je.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return je.getBuiltinModule(t)}return is(t)},{mkdir:as,writeFile:ls,stat:ps,rename:Ft,chown:cs,chmod:fs,unlink:ds}=us("node:fs/promises"),gs=async(t,e,r)=>{r={backup:!1,encoding:"utf8",flag:"w",overwrite:!0,recursive:!0,...r},he(t),Jo(e),t=ye(t);const y=await vt(t,Xt);if(y&&!r.overwrite)throw new hr(`file already exists, open '${t}'`);const p=os(t);try{!y&&r.recursive&&await as(ge(t),{recursive:!0});let o;if(await ls(p,typeof e=="string"?Buffer.from(e,r.encoding??"utf8"):ns(e),{flag:"wx"}),y&&r.backup&&(o=await ps(t),r.chown??={gid:o.gid,uid:o.uid},await Ft(t,`${t}.bak`)),r.chown)try{await cs(p,r.chown.uid,r.chown.gid)}catch{}await fs(p,o&&!r.mode?o.mode:r.mode??438),await Ft(p,t)}catch(o){throw new Error(`Failed to write file at: ${t} - ${o.message}`,{cause:o})}finally{await vt(p)&&await ds(p)}},hs=C(import.meta.url),Qe=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,ms=t=>{if(typeof Qe<"u"&&Qe.versions&&Qe.versions.node){const[e,r]=Qe.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Qe.getBuiltinModule(t)}return hs(t)};ms("node:fs");const ys=C(import.meta.url),qe=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,bs=t=>{if(typeof qe<"u"&&qe.versions&&qe.versions.node){const[e,r]=qe.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return qe.getBuiltinModule(t)}return ys(t)};bs("node:fs/promises");const $s=C(import.meta.url),Ve=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,vs=t=>{if(typeof Ve<"u"&&Ve.versions&&Ve.versions.node){const[e,r]=Ve.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Ve.getBuiltinModule(t)}return $s(t)};vs("node:fs");const Es=C(import.meta.url),Ye=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,Rt=t=>{if(typeof Ye<"u"&&Ye.versions&&Ye.versions.node){const[e,r]=Ye.versions.node.split(".").map(Number);if(e>22||e===22&&r>=3||e===20&&r>=16)return Ye.getBuiltinModule(t)}return Es(t)},As=Rt("fs"),Rs=Rt("os"),Ts=Rt("path");var ht={},Gt;function xs(){if(Gt)return ht;Gt=1;var t=Object.defineProperty,e=(g,T)=>t(g,"name",{value:T,configurable:!0}),r=As,y=Rs,p=Ts;const o=e(g=>{let T="";for(let w=0;w<g.length;w+=1){const b=g[w],k=b.toUpperCase();T+=b===k?b.toLowerCase():k}return T},"invertCase"),a=new Map,f=e((g,T)=>{const w=p.join(g,`.is-fs-case-sensitive-test-${process.pid}`);try{return T.writeFileSync(w,""),!T.existsSync(o(w))}finally{try{T.unlinkSync(w)}catch{}}},"checkDirectoryCaseWithWrite"),l=e((g,T,w)=>{try{return f(g,w)}catch(b){if(T===void 0)return f(y.tmpdir(),w);throw b}},"checkDirectoryCaseWithFallback"),A=e((g,T=r,w=!0)=>{const b=g??process.cwd();if(w&&a.has(b))return a.get(b);let k;const X=o(b);return X!==b&&T.existsSync(b)?k=!T.existsSync(X):k=l(b,g,T),w&&a.set(b,k),k},"isFsCaseSensitive");return ht.isFsCaseSensitive=A,ht}xs();class Fs extends nr{directory;constructor(e){super(e),this.directory=yt(e?.directory||Ut(rr(),"Upload_meta")),this.accessCheck().catch(r=>{this.logger?.error("Metadata storage access check failed: %O",r)})}getMetaPath=e=>{const r=yt(`${this.directory}/${this.prefix}${e}${this.suffix}`),y=this.directory.endsWith("/")?this.directory:`${this.directory}/`;return r.startsWith(y)?r:nt(it.INVALID_FILE_NAME,`Invalid id: "${e}" resolves outside the meta directory`)};getIdFromPath=e=>e.slice(`${this.directory}/${this.prefix}`.length,-this.suffix.length);async save(e,r){await this.accessCheck();const y={...r};return y.metadata&&(y.metadata=ir(r.metadata)),await gs(this.getMetaPath(e),JSON.stringify(y),{recursive:!0}),r}async touch(e,r){const y=new Date;return await tr(this.getMetaPath(e),y,y),r}async get(e){try{const r=await Mo(this.getMetaPath(e));if(r===void 0)throw nt(it.FILE_NOT_FOUND);const y=JSON.parse(r);return y.metadata&&typeof y.metadata=="string"&&(y.metadata=ur(y.metadata)),y}catch(r){const y=r,p=r instanceof SyntaxError;throw y.code==="ENOENT"||p?nt(it.FILE_NOT_FOUND):r}}async delete(e){await Vo(this.getMetaPath(e))}async accessCheck(){await zt(this.directory)}}export{Is as V,Hs as d,zt as f,Vo as l,Kr as x,Fs as y,Mo as z};
@@ -0,0 +1 @@
1
+ const $=/^[A-Z]:\//i,h=(t="")=>t&&t.replaceAll("\\","/").replace($,n=>n.toUpperCase()),p=/^[/\\]{2}/,d=/^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Z]:[/\\]/i,g=/^[A-Z]:$/i,i=/\/$/,x=()=>typeof process.cwd=="function"?process.cwd().replaceAll("\\","/"):"/",u=(t,n)=>{let e="",l=0,s=-1,r=0,o;for(let f=0;f<=t.length;++f){if(f<t.length)o=t[f];else{if(o==="/")break;o="/"}if(o==="/"){if(!(s===f-1||r===1))if(r===2){if(e.length<2||l!==2||!e.endsWith(".")||e.at(-2)!=="."){if(e.length>2){const a=e.lastIndexOf("/");a===-1?(e="",l=0):(e=e.slice(0,a),l=e.length-1-e.lastIndexOf("/")),s=f,r=0;continue}else if(e.length>0){e="",l=0,s=f,r=0;continue}}n&&(e+=e.length>0?"/..":"..",l=2)}else e.length>0?e+=`/${t.slice(s+1,f)}`:e=t.slice(s+1,f),l=f-s-1;s=f,r=0}else o==="."&&r!==-1?++r:r=-1}return e},c=t=>d.test(t),A=function(t){if(t.length===0)return".";t=h(t);const n=p.exec(t),e=c(t),l=t.at(-1)==="/";return t=u(t,!e),t.length===0?e?"/":l?"./":".":(l&&(t+="/"),g.test(t)&&(t+="/"),n?e?`//${t}`:`//./${t}`:e&&!c(t)?`/${t}`:t)},I=(...t)=>{let n="";for(const e of t)if(e)if(n.length>0){const l=n.at(-1)==="/",s=e[0]==="/";l&&s?n+=e.slice(1):n+=l||s?e:`/${e}`}else n+=e;return A(n)},O=function(...t){t=t.map(l=>h(l));let n="",e=!1;for(let l=t.length-1;l>=-1&&!e;l--){const s=l>=0?t[l]:x();!s||s.length===0||(n=`${s}/${n}`,e=c(s))}return n=u(n,!e),e&&!c(n)?`/${n}`:n.length>0?n:"."},m=t=>{const n=h(t).replace(i,""),e=n.lastIndexOf("/");if(e===-1)return c(t)?"/":".";const l=n.slice(0,e);return g.test(l)?`${l}/`:l||(c(t)?"/":".")},W=(t,n)=>{const e=h(t),l=e.slice(e.lastIndexOf("/")+1);if(n&&l.endsWith(n)){if(n===e)return"";const s=l.slice(0,-n.length);if(s.length>0)return s}return l};export{c as A,O as B,m as H,W as J,A as W,I as m,h as v};
@@ -1 +1 @@
1
- import{n as d}from"./headers-BAiAKekR.js";import{hasBody as _}from"type-is";import{b as h}from"./base-handler-core-EeV8gZck.js";import{ERRORS as E}from"./ERRORS-BIBxE2oR.js";import{b as g,a as C,c as S,d as X}from"./response-builder-CbSA8qPa.js";const M=(a,t={})=>{const e=h(a,"x-file-metadata",!0);if(!e)return t;try{return{...t,...JSON.parse(e)}}catch{return t}},v=a=>{if(!a)return;const t=2e3,e=a.length>t?a.slice(0,Math.max(0,t)):a,r=e.toLowerCase().indexOf("filename");if(r===-1)return;let s=r+8;for(;s<e.length&&(e[s]==="*"||e[s]===" "||e[s]===" ");)s++;if(s>=e.length||e[s]!=="=")return;for(s++;s<e.length&&(e[s]===" "||e[s]===" ");)s++;if(s>=e.length)return;let n=s,i;const o=e[s];return o==='"'||o==="'"?(n=s+1,i=e.indexOf(o,n),i===-1&&(i=e.indexOf(";",n),i===-1&&(i=e.length))):(i=e.indexOf(";",n),i===-1&&(i=e.length)),n>=i?void 0:e.substring(n,i).trim()||void 0},A=a=>{const t=h(a,"content-disposition",!0);return v(t)},L=a=>{const t=h(a,"x-chunked-upload",!0)==="true",e=h(a,"x-chunk-offset",!0),r=h(a,"x-total-size",!0),s={isChunkedUpload:t};if(e){const n=Number.parseInt(e,10);!Number.isNaN(n)&&n>=0&&(s.chunkOffset=n)}if(r){const n=Number.parseInt(r,10);!Number.isNaN(n)&&n>0&&(s.totalSize=n)}return s},P=(a,t=!1)=>{const e=h(a,"x-chunked-upload",!0)==="true";if(!(t&&e)){if(!_(a))throw d(400,"Request body is required");if(Number.parseInt(h(a,"content-length")||"0",10)===0&&!e)throw d(400,"Content-Length is required and must be greater than 0")}},B=(a,t=!1,e)=>{const r=h(a,"x-chunked-upload",!0)==="true",s=Number.parseInt(h(a,"content-length")||"0",10);if(!t&&!r&&s===0)throw d(400,"Content-Length is required and must be greater than 0");if(e!==void 0&&s>e)throw d(413,`File size exceeds maximum allowed size of ${e} bytes`);return s},W=(a,t,e="application/octet-stream")=>{const r=A(a),s=M(a),{isChunkedUpload:n,totalSize:i}=L(a),o=n&&i?i:t;return n&&i&&(s._chunkedUpload=!0,s._chunks=[],s._totalSize=i),{contentType:e,metadata:s,originalName:r,size:o}},x=(a,t)=>{if(a.length===0)return!1;const e=[...a].toSorted((n,i)=>n.offset-i.offset),r=e[0];if(r?.offset!==0)return!1;let s=r.length;for(let n=1;n<e.length;n+=1){const i=e[n];if(i){if(i.offset>s)return!1;s=Math.max(s,i.offset+i.length)}}return s>=t},T=(a,t,e,r)=>{if(Number.isNaN(a)||a<0)throw new Error("Chunk offset must be a valid non-negative number");if(t<=0)throw new Error("Chunk length must be greater than 0");if(t>r)throw new Error(`Chunk size exceeds maximum allowed size of ${r} bytes`);if(a+t>e)throw new Error(`Chunk exceeds file size. Offset: ${a}, Size: ${t}, Total: ${e}`)},D=(a,t)=>{const e=a.find(r=>r.offset===t.offset&&r.length===t.length);return e?t.checksum&&e.checksum!==t.checksum?a.map(r=>r.offset===t.offset?{...r,checksum:t.checksum}:r):a:[...a,t]},U=a=>(a.metadata||{})._chunkedUpload===!0,y=a=>{const t=a.metadata||{};if(t._chunkedUpload===!0&&typeof t._totalSize=="number")return t._totalSize};class j{async deleteSingle(t){const e=await this.storage.delete({id:t});if(e.status===void 0)throw d(404,"File not found");return{...e,headers:{},statusCode:204}}async handlePost(t,e,r,s,n){if(e&&t.size!==void 0){const l=typeof t.size=="number"?t.size:Number.parseInt(String(t.size),10);if(l>0&&l>this.storage.maxUploadSize)throw d(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`)}const i=await this.storage.create(t);if(e){const l=this.buildFileUrl(r,i);return g(i,{...C(i,l),"X-Chunked-Upload":"true","X-Upload-ID":i.id},201)}const o=await this.storage.write({body:s,contentLength:n,id:i.id,start:0}),c=this.buildFileUrl(r,o);return g(o,C(o,c),201)}async handlePut(t,e,r,s,n,i){let o,c=!1;try{await this.storage.getMeta(t),c=!0,i&&await this.storage.update({id:t},{metadata:i}),o=await this.storage.write({body:s,contentLength:n,id:t,start:0})}catch(f){const k=f;if(k.UploadErrorCode===E.FILE_NOT_FOUND||k.code==="ENOENT")try{const p=await this.storage.create(e);o=await this.storage.write({body:s,contentLength:n,id:p.id,start:0})}catch(p){throw p}else throw f}const l=this.buildFileUrl(r,o);return g(o,C(o,l),c?200:201)}async handlePatch(t,e,r,s,n,i){let o=await this.storage.getMeta(t);const c=o.metadata||{},l=U(o);if(l){const u=y(o);u&&o.size!==u&&(o={...o,size:u})}const f=typeof c._totalSize=="number"?c._totalSize:o.size||0;if(!l)throw d(400,"File is not a chunked upload. Use POST or PUT for full file uploads.");const k=100*1024*1024;try{T(e,r,f,k)}catch(u){throw u instanceof Error&&u.message.includes("exceeds maximum")?d(413,u.message):d(400,u instanceof Error?u.message:String(u))}if(o.status==="completed"){const u=this.buildFileUrl(n,o);return g(o,{...C(o,u),"X-Upload-Complete":"true"},200)}const p=await this.storage.withLock(`chunks:${t}`,async()=>{const u=(await this.storage.getMeta(t)).metadata??{},O=Array.isArray(u._chunks)?u._chunks:[],z=D(O,{checksum:s,length:r,offset:e});return await this.storage.update({id:t},{metadata:{...u,_chunks:z}}),z});let m=await this.storage.write({body:i,contentLength:r,id:t,start:e}),w=m.bytesWritten>=f;l&&(w=x(p,f),m.status==="completed"&&!w&&(await this.storage.update({id:t},{status:"part"}),m={...m,status:"part"}));const b=w&&m.bytesWritten!==f?{...m,bytesWritten:f}:m,N=this.buildFileUrl(n,b),F={...C(b,N),...S(b,w),"x-upload-offset":String(b.bytesWritten||0)};return g(b,F,w?200:202)}async handleHead(t){let e=await this.storage.getMeta(t);const r=U(e);if(r){const n=y(e);n&&e.size!==n&&(e={...e,size:n})}const s={...X(e)};if(r){const n=e.metadata||{},i=y(e)||e.size||0,o=Array.isArray(n._chunks)?n._chunks:[],c=x(o,i);Object.assign(s,S(e,c))}return g(e,s,200)}handleOptions(t,e){return{headers:{"Access-Control-Allow-Headers":"Authorization, Content-Type, Content-Length, Content-Disposition, X-File-Metadata, X-Chunked-Upload, X-Total-Size, X-Chunk-Offset, X-Chunk-Checksum","Access-Control-Allow-Methods":t.map(r=>r.toUpperCase()).join(", "),"Access-Control-Max-Age":86400,"X-Max-Upload-Size":String(e)},statusCode:204}}async deleteBatch(t){const e=await this.storage.deleteBatch(t);if(e.successfulCount===0&&e.failedCount>0){const r=e.failed.map(s=>s.id).join(", ");throw d(404,`Failed to delete files: ${r}`)}return{data:e.successful,headers:e.failedCount>0?{"X-Delete-Errors":JSON.stringify(e.failed),"X-Delete-Failed":String(e.failedCount),"X-Delete-Successful":String(e.successfulCount)}:{"X-Delete-Successful":String(e.successfulCount)},statusCode:e.successfulCount===t.length?204:207}}get storage(){throw new Error("storage must be implemented")}buildFileUrl(t,e){throw new Error("buildFileUrl must be implemented")}}export{j as X,B as a,A as b,L as c,W as e,v as p,P as v};
1
+ import{n as d}from"./headers-BAiAKekR.js";import{hasBody as _}from"type-is";import{b as h}from"./base-handler-core-D-9Ku1h-.js";import{ERRORS as E}from"./ERRORS-BIBxE2oR.js";import{b as g,a as C,c as S,d as X}from"./response-builder-CbSA8qPa.js";const M=(a,t={})=>{const e=h(a,"x-file-metadata",!0);if(!e)return t;try{return{...t,...JSON.parse(e)}}catch{return t}},v=a=>{if(!a)return;const t=2e3,e=a.length>t?a.slice(0,Math.max(0,t)):a,r=e.toLowerCase().indexOf("filename");if(r===-1)return;let s=r+8;for(;s<e.length&&(e[s]==="*"||e[s]===" "||e[s]===" ");)s++;if(s>=e.length||e[s]!=="=")return;for(s++;s<e.length&&(e[s]===" "||e[s]===" ");)s++;if(s>=e.length)return;let n=s,i;const o=e[s];return o==='"'||o==="'"?(n=s+1,i=e.indexOf(o,n),i===-1&&(i=e.indexOf(";",n),i===-1&&(i=e.length))):(i=e.indexOf(";",n),i===-1&&(i=e.length)),n>=i?void 0:e.substring(n,i).trim()||void 0},A=a=>{const t=h(a,"content-disposition",!0);return v(t)},L=a=>{const t=h(a,"x-chunked-upload",!0)==="true",e=h(a,"x-chunk-offset",!0),r=h(a,"x-total-size",!0),s={isChunkedUpload:t};if(e){const n=Number.parseInt(e,10);!Number.isNaN(n)&&n>=0&&(s.chunkOffset=n)}if(r){const n=Number.parseInt(r,10);!Number.isNaN(n)&&n>0&&(s.totalSize=n)}return s},P=(a,t=!1)=>{const e=h(a,"x-chunked-upload",!0)==="true";if(!(t&&e)){if(!_(a))throw d(400,"Request body is required");if(Number.parseInt(h(a,"content-length")||"0",10)===0&&!e)throw d(400,"Content-Length is required and must be greater than 0")}},B=(a,t=!1,e)=>{const r=h(a,"x-chunked-upload",!0)==="true",s=Number.parseInt(h(a,"content-length")||"0",10);if(!t&&!r&&s===0)throw d(400,"Content-Length is required and must be greater than 0");if(e!==void 0&&s>e)throw d(413,`File size exceeds maximum allowed size of ${e} bytes`);return s},W=(a,t,e="application/octet-stream")=>{const r=A(a),s=M(a),{isChunkedUpload:n,totalSize:i}=L(a),o=n&&i?i:t;return n&&i&&(s._chunkedUpload=!0,s._chunks=[],s._totalSize=i),{contentType:e,metadata:s,originalName:r,size:o}},x=(a,t)=>{if(a.length===0)return!1;const e=[...a].toSorted((n,i)=>n.offset-i.offset),r=e[0];if(r?.offset!==0)return!1;let s=r.length;for(let n=1;n<e.length;n+=1){const i=e[n];if(i){if(i.offset>s)return!1;s=Math.max(s,i.offset+i.length)}}return s>=t},T=(a,t,e,r)=>{if(Number.isNaN(a)||a<0)throw new Error("Chunk offset must be a valid non-negative number");if(t<=0)throw new Error("Chunk length must be greater than 0");if(t>r)throw new Error(`Chunk size exceeds maximum allowed size of ${r} bytes`);if(a+t>e)throw new Error(`Chunk exceeds file size. Offset: ${a}, Size: ${t}, Total: ${e}`)},D=(a,t)=>{const e=a.find(r=>r.offset===t.offset&&r.length===t.length);return e?t.checksum&&e.checksum!==t.checksum?a.map(r=>r.offset===t.offset?{...r,checksum:t.checksum}:r):a:[...a,t]},U=a=>(a.metadata||{})._chunkedUpload===!0,y=a=>{const t=a.metadata||{};if(t._chunkedUpload===!0&&typeof t._totalSize=="number")return t._totalSize};class j{async deleteSingle(t){const e=await this.storage.delete({id:t});if(e.status===void 0)throw d(404,"File not found");return{...e,headers:{},statusCode:204}}async handlePost(t,e,r,s,n){if(e&&t.size!==void 0){const l=typeof t.size=="number"?t.size:Number.parseInt(String(t.size),10);if(l>0&&l>this.storage.maxUploadSize)throw d(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`)}const i=await this.storage.create(t);if(e){const l=this.buildFileUrl(r,i);return g(i,{...C(i,l),"X-Chunked-Upload":"true","X-Upload-ID":i.id},201)}const o=await this.storage.write({body:s,contentLength:n,id:i.id,start:0}),c=this.buildFileUrl(r,o);return g(o,C(o,c),201)}async handlePut(t,e,r,s,n,i){let o,c=!1;try{await this.storage.getMeta(t),c=!0,i&&await this.storage.update({id:t},{metadata:i}),o=await this.storage.write({body:s,contentLength:n,id:t,start:0})}catch(f){const k=f;if(k.UploadErrorCode===E.FILE_NOT_FOUND||k.code==="ENOENT")try{const p=await this.storage.create(e);o=await this.storage.write({body:s,contentLength:n,id:p.id,start:0})}catch(p){throw p}else throw f}const l=this.buildFileUrl(r,o);return g(o,C(o,l),c?200:201)}async handlePatch(t,e,r,s,n,i){let o=await this.storage.getMeta(t);const c=o.metadata||{},l=U(o);if(l){const u=y(o);u&&o.size!==u&&(o={...o,size:u})}const f=typeof c._totalSize=="number"?c._totalSize:o.size||0;if(!l)throw d(400,"File is not a chunked upload. Use POST or PUT for full file uploads.");const k=100*1024*1024;try{T(e,r,f,k)}catch(u){throw u instanceof Error&&u.message.includes("exceeds maximum")?d(413,u.message):d(400,u instanceof Error?u.message:String(u))}if(o.status==="completed"){const u=this.buildFileUrl(n,o);return g(o,{...C(o,u),"X-Upload-Complete":"true"},200)}const p=await this.storage.withLock(`chunks:${t}`,async()=>{const u=(await this.storage.getMeta(t)).metadata??{},O=Array.isArray(u._chunks)?u._chunks:[],z=D(O,{checksum:s,length:r,offset:e});return await this.storage.update({id:t},{metadata:{...u,_chunks:z}}),z});let m=await this.storage.write({body:i,contentLength:r,id:t,start:e}),w=m.bytesWritten>=f;l&&(w=x(p,f),m.status==="completed"&&!w&&(await this.storage.update({id:t},{status:"part"}),m={...m,status:"part"}));const b=w&&m.bytesWritten!==f?{...m,bytesWritten:f}:m,N=this.buildFileUrl(n,b),F={...C(b,N),...S(b,w),"x-upload-offset":String(b.bytesWritten||0)};return g(b,F,w?200:202)}async handleHead(t){let e=await this.storage.getMeta(t);const r=U(e);if(r){const n=y(e);n&&e.size!==n&&(e={...e,size:n})}const s={...X(e)};if(r){const n=e.metadata||{},i=y(e)||e.size||0,o=Array.isArray(n._chunks)?n._chunks:[],c=x(o,i);Object.assign(s,S(e,c))}return g(e,s,200)}handleOptions(t,e){return{headers:{"Access-Control-Allow-Headers":"Authorization, Content-Type, Content-Length, Content-Disposition, X-File-Metadata, X-Chunked-Upload, X-Total-Size, X-Chunk-Offset, X-Chunk-Checksum","Access-Control-Allow-Methods":t.map(r=>r.toUpperCase()).join(", "),"Access-Control-Max-Age":86400,"X-Max-Upload-Size":String(e)},statusCode:204}}async deleteBatch(t){const e=await this.storage.deleteBatch(t);if(e.successfulCount===0&&e.failedCount>0){const r=e.failed.map(s=>s.id).join(", ");throw d(404,`Failed to delete files: ${r}`)}return{data:e.successful,headers:e.failedCount>0?{"X-Delete-Errors":JSON.stringify(e.failed),"X-Delete-Failed":String(e.failedCount),"X-Delete-Successful":String(e.successfulCount)}:{"X-Delete-Successful":String(e.successfulCount)},statusCode:e.successfulCount===t.length?204:207}}get storage(){throw new Error("storage must be implemented")}buildFileUrl(t,e){throw new Error("buildFileUrl must be implemented")}}export{j as X,B as a,A as b,L as c,W as e,v as p,P as v};
@@ -1 +1 @@
1
- import{Readable as w}from"node:stream";import{C,B as M,X as U,c as O}from"./storage-Cyy73Y6r.js";import{d as T}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as m,ERRORS as y}from"./ERRORS-BIBxE2oR.js";import{createRetryWrapper as A}from"./createRetryWrapper-CxgiV_hH.js";import{y as k}from"./local-meta-storage-C2T92TYb.js";import{t as x}from"./update-size-DuNuLyxj.js";import{i as I}from"./part-match-D-9dGX42.js";import{e as R}from"./has-content-50BsqrWw.js";import{t as S}from"./get-file-status-y3wTtDQs.js";const z=(u,t)=>{const i={};return Object.keys(u).forEach(e=>{i[e]=t(u[e])}),i},v=u=>u===Number(u)?u:(C(u)??0)/1e3,B=5*1024*1024,L=16*1024*1024,N=u=>{if(u)return`bytes=${Math.max(0,u.start)}-${u.end===void 0?"":u.end}`};class b extends M{checksumTypes=["md5","crc32","crc32c","sha1","sha256"];supportsRange=!0;supportsDelimiter=!0;bucket;meta;MAX_PARTS=1e4;partSize;retry;resolvedRetryConfig;constructor(t){if(super(t),this.bucket=t.bucket,this.partSize=typeof t.partSize=="string"?U(t.partSize):t.partSize||L,this.partSize<B)throw new Error("Minimum allowed partSize value is 5MB");const i={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:a=>{const s=a;return s.statusCode&&[408,429,500,502,503,504].includes(s.statusCode)?!0:s.retryable??!1},...t.retryConfig};this.retry=A(i),this.resolvedRetryConfig=i;const{metaStorage:e,metaStorageConfig:r}=t;if(e)this.meta=e;else{const a={...t,...r,logger:this.logger};"directory"in a?(this.logger?.debug("Using local meta storage"),this.meta=new k(a)):this.meta=new k(a)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(a=>{this.logger?.error("Storage access check failed: %O",a)})}getRetryConfig(){return this.resolvedRetryConfig}async create(t,i){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const n=typeof t.ttl=="string"?O(t.ttl):t.ttl;n!==void 0&&(e.expiredAt=Date.now()+n)}const r=new(this.getFileClass())(e);r.name=this.namingFunction(r),await this.validate(r);try{const n=await this.getMeta(r.id);if(n.bytesWritten>=0)return n}catch{}const a=this.getS3Api();let s;try{s=await this.runOperation(i,n=>a.createMultipartUpload({ACL:this.getAcl(),Bucket:this.bucket,ContentType:r.contentType,Key:r.name,Metadata:z({originalName:r.originalName,...r.metadata},o=>encodeURI(String(o)))},{signal:n}))}catch{return m(y.FILE_ERROR,"s3 create upload error")}const{UploadId:c}=s||{};return c?(r.UploadId=c,r.bytesWritten=0,this.config.clientDirectUpload&&(r.partSize??=this.partSize),await this.saveMeta(r),r.status="created",await this.onCreate(r),this.config.clientDirectUpload?this.buildPresigned(r):r):m(y.FILE_ERROR,"s3 create upload error")})}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(typeof t.size=="number"&&t.size>0&&x(e,t.size),!I(t,e))return m(y.FILE_CONFLICT);if(this.config.clientDirectUpload)return this.buildPresigned(e);e.Parts??=await this.getParts(e),e.bytesWritten=e.Parts.map(a=>a.Size||0).reduce((a,s)=>a+s,0);const r=await this.lock(t.id);try{if(R(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return m(y.UNSUPPORTED_CHECKSUM_ALGORITHM);if(e.Parts.length===0&&(!e.contentType||e.contentType==="application/octet-stream"))try{const d=t.body instanceof w?t.body:w.fromWeb(t.body),{fileType:g,stream:f}=await T(d);g?.mime&&(e.contentType=g.mime),t.body=f}catch{}if(e.Parts.length>this.MAX_PARTS)throw new Error(`Exceeded ${this.MAX_PARTS} as part of the upload to ${this.bucket}.`);const a=e.Parts.length+1,s=this.getS3Api(),c=e.UploadId;if(!c)throw new Error("UploadId is required");const n=t.body,o=n instanceof Uint8Array,{ETag:l}=await this.runOperation(i,d=>s.uploadPart({Body:n,Bucket:this.bucket,ContentLength:t.contentLength||0,Key:e.name,PartNumber:a,UploadId:c,...t.checksumAlgorithm==="md5"?{ContentMD5:t.checksum}:{}},{signal:d}),{replayable:o}),p={ETag:l,PartNumber:a,Size:t.contentLength};e.Parts=[...e.Parts,p],e.bytesWritten+=t.contentLength||0}if(this.cache.set(e.id,e),e.status=S(e),e.status==="completed"){const[a]=await this.internalOnComplete(e);delete e.Parts,e.uri=a.Location,e.ETag=a.ETag}}finally{await this.unlock(t.id,r)}return e})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);e.status="deleted",await this.abortMultipartUpload(e,i),await this.deleteMeta(e.id);const r={...e};return await this.onDelete(r),r})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{b.assertSafeId(t),b.assertSafeId(i);const r=await this.getMeta(t),a=`${this.bucket}/${t}`,s=this.bucket,c=i,n=this.getS3Api();return await this.runOperation(e,o=>n.copyObject({Bucket:s,CopySource:a,Key:c,...e?.storageClass&&{StorageClass:e.storageClass}},{signal:o})),{...r,id:c,name:c}})}async move(t,i,e){return this.instrumentOperation("move",async()=>{await this.copy(t,i,e);const r=this.getS3Api();return await this.runOperation(e,a=>r.deleteObject({Bucket:this.bucket,Key:t},{signal:a})),await this.getMeta(i)})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>{const e=this.getS3Api(),r=Math.min(t,1e3);let a={Bucket:this.bucket,MaxKeys:r};const s=[];let c=!0;for(;c&&s.length<t;)try{const n=await this.runOperation(i,o=>e.listObjectsV2(a,{signal:o}));for(const{Key:o,LastModified:l}of n?.Contents||[]){if(s.length>=t)break;o!==void 0&&s.push({id:o,...l&&{createdAt:l}})}c=n.IsTruncated||!1,c&&n.NextContinuationToken&&s.length<t&&(a={...a,ContinuationToken:n.NextContinuationToken,MaxKeys:Math.min(r,t-s.length)})}catch(n){const o=this.normalizeError(n instanceof Error?n:new Error(String(n)));throw await this.onError(o),n}return s},{limit:t})}async listDirectory(t){return this.instrumentOperation("listDirectory",async()=>{const i=this.getS3Api(),e=t?.limit??1e3,r=Math.min(e,1e3);let a={Bucket:this.bucket,Delimiter:t?.delimiter,MaxKeys:r,...t?.prefix!==void 0&&{Prefix:t.prefix}};const s=[],c=new Set;let n=!0;for(;n&&s.length<e;)try{const o=await this.runOperation(t,l=>i.listObjectsV2(a,{signal:l}));for(const{Prefix:l}of o?.CommonPrefixes||[])l!==void 0&&c.add(l);for(const{Key:l,LastModified:p}of o?.Contents||[]){if(s.length>=e)break;l!==void 0&&s.push({id:l,...p&&{createdAt:p}})}n=o.IsTruncated||!1,n&&o.NextContinuationToken&&s.length<e&&(a={...a,ContinuationToken:o.NextContinuationToken,MaxKeys:Math.min(r,e-s.length)})}catch(o){const l=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(l),o}return{files:s,prefixes:[...c]}},{limit:t?.limit??1e3})}async exists({id:t},i){return this.instrumentOperation("exists",async()=>{try{await this.getMeta(t);const e=this.getS3Api();return await this.runOperation(i,r=>e.headObject({Bucket:this.bucket,Key:t},{signal:r})),!0}catch{return!1}})}async get({id:t},i){return this.instrumentOperation("get",async()=>{const e=this.getS3Api(),r=N(i?.range),{Body:a,ContentLength:s,ContentType:c,ETag:n,Expires:o,LastModified:l,Metadata:p}=await this.runOperation(i,h=>e.getObject({Bucket:this.bucket,Key:t,...r!==void 0&&{Range:r}},{signal:h}));await this.checkIfExpired({expiredAt:o});const d=[];if(a)if(a instanceof w)for await(const h of a)d.push(h instanceof Uint8Array?h:new Uint8Array(h));else{const h=a.getReader();try{for(;;){const{done:P,value:E}=await h.read();if(P)break;d.push(E)}}finally{h.releaseLock()}}const{originalName:g,...f}=p||{};return{content:Buffer.concat(d),contentType:c,ETag:n,expiredAt:o,id:t,metadata:f,modifiedAt:l,name:t,originalName:g||t,size:Number(s)}})}async buildPresigned(t){const i=t;if(i.Parts?.length||(i.Parts=await this.getParts(t)),i.bytesWritten=i.Parts.map(e=>e.Size||0).reduce((e,r)=>e+r,0),t.status=S(i),i.partsUrls?.length||(i.partsUrls=await this.getPartsPresignedUrls(t)),t.status==="completed"){const[e]=await this.internalOnComplete(t);return delete i.Parts,i.uri=e.Location,t}return t}async getPartsPresignedUrls(t){t.partSize??=this.partSize;const i=t.UploadId;if(!i)throw new Error("UploadId is required for getting presigned URLs");const e=Math.trunc(t.size/this.partSize)+1,r=[],a=Math.trunc(v(this.config.expiration?.maxAge||"6hrs")),s=this.getS3Api();for(let c=0;c<e;c++)r.push(s.getPresignedUrl({Bucket:this.bucket,expiresIn:a,Key:t.name,PartNumber:c+1,UploadId:i}));return Promise.all(r)}async getParts(t){const i=this.getS3Api(),e=t.UploadId;if(!e)throw new Error("UploadId is required");const{Parts:r=[]}=await this.runOperation(void 0,a=>i.listParts({Bucket:this.bucket,Key:t.name,UploadId:e},{signal:a}));return r}completeMultipartUpload(t){const i=this.getS3Api(),e=t.UploadId;if(!e)throw new Error("UploadId is required");const r=t.Parts?.map(({ETag:a,PartNumber:s})=>{if(!a||!s)throw new Error("ETag and PartNumber are required");return{ETag:a,PartNumber:s}})||[];return this.runOperation(void 0,a=>i.completeMultipartUpload({Bucket:this.bucket,Key:t.name,Parts:r,UploadId:e},{signal:a}))}async abortMultipartUpload(t,i){if(t.status!=="completed")try{const e=this.getS3Api(),r=t.UploadId;if(!r)return;await this.runOperation(i,a=>e.abortMultipartUpload({Bucket:this.bucket,Key:t.name,UploadId:r},{signal:a}))}catch(e){this.logger?.error("abortMultipartUploadError: ",e);const r=this.normalizeError(e instanceof Error?e:new Error(String(e)));await this.onError(r)}}internalOnComplete=async t=>{const[i]=await Promise.all([this.completeMultipartUpload(t),this.deleteMeta(t.id)]);return[i,t]}}export{b as S,N as b};
1
+ import{Readable as w}from"node:stream";import{C,B as M,X as U,c as O}from"./storage-0j5nCAUp.js";import{d as T}from"./detect-file-type-BA7UBLKA.js";import{throwErrorCode as m,ERRORS as y}from"./ERRORS-BIBxE2oR.js";import{createRetryWrapper as A}from"./createRetryWrapper-CxgiV_hH.js";import{y as k}from"./local-meta-storage-iuJnu90B.js";import{t as x}from"./update-size-DuNuLyxj.js";import{i as I}from"./part-match-D-9dGX42.js";import{e as R}from"./has-content-50BsqrWw.js";import{t as S}from"./get-file-status-y3wTtDQs.js";const z=(u,t)=>{const i={};return Object.keys(u).forEach(e=>{i[e]=t(u[e])}),i},v=u=>u===Number(u)?u:(C(u)??0)/1e3,B=5*1024*1024,L=16*1024*1024,N=u=>{if(u)return`bytes=${Math.max(0,u.start)}-${u.end===void 0?"":u.end}`};class b extends M{checksumTypes=["md5","crc32","crc32c","sha1","sha256"];supportsRange=!0;supportsDelimiter=!0;bucket;meta;MAX_PARTS=1e4;partSize;retry;resolvedRetryConfig;constructor(t){if(super(t),this.bucket=t.bucket,this.partSize=typeof t.partSize=="string"?U(t.partSize):t.partSize||L,this.partSize<B)throw new Error("Minimum allowed partSize value is 5MB");const i={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:a=>{const s=a;return s.statusCode&&[408,429,500,502,503,504].includes(s.statusCode)?!0:s.retryable??!1},...t.retryConfig};this.retry=A(i),this.resolvedRetryConfig=i;const{metaStorage:e,metaStorageConfig:r}=t;if(e)this.meta=e;else{const a={...t,...r,logger:this.logger};"directory"in a?(this.logger?.debug("Using local meta storage"),this.meta=new k(a)):this.meta=new k(a)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(a=>{this.logger?.error("Storage access check failed: %O",a)})}getRetryConfig(){return this.resolvedRetryConfig}async create(t,i){return this.instrumentOperation("create",async()=>{const e={...t};if(t.ttl){const n=typeof t.ttl=="string"?O(t.ttl):t.ttl;n!==void 0&&(e.expiredAt=Date.now()+n)}const r=new(this.getFileClass())(e);r.name=this.namingFunction(r),await this.validate(r);try{const n=await this.getMeta(r.id);if(n.bytesWritten>=0)return n}catch{}const a=this.getS3Api();let s;try{s=await this.runOperation(i,n=>a.createMultipartUpload({ACL:this.getAcl(),Bucket:this.bucket,ContentType:r.contentType,Key:r.name,Metadata:z({originalName:r.originalName,...r.metadata},o=>encodeURI(String(o)))},{signal:n}))}catch{return m(y.FILE_ERROR,"s3 create upload error")}const{UploadId:c}=s||{};return c?(r.UploadId=c,r.bytesWritten=0,this.config.clientDirectUpload&&(r.partSize??=this.partSize),await this.saveMeta(r),r.status="created",await this.onCreate(r),this.config.clientDirectUpload?this.buildPresigned(r):r):m(y.FILE_ERROR,"s3 create upload error")})}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(typeof t.size=="number"&&t.size>0&&x(e,t.size),!I(t,e))return m(y.FILE_CONFLICT);if(this.config.clientDirectUpload)return this.buildPresigned(e);e.Parts??=await this.getParts(e),e.bytesWritten=e.Parts.map(a=>a.Size||0).reduce((a,s)=>a+s,0);const r=await this.lock(t.id);try{if(R(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return m(y.UNSUPPORTED_CHECKSUM_ALGORITHM);if(e.Parts.length===0&&(!e.contentType||e.contentType==="application/octet-stream"))try{const d=t.body instanceof w?t.body:w.fromWeb(t.body),{fileType:g,stream:f}=await T(d);g?.mime&&(e.contentType=g.mime),t.body=f}catch{}if(e.Parts.length>this.MAX_PARTS)throw new Error(`Exceeded ${this.MAX_PARTS} as part of the upload to ${this.bucket}.`);const a=e.Parts.length+1,s=this.getS3Api(),c=e.UploadId;if(!c)throw new Error("UploadId is required");const n=t.body,o=n instanceof Uint8Array,{ETag:l}=await this.runOperation(i,d=>s.uploadPart({Body:n,Bucket:this.bucket,ContentLength:t.contentLength||0,Key:e.name,PartNumber:a,UploadId:c,...t.checksumAlgorithm==="md5"?{ContentMD5:t.checksum}:{}},{signal:d}),{replayable:o}),p={ETag:l,PartNumber:a,Size:t.contentLength};e.Parts=[...e.Parts,p],e.bytesWritten+=t.contentLength||0}if(this.cache.set(e.id,e),e.status=S(e),e.status==="completed"){const[a]=await this.internalOnComplete(e);delete e.Parts,e.uri=a.Location,e.ETag=a.ETag}}finally{await this.unlock(t.id,r)}return e})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{const e=await this.getMeta(t);e.status="deleted",await this.abortMultipartUpload(e,i),await this.deleteMeta(e.id);const r={...e};return await this.onDelete(r),r})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{b.assertSafeId(t),b.assertSafeId(i);const r=await this.getMeta(t),a=`${this.bucket}/${t}`,s=this.bucket,c=i,n=this.getS3Api();return await this.runOperation(e,o=>n.copyObject({Bucket:s,CopySource:a,Key:c,...e?.storageClass&&{StorageClass:e.storageClass}},{signal:o})),{...r,id:c,name:c}})}async move(t,i,e){return this.instrumentOperation("move",async()=>{await this.copy(t,i,e);const r=this.getS3Api();return await this.runOperation(e,a=>r.deleteObject({Bucket:this.bucket,Key:t},{signal:a})),await this.getMeta(i)})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>{const e=this.getS3Api(),r=Math.min(t,1e3);let a={Bucket:this.bucket,MaxKeys:r};const s=[];let c=!0;for(;c&&s.length<t;)try{const n=await this.runOperation(i,o=>e.listObjectsV2(a,{signal:o}));for(const{Key:o,LastModified:l}of n?.Contents||[]){if(s.length>=t)break;o!==void 0&&s.push({id:o,...l&&{createdAt:l}})}c=n.IsTruncated||!1,c&&n.NextContinuationToken&&s.length<t&&(a={...a,ContinuationToken:n.NextContinuationToken,MaxKeys:Math.min(r,t-s.length)})}catch(n){const o=this.normalizeError(n instanceof Error?n:new Error(String(n)));throw await this.onError(o),n}return s},{limit:t})}async listDirectory(t){return this.instrumentOperation("listDirectory",async()=>{const i=this.getS3Api(),e=t?.limit??1e3,r=Math.min(e,1e3);let a={Bucket:this.bucket,Delimiter:t?.delimiter,MaxKeys:r,...t?.prefix!==void 0&&{Prefix:t.prefix}};const s=[],c=new Set;let n=!0;for(;n&&s.length<e;)try{const o=await this.runOperation(t,l=>i.listObjectsV2(a,{signal:l}));for(const{Prefix:l}of o?.CommonPrefixes||[])l!==void 0&&c.add(l);for(const{Key:l,LastModified:p}of o?.Contents||[]){if(s.length>=e)break;l!==void 0&&s.push({id:l,...p&&{createdAt:p}})}n=o.IsTruncated||!1,n&&o.NextContinuationToken&&s.length<e&&(a={...a,ContinuationToken:o.NextContinuationToken,MaxKeys:Math.min(r,e-s.length)})}catch(o){const l=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(l),o}return{files:s,prefixes:[...c]}},{limit:t?.limit??1e3})}async exists({id:t},i){return this.instrumentOperation("exists",async()=>{try{await this.getMeta(t);const e=this.getS3Api();return await this.runOperation(i,r=>e.headObject({Bucket:this.bucket,Key:t},{signal:r})),!0}catch{return!1}})}async get({id:t},i){return this.instrumentOperation("get",async()=>{const e=this.getS3Api(),r=N(i?.range),{Body:a,ContentLength:s,ContentType:c,ETag:n,Expires:o,LastModified:l,Metadata:p}=await this.runOperation(i,h=>e.getObject({Bucket:this.bucket,Key:t,...r!==void 0&&{Range:r}},{signal:h}));await this.checkIfExpired({expiredAt:o});const d=[];if(a)if(a instanceof w)for await(const h of a)d.push(h instanceof Uint8Array?h:new Uint8Array(h));else{const h=a.getReader();try{for(;;){const{done:P,value:E}=await h.read();if(P)break;d.push(E)}}finally{h.releaseLock()}}const{originalName:g,...f}=p||{};return{content:Buffer.concat(d),contentType:c,ETag:n,expiredAt:o,id:t,metadata:f,modifiedAt:l,name:t,originalName:g||t,size:Number(s)}})}async buildPresigned(t){const i=t;if(i.Parts?.length||(i.Parts=await this.getParts(t)),i.bytesWritten=i.Parts.map(e=>e.Size||0).reduce((e,r)=>e+r,0),t.status=S(i),i.partsUrls?.length||(i.partsUrls=await this.getPartsPresignedUrls(t)),t.status==="completed"){const[e]=await this.internalOnComplete(t);return delete i.Parts,i.uri=e.Location,t}return t}async getPartsPresignedUrls(t){t.partSize??=this.partSize;const i=t.UploadId;if(!i)throw new Error("UploadId is required for getting presigned URLs");const e=Math.trunc(t.size/this.partSize)+1,r=[],a=Math.trunc(v(this.config.expiration?.maxAge||"6hrs")),s=this.getS3Api();for(let c=0;c<e;c++)r.push(s.getPresignedUrl({Bucket:this.bucket,expiresIn:a,Key:t.name,PartNumber:c+1,UploadId:i}));return Promise.all(r)}async getParts(t){const i=this.getS3Api(),e=t.UploadId;if(!e)throw new Error("UploadId is required");const{Parts:r=[]}=await this.runOperation(void 0,a=>i.listParts({Bucket:this.bucket,Key:t.name,UploadId:e},{signal:a}));return r}completeMultipartUpload(t){const i=this.getS3Api(),e=t.UploadId;if(!e)throw new Error("UploadId is required");const r=t.Parts?.map(({ETag:a,PartNumber:s})=>{if(!a||!s)throw new Error("ETag and PartNumber are required");return{ETag:a,PartNumber:s}})||[];return this.runOperation(void 0,a=>i.completeMultipartUpload({Bucket:this.bucket,Key:t.name,Parts:r,UploadId:e},{signal:a}))}async abortMultipartUpload(t,i){if(t.status!=="completed")try{const e=this.getS3Api(),r=t.UploadId;if(!r)return;await this.runOperation(i,a=>e.abortMultipartUpload({Bucket:this.bucket,Key:t.name,UploadId:r},{signal:a}))}catch(e){this.logger?.error("abortMultipartUploadError: ",e);const r=this.normalizeError(e instanceof Error?e:new Error(String(e)));await this.onError(r)}}internalOnComplete=async t=>{const[i]=await Promise.all([this.completeMultipartUpload(t),this.deleteMeta(t.id)]);return[i,t]}}export{b as S,N as b};