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

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 (121) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/adapter/nuxt/module.d.ts +4 -4
  3. package/dist/adapter/nuxt/node_modules/.bin/nuxi +2 -2
  4. package/dist/adapter/nuxt/node_modules/.bin/nuxt +2 -2
  5. package/dist/ai/ai-sdk/index.d.ts +3 -3
  6. package/dist/ai/claude/index.d.ts +2 -2
  7. package/dist/ai/openai/index.d.ts +3 -3
  8. package/dist/ai/tanstack/index.d.ts +2 -2
  9. package/dist/handler/http/fetch/index.d.ts +7 -7
  10. package/dist/handler/http/fetch/index.js +1 -1
  11. package/dist/handler/http/hono/index.d.ts +4 -4
  12. package/dist/handler/http/hono/index.js +1 -1
  13. package/dist/handler/http/nextjs/index.d.ts +4 -4
  14. package/dist/handler/http/nextjs/index.js +1 -1
  15. package/dist/handler/http/node/index.d.ts +7 -7
  16. package/dist/handler/http/node/index.js +1 -1
  17. package/dist/handler/http/solid-start/index.d.ts +4 -4
  18. package/dist/handler/http/solid-start/index.js +1 -1
  19. package/dist/index.d.ts +5 -5
  20. package/dist/index.js +1 -1
  21. package/dist/packem_shared/{AwsLightStorage-w21RxjUm.js → AwsLightStorage-DbQrK9m7.js} +1 -1
  22. package/dist/packem_shared/{AzureStorage-2kl7JDXs.js → AzureStorage-Cmr0nPDq.js} +1 -1
  23. package/dist/packem_shared/{BoxStorage-BUeEJoGL.js → BoxStorage-DYzAYPIr.js} +1 -1
  24. package/dist/packem_shared/{BunS3Storage-WM3rF6Fw.js → BunS3Storage-BvaFeKeu.js} +1 -1
  25. package/dist/packem_shared/{BunnyStorage-D3s2fRB3.js → BunnyStorage-DsQndiy5.js} +1 -1
  26. package/dist/packem_shared/{CloudinaryStorage-BBE2-aVz.js → CloudinaryStorage-DiK0T7N7.js} +1 -1
  27. package/dist/packem_shared/{DiskStorage-DL0GiG6k.js → DiskStorage-RvZNMWe7.js} +1 -1
  28. package/dist/packem_shared/{DiskStorageWithChecksum-BvUTn7O-.js → DiskStorageWithChecksum-eGOV3leX.js} +1 -1
  29. package/dist/packem_shared/{DropboxStorage-BL3OIdE_.js → DropboxStorage-Dfd78aJL.js} +1 -1
  30. package/dist/packem_shared/Files-CtggibJ-.js +1 -0
  31. package/dist/packem_shared/{FirebaseStorage-lXMXy3Pm.js → FirebaseStorage-C-FwZOYA.js} +1 -1
  32. package/dist/packem_shared/{FtpStorage-Dw94efNW.js → FtpStorage-DzaP89bG.js} +1 -1
  33. package/dist/packem_shared/{GCSMetaStorage-udgXA5ia.js → GCSMetaStorage-DFIjFmn-.js} +1 -1
  34. package/dist/packem_shared/{GCStorage-ChY6uJuO.js → GCStorage-1vA3xkFO.js} +1 -1
  35. package/dist/packem_shared/{GoogleDriveStorage-C0NhBBWH.js → GoogleDriveStorage-D_RaKV_j.js} +1 -1
  36. package/dist/packem_shared/{Multipart-D9WIud9R.js → Multipart-C6Mw7V9W.js} +1 -1
  37. package/dist/packem_shared/{Multipart-CIFfQksD.js → Multipart-DkH4QwNs.js} +1 -1
  38. package/dist/packem_shared/{NetlifyBlobStorage-CO89TGvF.js → NetlifyBlobStorage-C-IkXF0_.js} +1 -1
  39. package/dist/packem_shared/{OneDriveStorage-jAN46vRm.js → OneDriveStorage-C7rqK2Wp.js} +1 -1
  40. package/dist/packem_shared/{PocketBaseStorage-DpOjOKAt.js → PocketBaseStorage-Cdgr5w88.js} +1 -1
  41. package/dist/packem_shared/{Rest-BuD3ySAg.js → Rest-DWrS4Z_j.js} +1 -1
  42. package/dist/packem_shared/{Rest-URrQ5FYM.js → Rest-DY1neM_3.js} +1 -1
  43. package/dist/packem_shared/{S3Storage-n1ohEZj4.js → S3Storage-Dn3l4WkO.js} +1 -1
  44. package/dist/packem_shared/{SftpStorage-Ban-WN8v.js → SftpStorage-CBW6MBLV.js} +1 -1
  45. package/dist/packem_shared/{SharePointStorage-BY90zh1c.js → SharePointStorage-r934t5HX.js} +1 -1
  46. package/dist/packem_shared/{SupabaseStorage-pNbHAE1Y.js → SupabaseStorage-DMRhLPNo.js} +1 -1
  47. package/dist/packem_shared/{Tus-TNG9HAY8.js → Tus-BMd67Cnb.js} +1 -1
  48. package/dist/packem_shared/{Tus-Fp_hx5ug.js → Tus-d2hPK5nV.js} +1 -1
  49. package/dist/packem_shared/{UploadThingStorage-BcmIE2dI.js → UploadThingStorage-BjF_gRMY.js} +1 -1
  50. package/dist/packem_shared/{VercelBlobStorage-s260zfFo.js → VercelBlobStorage-Dx2jywjl.js} +1 -1
  51. package/dist/packem_shared/{base-handler-core-BYDQditz.js → base-handler-core-Cwd9uq_E.js} +1 -1
  52. package/dist/packem_shared/{base-handler-fetch-DWzsPkmV.js → base-handler-fetch-_BD4V1W2.js} +1 -1
  53. package/dist/packem_shared/{base-handler-node-Dety2rQB.js → base-handler-node-BDNRnVIc.js} +1 -1
  54. package/dist/packem_shared/{defaultCloudStorageFileNameValidation-shIZX_7L.js → defaultCloudStorageFileNameValidation-hWLdEgOD.js} +1 -1
  55. package/dist/packem_shared/disk-storage-Bmvawf-b.js +1 -0
  56. package/dist/packem_shared/{disk-storage-with-checksum.d-mHcg2uLw.d.ts → disk-storage-with-checksum.d-Dm4agCey.d.ts} +1 -1
  57. package/dist/packem_shared/{executors.d-X4hz3zfu.d.ts → executors.d-Cut3Gstb.d.ts} +1 -1
  58. package/dist/packem_shared/{gcs-meta-storage-mZiqlX-9.js → gcs-meta-storage-Bwts-MUe.js} +1 -1
  59. package/dist/packem_shared/index.d-DSZjPbvW.d.ts +230 -0
  60. package/dist/packem_shared/{local-meta-storage.d-B11vHYNm.d.ts → local-meta-storage.d-qZQI1JUe.d.ts} +1 -1
  61. package/dist/packem_shared/{media-transformer.d-C3QvECD7.d.ts → media-transformer.d-lQ_RUjb5.d.ts} +2 -2
  62. package/dist/packem_shared/{rest-base-DI7xFXr5.js → rest-base-C-a7pXUc.js} +1 -1
  63. package/dist/packem_shared/{s3-base-storage-Dbexfg7p.js → s3-base-storage-Ek1HinGR.js} +1 -1
  64. package/dist/packem_shared/{s3-base-storage.d-V3N2nKCt.d.ts → s3-base-storage.d-CDIOMTpp.d.ts} +1 -1
  65. package/dist/packem_shared/storage-B-NDsI-o.js +1 -0
  66. package/dist/packem_shared/{storage.d-RteRC-cG.d.ts → storage.d-BoJgdi1n.d.ts} +19 -14
  67. package/dist/packem_shared/{tus-base.d-CygntIPM.d.ts → tus-base.d-C28C_AY9.d.ts} +3 -3
  68. package/dist/packem_shared/{types.d-ChNXbbHG.d.ts → types.d-C0MDnUYc.d.ts} +1 -1
  69. package/dist/packem_shared/{types.d-cI_cMxcZ.d.ts → types.d-CPxJpoPH.d.ts} +2 -2
  70. package/dist/packem_shared/{types.d-DxonY4XS.d.ts → types.d-DCPQvHDI.d.ts} +2 -2
  71. package/dist/storage/aws/index.d.ts +2 -2
  72. package/dist/storage/aws/index.js +1 -1
  73. package/dist/storage/aws-light/index.d.ts +2 -2
  74. package/dist/storage/aws-light/index.js +1 -1
  75. package/dist/storage/azure/index.d.ts +1 -1
  76. package/dist/storage/azure/index.js +1 -1
  77. package/dist/storage/box/index.d.ts +2 -2
  78. package/dist/storage/box/index.js +1 -1
  79. package/dist/storage/bun-s3/index.d.ts +2 -2
  80. package/dist/storage/bun-s3/index.js +1 -1
  81. package/dist/storage/bunny/index.d.ts +2 -2
  82. package/dist/storage/bunny/index.js +1 -1
  83. package/dist/storage/cloudinary/index.d.ts +2 -2
  84. package/dist/storage/cloudinary/index.js +1 -1
  85. package/dist/storage/dropbox/index.d.ts +2 -2
  86. package/dist/storage/dropbox/index.js +1 -1
  87. package/dist/storage/firebase/index.d.ts +2 -2
  88. package/dist/storage/firebase/index.js +1 -1
  89. package/dist/storage/ftp/index.d.ts +2 -2
  90. package/dist/storage/ftp/index.js +1 -1
  91. package/dist/storage/gcs/index.d.ts +1 -1
  92. package/dist/storage/gcs/index.js +1 -1
  93. package/dist/storage/google-drive/index.d.ts +2 -2
  94. package/dist/storage/google-drive/index.js +1 -1
  95. package/dist/storage/local/index.d.ts +3 -3
  96. package/dist/storage/local/index.js +1 -1
  97. package/dist/storage/netlify-blob/index.d.ts +2 -2
  98. package/dist/storage/netlify-blob/index.js +1 -1
  99. package/dist/storage/onedrive/index.d.ts +4 -4
  100. package/dist/storage/onedrive/index.js +1 -1
  101. package/dist/storage/pocketbase/index.d.ts +2 -2
  102. package/dist/storage/pocketbase/index.js +1 -1
  103. package/dist/storage/sftp/index.d.ts +2 -2
  104. package/dist/storage/sftp/index.js +1 -1
  105. package/dist/storage/sharepoint/index.d.ts +3 -3
  106. package/dist/storage/sharepoint/index.js +1 -1
  107. package/dist/storage/supabase/index.d.ts +2 -2
  108. package/dist/storage/supabase/index.js +1 -1
  109. package/dist/storage/uploadthing/index.d.ts +2 -2
  110. package/dist/storage/uploadthing/index.js +1 -1
  111. package/dist/storage/vercel-blob/index.d.ts +2 -2
  112. package/dist/storage/vercel-blob/index.js +1 -1
  113. package/dist/transformer/audio-transformer.d.ts +2 -2
  114. package/dist/transformer/image-transformer.d.ts +2 -2
  115. package/dist/transformer/index.d.ts +3 -3
  116. package/dist/transformer/video-transformer.d.ts +2 -2
  117. package/package.json +1 -1
  118. package/dist/packem_shared/Files-CJh9_N-9.js +0 -1
  119. package/dist/packem_shared/disk-storage-CKAJvhcj.js +0 -1
  120. package/dist/packem_shared/index.d-C4Fivh4I.d.ts +0 -94
  121. package/dist/packem_shared/storage-Dh0tJh7j.js +0 -1
@@ -1 +1 @@
1
- var F=Object.defineProperty;var k=(h,a)=>F(h,"name",{value:a,configurable:!0});import{S as O}from"./index-B4ETk0Lu.js";import M from"ssh2-sftp-client";import{throwErrorCode as d,ERRORS as p}from"./ERRORS-CyOuSMLY.js";import{B as E}from"./storage-Dh0tJh7j.js";import P from"./SftpFile-CQCxZNVq.js";import v from"./SftpMetaStorage-DYqXwCdM.js";import{i as w,n as A,o as l}from"./posix-dirname-CiHXPPnw.js";import{o as b,r as S}from"./part-match-B5fLLmFw.js";import{u as $}from"./update-size-DANV7aa2.js";import{o as x}from"./has-content-Bx2p8Okx.js";var L=Object.defineProperty,T=k((h,a)=>L(h,"name",{value:a,configurable:!0}),"l");const f=T(h=>{const a=h?.code,e=h instanceof Error?h.message:String(h);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},"isNotFoundError"),g=T(h=>{if(h instanceof Error&&h.name==="AbortError")return h;const a=new Error(h instanceof Error&&h.message?h.message:"The operation was aborted",{cause:h});return a.name="AbortError",a},"toAbortError");class K extends E{static name="sftp";checksumTypes=[];meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=w(a.rootFolderPath??""),this.meta=a.metaStorage??new v(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new P(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const n=await this.getMeta(t.id);if(n.status==="completed")return n}catch{}return t.bytesWritten=0,t.status=b(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&$(t,a.size),!S(a,t))return d(p.FILE_CONFLICT);const n=await this.lock(a.id);try{if(x(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return d(p.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return d(p.METHOD_NOT_ALLOWED,"SFTP storage does not support chunked or resumable uploads; send the file in a single request.");const r=await A(a.body),i=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,o=>this.run(o,async s=>{const c=l(i);c&&await s.mkdir(c,!0),await s.put(r,i)})),t.bytesWritten=r.length,t.size=r.length,t.path=i,t.ETag=O(r)}return t.status=b(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,n)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),n=t.path??this.keyToPath(t.name||a),r=await this.runOperation(e,i=>this.run(i,async o=>{try{return await o.get(n)}catch(s){if(f(s))return d(p.FILE_NOT_FOUND);throw s}}));return{content:r,contentType:t.contentType,ETag:t.ETag??O(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),n=t.path??this.keyToPath(t.name||a);await this.runOperation(e,i=>this.run(i,async o=>{try{await o.delete(n)}catch(s){if(!f(s))throw s}})),await this.deleteMeta(a);const r={...t,status:"deleted"};return await this.onDelete(r),r})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const n=await this.getMeta(a),r=n.path??this.keyToPath(n.name||a),i=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async c=>{const u=await c.get(r),m=l(i);m&&await c.mkdir(m,!0),await c.put(u,i)}));const o={...n,id:e,name:e,path:i};return await this.saveMeta(o),o})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const n=await this.getMeta(a),r=n.path??this.keyToPath(n.name||a),i=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async c=>{const u=l(i);u&&await c.mkdir(u,!0);try{await c.rename(r,i)}catch(m){try{const y=await c.get(r);await c.put(y,i),await c.delete(r)}catch(y){throw new AggregateError([m,y],`SFTP move failed: rename and copy+delete fallback both failed for "${r}" → "${i}"`)}}}));const o={...n,id:e,name:e,path:i};await this.saveMeta(o);try{await this.deleteMeta(a)}catch{}return o})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,n=>this.run(n,async r=>{const i=[];return await this.walkList(r,t,i),i}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const n=t.path??this.keyToPath(t.name||a);return this.runOperation(e,r=>this.run(r,async i=>{const o=await i.exists(n);return o==="-"||o==="l"}))})}async walkList(a,e,t){let n;try{n=await a.list(e||".")}catch(r){if(f(r))return;throw r}for(const r of n){const i=e?`${e}/${r.name}`:r.name;if(r.type==="d"){await this.walkList(a,i,t);continue}if(r.type!=="-")continue;const o=this.pathToKey(i);if(!o)continue;const s=new P({contentType:"application/octet-stream",metadata:{},originalName:r.name});s.id=o,s.name=o,s.path=i,s.size=r.size,s.modifiedAt=new Date(r.modifyTime).toISOString(),t.push(s)}}async run(a,e){const t=new M;if(a?.aborted)throw g(a.reason);const n=T(()=>{t.end()},"onAbort");a?.addEventListener("abort",n,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(r){throw a?.aborted?g(r):r}finally{a?.removeEventListener("abort",n),await t.end()}}keyToPath(a){const e=w(a);e&&E.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":this.rootFolderPath.startsWith("/")?`/${t.join("/")}`:t.join("/")}pathToKey(a){const e=w(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{K as default};
1
+ var F=Object.defineProperty;var k=(h,a)=>F(h,"name",{value:a,configurable:!0});import{S as O}from"./index-B4ETk0Lu.js";import M from"ssh2-sftp-client";import{throwErrorCode as d,ERRORS as p}from"./ERRORS-CyOuSMLY.js";import{B as E}from"./storage-B-NDsI-o.js";import P from"./SftpFile-CQCxZNVq.js";import v from"./SftpMetaStorage-DYqXwCdM.js";import{i as w,n as A,o as l}from"./posix-dirname-CiHXPPnw.js";import{o as b,r as S}from"./part-match-B5fLLmFw.js";import{u as $}from"./update-size-DANV7aa2.js";import{o as x}from"./has-content-Bx2p8Okx.js";var L=Object.defineProperty,T=k((h,a)=>L(h,"name",{value:a,configurable:!0}),"l");const f=T(h=>{const a=h?.code,e=h instanceof Error?h.message:String(h);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},"isNotFoundError"),g=T(h=>{if(h instanceof Error&&h.name==="AbortError")return h;const a=new Error(h instanceof Error&&h.message?h.message:"The operation was aborted",{cause:h});return a.name="AbortError",a},"toAbortError");class K extends E{static name="sftp";checksumTypes=[];meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=w(a.rootFolderPath??""),this.meta=a.metaStorage??new v(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new P(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const n=await this.getMeta(t.id);if(n.status==="completed")return n}catch{}return t.bytesWritten=0,t.status=b(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(a,e){return this.instrumentOperation("write",async()=>{let t;if("contentType"in a&&"metadata"in a&&!("body"in a)&&!("start"in a)?t=a:(t=await this.getMeta(a.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(a.size!==void 0&&$(t,a.size),!S(a,t))return d(p.FILE_CONFLICT);const n=await this.lock(a.id);try{if(x(a)){if(this.isUnsupportedChecksum(a.checksumAlgorithm))return d(p.UNSUPPORTED_CHECKSUM_ALGORITHM);if(a.start>0)return d(p.METHOD_NOT_ALLOWED,"SFTP storage does not support chunked or resumable uploads; send the file in a single request.");const r=await A(a.body),i=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,o=>this.run(o,async s=>{const c=l(i);c&&await s.mkdir(c,!0),await s.put(r,i)})),t.bytesWritten=r.length,t.size=r.length,t.path=i,t.ETag=O(r)}return t.status=b(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,n)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),n=t.path??this.keyToPath(t.name||a),r=await this.runOperation(e,i=>this.run(i,async o=>{try{return await o.get(n)}catch(s){if(f(s))return d(p.FILE_NOT_FOUND);throw s}}));return{content:r,contentType:t.contentType,ETag:t.ETag??O(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),n=t.path??this.keyToPath(t.name||a);await this.runOperation(e,i=>this.run(i,async o=>{try{await o.delete(n)}catch(s){if(!f(s))throw s}})),await this.deleteMeta(a);const r={...t,status:"deleted"};return await this.onDelete(r),r})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const n=await this.getMeta(a),r=n.path??this.keyToPath(n.name||a),i=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async c=>{const u=await c.get(r),m=l(i);m&&await c.mkdir(m,!0),await c.put(u,i)}));const o={...n,id:e,name:e,path:i};return await this.saveMeta(o),o})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const n=await this.getMeta(a),r=n.path??this.keyToPath(n.name||a),i=this.keyToPath(e);await this.runOperation(t,s=>this.run(s,async c=>{const u=l(i);u&&await c.mkdir(u,!0);try{await c.rename(r,i)}catch(m){try{const y=await c.get(r);await c.put(y,i),await c.delete(r)}catch(y){throw new AggregateError([m,y],`SFTP move failed: rename and copy+delete fallback both failed for "${r}" → "${i}"`)}}}));const o={...n,id:e,name:e,path:i};await this.saveMeta(o);try{await this.deleteMeta(a)}catch{}return o})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,n=>this.run(n,async r=>{const i=[];return await this.walkList(r,t,i),i}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const n=t.path??this.keyToPath(t.name||a);return this.runOperation(e,r=>this.run(r,async i=>{const o=await i.exists(n);return o==="-"||o==="l"}))})}async walkList(a,e,t){let n;try{n=await a.list(e||".")}catch(r){if(f(r))return;throw r}for(const r of n){const i=e?`${e}/${r.name}`:r.name;if(r.type==="d"){await this.walkList(a,i,t);continue}if(r.type!=="-")continue;const o=this.pathToKey(i);if(!o)continue;const s=new P({contentType:"application/octet-stream",metadata:{},originalName:r.name});s.id=o,s.name=o,s.path=i,s.size=r.size,s.modifiedAt=new Date(r.modifyTime).toISOString(),t.push(s)}}async run(a,e){const t=new M;if(a?.aborted)throw g(a.reason);const n=T(()=>{t.end()},"onAbort");a?.addEventListener("abort",n,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(r){throw a?.aborted?g(r):r}finally{a?.removeEventListener("abort",n),await t.end()}}keyToPath(a){const e=w(a);e&&E.assertSafeId(e);const t=[];return this.rootFolderPath&&t.push(this.rootFolderPath),e&&t.push(e),t.length===0?"":this.rootFolderPath.startsWith("/")?`/${t.join("/")}`:t.join("/")}pathToKey(a){const e=w(a);if(!this.rootFolderPath)return e;if(e===this.rootFolderPath)return"";const t=`${this.rootFolderPath}/`;return e.startsWith(t)?e.slice(t.length):e}}export{K as default};
@@ -1 +1 @@
1
- var I=Object.defineProperty;var h=(i,e)=>I(i,"name",{value:e,configurable:!0});import{throwErrorCode as c,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import u,{buildGraphClient as g}from"./OneDriveStorage-jAN46vRm.js";import{B as v}from"./storage-Dh0tJh7j.js";import E from"./SharePointMetaStorage-DVM5-X6g.js";var m=Object.defineProperty,l=h((i,e)=>m(i,"name",{value:e,configurable:!0}),"d");const p=l(i=>{if(!i)return;const e=i.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},"webUrlLeaf"),S=l(i=>{let e;try{e=new URL(i)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${i}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}},"parseSiteUrl");class C extends v{static name="sharepoint";checksumTypes=[];meta;client;inner;innerPromise;oneDriveAuth;resolvedConfig;constructor(e){super(e);const t=e.accessToken??process.env.SHAREPOINT_ACCESS_TOKEN??process.env.ONEDRIVE_ACCESS_TOKEN,r=e.clientCredentials??(()=>{const o=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,a=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,n=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(o&&a&&n)return{clientId:a,clientSecret:n,tenantId:o}})();this.oneDriveAuth={...e.client&&{client:e.client},...t!==void 0&&{accessToken:t},...r&&{clientCredentials:r},...e.oauth&&{oauth:e.oauth}},this.resolvedConfig={...e,...e.driveId??process.env.SHAREPOINT_DRIVE_ID?{driveId:e.driveId??process.env.SHAREPOINT_DRIVE_ID}:{},...e.siteId??process.env.SHAREPOINT_SITE_ID?{siteId:e.siteId??process.env.SHAREPOINT_SITE_ID}:{},...e.siteUrl??process.env.SHAREPOINT_SITE_URL?{siteUrl:e.siteUrl??process.env.SHAREPOINT_SITE_URL}:{},...e.hostname??process.env.SHAREPOINT_HOSTNAME?{hostname:e.hostname??process.env.SHAREPOINT_HOSTNAME}:{}},this.client=g(this.oneDriveAuth),this.meta=e.metaStorage??new E(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,t){return(await this.getInner()).create(e,t)}async write(e,t){return(await this.getInner()).write(e,t)}async delete(e,t){return(await this.getInner()).delete(e,t)}async get(e,t){return(await this.getInner()).get(e,t)}async copy(e,t,r){return(await this.getInner()).copy(e,t,r)}async move(e,t,r){return(await this.getInner()).move(e,t,r)}async exists(e,t){return(await this.getInner()).exists(e)}async list(e=1e3,t){return(await this.getInner()).list(e,t)}async update(e,t,r){return(await this.getInner()).update(e,t)}async getStream(e,t){return(await this.getInner()).getStream(e)}async getReadUrl(e,t){return(await this.getInner()).getReadUrl(e,t)}async getUploadUrl(e,t){return(await this.getInner()).getUploadUrl(e,t)}async getInner(){return this.inner?this.inner:(this.innerPromise??=this.buildInner(),this.inner=await this.innerPromise,this.inner)}async buildInner(){const e=await this.resolveDriveId(),{documentLibrary:t,hostname:r,siteId:o,sitePath:a,siteUrl:n,...s}=this.genericConfig;return new u({...s,...this.oneDriveAuth,driveId:e,...this.resolvedConfig.copyTimeoutMs!==void 0&&{copyTimeoutMs:this.resolvedConfig.copyTimeoutMs},...this.resolvedConfig.metaStorageConfig&&{metaStorageConfig:this.resolvedConfig.metaStorageConfig},metaStorage:this.meta,...this.resolvedConfig.publicByDefault!==void 0&&{publicByDefault:this.resolvedConfig.publicByDefault},...this.resolvedConfig.rootFolderPath!==void 0&&{rootFolderPath:this.resolvedConfig.rootFolderPath}})}async resolveDriveId(){const e=this.resolvedConfig;if(e.driveId)return e.driveId;const t=await this.resolveSiteId();if(e.documentLibrary){const o=await this.client.api(`/sites/${t}/drives`).get(),a=e.documentLibrary.toLowerCase(),n=(o.value??[]).find(s=>s.name===e.documentLibrary)??(o.value??[]).find(s=>s.name?.toLowerCase()===a||p(s.webUrl)?.toLowerCase()===a);return n?n.id:c(d.FILE_NOT_FOUND,`SharePoint storage: document library "${e.documentLibrary}" not found in site "${t}".`)}const r=await this.client.api(`/sites/${t}/drive`).get();return r?.id?r.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site "${t}" has no default drive.`)}async resolveSiteId(){const e=this.resolvedConfig;if(e.siteId)return e.siteId;let t,r;if(e.siteUrl?{hostname:t,sitePath:r}=S(e.siteUrl):e.hostname&&(t=e.hostname,r=e.sitePath??"/"),!t||!r)return c(d.BAD_REQUEST,"SharePoint storage: missing site targeting. Provide `driveId`, `siteId`, `siteUrl`, or `hostname` (+ `sitePath`).");const o=r==="/"?"":r.replace(/^\/+/,""),a=o?`/sites/${t}:/${o}`:`/sites/${t}`;let n;try{n=await this.client.api(a).get()}catch(s){return c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}" (${s instanceof Error?s.message:String(s)}).`)}return n?.id?n.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{C as default};
1
+ var I=Object.defineProperty;var h=(i,e)=>I(i,"name",{value:e,configurable:!0});import{throwErrorCode as c,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import u,{buildGraphClient as g}from"./OneDriveStorage-C7rqK2Wp.js";import{B as v}from"./storage-B-NDsI-o.js";import E from"./SharePointMetaStorage-DVM5-X6g.js";var m=Object.defineProperty,l=h((i,e)=>m(i,"name",{value:e,configurable:!0}),"d");const p=l(i=>{if(!i)return;const e=i.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},"webUrlLeaf"),S=l(i=>{let e;try{e=new URL(i)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${i}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}},"parseSiteUrl");class C extends v{static name="sharepoint";checksumTypes=[];meta;client;inner;innerPromise;oneDriveAuth;resolvedConfig;constructor(e){super(e);const t=e.accessToken??process.env.SHAREPOINT_ACCESS_TOKEN??process.env.ONEDRIVE_ACCESS_TOKEN,r=e.clientCredentials??(()=>{const o=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,a=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,n=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(o&&a&&n)return{clientId:a,clientSecret:n,tenantId:o}})();this.oneDriveAuth={...e.client&&{client:e.client},...t!==void 0&&{accessToken:t},...r&&{clientCredentials:r},...e.oauth&&{oauth:e.oauth}},this.resolvedConfig={...e,...e.driveId??process.env.SHAREPOINT_DRIVE_ID?{driveId:e.driveId??process.env.SHAREPOINT_DRIVE_ID}:{},...e.siteId??process.env.SHAREPOINT_SITE_ID?{siteId:e.siteId??process.env.SHAREPOINT_SITE_ID}:{},...e.siteUrl??process.env.SHAREPOINT_SITE_URL?{siteUrl:e.siteUrl??process.env.SHAREPOINT_SITE_URL}:{},...e.hostname??process.env.SHAREPOINT_HOSTNAME?{hostname:e.hostname??process.env.SHAREPOINT_HOSTNAME}:{}},this.client=g(this.oneDriveAuth),this.meta=e.metaStorage??new E(e.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(e,t){return(await this.getInner()).create(e,t)}async write(e,t){return(await this.getInner()).write(e,t)}async delete(e,t){return(await this.getInner()).delete(e,t)}async get(e,t){return(await this.getInner()).get(e,t)}async copy(e,t,r){return(await this.getInner()).copy(e,t,r)}async move(e,t,r){return(await this.getInner()).move(e,t,r)}async exists(e,t){return(await this.getInner()).exists(e)}async list(e=1e3,t){return(await this.getInner()).list(e,t)}async update(e,t,r){return(await this.getInner()).update(e,t)}async getStream(e,t){return(await this.getInner()).getStream(e)}async getReadUrl(e,t){return(await this.getInner()).getReadUrl(e,t)}async getUploadUrl(e,t){return(await this.getInner()).getUploadUrl(e,t)}async getInner(){return this.inner?this.inner:(this.innerPromise??=this.buildInner(),this.inner=await this.innerPromise,this.inner)}async buildInner(){const e=await this.resolveDriveId(),{documentLibrary:t,hostname:r,siteId:o,sitePath:a,siteUrl:n,...s}=this.genericConfig;return new u({...s,...this.oneDriveAuth,driveId:e,...this.resolvedConfig.copyTimeoutMs!==void 0&&{copyTimeoutMs:this.resolvedConfig.copyTimeoutMs},...this.resolvedConfig.metaStorageConfig&&{metaStorageConfig:this.resolvedConfig.metaStorageConfig},metaStorage:this.meta,...this.resolvedConfig.publicByDefault!==void 0&&{publicByDefault:this.resolvedConfig.publicByDefault},...this.resolvedConfig.rootFolderPath!==void 0&&{rootFolderPath:this.resolvedConfig.rootFolderPath}})}async resolveDriveId(){const e=this.resolvedConfig;if(e.driveId)return e.driveId;const t=await this.resolveSiteId();if(e.documentLibrary){const o=await this.client.api(`/sites/${t}/drives`).get(),a=e.documentLibrary.toLowerCase(),n=(o.value??[]).find(s=>s.name===e.documentLibrary)??(o.value??[]).find(s=>s.name?.toLowerCase()===a||p(s.webUrl)?.toLowerCase()===a);return n?n.id:c(d.FILE_NOT_FOUND,`SharePoint storage: document library "${e.documentLibrary}" not found in site "${t}".`)}const r=await this.client.api(`/sites/${t}/drive`).get();return r?.id?r.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site "${t}" has no default drive.`)}async resolveSiteId(){const e=this.resolvedConfig;if(e.siteId)return e.siteId;let t,r;if(e.siteUrl?{hostname:t,sitePath:r}=S(e.siteUrl):e.hostname&&(t=e.hostname,r=e.sitePath??"/"),!t||!r)return c(d.BAD_REQUEST,"SharePoint storage: missing site targeting. Provide `driveId`, `siteId`, `siteUrl`, or `hostname` (+ `sitePath`).");const o=r==="/"?"":r.replace(/^\/+/,""),a=o?`/sites/${t}:/${o}`:`/sites/${t}`;let n;try{n=await this.client.api(a).get()}catch(s){return c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}" (${s instanceof Error?s.message:String(s)}).`)}return n?.id?n.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{C as default};
@@ -1 +1 @@
1
- var g=Object.defineProperty;var u=(o,t)=>g(o,"name",{value:t,configurable:!0});import{StorageClient as w}from"@supabase/storage-js";import{throwErrorCode as p,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import{B as y}from"./storage-Dh0tJh7j.js";import c from"./SupabaseFile-DZ1iv9gM.js";import b from"./SupabaseMetaStorage-ivXoYVUu.js";import{o as l,r as E}from"./part-match-B5fLLmFw.js";import{u as k}from"./update-size-DANV7aa2.js";import{o as S}from"./has-content-Bx2p8Okx.js";var O=Object.defineProperty,h=u((o,t)=>O(o,"name",{value:t,configurable:!0}),"p");const f=3600*24*7,U=h(o=>{if(!o||!/^attachment(\s*;|\s*$)/i.test(o.trim()))return;const t=o.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),a=t?.[1]??t?.[2];if(!a)return!0;try{return decodeURIComponent(a.trim())}catch{return a.trim()}},"parseDownloadOption"),C=h(async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream");class z extends y{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(t){if(super(t),this.bucket=t.bucket,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,f),t.client)this.storageClient=t.client;else{const a=t.url??process.env.SUPABASE_URL,e=t.serviceKey??process.env.SUPABASE_SERVICE_ROLE_KEY??process.env.SUPABASE_KEY;if(!a)throw new Error("Supabase storage: `url` is required (or set SUPABASE_URL).");if(!e)throw new Error("Supabase storage: `serviceKey` is required (or set SUPABASE_SERVICE_ROLE_KEY / SUPABASE_KEY).");const r=a.replace(/\/+$/,"")+(a.endsWith("/storage/v1")?"":"/storage/v1");this.storageClient=new w(r,{apikey:e,Authorization:`Bearer ${e}`},t.fetch)}this.meta=t.metaStorage??new b(t.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucket,e.path=e.name,await this.validate(e);try{const r=await this.getMeta(e.id);if(r.bytesWritten>=0)return r}catch{}return e.bytesWritten=0,e.status=l(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&k(e,t.size),!E(t,e))throw new Error("File part does not match");const r=await this.lock(t.id);try{if(S(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await C(t.body),n=e.path??e.name,{data:s,error:m}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).upload(n,i,{contentType:e.contentType,upsert:!0}));if(m)throw m;e.bytesWritten=i.length,e.size=i.length,e.path=s?.path??n,e.ETag=s?.id}return e.status=l(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,r)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const r=e?.path??e?.name??t,{error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).remove([r]));if(i&&i.message&&!/not.*found/i.test(i.message))throw i;return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.bucket,id:t,name:t,path:r,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}const{data:r,error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).exists(e));return i?!1:!!r})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,r;try{r=await this.checkIfExpired(await this.getMeta(t)),e=r.path??r.name??t}catch{}const{data:i,error:n}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).download(e));if(n||!i)throw n??new Error(`Supabase: object not found at "${e}"`);const s=Buffer.from(await this.runOperation(a,()=>i.arrayBuffer()));return{content:s,contentType:r?.contentType??i.type??"application/octet-stream",ETag:r?.ETag,expiredAt:r?.expiredAt,id:t,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??e,originalName:r?.originalName??e,size:r?.size??s.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const r=(await this.getMetaSafe(t))?.path??t,i=a,{error:n}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).copy(r,i));if(n)throw n;const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=i,s.bucket=this.bucket,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const r=(await this.getMetaSafe(t))?.path??t,{error:i}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).move(r,a));if(i)throw i;const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucket;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const{data:e,error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).list("",{limit:t}));if(r)throw r;return(e??[]).map(i=>{const n=new c({contentType:i.metadata?.mimetype??"application/octet-stream",metadata:i.metadata??{},originalName:i.name});return n.id=i.name,n.name=i.name,n.path=i.name,n.bucket=this.bucket,n.size=typeof i.metadata?.size=="number"?i.metadata.size:void 0,n.createdAt=i.created_at??void 0,n.modifiedAt=i.updated_at??void 0,n.ETag=i.metadata?.eTag??i.id??void 0,n})},{limit:t})}async getReadUrl(t,a){const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{data:r,error:i}=await this.storageClient.from(this.bucket).createSignedUrl(t,e,{download:U(a?.responseContentDisposition)});return i||!r?p(d.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUrl failed"):r.signedUrl}async getUploadUrl(t,a){const{data:e,error:r}=await this.storageClient.from(this.bucket).createSignedUploadUrl(t);return r||!e?p(d.METHOD_NOT_ALLOWED,r?.message??"Supabase: createSignedUploadUrl failed"):e.signedUrl}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=h(t=>this.deleteMeta(t.id),"internalOnComplete")}export{z as default};
1
+ var g=Object.defineProperty;var u=(o,t)=>g(o,"name",{value:t,configurable:!0});import{StorageClient as w}from"@supabase/storage-js";import{throwErrorCode as p,ERRORS as d}from"./ERRORS-CyOuSMLY.js";import{B as y}from"./storage-B-NDsI-o.js";import c from"./SupabaseFile-DZ1iv9gM.js";import b from"./SupabaseMetaStorage-ivXoYVUu.js";import{o as l,r as E}from"./part-match-B5fLLmFw.js";import{u as k}from"./update-size-DANV7aa2.js";import{o as S}from"./has-content-Bx2p8Okx.js";var O=Object.defineProperty,h=u((o,t)=>O(o,"name",{value:t,configurable:!0}),"p");const f=3600*24*7,U=h(o=>{if(!o||!/^attachment(\s*;|\s*$)/i.test(o.trim()))return;const t=o.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),a=t?.[1]??t?.[2];if(!a)return!0;try{return decodeURIComponent(a.trim())}catch{return a.trim()}},"parseDownloadOption"),C=h(async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream");class z extends y{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(t){if(super(t),this.bucket=t.bucket,this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,f),t.client)this.storageClient=t.client;else{const a=t.url??process.env.SUPABASE_URL,e=t.serviceKey??process.env.SUPABASE_SERVICE_ROLE_KEY??process.env.SUPABASE_KEY;if(!a)throw new Error("Supabase storage: `url` is required (or set SUPABASE_URL).");if(!e)throw new Error("Supabase storage: `serviceKey` is required (or set SUPABASE_SERVICE_ROLE_KEY / SUPABASE_KEY).");const r=a.replace(/\/+$/,"")+(a.endsWith("/storage/v1")?"":"/storage/v1");this.storageClient=new w(r,{apikey:e,Authorization:`Bearer ${e}`},t.fetch)}this.meta=t.metaStorage??new b(t.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new c(t);e.name=this.namingFunction(e),e.bucket=this.bucket,e.path=e.name,await this.validate(e);try{const r=await this.getMeta(e.id);if(r.bytesWritten>=0)return r}catch{}return e.bytesWritten=0,e.status=l(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&k(e,t.size),!E(t,e))throw new Error("File part does not match");const r=await this.lock(t.id);try{if(S(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const i=await C(t.body),n=e.path??e.name,{data:s,error:m}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).upload(n,i,{contentType:e.contentType,upsert:!0}));if(m)throw m;e.bytesWritten=i.length,e.size=i.length,e.path=s?.path??n,e.ETag=s?.id}return e.status=l(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,r)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const r=e?.path??e?.name??t,{error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).remove([r]));if(i&&i.message&&!/not.*found/i.test(i.message))throw i;return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.bucket,id:t,name:t,path:r,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}const{data:r,error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).exists(e));return i?!1:!!r})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,r;try{r=await this.checkIfExpired(await this.getMeta(t)),e=r.path??r.name??t}catch{}const{data:i,error:n}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).download(e));if(n||!i)throw n??new Error(`Supabase: object not found at "${e}"`);const s=Buffer.from(await this.runOperation(a,()=>i.arrayBuffer()));return{content:s,contentType:r?.contentType??i.type??"application/octet-stream",ETag:r?.ETag,expiredAt:r?.expiredAt,id:t,metadata:r?.metadata??{},modifiedAt:r?.modifiedAt,name:r?.name??e,originalName:r?.originalName??e,size:r?.size??s.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const r=(await this.getMetaSafe(t))?.path??t,i=a,{error:n}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).copy(r,i));if(n)throw n;const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=i,s.bucket=this.bucket,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const r=(await this.getMetaSafe(t))?.path??t,{error:i}=await this.runOperation(e,()=>this.storageClient.from(this.bucket).move(r,a));if(i)throw i;const n=new c({contentType:"application/octet-stream",metadata:{},originalName:a});n.id=a,n.name=a,n.path=a,n.bucket=this.bucket;try{await this.deleteMeta(t)}catch{}return n})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{const{data:e,error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).list("",{limit:t}));if(r)throw r;return(e??[]).map(i=>{const n=new c({contentType:i.metadata?.mimetype??"application/octet-stream",metadata:i.metadata??{},originalName:i.name});return n.id=i.name,n.name=i.name,n.path=i.name,n.bucket=this.bucket,n.size=typeof i.metadata?.size=="number"?i.metadata.size:void 0,n.createdAt=i.created_at??void 0,n.modifiedAt=i.updated_at??void 0,n.ETag=i.metadata?.eTag??i.id??void 0,n})},{limit:t})}async getReadUrl(t,a){const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{data:r,error:i}=await this.storageClient.from(this.bucket).createSignedUrl(t,e,{download:U(a?.responseContentDisposition)});return i||!r?p(d.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUrl failed"):r.signedUrl}async getUploadUrl(t,a){const{data:e,error:r}=await this.storageClient.from(this.bucket).createSignedUploadUrl(t);return r||!e?p(d.METHOD_NOT_ALLOWED,r?.message??"Supabase: createSignedUploadUrl failed"):e.signedUrl}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=h(t=>this.deleteMeta(t.id),"internalOnComplete")}export{z as default};
@@ -1 +1 @@
1
- var U=Object.defineProperty;var p=(h,e)=>U(h,"name",{value:e,configurable:!0});import{format as F}from"node:url";import{n as d}from"./headers-DC2MEOrK.js";import{a,b as m,g as n,c as T}from"./base-handler-core-BYDQditz.js";import{F as E}from"./base-handler-node-Dety2rQB.js";import{TusBase as y,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as w}from"./TUS_RESUMABLE-B7KtPVeC.js";var B=Object.defineProperty,H=p((h,e)=>B(h,"name",{value:e,configurable:!0}),"h");class g extends E{static{p(this,"Tus")}static{H(this,"Tus")}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 y{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(g.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")||"",l=Number.parseInt(a(e,"content-length")||"0",10),u=e.originalUrl||e.url||"",c=m(e);return this.tusBase.handlePost(t,s,r,o,u,c,l,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")),l=a(e,"upload-checksum"),{checksum:u,checksumAlgorithm:c}=this.tusBase.extractChecksum(l),b=e.originalUrl||e.url||"",f=m(e);return this.tusBase.handlePatch(t,s,r,o,u,c,b,f,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":O},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=F({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:T({url:e})+i}}export{O as TUS_RESUMABLE,w as TUS_VERSION,g as Tus};
1
+ var U=Object.defineProperty;var p=(h,e)=>U(h,"name",{value:e,configurable:!0});import{format as F}from"node:url";import{n as d}from"./headers-DC2MEOrK.js";import{a,b as m,g as n,c as T}from"./base-handler-core-Cwd9uq_E.js";import{F as E}from"./base-handler-node-BDNRnVIc.js";import{TusBase as y,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as w}from"./TUS_RESUMABLE-B7KtPVeC.js";var B=Object.defineProperty,H=p((h,e)=>B(h,"name",{value:e,configurable:!0}),"h");class g extends E{static{p(this,"Tus")}static{H(this,"Tus")}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 y{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(g.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")||"",l=Number.parseInt(a(e,"content-length")||"0",10),u=e.originalUrl||e.url||"",c=m(e);return this.tusBase.handlePost(t,s,r,o,u,c,l,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")),l=a(e,"upload-checksum"),{checksum:u,checksumAlgorithm:c}=this.tusBase.extractChecksum(l),b=e.originalUrl||e.url||"",f=m(e);return this.tusBase.handlePatch(t,s,r,o,u,c,b,f,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":O},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=F({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:T({url:e})+i}}export{O as TUS_RESUMABLE,w as TUS_VERSION,g as Tus};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var g=(i,e)=>E(i,"name",{value:e,configurable:!0});import{n as a}from"./headers-DC2MEOrK.js";import{B as w}from"./storage-Dh0tJh7j.js";import{O as B}from"./base-handler-fetch-DWzsPkmV.js";import{TusBase as H,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as k}from"./TUS_RESUMABLE-B7KtPVeC.js";var R=Object.defineProperty,b=g((i,e)=>R(i,"name",{value:e,configurable:!0}),"g");const l=b(i=>{let e;try{const t=new URL(i).pathname.split("/").filter(Boolean);e=t[t.length-1]||void 0}catch{return}if(e){try{w.assertSafeId(e)}catch{throw a(400,`Invalid file id: "${e}"`)}return e}},"getIdFromRequestUrl");class T extends B{static{g(this,"Tus")}static{b(this,"Tus")}static methods=["delete","download","get","head","options","patch","post"];tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends H{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads??!1}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async fetch(e){const t=await super.fetch(e);if(t.headers.has("Tus-Resumable"))return t;const s=new Headers(t.headers);return s.set("Tus-Resumable",O),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})}async options(){return this.tusBase.handleOptions(T.methods)}async post(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=e.headers.get("upload-length")||void 0,r=e.headers.get("upload-defer-length")||void 0,o=e.headers.get("upload-concat")||void 0,d=e.headers.get("upload-metadata")||void 0,u=e.headers.get("content-type")||"",n=e.headers.get("content-length"),h=n?Number.parseInt(n,10):0,c=e.url,p=e.body;return this.tusBase.handlePost(s,r,o,d,c,p,h,u)}async patch(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");const r=e.headers.get("upload-offset");if(!r)throw a(412,"Missing Upload-Offset header");const o=e.headers.get("content-type");if(!o)throw a(412,"Content-Type header required");if(o!=="application/offset+octet-stream")throw a(415,"Unsupported Media Type");const d=Number.parseInt(r,10),u=e.headers.get("upload-length")||void 0,n=e.headers.get("upload-metadata")||void 0,h=e.headers.get("content-length"),c=h?Number.parseInt(h,10):0,p=e.headers.get("upload-checksum")||void 0,{checksum:U,checksumAlgorithm:F}=this.tusBase.extractChecksum(p),v=e.url,y=e.body;try{return this.tusBase.handlePatch(s,d,u,n,U,F,v,y,c)}catch(m){const f=m;throw f.UploadErrorCode==="GONE"||f.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):m}}async head(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleHead(s)}catch(r){const o=r;throw o.UploadErrorCode==="GONE"||o.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):r}}async get(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleGet(s)}catch(r){throw r.UploadErrorCode==="GONE"?a(410,"Upload expired"):r}}async delete(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleDelete(s)}catch(r){throw r.code==="ENOENT"?a(404,"File not found"):r}}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),{pathname:r,search:o}=s,d=`${r}/${t.id}${o}`;return this.storage.config.useRelativeLocation?d:s.origin+d}}export{O as TUS_RESUMABLE,k as TUS_VERSION,T as Tus};
1
+ var E=Object.defineProperty;var g=(i,e)=>E(i,"name",{value:e,configurable:!0});import{n as a}from"./headers-DC2MEOrK.js";import{B as w}from"./storage-B-NDsI-o.js";import{O as B}from"./base-handler-fetch-_BD4V1W2.js";import{TusBase as H,TUS_RESUMABLE as O}from"./TUS_RESUMABLE-B7KtPVeC.js";import{TUS_VERSION as k}from"./TUS_RESUMABLE-B7KtPVeC.js";var R=Object.defineProperty,b=g((i,e)=>R(i,"name",{value:e,configurable:!0}),"g");const l=b(i=>{let e;try{const t=new URL(i).pathname.split("/").filter(Boolean);e=t[t.length-1]||void 0}catch{return}if(e){try{w.assertSafeId(e)}catch{throw a(400,`Invalid file id: "${e}"`)}return e}},"getIdFromRequestUrl");class T extends B{static{g(this,"Tus")}static{b(this,"Tus")}static methods=["delete","download","get","head","options","patch","post"];tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends H{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads??!1}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async fetch(e){const t=await super.fetch(e);if(t.headers.has("Tus-Resumable"))return t;const s=new Headers(t.headers);return s.set("Tus-Resumable",O),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})}async options(){return this.tusBase.handleOptions(T.methods)}async post(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=e.headers.get("upload-length")||void 0,r=e.headers.get("upload-defer-length")||void 0,o=e.headers.get("upload-concat")||void 0,d=e.headers.get("upload-metadata")||void 0,u=e.headers.get("content-type")||"",n=e.headers.get("content-length"),h=n?Number.parseInt(n,10):0,c=e.url,p=e.body;return this.tusBase.handlePost(s,r,o,d,c,p,h,u)}async patch(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");const r=e.headers.get("upload-offset");if(!r)throw a(412,"Missing Upload-Offset header");const o=e.headers.get("content-type");if(!o)throw a(412,"Content-Type header required");if(o!=="application/offset+octet-stream")throw a(415,"Unsupported Media Type");const d=Number.parseInt(r,10),u=e.headers.get("upload-length")||void 0,n=e.headers.get("upload-metadata")||void 0,h=e.headers.get("content-length"),c=h?Number.parseInt(h,10):0,p=e.headers.get("upload-checksum")||void 0,{checksum:U,checksumAlgorithm:F}=this.tusBase.extractChecksum(p),v=e.url,y=e.body;try{return this.tusBase.handlePatch(s,d,u,n,U,F,v,y,c)}catch(m){const f=m;throw f.UploadErrorCode==="GONE"||f.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):m}}async head(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleHead(s)}catch(r){const o=r;throw o.UploadErrorCode==="GONE"||o.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):r}}async get(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleGet(s)}catch(r){throw r.UploadErrorCode==="GONE"?a(410,"Upload expired"):r}}async delete(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=l(e.url);if(!s)throw a(404,"File not found");try{return this.tusBase.handleDelete(s)}catch(r){throw r.code==="ENOENT"?a(404,"File not found"):r}}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),{pathname:r,search:o}=s,d=`${r}/${t.id}${o}`;return this.storage.config.useRelativeLocation?d:s.origin+d}}export{O as TUS_RESUMABLE,k as TUS_VERSION,T as Tus};
@@ -1 +1 @@
1
- var T=Object.defineProperty;var l=(n,t)=>T(n,"name",{value:t,configurable:!0});import{UTApi as U,UTFile as h}from"uploadthing/server";import{throwErrorCode as m,ERRORS as f}from"./ERRORS-CyOuSMLY.js";import{B as I}from"./storage-Dh0tJh7j.js";import d from"./UploadThingFile-BpG9mE8K.js";import O from"./UploadThingMetaStorage-BvKNzgm7.js";import{o as y,r as E}from"./part-match-B5fLLmFw.js";import{u as k}from"./update-size-DANV7aa2.js";import{o as v}from"./has-content-Bx2p8Okx.js";var b=Object.defineProperty,u=l((n,t)=>b(n,"name",{value:t,configurable:!0}),"c");const w=3600*24*7,x=u(n=>{let t;try{t=typeof atob=="function"?atob(n):Buffer.from(n,"base64").toString("utf8")}catch(e){throw new Error(`UploadThing: token is not valid base64: ${e.message}`)}let a;try{a=JSON.parse(t)}catch(e){throw new Error(`UploadThing: token does not decode to JSON: ${e.message}`)}if(!a||typeof a!="object"||typeof a.apiKey!="string"||typeof a.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return a},"decodeToken"),N=u(async n=>{const t=[];for await(const a of n)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream"),g=u(n=>{const t=n.lastIndexOf("/");return t===-1?n:n.slice(t+1)},"basename");class F extends I{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(t){super(t);const a=t.token??process.env.UPLOADTHING_TOKEN;if(t.client)this.utapi=t.client;else{if(!a)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new U({defaultKeyType:"customId",token:a})}if(!a)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=x(a).appId,this.acl=t.acl??"public-read",this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w),this.meta=t.metaStorage??new O(t.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new d(t);e.name=this.namingFunction(e),e.customId=e.name,await this.validate(e);try{const i=await this.getMeta(e.id);if(i.bytesWritten>=0)return i}catch{}return e.bytesWritten=0,e.status=y(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&k(e,t.size),!E(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(v(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await N(t.body),p=new Blob([new Uint8Array(r)],{type:e.contentType}),o=new h([p],g(e.name||e.id),{customId:e.name||e.id,type:e.contentType}),s=await this.runOperation(a,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const{data:c}=s;e.bytesWritten=r.length,e.size=r.length,e.ufsKey=c.key,e.url=c.ufsUrl??c.url,e.ETag=c.fileHash,e.fileHash=c.fileHash}return e.status=y(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,i)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const i=e?.customId??e?.name??t;return await this.runOperation(a,()=>this.utapi.deleteFiles(i)),e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:t}),{customId:i,id:t,name:t,status:"deleted"})})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e,i=t;try{e=await this.checkIfExpired(await this.getMeta(t)),i=e.customId??e.name??t}catch{}const r=await this.resolveFetchUrl(i,a),p=await this.runOperation(a,()=>fetch(r));if(!p.ok)throw new Error(`UploadThing: fetch failed: ${p.status} ${p.statusText} for ${i}`);const o=Buffer.from(await p.arrayBuffer());return{content:o,contentType:e?.contentType??p.headers.get("content-type")??"application/octet-stream",ETag:e?.ETag??p.headers.get("etag")??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt,name:e?.name??i,originalName:e?.originalName??i,size:e?.size??o.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=await this.get({id:t},e),r=new Blob([new Uint8Array(i.content)],{type:i.contentType}),p=new h([r],g(a),{customId:a,type:i.contentType}),o=await this.runOperation(e,()=>this.utapi.uploadFiles(p,{acl:this.acl}));if(o.error)throw new Error(o.error.message);const s=new d({contentType:i.contentType,metadata:{},originalName:a});return s.id=a,s.name=a,s.customId=a,s.size=typeof i.size=="string"?Number(i.size):i.size,s.ufsKey=o.data.key,s.url=o.data.ufsUrl??o.data.url,s.ETag=o.data.fileHash,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=await this.copy(t,a,e);return await this.delete({id:t},e),i})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>(await this.runOperation(a,()=>this.utapi.listFiles({limit:t}))).files.map(e=>{const i=e.customId??e.key,r=new d({contentType:"application/octet-stream",metadata:{},originalName:i});return r.id=i,r.name=i,r.customId=e.customId??void 0,r.ufsKey=e.key,r.size=e.size,r.modifiedAt=e.uploadedAt?new Date(e.uploadedAt).toISOString():void 0,r}),{limit:t})}async getReadUrl(t,a){if(a?.responseContentDisposition)return m(f.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition` is not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,w),{ufsUrl:i}=await this.utapi.generateSignedURL(t,{expiresIn:e,keyType:"customId"});return i}async getUploadUrl(t,a){return m(f.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(t,a){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const{ufsUrl:e}=await this.runOperation(a,()=>this.utapi.generateSignedURL(t,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return e}internalOnComplete=u(t=>this.deleteMeta(t.id),"internalOnComplete")}export{F as default};
1
+ var T=Object.defineProperty;var l=(n,t)=>T(n,"name",{value:t,configurable:!0});import{UTApi as U,UTFile as h}from"uploadthing/server";import{throwErrorCode as m,ERRORS as f}from"./ERRORS-CyOuSMLY.js";import{B as I}from"./storage-B-NDsI-o.js";import d from"./UploadThingFile-BpG9mE8K.js";import O from"./UploadThingMetaStorage-BvKNzgm7.js";import{o as y,r as E}from"./part-match-B5fLLmFw.js";import{u as k}from"./update-size-DANV7aa2.js";import{o as v}from"./has-content-Bx2p8Okx.js";var b=Object.defineProperty,u=l((n,t)=>b(n,"name",{value:t,configurable:!0}),"c");const w=3600*24*7,x=u(n=>{let t;try{t=typeof atob=="function"?atob(n):Buffer.from(n,"base64").toString("utf8")}catch(e){throw new Error(`UploadThing: token is not valid base64: ${e.message}`)}let a;try{a=JSON.parse(t)}catch(e){throw new Error(`UploadThing: token does not decode to JSON: ${e.message}`)}if(!a||typeof a!="object"||typeof a.apiKey!="string"||typeof a.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return a},"decodeToken"),N=u(async n=>{const t=[];for await(const a of n)t.push(Buffer.from(a));return Buffer.concat(t)},"collectStream"),g=u(n=>{const t=n.lastIndexOf("/");return t===-1?n:n.slice(t+1)},"basename");class F extends I{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(t){super(t);const a=t.token??process.env.UPLOADTHING_TOKEN;if(t.client)this.utapi=t.client;else{if(!a)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new U({defaultKeyType:"customId",token:a})}if(!a)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=x(a).appId,this.acl=t.acl??"public-read",this.defaultUrlExpiresIn=Math.min(t.defaultUrlExpiresIn??3600,w),this.meta=t.metaStorage??new O(t.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new d(t);e.name=this.namingFunction(e),e.customId=e.name,await this.validate(e);try{const i=await this.getMeta(e.id);if(i.bytesWritten>=0)return i}catch{}return e.bytesWritten=0,e.status=y(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&k(e,t.size),!E(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(v(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await N(t.body),p=new Blob([new Uint8Array(r)],{type:e.contentType}),o=new h([p],g(e.name||e.id),{customId:e.name||e.id,type:e.contentType}),s=await this.runOperation(a,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const{data:c}=s;e.bytesWritten=r.length,e.size=r.length,e.ufsKey=c.key,e.url=c.ufsUrl??c.url,e.ETag=c.fileHash,e.fileHash=c.fileHash}return e.status=y(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,i)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const i=e?.customId??e?.name??t;return await this.runOperation(a,()=>this.utapi.deleteFiles(i)),e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:t}),{customId:i,id:t,name:t,status:"deleted"})})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e,i=t;try{e=await this.checkIfExpired(await this.getMeta(t)),i=e.customId??e.name??t}catch{}const r=await this.resolveFetchUrl(i,a),p=await this.runOperation(a,()=>fetch(r));if(!p.ok)throw new Error(`UploadThing: fetch failed: ${p.status} ${p.statusText} for ${i}`);const o=Buffer.from(await p.arrayBuffer());return{content:o,contentType:e?.contentType??p.headers.get("content-type")??"application/octet-stream",ETag:e?.ETag??p.headers.get("etag")??void 0,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt,name:e?.name??i,originalName:e?.originalName??i,size:e?.size??o.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=await this.get({id:t},e),r=new Blob([new Uint8Array(i.content)],{type:i.contentType}),p=new h([r],g(a),{customId:a,type:i.contentType}),o=await this.runOperation(e,()=>this.utapi.uploadFiles(p,{acl:this.acl}));if(o.error)throw new Error(o.error.message);const s=new d({contentType:i.contentType,metadata:{},originalName:a});return s.id=a,s.name=a,s.customId=a,s.size=typeof i.size=="string"?Number(i.size):i.size,s.ufsKey=o.data.key,s.url=o.data.ufsUrl??o.data.url,s.ETag=o.data.fileHash,s})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=await this.copy(t,a,e);return await this.delete({id:t},e),i})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>(await this.runOperation(a,()=>this.utapi.listFiles({limit:t}))).files.map(e=>{const i=e.customId??e.key,r=new d({contentType:"application/octet-stream",metadata:{},originalName:i});return r.id=i,r.name=i,r.customId=e.customId??void 0,r.ufsKey=e.key,r.size=e.size,r.modifiedAt=e.uploadedAt?new Date(e.uploadedAt).toISOString():void 0,r}),{limit:t})}async getReadUrl(t,a){if(a?.responseContentDisposition)return m(f.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition` is not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const e=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,w),{ufsUrl:i}=await this.utapi.generateSignedURL(t,{expiresIn:e,keyType:"customId"});return i}async getUploadUrl(t,a){return m(f.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(t,a){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(t)}`;const{ufsUrl:e}=await this.runOperation(a,()=>this.utapi.generateSignedURL(t,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return e}internalOnComplete=u(t=>this.deleteMeta(t.id),"internalOnComplete")}export{F as default};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var u=(c,e)=>E(c,"name",{value:e,configurable:!0});import{put as d,list as h,del as m,copy as p}from"@vercel/blob";import{a as g}from"./detect-file-type-5JhzC9RU.js";import{B as v,t as T}from"./storage-Dh0tJh7j.js";import{v as b}from"./local-meta-storage-Bi0mK6gD.js";import f from"./VercelBlobFile-Cni_1qwD.js";import{o as w,r as B}from"./part-match-B5fLLmFw.js";import{u as _}from"./update-size-DANV7aa2.js";import{o as k}from"./has-content-Bx2p8Okx.js";var I=Object.defineProperty,C=u((c,e)=>I(c,"name",{value:e,configurable:!0}),"p");class y extends v{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:p,credentials:this.credentials,del:m,list:h,put:d}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=y.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:i,metaStorageConfig:t}=e;this.meta=i||new b(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const i=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,r=t?.startsWith("store_")?t.slice(6):t;if(i&&r)return{oidcToken:i,storeId:r};if(i||r)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${i?"set":"missing"}, storeId=${r?"set":"missing"}.`);const a=process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN;if(a)return{token:a};throw new Error("Vercel Blob credentials are required. Provide `token`, an `oidcToken`+`storeId` pair, or set BLOB_READ_WRITE_TOKEN / (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) env vars.")}async create(e,i){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?T(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const r=new f(t);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);if(a.bytesWritten>=0)return a}catch{}return r.bytesWritten=0,r.status=w(r),await this.saveMeta(r),await this.onCreate(r),r})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&_(t,e.size),!B(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(k(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],n=e.body;for await(const o of n)a.push(Buffer.from(o));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await g(s);o?.mime&&(t.contentType=o.mime)}catch{}const O=new Blob([s],{type:t.contentType}),l=await this.runOperation(i,()=>d(t.name,O,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=l.url,t.pathname=l.pathname,t.downloadUrl=l.downloadUrl,t.bytesWritten=s.length}return t.status=w(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);const{url:r}=t;t.status="deleted";try{await this.runOperation(i,()=>m(r,{...this.credentials}))}catch(n){this.logger?.error("Failed to delete blob from Vercel Blob:",n);const s=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},i){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:r}=t;return(await this.runOperation(i,()=>fetch(r,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},i){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.url||t.url.length===0)throw new Error("File URL not found");const{url:r}=t,a=await this.runOperation(i,()=>fetch(r)),n=Buffer.from(await this.runOperation(i,()=>a.arrayBuffer()));return{content:n,contentType:t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||n.length}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const r=await this.getMeta(e);if(!r.url)throw new Error("Source file URL not found");const a=r.url,n=await this.runOperation(t,()=>p(a,i,{access:"public",...this.credentials}));return{...r,id:i,name:i,pathname:n.pathname,url:n.url}})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const r=await this.copy(e,i,t);return await this.delete({id:e},t),r})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>(await this.runOperation(i,()=>h({limit:e,...this.credentials}))).blobs.map(t=>{const r=new f({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return r.createdAt=t.uploadedAt?.toISOString(),r.id=t.pathname,r.modifiedAt=t.uploadedAt?.toISOString(),r.name=t.pathname,r.pathname=t.pathname,r.size=t.size,r.url=t.url,r.downloadUrl=t.downloadUrl,r}),{limit:e})}internalOnComplete=C(e=>this.deleteMeta(e.id),"internalOnComplete");shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{y as default};
1
+ var E=Object.defineProperty;var u=(c,e)=>E(c,"name",{value:e,configurable:!0});import{put as d,list as h,del as m,copy as p}from"@vercel/blob";import{a as g}from"./detect-file-type-5JhzC9RU.js";import{B as v,t as T}from"./storage-B-NDsI-o.js";import{v as b}from"./local-meta-storage-Bi0mK6gD.js";import f from"./VercelBlobFile-Cni_1qwD.js";import{o as w,r as B}from"./part-match-B5fLLmFw.js";import{u as _}from"./update-size-DANV7aa2.js";import{o as k}from"./has-content-Bx2p8Okx.js";var I=Object.defineProperty,C=u((c,e)=>I(c,"name",{value:e,configurable:!0}),"p");class y extends v{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:p,credentials:this.credentials,del:m,list:h,put:d}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=y.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:i,metaStorageConfig:t}=e;this.meta=i||new b(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const i=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,r=t?.startsWith("store_")?t.slice(6):t;if(i&&r)return{oidcToken:i,storeId:r};if(i||r)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${i?"set":"missing"}, storeId=${r?"set":"missing"}.`);const a=process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN;if(a)return{token:a};throw new Error("Vercel Blob credentials are required. Provide `token`, an `oidcToken`+`storeId` pair, or set BLOB_READ_WRITE_TOKEN / (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) env vars.")}async create(e,i){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?T(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const r=new f(t);r.name=this.namingFunction(r),await this.validate(r);try{const a=await this.getMeta(r.id);if(a.bytesWritten>=0)return a}catch{}return r.bytesWritten=0,r.status=w(r),await this.saveMeta(r),await this.onCreate(r),r})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&_(t,e.size),!B(e,t))throw new Error("File part does not match");const r=await this.lock(e.id);try{if(k(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],n=e.body;for await(const o of n)a.push(Buffer.from(o));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await g(s);o?.mime&&(t.contentType=o.mime)}catch{}const O=new Blob([s],{type:t.contentType}),l=await this.runOperation(i,()=>d(t.name,O,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=l.url,t.pathname=l.pathname,t.downloadUrl=l.downloadUrl,t.bytesWritten=s.length}return t.status=w(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,r)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);const{url:r}=t;t.status="deleted";try{await this.runOperation(i,()=>m(r,{...this.credentials}))}catch(n){this.logger?.error("Failed to delete blob from Vercel Blob:",n);const s=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},i){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:r}=t;return(await this.runOperation(i,()=>fetch(r,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},i){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.url||t.url.length===0)throw new Error("File URL not found");const{url:r}=t,a=await this.runOperation(i,()=>fetch(r)),n=Buffer.from(await this.runOperation(i,()=>a.arrayBuffer()));return{content:n,contentType:t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||n.length}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const r=await this.getMeta(e);if(!r.url)throw new Error("Source file URL not found");const a=r.url,n=await this.runOperation(t,()=>p(a,i,{access:"public",...this.credentials}));return{...r,id:i,name:i,pathname:n.pathname,url:n.url}})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const r=await this.copy(e,i,t);return await this.delete({id:e},t),r})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>(await this.runOperation(i,()=>h({limit:e,...this.credentials}))).blobs.map(t=>{const r=new f({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return r.createdAt=t.uploadedAt?.toISOString(),r.id=t.pathname,r.modifiedAt=t.uploadedAt?.toISOString(),r.name=t.pathname,r.pathname=t.pathname,r.size=t.size,r.url=t.url,r.downloadUrl=t.downloadUrl,r}),{limit:e})}internalOnComplete=C(e=>this.deleteMeta(e.id),"internalOnComplete");shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{y as default};
@@ -1 +1 @@
1
- var b=Object.defineProperty;var u=(r,e)=>b(r,"name",{value:e,configurable:!0});import{EventEmitter as y}from"node:events";import{format as w}from"node:url";import R from"mime";import{ErrorMap as E}from"./ERRORS-CyOuSMLY.js";import{H as v}from"./headers-DC2MEOrK.js";import{Readable as p}from"node:stream";import U,{hasBody as I}from"type-is";import{B as h}from"./storage-Dh0tJh7j.js";var H=Object.defineProperty,L=u((r,e)=>H(r,"name",{value:e,configurable:!0}),"a");const $=L(r=>r.at(-1),"getLastOne");var B=Object.defineProperty,i=u((r,e)=>B(r,"name",{value:e,configurable:!0}),"n");const N=i(r=>{let e="",t="";const s=c(r,"forwarded");return s&&s.split(";").forEach(a=>{const[n,o]=a.split("=");n==="proto"&&(e=o),n==="host"&&(t=o)}),{host:t,proto:e}},"extractForwarded"),x=i((r,e="utf8",t)=>new Promise((s,a)=>{const n=[];let o=0;r.on("data",l=>{const d=Buffer.isBuffer(l)?l:Buffer.from(l,e);if(o+=d.length,t!==void 0&&o>t){a(new Error("Request body length limit exceeded")),r.destroy();return}n.push(d)}),r.once("end",()=>{s(Buffer.concat(n).toString(e))}),r.once("error",a)}),"readBody"),c=i((r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const a=Array.isArray(s)?s:s.split(",");return $(a).trim()},"getHeader");i(async(r,e=16777216)=>{if(!U(r,["json"]))return{};if(r.body)return{...r.body};if(I(r)){const s=Number.parseInt(c(r,"content-length"),10);if(!Number.isNaN(s)&&s>e)throw new Error("body length limit")}const t=await x(r,"utf8",e);return{...JSON.parse(t)}},"getMetadata");const P=i((r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},"appendHeader"),V=i((r,e={})=>{const t=Object.keys(e);t.length>0&&P(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{if(["link","location"].includes(s.toLowerCase())){const a=encodeURI(e[s].toString()).replaceAll("#","%23");r.setHeader(s,a)}else r.setHeader(s,e[s])})},"setHeaders"),q=i(r=>c(r,"host")||c(r,"x-forwarded-host"),"extractHost"),F=i(r=>c(r,"x-forwarded-proto").toLowerCase(),"extractProto"),T=i(r=>{let{host:e,proto:t}=N(r);return e||=q(r),t||=F(r),e?t?`${t}://${e}`:`//${e}`:""},"getBaseUrl"),S=i(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},"getRealPath"),O=/^[\da-z]{4,}(?:-[\da-z]{4,}){2,}$/i,X=i(r=>{const e=S(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let a=e.length-1;a>=0;a-=1){const n=e[a];if(!n)continue;const o=n.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(o.toLowerCase())&&O.test(o))return h.assertSafeId(o),o}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")},"getIdFromRequest"),Y=i(r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?p.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?p.from(Buffer.from(r.body)):r instanceof p?r:p.from(new Uint8Array(0)),"getRequestStream");var j=Object.defineProperty,C=u((r,e)=>j(r,"name",{value:e,configurable:!0}),"r");const Z=C((r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},"pick");var k=Object.defineProperty,m=u((r,e)=>k(r,"name",{value:e,configurable:!0}),"d");class _ extends y{static{u(this,"E")}static{m(this,"BaseHandlerCore")}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=m((e={})=>{this.internalErrorResponses={...E,...this.internalErrorResponses,...this.storage.errorResponses,...e}},"assembleErrors");parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const a=s[0]?.trim();if(!a)return;const n=a.split("-");if(n.length!==2)return;const[o,l]=n;let d,f;if(o&&l)d=Number.parseInt(o,10),f=Number.parseInt(l,10);else if(o&&!l)d=Number.parseInt(o,10),f=t-1;else if(!o&&l){const g=Number.parseInt(l,10);d=Math.max(0,t-g),f=t-1}else return;if(!(Number.isNaN(d)||Number.isNaN(f)||d>=t||f>=t||d>f))return{end:f,start:d}}buildFileUrlFromString(e,t){const s=new URL(e,"http://localhost"),{pathname:a}=s,n=Object.fromEntries(s.searchParams.entries()),o=w({pathname:`${a}/${t.id}`,query:n});return`${this.storage.config.useRelativeLocation?"":T({url:e})}${o}.${R.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return v.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{_ as E,Z as T,c as a,Y as b,T as c,S as d,X as g,x as r,V as s,O as u};
1
+ var b=Object.defineProperty;var u=(r,e)=>b(r,"name",{value:e,configurable:!0});import{EventEmitter as y}from"node:events";import{format as w}from"node:url";import R from"mime";import{ErrorMap as E}from"./ERRORS-CyOuSMLY.js";import{H as v}from"./headers-DC2MEOrK.js";import{Readable as p}from"node:stream";import U,{hasBody as I}from"type-is";import{B as h}from"./storage-B-NDsI-o.js";var H=Object.defineProperty,L=u((r,e)=>H(r,"name",{value:e,configurable:!0}),"a");const $=L(r=>r.at(-1),"getLastOne");var x=Object.defineProperty,i=u((r,e)=>x(r,"name",{value:e,configurable:!0}),"n");const B=i(r=>{let e="",t="";const s=c(r,"forwarded");return s&&s.split(";").forEach(a=>{const[n,o]=a.split("=");n==="proto"&&(e=o),n==="host"&&(t=o)}),{host:t,proto:e}},"extractForwarded"),N=i((r,e="utf8",t)=>new Promise((s,a)=>{const n=[];let o=0;r.on("data",l=>{const d=Buffer.isBuffer(l)?l:Buffer.from(l,e);if(o+=d.length,t!==void 0&&o>t){a(new Error("Request body length limit exceeded")),r.destroy();return}n.push(d)}),r.once("end",()=>{s(Buffer.concat(n).toString(e))}),r.once("error",a)}),"readBody"),c=i((r,e,t=!1)=>{const s=r.headers?.[e.toLowerCase()];if(!s||s.length===0)return"";if(t)return s.toString().trim();const a=Array.isArray(s)?s:s.split(",");return $(a).trim()},"getHeader");i(async(r,e=16777216)=>{if(!U(r,["json"]))return{};if(r.body)return{...r.body};if(I(r)){const s=Number.parseInt(c(r,"content-length"),10);if(!Number.isNaN(s)&&s>e)throw new Error("body length limit")}const t=await N(r,"utf8",e);return{...JSON.parse(t)}},"getMetadata");const q=i((r,e,t)=>{const s=[r.getHeader(e),t].flat().filter(Boolean).toString();r.setHeader(e,s)},"appendHeader"),V=i((r,e={})=>{const t=Object.keys(e);t.length>0&&q(r,"Access-Control-Expose-Headers",t),t.forEach(s=>{if(["link","location"].includes(s.toLowerCase())){const a=encodeURI(e[s].toString()).replaceAll("#","%23");r.setHeader(s,a)}else r.setHeader(s,e[s])})},"setHeaders"),F=i(r=>c(r,"host")||c(r,"x-forwarded-host"),"extractHost"),P=i(r=>c(r,"x-forwarded-proto").toLowerCase(),"extractProto"),T=i(r=>{let{host:e,proto:t}=B(r);return e||=F(r),t||=P(r),e?t?`${t}://${e}`:`//${e}`:""},"getBaseUrl"),S=i(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},"getRealPath"),O=/^[\da-z]{4,}(?:-[\da-z]{4,}){2,}$/i,X=i(r=>{const e=S(r).split("/").filter(Boolean);if(e.length===0)throw new Error("Invalid request URL");for(let a=e.length-1;a>=0;a-=1){const n=e[a];if(!n)continue;const o=n.replace(/\.[^/.]+$/,"");if(!["files","metadata","upload","download","http-rest","http-rest-chunked"].includes(o.toLowerCase())&&O.test(o))return h.assertSafeId(o),o}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")},"getIdFromRequest"),Y=i(r=>"body"in r&&r.body&&typeof r.body.getReader=="function"?p.fromWeb(r.body):"body"in r&&r.body&&r.body instanceof Uint8Array?p.from(Buffer.from(r.body)):r instanceof p?r:p.from(new Uint8Array(0)),"getRequestStream");var j=Object.defineProperty,C=u((r,e)=>j(r,"name",{value:e,configurable:!0}),"r");const Z=C((r,e)=>{const t={};return e.forEach(s=>{t[s]=r[s]}),t},"pick");var k=Object.defineProperty,m=u((r,e)=>k(r,"name",{value:e,configurable:!0}),"d");class _ extends y{static{u(this,"E")}static{m(this,"BaseHandlerCore")}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=m((e={})=>{this.internalErrorResponses={...E,...this.internalErrorResponses,...this.storage.errorResponses,...e}},"assembleErrors");parseRangeHeader(e,t){if(!e?.startsWith("bytes="))return;const s=e.slice(6).split(",");if(s.length!==1)return;const a=s[0]?.trim();if(!a)return;const n=a.split("-");if(n.length!==2)return;const[o,l]=n;let d,f;if(o&&l)d=Number.parseInt(o,10),f=Number.parseInt(l,10);else if(o&&!l)d=Number.parseInt(o,10),f=t-1;else if(!o&&l){const g=Number.parseInt(l,10);d=Math.max(0,t-g),f=t-1}else return;if(!(Number.isNaN(d)||Number.isNaN(f)||d>=t||f>=t||d>f))return{end:f,start:d}}buildFileUrlFromString(e,t){const s=new URL(e,"http://localhost"),{pathname:a}=s,n=Object.fromEntries(s.searchParams.entries()),o=w({pathname:`${a}/${t.id}`,query:n});return`${this.storage.config.useRelativeLocation?"":T({url:e})}${o}.${R.getExtension(t.contentType)}`}negotiateContentTypeFromHeader(e,t){if(e)return v.getPreferredMediaType(e,t)}checkForUndefinedIdOrPath(e){if(e instanceof Error&&["Id is undefined","Invalid request URL","Path is undefined"].includes(e.message))throw e}}export{_ as E,Z as T,c as a,Y as b,T as c,S as d,X as g,N as r,V as s,O as u};
@@ -1 +1 @@
1
- var E=Object.defineProperty;var u=(h,t)=>E(h,"name",{value:t,configurable:!0});import{H as m,h as b}from"./headers-DC2MEOrK.js";import{ERRORS as g,isUploadError as R}from"./ERRORS-CyOuSMLY.js";import{E as v,T as O}from"./base-handler-core-BYDQditz.js";import{i as H}from"./storage-Dh0tJh7j.js";import{waitForStorage as w}from"./waitForStorage-ChSBLhLc.js";var T=Object.defineProperty,x=u((h,t)=>T(h,"name",{value:t,configurable:!0}),"m");class z extends v{static{u(this,"O")}static{x(this,"BaseHandlerFetch")}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:g.METHOD_NOT_ALLOWED});try{await w(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:g.STORAGE_ERROR})}try{const r=await e.call(this,t);return this.handleFetchResponse(t,r)}catch(r){const s=r instanceof Error?r:new Error(String(r)),o={...O(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",o),this.logger?.error("[fetch error]: %O",o),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:r,statusCode:s,...o}=e;if(o.status!==void 0&&this.listenerCount(o.status)>0&&this.emit(o.status,{...o,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),o.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(o,n)}catch(p){throw this.logger?.error("[onComplete error]: %O",p),p}const{headers:d,statusCode:c,...f}=n,{content:j,stream:S,...C}=f;return this.createResponse({body:C,headers:d||r,statusCode:c||s||200})}const y={...r,...e.headers},a=this.convertHeaders({...y,"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",...o.hash===void 0?{}:{[`X-Range-${o.hash?.algorithm.toUpperCase()}`]:o.hash?.value}}),l=e.headers||{};l.Location&&!a.location&&!a.Location?a.location=String(l.Location):l.location&&!a.location&&!a.Location?a.location=String(l.location):r.Location&&!a.location&&!a.Location?a.location=String(r.Location):r.location&&!a.location&&!a.Location&&(a.location=String(r.location));let i;return s>=200&&s<300&&(i=Object.keys(o).length>0?{...o}:{},"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[r,s]of Object.entries(t))e[r]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:r={},statusCode:s}=t;let o;return s===204?o=null:typeof e=="string"?o=e:e instanceof Buffer?o=new Uint8Array(e):e&&typeof e=="object"?(o=JSON.stringify(e),r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(o="{}",r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(o,{headers:this.convertHeaders(r),status:s})}async createErrorResponse(t){let e;R(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!H(t)&&!b.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 r;return e.body?typeof e.body=="object"&&e.body!==null?r={body:e.body,headers:e.headers,statusCode:e.statusCode}:r={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}:r={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(r)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{z as O};
1
+ var E=Object.defineProperty;var u=(h,t)=>E(h,"name",{value:t,configurable:!0});import{H as m,h as b}from"./headers-DC2MEOrK.js";import{ERRORS as g,isUploadError as R}from"./ERRORS-CyOuSMLY.js";import{E as v,T as O}from"./base-handler-core-Cwd9uq_E.js";import{i as H}from"./storage-B-NDsI-o.js";import{waitForStorage as w}from"./waitForStorage-ChSBLhLc.js";var T=Object.defineProperty,x=u((h,t)=>T(h,"name",{value:t,configurable:!0}),"m");class z extends v{static{u(this,"O")}static{x(this,"BaseHandlerFetch")}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:g.METHOD_NOT_ALLOWED});try{await w(this.storage)}catch{return this.createErrorResponse({UploadErrorCode:g.STORAGE_ERROR})}try{const r=await e.call(this,t);return this.handleFetchResponse(t,r)}catch(r){const s=r instanceof Error?r:new Error(String(r)),o={...O(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",o),this.logger?.error("[fetch error]: %O",o),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:r,statusCode:s,...o}=e;if(o.status!==void 0&&this.listenerCount(o.status)>0&&this.emit(o.status,{...o,request:{headers:Object.fromEntries(t.headers.entries()),method:t.method,url:t.url}}),o.status==="completed"){const n=e;n.headers===void 0&&(n.headers={}),n.statusCode===void 0&&(n.statusCode=200);try{await this.storage.onComplete(o,n)}catch(p){throw this.logger?.error("[onComplete error]: %O",p),p}const{headers:d,statusCode:c,...f}=n,{content:j,stream:S,...C}=f;return this.createResponse({body:C,headers:d||r,statusCode:c||s||200})}const y={...r,...e.headers},a=this.convertHeaders({...y,"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",...o.hash===void 0?{}:{[`X-Range-${o.hash?.algorithm.toUpperCase()}`]:o.hash?.value}}),l=e.headers||{};l.Location&&!a.location&&!a.Location?a.location=String(l.Location):l.location&&!a.location&&!a.Location?a.location=String(l.location):r.Location&&!a.location&&!a.Location?a.location=String(r.Location):r.location&&!a.location&&!a.Location&&(a.location=String(r.location));let i;return s>=200&&s<300&&(i=Object.keys(o).length>0?{...o}:{},"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[r,s]of Object.entries(t))e[r]=Array.isArray(s)?s.join(", "):String(s);return e}createResponse(t){const{body:e,headers:r={},statusCode:s}=t;let o;return s===204?o=null:typeof e=="string"?o=e:e instanceof Buffer?o=new Uint8Array(e):e&&typeof e=="object"?(o=JSON.stringify(e),r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))):e===void 0&&s!==void 0&&s>=200&&s<300&&(o="{}",r["Content-Type"]||(r["Content-Type"]=m.createContentType({charset:"utf8",mediaType:"application/json"}))),new Response(o,{headers:this.convertHeaders(r),status:s})}async createErrorResponse(t){let e;R(t)?e=this.internalErrorResponses[t.UploadErrorCode]:!H(t)&&!b.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 r;return e.body?typeof e.body=="object"&&e.body!==null?r={body:e.body,headers:e.headers,statusCode:e.statusCode}:r={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}:r={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(r)}buildFileUrl(t,e){return this.buildFileUrlFromString(t.url,e)}negotiateContentType(t,e){return super.negotiateContentTypeFromHeader(t.headers.get("accept")||void 0,e)}}export{z as O};
@@ -1 +1 @@
1
- var M=Object.defineProperty;var C=(i,e)=>M(i,"name",{value:e,configurable:!0});import{paginate as P}from"@visulima/pagination";import{H as T,h as z,n as y}from"./headers-DC2MEOrK.js";import O from"mime";import{isUploadError as $,ERRORS as m}from"./ERRORS-CyOuSMLY.js";import{match as k}from"path-to-regexp";import{T as S,E as q,s as A,d as U,u as x}from"./base-handler-core-BYDQditz.js";import{i as D}from"./storage-Dh0tJh7j.js";import{waitForStorage as _}from"./waitForStorage-ChSBLhLc.js";import{PassThrough as I}from"node:stream";import{e as H}from"./response-builder-Wdo_fvcF.js";var X=Object.defineProperty,G=C((i,e)=>X(i,"name",{value:e,configurable:!0}),"n");const W=k(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),L=G(i=>{const e=W(i);if(!e)return;const{params:t}=e;if(!t.uuid)return;const r={uuid:t.uuid};return t.metadata!==void 0&&(r.metadata=t.metadata),t.path!==void 0&&(r.path=t.path),t.ext!==void 0&&(r.ext=t.ext),{params:r,path:e.path}},"filePathUrlMatcher");var B=Object.defineProperty,v=C((i,e)=>B(i,"name",{value:e,configurable:!0}),"a");const J=v((i,e,t)=>{let r=0,a=0;const o=t-e+1;return new I({highWaterMark:Math.min(64*1024,o),transform(n,h,s){const l=n.length,d=r,p=d+l-1;if(r+=l,p<e){s();return}if(d>t){this.end(),s();return}const u=Math.max(0,e-d),f=Math.min(l,t-d+1);if(u<f){const b=n.subarray(u,f);a+=b.length,this.push(b)||i.pause()}a>=o&&(this.end(),i.destroy()),s()}})},"createRangeLimitedStream"),V=v((i,e,t)=>{let r=!1;const a=v(()=>{r||(r=!0,i.destroy())},"cleanup");e.on("drain",()=>{i.resume()}),e.on("close",a),e.on("finish",a),e.on("error",a),i.on("end",()=>{e.end()}),i.on("error",async o=>{r||(await t(e,o),a())}),i.on("data",o=>{e.write(o)||i.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",a)},"pipeWithBackpressure");v((i,e,t={})=>({headers:t,size:e,stream:i}),"createStreamResponse");var K=Object.defineProperty,w=C((i,e)=>K(i,"name",{value:e,configurable:!0}),"u");const Q=w((i,e,t)=>{const{headers:r,statusCode:a}=i;e(t,{headers:r,statusCode:a})},"handleHeadOptionsRequest"),Y=w((i,e,t,r,a,o,n)=>{e.body=i?.data===void 0?i:i.data;const{headers:h,statusCode:s}=i,l=i;if(l.stream)if(typeof r=="function")r();else{const d=n(e.headers.range,l.size||0);o(t,l.stream,{headers:h,range:d||void 0,size:l.size,statusCode:s})}else{let d="";i.content!==void 0?d=i.content:typeof i=="object"&&"data"in i&&(d=i.data),typeof r=="function"?r():a(t,{body:d,headers:h,statusCode:s})}},"handleGetRequest"),Z=w(async(i,e,t,r,a,o,n)=>{const{headers:h,statusCode:s,...l}=i;if(typeof r=="function")e._body=!0,e.body=l,r();else{const d=i,p=d.headers?{...d.headers}:{};d.headers===void 0&&(d.headers={}),d.statusCode===void 0&&(d.statusCode=200);try{const u=a.onComplete(l,d,e);u instanceof Promise&&await u}catch(u){throw o?.error&&o.error("[onComplete error]: %O",u),u}Object.keys(d.headers||{}).length===0&&Object.keys(p).length>0?d.headers=p:d.headers&&Object.keys(p).length>0&&(d.headers={...p,...d.headers}),n(e,t,d)}},"handleCompletedUpload"),ee=w((i,e,t,r)=>{const{headers:a,statusCode:o,...n}=i,h=a||{},s=h["X-Chunked-Upload"]==="true"||h["x-chunked-upload"]==="true";let l;const d={...H(h),...a?H(a):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};s&&(l=JSON.stringify(n),!d["Content-Type"]&&!d["content-type"]&&(d["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(l=""),r(t,{body:l,headers:d,statusCode:o||200})},"handlePartialUpload"),te=w(async(i,e,t,r,a,o,n)=>{const h=i instanceof Error?i:new Error(String(i)),s={...S(h,["name",...Object.getOwnPropertyNames(h)]),request:S(e,["headers","method","url"])};r("error")>0&&t("error",s),a?.error&&a.error("[error]: %O",s),await o(n,h)},"handleUploadError");var re=Object.defineProperty,R=C((i,e)=>re(i,"name",{value:e,configurable:!0}),"C");const g="Content-Type";class N extends q{static{C(this,"F")}static{R(this,"BaseHandlerNode")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=R(async(e,t)=>this.upload(e,t),"handle");upload=R(async(e,t,r)=>{e.on("error",o=>this.logger?.error("[request error]: %O",o)),this.logger?.debug("[request]: %s %s",e.method,e.url);const a=this.registeredHandlers.get(e.method);if(!a){await this.sendError(t,{UploadErrorCode:m.METHOD_NOT_ALLOWED});return}try{await _(this.storage)}catch{await this.sendError(t,{UploadErrorCode:m.STORAGE_ERROR});return}try{const o=await a.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))Q(o,this.send.bind(this),t);else if(e.method==="GET"){const n=o;n&&Y(n,e,t,r,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:h,...s}=o;this.logger?.debug("[%s]: %s: %d/%d",s.status,s.name,s.bytesWritten,s.size),s.status!==void 0&&this.listenerCount(s.status)>0&&this.emit(s.status,{...s,request:S(e,["headers","method","url"])}),s.status==="completed"?await Z(o,e,t,r,this.storage,this.logger,(l,d,p)=>{this.finish(l,d,p)}):ee(o,e,t,(l,d)=>{this.send(l,{body:d.body,headers:d.headers,statusCode:d.statusCode})})}}catch(o){await te(o,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}},"upload");send(e,{body:t="",headers:r={},statusCode:a=200}){let o;const n={...r};if(typeof t=="string"){if(o=t,n[g]===void 0)n[g]=T.createContentType({mediaType:"text/plain"});else{const h=Array.isArray(n[g])?n[g].join(", "):String(n[g]);n[g]=T.ensureCharset(h)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?o=t:(o=JSON.stringify(t),n[g]||(n[g]=T.createContentType({charset:"utf8",mediaType:"application/json"})));A(e,n),e.statusCode=a,e.end(o)}async sendError(e,t){let r;$(t)?r=this.internalErrorResponses[t.UploadErrorCode]:!D(t)&&!z.isHttpError(t)?r=this.storage.normalizeError(t):r={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(r);let a;r.body?typeof r.body=="object"&&r.body!==null?a={body:r.body,headers:r.headers,statusCode:r.statusCode}:a={body:{error:{code:r.code||r.name||"Error",message:r.body||r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500}:a={body:{error:{code:r.code||r.name||"Error",message:r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500},this.send(e,a)}sendStream(e,t,{headers:r={},range:a,size:o,statusCode:n=200}){A(e,r),e.statusCode=n;let h=t;a&&o?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${a.start}-${a.end}/${o}`),e.setHeader("Content-Length",a.end-a.start+1),e.setHeader("Accept-Ranges","bytes"),h=J(t,a.start,a.end)):(o&&e.setHeader("Content-Length",o),e.setHeader("Accept-Ranges","bytes")),V(h,e,(s,l)=>this.sendError(s,l))}finish(e,t,r){const a="id"in r&&"headers"in r&&!("body"in r);let o,n,h;if(a){const s=r,l=s.headers||{},d=s.statusCode||200,{headers:p,statusCode:u,...f}=s;o=f,n={...l},h=d}else{const s=r;o=s.body,n=s.headers||{},h=s.statusCode||200}if(o&&typeof o=="object"&&o.content!==void 0){const{content:s,contentType:l}=o;o=s,n={...n,"Content-Type":l}}this.send(t,{body:o||r,headers:n,statusCode:h})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||N.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const r=L(U(e));if(r?.params.uuid){const{ext:a,metadata:o,uuid:n}=r.params,h=a?n.replace(new RegExp(String.raw`\.${a}$`),""):n;if(o==="metadata"&&U(e).endsWith("/metadata"))try{const s=await this.storage.getMeta(h);return{...s,content:JSON.stringify(s),headers:{"Content-Type":T.createContentType({charset:"utf8",mediaType:"application/json"}),...s.expiredAt===void 0?{}:{"X-Upload-Expires":s.expiredAt.toString()},...s.modifiedAt===void 0?{}:{"Last-Modified":s.modifiedAt.toString()}},statusCode:200}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File metadata not found"):s}if(!x.test(h))return this.list(e,t);try{const s=new URL(e.url||"","http://localhost"),l=Object.fromEntries(s.searchParams.entries());if(Object.keys(l).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const c=await this.mediaTransformer.handle(h,l);return{content:c.buffer,headers:{"Content-Length":String(c.size),"Content-Type":`${c.mediaType}/${c.format}`,"X-Media-Type":c.mediaType,"X-Original-Format":c.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":c.format,...c.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":c.originalFile.expiredAt.toString()},...c.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":c.originalFile.modifiedAt.toString()},...c.originalFile?.ETag===void 0?{}:{ETag:c.originalFile.ETag}},statusCode:200}}catch(c){if(c.name==="ValidationError")throw y(400,c.message);this.logger?.warn(`Media transformation failed: ${c.message}`)}const d=await this.storage.getMeta(h);if((e.headers.range||d.size&&d.size>1024*1024)&&this.storage.getStream)try{const c=await this.storage.getStream({id:h});let E=c.headers?.["Content-Type"]||d.contentType;return E.includes("image")&&typeof a=="string"&&(E=O.getType(a)||E),{headers:{...c.headers,"Accept-Ranges":"bytes","Content-Type":E},size:c.size,statusCode:200,stream:c.stream,...d,contentType:E}}catch(c){this.logger?.warn(`Streaming failed, falling back to buffer: ${c}`)}const p=await this.storage.get({id:h});let{contentType:u}=p;u.includes("image")&&typeof a=="string"&&(u=O.getType(a)||u);const{ETag:f,expiredAt:b,modifiedAt:F,size:j}=p;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(j),"Content-Type":u,...b===void 0?{}:{"X-Upload-Expires":b.toString()},...F===void 0?{}:{"Last-Modified":F.toString()},...f===void 0?{}:{ETag:f}},statusCode:200,...p,contentType:u}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File not found"):s}}return this.list(e,t)}async list(e,t){const r=new URL(e.url||"","http://localhost"),a=r.searchParams.get("limit"),o=r.searchParams.get("page"),n=await this.storage.list(Number(a||1e3));return n.length===0?{data:[],headers:{},statusCode:200}:o!==void 0&&a!==void 0?{data:P(Number(o),Number(a),n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const r=L(U(e));if(!r?.params.uuid||!x.test(r.params.uuid))throw y(404,"File not found");const{ext:a,uuid:o}=r.params;try{const n=await this.storage.getMeta(o);if(!this.storage.getStream){await this.sendError(t,y(501,"Streaming download not supported"));return}const h=await this.storage.getStream({id:o});let s=h.headers?.["Content-Type"]||n.contentType;s.includes("image")&&typeof a=="string"&&(s=O.getType(a)||s);const l=this.parseRangeHeader(e.headers.range,h.size||0),d={...h.headers,"Accept-Ranges":"bytes","Content-Disposition":T.createContentDisposition({filename:n.originalName||o,type:"attachment"}),"Content-Type":s};this.sendStream(t,h.stream,{headers:d,range:l||void 0,size:h.size,statusCode:l?206:200})}catch(n){const h=n;if(h.UploadErrorCode===m.FILE_NOT_FOUND||h.UploadErrorCode===m.GONE){await this.sendError(t,y(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 y(404,"File not found")}}export{N as F};
1
+ var M=Object.defineProperty;var C=(i,e)=>M(i,"name",{value:e,configurable:!0});import{paginate as P}from"@visulima/pagination";import{H as T,h as z,n as y}from"./headers-DC2MEOrK.js";import O from"mime";import{isUploadError as $,ERRORS as m}from"./ERRORS-CyOuSMLY.js";import{match as k}from"path-to-regexp";import{T as S,E as q,s as A,d as U,u as x}from"./base-handler-core-Cwd9uq_E.js";import{i as D}from"./storage-B-NDsI-o.js";import{waitForStorage as _}from"./waitForStorage-ChSBLhLc.js";import{PassThrough as I}from"node:stream";import{e as H}from"./response-builder-Wdo_fvcF.js";var X=Object.defineProperty,G=C((i,e)=>X(i,"name",{value:e,configurable:!0}),"n");const W=k(["/:uuid","/*path/:uuid.:ext/:metadata","/*path/:uuid/:metadata","/*path/:uuid.:ext","/*path/:uuid"],{decode:decodeURIComponent}),L=G(i=>{const e=W(i);if(!e)return;const{params:t}=e;if(!t.uuid)return;const r={uuid:t.uuid};return t.metadata!==void 0&&(r.metadata=t.metadata),t.path!==void 0&&(r.path=t.path),t.ext!==void 0&&(r.ext=t.ext),{params:r,path:e.path}},"filePathUrlMatcher");var B=Object.defineProperty,v=C((i,e)=>B(i,"name",{value:e,configurable:!0}),"a");const J=v((i,e,t)=>{let r=0,a=0;const o=t-e+1;return new I({highWaterMark:Math.min(64*1024,o),transform(n,h,s){const l=n.length,d=r,p=d+l-1;if(r+=l,p<e){s();return}if(d>t){this.end(),s();return}const u=Math.max(0,e-d),f=Math.min(l,t-d+1);if(u<f){const b=n.subarray(u,f);a+=b.length,this.push(b)||i.pause()}a>=o&&(this.end(),i.destroy()),s()}})},"createRangeLimitedStream"),V=v((i,e,t)=>{let r=!1;const a=v(()=>{r||(r=!0,i.destroy())},"cleanup");e.on("drain",()=>{i.resume()}),e.on("close",a),e.on("finish",a),e.on("error",a),i.on("end",()=>{e.end()}),i.on("error",async o=>{r||(await t(e,o),a())}),i.on("data",o=>{e.write(o)||i.pause()}),typeof e.listeners=="function"&&e.listeners("close")?.length===0&&e.on("close",a)},"pipeWithBackpressure");v((i,e,t={})=>({headers:t,size:e,stream:i}),"createStreamResponse");var K=Object.defineProperty,w=C((i,e)=>K(i,"name",{value:e,configurable:!0}),"u");const Q=w((i,e,t)=>{const{headers:r,statusCode:a}=i;e(t,{headers:r,statusCode:a})},"handleHeadOptionsRequest"),Y=w((i,e,t,r,a,o,n)=>{e.body=i?.data===void 0?i:i.data;const{headers:h,statusCode:s}=i,l=i;if(l.stream)if(typeof r=="function")r();else{const d=n(e.headers.range,l.size||0);o(t,l.stream,{headers:h,range:d||void 0,size:l.size,statusCode:s})}else{let d="";i.content!==void 0?d=i.content:typeof i=="object"&&"data"in i&&(d=i.data),typeof r=="function"?r():a(t,{body:d,headers:h,statusCode:s})}},"handleGetRequest"),Z=w(async(i,e,t,r,a,o,n)=>{const{headers:h,statusCode:s,...l}=i;if(typeof r=="function")e._body=!0,e.body=l,r();else{const d=i,p=d.headers?{...d.headers}:{};d.headers===void 0&&(d.headers={}),d.statusCode===void 0&&(d.statusCode=200);try{const u=a.onComplete(l,d,e);u instanceof Promise&&await u}catch(u){throw o?.error&&o.error("[onComplete error]: %O",u),u}Object.keys(d.headers||{}).length===0&&Object.keys(p).length>0?d.headers=p:d.headers&&Object.keys(p).length>0&&(d.headers={...p,...d.headers}),n(e,t,d)}},"handleCompletedUpload"),ee=w((i,e,t,r)=>{const{headers:a,statusCode:o,...n}=i,h=a||{},s=h["X-Chunked-Upload"]==="true"||h["x-chunked-upload"]==="true";let l;const d={...H(h),...a?H(a):{},...n.hash===void 0?{}:{[`X-Range-${n.hash?.algorithm.toUpperCase()}`]:String(n.hash?.value)}};s&&(l=JSON.stringify(n),!d["Content-Type"]&&!d["content-type"]&&(d["Content-Type"]="application/json; charset=utf-8")),e.method==="HEAD"&&(l=""),r(t,{body:l,headers:d,statusCode:o||200})},"handlePartialUpload"),te=w(async(i,e,t,r,a,o,n)=>{const h=i instanceof Error?i:new Error(String(i)),s={...S(h,["name",...Object.getOwnPropertyNames(h)]),request:S(e,["headers","method","url"])};r("error")>0&&t("error",s),a?.error&&a.error("[error]: %O",s),await o(n,h)},"handleUploadError");var re=Object.defineProperty,R=C((i,e)=>re(i,"name",{value:e,configurable:!0}),"C");const g="Content-Type";class N extends q{static{C(this,"F")}static{R(this,"BaseHandlerNode")}static methods=["delete","get","head","options","patch","post","put"];registeredHandlers=new Map;constructor(e){super(e),this.compose()}get handlers(){return this.registeredHandlers}handle=R(async(e,t)=>this.upload(e,t),"handle");upload=R(async(e,t,r)=>{e.on("error",o=>this.logger?.error("[request error]: %O",o)),this.logger?.debug("[request]: %s %s",e.method,e.url);const a=this.registeredHandlers.get(e.method);if(!a){await this.sendError(t,{UploadErrorCode:m.METHOD_NOT_ALLOWED});return}try{await _(this.storage)}catch{await this.sendError(t,{UploadErrorCode:m.STORAGE_ERROR});return}try{const o=await a.call(this,e,t);if(["HEAD","OPTIONS"].includes(e.method))Q(o,this.send.bind(this),t);else if(e.method==="GET"){const n=o;n&&Y(n,e,t,r,this.send.bind(this),this.sendStream.bind(this),this.parseRangeHeader.bind(this))}else{const{headers:n,statusCode:h,...s}=o;this.logger?.debug("[%s]: %s: %d/%d",s.status,s.name,s.bytesWritten,s.size),s.status!==void 0&&this.listenerCount(s.status)>0&&this.emit(s.status,{...s,request:S(e,["headers","method","url"])}),s.status==="completed"?await Z(o,e,t,r,this.storage,this.logger,(l,d,p)=>{this.finish(l,d,p)}):ee(o,e,t,(l,d)=>{this.send(l,{body:d.body,headers:d.headers,statusCode:d.statusCode})})}}catch(o){await te(o,e,this.emit.bind(this),this.listenerCount.bind(this),this.logger,this.sendError.bind(this),t)}},"upload");send(e,{body:t="",headers:r={},statusCode:a=200}){let o;const n={...r};if(typeof t=="string"){if(o=t,n[g]===void 0)n[g]=T.createContentType({mediaType:"text/plain"});else{const h=Array.isArray(n[g])?n[g].join(", "):String(n[g]);n[g]=T.ensureCharset(h)}n["Content-Length"]===void 0&&(n["Content-Length"]=Buffer.byteLength(t))}else t instanceof Buffer?o=t:(o=JSON.stringify(t),n[g]||(n[g]=T.createContentType({charset:"utf8",mediaType:"application/json"})));A(e,n),e.statusCode=a,e.end(o)}async sendError(e,t){let r;$(t)?r=this.internalErrorResponses[t.UploadErrorCode]:!D(t)&&!z.isHttpError(t)?r=this.storage.normalizeError(t):r={...t,code:t.code||t.name,headers:t.headers||{},message:t.message,name:t.name,statusCode:t.statusCode||500},await this.storage.onError(r);let a;r.body?typeof r.body=="object"&&r.body!==null?a={body:r.body,headers:r.headers,statusCode:r.statusCode}:a={body:{error:{code:r.code||r.name||"Error",message:r.body||r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500}:a={body:{error:{code:r.code||r.name||"Error",message:r.message||"Unknown error",name:r.name||"Error"}},headers:r.headers,statusCode:r.statusCode||500},this.send(e,a)}sendStream(e,t,{headers:r={},range:a,size:o,statusCode:n=200}){A(e,r),e.statusCode=n;let h=t;a&&o?(e.statusCode=206,e.setHeader("Content-Range",`bytes ${a.start}-${a.end}/${o}`),e.setHeader("Content-Length",a.end-a.start+1),e.setHeader("Accept-Ranges","bytes"),h=J(t,a.start,a.end)):(o&&e.setHeader("Content-Length",o),e.setHeader("Accept-Ranges","bytes")),V(h,e,(s,l)=>this.sendError(s,l))}finish(e,t,r){const a="id"in r&&"headers"in r&&!("body"in r);let o,n,h;if(a){const s=r,l=s.headers||{},d=s.statusCode||200,{headers:p,statusCode:u,...f}=s;o=f,n={...l},h=d}else{const s=r;o=s.body,n=s.headers||{},h=s.statusCode||200}if(o&&typeof o=="object"&&o.content!==void 0){const{content:s,contentType:l}=o;o=s,n={...n,"Content-Type":l}}this.send(t,{body:o||r,headers:n,statusCode:h})}buildFileUrl(e,t){return this.buildFileUrlFromString(e.originalUrl||e.url,t)}negotiateContentType(e,t){return super.negotiateContentTypeFromHeader(e.headers.accept,t)}async options(e,t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||N.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(e,t){const r=L(U(e));if(r?.params.uuid){const{ext:a,metadata:o,uuid:n}=r.params,h=a?n.replace(new RegExp(String.raw`\.${a}$`),""):n;if(o==="metadata"&&U(e).endsWith("/metadata"))try{const s=await this.storage.getMeta(h);return{...s,content:JSON.stringify(s),headers:{"Content-Type":T.createContentType({charset:"utf8",mediaType:"application/json"}),...s.expiredAt===void 0?{}:{"X-Upload-Expires":s.expiredAt.toString()},...s.modifiedAt===void 0?{}:{"Last-Modified":s.modifiedAt.toString()}},statusCode:200}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File metadata not found"):s}if(!x.test(h))return this.list(e,t);try{const s=new URL(e.url||"","http://localhost"),l=Object.fromEntries(s.searchParams.entries());if(Object.keys(l).length>0&&this.mediaTransformer&&this.mediaTransformer)try{const c=await this.mediaTransformer.handle(h,l);return{content:c.buffer,headers:{"Content-Length":String(c.size),"Content-Type":`${c.mediaType}/${c.format}`,"X-Media-Type":c.mediaType,"X-Original-Format":c.originalFile?.contentType?.split("/")[1]||"","X-Transformed-Format":c.format,...c.originalFile?.expiredAt===void 0?{}:{"X-Upload-Expires":c.originalFile.expiredAt.toString()},...c.originalFile?.modifiedAt===void 0?{}:{"Last-Modified":c.originalFile.modifiedAt.toString()},...c.originalFile?.ETag===void 0?{}:{ETag:c.originalFile.ETag}},statusCode:200}}catch(c){if(c.name==="ValidationError")throw y(400,c.message);this.logger?.warn(`Media transformation failed: ${c.message}`)}const d=await this.storage.getMeta(h);if((e.headers.range||d.size&&d.size>1024*1024)&&this.storage.getStream)try{const c=await this.storage.getStream({id:h});let E=c.headers?.["Content-Type"]||d.contentType;return E.includes("image")&&typeof a=="string"&&(E=O.getType(a)||E),{headers:{...c.headers,"Accept-Ranges":"bytes","Content-Type":E},size:c.size,statusCode:200,stream:c.stream,...d,contentType:E}}catch(c){this.logger?.warn(`Streaming failed, falling back to buffer: ${c}`)}const p=await this.storage.get({id:h});let{contentType:u}=p;u.includes("image")&&typeof a=="string"&&(u=O.getType(a)||u);const{ETag:f,expiredAt:b,modifiedAt:F,size:j}=p;return{headers:{"Accept-Ranges":"bytes","Content-Length":String(j),"Content-Type":u,...b===void 0?{}:{"X-Upload-Expires":b.toString()},...F===void 0?{}:{"Last-Modified":F.toString()},...f===void 0?{}:{ETag:f}},statusCode:200,...p,contentType:u}}catch(s){const l=s;throw l.UploadErrorCode===m.FILE_NOT_FOUND||l.UploadErrorCode===m.GONE?y(404,"File not found"):s}}return this.list(e,t)}async list(e,t){const r=new URL(e.url||"","http://localhost"),a=r.searchParams.get("limit"),o=r.searchParams.get("page"),n=await this.storage.list(Number(a||1e3));return n.length===0?{data:[],headers:{},statusCode:200}:o!==void 0&&a!==void 0?{data:P(Number(o),Number(a),n.length,n),headers:{},statusCode:200}:{data:n,headers:{},statusCode:200}}async download(e,t){const r=L(U(e));if(!r?.params.uuid||!x.test(r.params.uuid))throw y(404,"File not found");const{ext:a,uuid:o}=r.params;try{const n=await this.storage.getMeta(o);if(!this.storage.getStream){await this.sendError(t,y(501,"Streaming download not supported"));return}const h=await this.storage.getStream({id:o});let s=h.headers?.["Content-Type"]||n.contentType;s.includes("image")&&typeof a=="string"&&(s=O.getType(a)||s);const l=this.parseRangeHeader(e.headers.range,h.size||0),d={...h.headers,"Accept-Ranges":"bytes","Content-Disposition":T.createContentDisposition({filename:n.originalName||o,type:"attachment"}),"Content-Type":s};this.sendStream(t,h.stream,{headers:d,range:l||void 0,size:h.size,statusCode:l?206:200})}catch(n){const h=n;if(h.UploadErrorCode===m.FILE_NOT_FOUND||h.UploadErrorCode===m.GONE){await this.sendError(t,y(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 y(404,"File not found")}}export{N as F};
@@ -1 +1 @@
1
- import"node:stream";import"node:timers";import"node:util";import{B as u,d as F,a as g}from"./storage-Dh0tJh7j.js";import"./path-D7rMc9nq-B718mbm6.js";import"type-is";import"./NoOpMetrics-Dky06sf1.js";import"./cache-qV_5Umeq.js";import"./ERRORS-CyOuSMLY.js";import"./isRetryableError-BhizNeAz.js";import"./is-expired-1JuZjDtb.js";export{u as BaseStorage,F as defaultCloudStorageFileNameValidation,g as defaultFilesystemFileNameValidation};
1
+ import"node:stream";import"node:timers";import"node:util";import{B as u,d as F,a as g}from"./storage-B-NDsI-o.js";import"./path-D7rMc9nq-B718mbm6.js";import"type-is";import"./NoOpMetrics-Dky06sf1.js";import"./cache-qV_5Umeq.js";import"./ERRORS-CyOuSMLY.js";import"./isRetryableError-BhizNeAz.js";import"./is-expired-1JuZjDtb.js";export{u as BaseStorage,F as defaultCloudStorageFileNameValidation,g as defaultFilesystemFileNameValidation};
@@ -0,0 +1 @@
1
+ var ct=Object.defineProperty;var h=(e,t)=>ct(e,"name",{value:t,configurable:!0});import{createReadStream as lt,createWriteStream as ut}from"node:fs";import{truncate as mt,stat as C,copyFile as z}from"node:fs/promises";import{Transform as Q,PassThrough as dt,pipeline as ht}from"node:stream";import{f as L,l as yt,w as H,U as b,_ as ft,i as pt,v as gt,B as wt,y as W}from"./local-meta-storage-Bi0mK6gD.js";import{createRequire as P}from"node:module";import{K as w,C as F,M as K,L as bt,Q as vt,O as Et}from"./path-D7rMc9nq-B718mbm6.js";import{S as St}from"./index-B4ETk0Lu.js";import{d as $t}from"./detect-file-type-5JhzC9RU.js";import{throwErrorCode as g,ERRORS as y,isUploadError as Ot}from"./ERRORS-CyOuSMLY.js";import{createHash as Tt}from"node:crypto";import{B as Ft,a as kt,t as Nt}from"./storage-B-NDsI-o.js";import Pt from"./File-BhfUgJjs.js";import{o as B,r as Dt}from"./part-match-B5fLLmFw.js";import{u as _t}from"./update-size-DANV7aa2.js";import{o as It}from"./has-content-Bx2p8Okx.js";var Mt=Object.defineProperty,xt=h((e,t)=>Mt(e,"name",{value:t,configurable:!0}),"i$4"),Rt=Object.defineProperty,X=xt((e,t)=>Rt(e,"name",{value:t,configurable:!0}),"t");const Lt=P(import.meta.url),$=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,jt=X(e=>{if(typeof $<"u"&&$.versions&&$.versions.node){const[t,r]=$.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return $.getBuiltinModule(e)}return Lt(e)},"__cjs_getBuiltinModule"),{lstat:At,writeFile:Ct}=jt("node:fs/promises");var zt=Object.defineProperty,Wt=X((e,t)=>zt(e,"name",{value:t,configurable:!0}),"o");const x=Wt(async e=>{L(e);try{const t=await At(e);if(!t.isFile())throw new Error(`Ensure path exists, expected 'file', got '${String(yt(t))}'`)}catch(t){if(t.code==="ENOENT"){await H(w(b(e))),await Ct(e,new Uint8Array);return}throw t}},"ensureFile");var Bt=Object.defineProperty,q=h((e,t)=>Bt(e,"name",{value:t,configurable:!0}),"t$1"),Ut=Object.defineProperty,Y=q((e,t)=>Ut(e,"name",{value:t,configurable:!0}),"t"),Vt=Object.defineProperty,Qt=Y((e,t)=>Vt(e,"name",{value:t,configurable:!0}),"t");let U=class extends Error{static{h(this,"l")}static{q(this,"c")}static{Y(this,"i")}static{Qt(this,"WalkError")}root;constructor(t,r){super(`${t instanceof Error?t.message:String(t)} for path "${r}"`),this.cause=t,this.root=r}get name(){return"WalkError"}set name(t){throw new Error("Cannot overwrite name of WalkError")}};var Ht=Object.defineProperty,Kt=h((e,t)=>Ht(e,"name",{value:t,configurable:!0}),"l$1"),Xt=Object.defineProperty,G=Kt((e,t)=>Xt(e,"name",{value:t,configurable:!0}),"t"),qt=Object.defineProperty,Yt=G((e,t)=>qt(e,"name",{value:t,configurable:!0}),"g");const V=Yt(e=>{const t=e.replace(/\.\*/g,".([^/]*)").replace(/\*\*/g,"(.*)").replace(/(?<!\.)\*(?!\*)/g,"([^/]*)").replace(/\?/g,"[^/]").replace(/\.(?!\*)/g,String.raw`\.`).replace(/\{/g,"(").replace(/\}/g,")").replace(/,/g,"|").replace(/\[!(.*?)\]/g,"[^$1]");return new RegExp(`^${t}$`)},"globToRegExp");var Gt=Object.defineProperty,Jt=G((e,t)=>Gt(e,"name",{value:t,configurable:!0}),"t");const N=Jt((e,t,r,i)=>{if(Array.isArray(t)&&t.length>0&&!t.some(a=>e.endsWith(a)))return!1;const n=e.includes("\\")?e.replaceAll("\\","/"):e;return r&&!r.some(a=>a.test(n))?!1:!i?.some(a=>a.test(n))},"walkInclude");var Zt=Object.defineProperty,J=h((e,t)=>Zt(e,"name",{value:t,configurable:!0}),"f$2"),te=Object.defineProperty,j=J((e,t)=>te(e,"name",{value:t,configurable:!0}),"y");const ee=P(import.meta.url),O=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,re=j(e=>{if(typeof O<"u"&&O.versions&&O.versions.node){const[t,r]=O.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return O.getBuiltinModule(e)}return ee(e)},"__cjs_getBuiltinModule"),{readdir:ie,realpath:ae,stat:se}=re("node:fs/promises");var ne=Object.defineProperty,p=j((e,t)=>ne(e,"name",{value:t,configurable:!0}),"r");const oe=p(async e=>{const t=bt(e),r=vt(t),i=await se(t);return{isDirectory:p(()=>i.isDirectory(),"isDirectory"),isFile:p(()=>i.isFile(),"isFile"),isSymbolicLink:p(()=>i.isSymbolicLink(),"isSymbolicLink"),name:r,path:t}},"_createWalkEntry");async function*k(e,{extensions:t,followSymlinks:r=!1,includeDirs:i=!0,includeFiles:n=!0,includeSymlinks:a=!0,match:s,maxDepth:l=Number.POSITIVE_INFINITY,skip:u}={}){if(L(e),l<0)return;const m=s?s.map(c=>typeof c=="string"?V(c):c):void 0,d=u?u.map(c=>typeof c=="string"?V(c):c):void 0;if(e=F(b(e)),i&&N(e,t,m,d)&&(yield await oe(e)),!(l<1||!N(e,void 0,void 0,d)))try{const c=await ie(e,{withFileTypes:!0});for(const o of c){let f=K(e,o.name);if(o.isSymbolicLink())if(r)f=await ae(f);else if(a&&N(f,t,m,d)){yield{isDirectory:p(()=>o.isDirectory(),"isDirectory"),isFile:p(()=>o.isFile(),"isFile"),isSymbolicLink:p(()=>o.isSymbolicLink(),"isSymbolicLink"),name:o.name,path:f};continue}else continue;o.isDirectory()?yield*k(f,{extensions:t,followSymlinks:r,includeDirs:i,includeFiles:n,includeSymlinks:a,match:m,maxDepth:l-1,skip:d}):o.isFile()&&n&&N(f,t,m,d)&&(yield{isDirectory:p(()=>o.isDirectory(),"isDirectory"),isFile:p(()=>o.isFile(),"isFile"),isSymbolicLink:p(()=>o.isSymbolicLink(),"isSymbolicLink"),name:o.name,path:f})}}catch(c){throw c instanceof U?c:new U(c,e)}}h(k,"p$2");J(k,"D");j(k,"g");p(k,"walk");var ce=Object.defineProperty,Z=h((e,t)=>ce(e,"name",{value:t,configurable:!0}),"t"),le=Object.defineProperty,A=Z((e,t)=>le(e,"name",{value:t,configurable:!0}),"t");const ue=P(import.meta.url),T=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,me=A(e=>{if(typeof T<"u"&&T.versions&&T.versions.node){const[t,r]=T.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return T.getBuiltinModule(e)}return ue(e)},"__cjs_getBuiltinModule"),{accessSync:de}=me("node:fs");var he=Object.defineProperty,ye=A((e,t)=>he(e,"name",{value:t,configurable:!0}),"o");function D(e,t=ft){L(e),e=b(e);try{return de(e,t),!0}catch{return!1}}h(D,"i$1");Z(D,"d");A(D,"m");ye(D,"isAccessibleSync");var fe=Object.defineProperty,tt=h((e,t)=>fe(e,"name",{value:t,configurable:!0}),"v"),pe=Object.defineProperty,S=tt((e,t)=>pe(e,"name",{value:t,configurable:!0}),"i");const ge=P(import.meta.url),v=typeof globalThis<"u"&&typeof globalThis.process<"u"?globalThis.process:process,et=S(e=>{if(typeof v<"u"&&v.versions&&v.versions.node){const[t,r]=v.versions.node.split(".").map(Number);if(t>22||t===22&&r>=3||t===20&&r>=16)return v.getBuiltinModule(e)}return ge(e)},"__cjs_getBuiltinModule"),{cwd:_}=v,{mkdir:we,rename:be,copyFile:ve,unlink:Ee}=et("node:fs/promises"),{mkdirSync:Se,renameSync:$e,copyFileSync:Oe,unlinkSync:Te}=et("node:fs");var Fe=Object.defineProperty,rt=S((e,t)=>Fe(e,"name",{value:t,configurable:!0}),"o");class ke extends Error{static{h(this,"V")}static{tt(this,"O")}static{S(this,"a")}static{rt(this,"SameDirectoryError")}constructor(t,r){super(`Source directory "${w(t)}" does not match destination directory "${w(r)}"`),this.name="SameDirectoryError"}}const it=rt((e,t)=>{if(!e||!t)throw new Error("Source and destination paths must not be empty");if(w(e)!==w(t))throw new ke(e,t)},"validateSameDirectory");var Ne=Object.defineProperty,Pe=S((e,t)=>Ne(e,"name",{value:t,configurable:!0}),"m$1");const at=Pe(async(e,t,{cwd:r,directoryMode:i,overwrite:n,validateDirectory:a})=>{if(r&&(e=F(r,e),t=F(r,t)),a&&it(e,t),!n&&await pt(t))throw new Error(`The destination file exists: ${t}`);await we(w(t),{mode:i,recursive:!0});try{await be(e,t)}catch(s){if(s.code==="EXDEV")await ve(e,t),await Ee(e);else throw s}},"internalMoveFile");var De=Object.defineProperty,_e=S((e,t)=>De(e,"name",{value:t,configurable:!0}),"m");const st=_e((e,t,{cwd:r,directoryMode:i,overwrite:n,validateDirectory:a})=>{if(r&&(e=F(r,e),t=F(r,t)),a&&it(e,t),!n&&D(t))throw new Error(`The destination file exists: ${t}`);Se(w(t),{mode:i,recursive:!0});try{$e(e,t)}catch(s){if(s.code==="EXDEV")Oe(e,t),Te(e);else throw s}},"internalMoveFileSync");var Ie=Object.defineProperty,I=S((e,t)=>Ie(e,"name",{value:t,configurable:!0}),"i");const Me=I(async(e,t,r={})=>{const i={overwrite:!0,validateDirectory:!1,...r,cwd:r.cwd?b(r.cwd):_()};await at(e,t,i)},"move");I((e,t,r)=>{const i={overwrite:!0,validateDirectory:!1,...r};i.cwd=i.cwd?b(i.cwd):_(),st(e,t,i)},"moveSync");I(async(e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?b(i.cwd):_(),await at(e,t,i)},"rename");I((e,t,r)=>{const i={overwrite:!0,...r,validateDirectory:!0};i.cwd=i.cwd?b(i.cwd):_(),st(e,t,i)},"renameSync");var xe=Object.defineProperty,nt=h((e,t)=>xe(e,"name",{value:t,configurable:!0}),"r");class Re extends Q{static{h(this,"StreamChecksum")}constructor(t,r,i="base64"){super(),this.checksum=t,this.algorithm=r,this.encoding=i,this.hash=Tt(r)}checksum;algorithm;encoding;static{nt(this,"StreamChecksum")}length=0;digest="";hash;get calculatedDigest(){return this.digest}_transform(t,r,i){this.push(t),this.hash.update(t),this.length+=t.length,i()}_flush(t){this.digest=this.hash.digest(this.encoding),this.checksum&&this.checksum!==this.digest?t(new Error("Checksum mismatch")):t()}}const Le=nt((e,t,r="base64")=>t?new Re(e,t,r):new dt,"streamChecksum");var je=Object.defineProperty,Ae=h((e,t)=>je(e,"name",{value:t,configurable:!0}),"o");class Ce extends Q{static{h(this,"m")}constructor(t=Number.POSITIVE_INFINITY){super(),this.limit=t}limit;static{Ae(this,"StreamLength")}length=0;_transform(t,r,i){const n=this.length+t.length;this.limit>=n?(this.push(t),this.length=n,i()):i(new Error("Stream length limit exceeded"))}}var ze=Object.defineProperty,R=h((e,t)=>ze(e,"name",{value:t,configurable:!0}),"p");class E extends Ft{static name="disk";checksumTypes=["md5","sha1"];get raw(){return{directory:this.directory}}directory;meta;constructor(t){const r={...t,fileNameValidation:t.fileNameValidation??kt};if(super(r),this.directory=r.directory,r.metaStorage)this.meta=r.metaStorage;else{const i={...r,...r.metaStorageConfig,logger:this.logger};this.meta=new gt(i)}this.isReady=!1,this.accessCheck().then(()=>{this.isReady=!0}).catch(i=>{this.logger?.error("Storage access check failed: %O",i)})}normalizeError(t){return super.normalizeError(t)}async create(t){return this.instrumentOperation("create",async()=>{const r={...t};if(t.ttl){const a=typeof t.ttl=="string"?Nt(t.ttl):t.ttl;a!==void 0&&(r.expiredAt=Date.now()+a)}r.size!==void 0&&Number(r.size)<0&&g(y.REQUEST_ENTITY_TOO_LARGE,"Request entity too large");const i=new Pt(r);try{const a=await this.getMeta(i.id);if(a.status==="completed")return a}catch{}i.name=this.namingFunction(i),(i.size===void 0||Number.isNaN(i.size))&&(i.size===void 0||(i.size=this.maxUploadSize)),await this.validate(i);const n=this.getFilePath(i.name);try{await x(n),i.bytesWritten=0}catch(a){const s=this.normalizeError(a instanceof Error?a:new Error(String(a)));await this.onError(s),g(y.FILE_ERROR,s.message)}return i.status=B(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(t){return this.instrumentOperation("write",async()=>{let r;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?r=t:(r=await this.getMeta(t.id),await this.checkIfExpired(r)),r.status==="completed")return r;if(t.size!==void 0&&_t(r,t.size),!Dt(t,r))return g(y.FILE_CONFLICT);const i=this.getFilePath(r.name),n=await this.lock(i);try{const a=t.start||0;if(await x(i),r.bytesWritten===0&&(r.bytesWritten=a),It(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))return g(y.UNSUPPORTED_CHECKSUM_ALGORITHM);if((t.start===0||t.start===void 0)&&(r.bytesWritten===0||Number.isNaN(r.bytesWritten))&&(!r.contentType||r.contentType==="application/octet-stream"))try{const{fileType:c,stream:o}=await $t(t.body);c?.mime&&(r.contentType=c.mime),t.body=o}catch{}const s=t.signal,l={...r,...t,body:t.body};s&&(l.signal=s);const[u,m]=await this.lazyWrite(l);if(m)return await mt(i,r.bytesWritten),g(m);const d=a+(t.contentLength||0);r.bytesWritten=Math.max(r.bytesWritten||0,d),r.bytesWritten=Math.max(r.bytesWritten||0,u),r.status=B(r),await this.saveMeta(r)}else await x(i),r.bytesWritten=0;return r}catch(a){if(Ot(a))throw a;const s=this.normalizeError(a instanceof Error?a:new Error(String(a)));return await this.onError(s),g(y.FILE_ERROR,(typeof s.message=="string"?s.message:String(a))||String(a))}finally{await this.unlock(i,n)}})}async get({id:t}){return this.instrumentOperation("get",async()=>{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:i,contentType:n,expiredAt:a,metadata:s,modifiedAt:l,name:u,originalName:m,size:d}=r;let c;try{c=await wt(this.getFilePath(u),{buffer:!0})}catch(o){const f=o;if(f.code==="ENOENT"||f.code==="EPERM"){const M=this.normalizeError(o instanceof Error?o:new Error(f.message||String(o)));return await this.onError(M),g(y.FILE_NOT_FOUND,(typeof M.message=="string"?M.message:String(o))||String(o))}const ot=this.normalizeError(o instanceof Error?o:new Error(String(o)));throw await this.onError(ot),o}return{content:c,contentType:n,ETag:St(c),expiredAt:a,id:t,metadata:s,modifiedAt:l,name:u,originalName:m,size:d||i}})}async exists({id:t}){return this.instrumentOperation("exists",async()=>{try{const r=await this.getMeta(t),i=this.getFilePath(r.name);return await C(i),!0}catch{return!1}})}async getStream({id:t}){return this.instrumentOperation("getStream",async()=>{try{const r=await this.checkIfExpired(await this.meta.get(t)),{bytesWritten:i,contentType:n,expiredAt:a,modifiedAt:s,name:l,size:u}=r,m=lt(this.getFilePath(l));return{headers:{"Content-Length":String(u||i),"Content-Type":n,...a&&{"X-Upload-Expires":a.toString()},...s&&{"Last-Modified":s.toString()}},size:u||i,stream:m}}catch(r){const i=this.normalizeError(r instanceof Error?r:new Error(String(r)));throw await this.onError(i),g(y.FILE_NOT_FOUND,(typeof i.message=="string"?i.message:String(r))||String(r))}})}async delete({id:t}){return this.instrumentOperation("delete",async()=>{const r=await this.getMeta(t);await W(this.getFilePath(r.name)),await this.deleteMeta(t);const i={...r,status:"deleted"};return await this.onDelete(i),i})}async copy(t,r){return this.instrumentOperation("copy",async()=>{E.assertSafeId(t),E.assertSafeId(r);const i=await this.getMeta(t);return await z(this.getFilePath(i.name),this.getFilePath(r)),{...i,name:r}})}async move(t,r){return this.instrumentOperation("move",async()=>{E.assertSafeId(t),E.assertSafeId(r);const i=await this.getMeta(t),n=this.getFilePath(i.name),a=this.getFilePath(r);try{await Me(n,a)}catch(s){if(s?.code==="EXDEV")await z(n,a),await W(n);else{const l=this.normalizeError(s instanceof Error?s:new Error(String(s)));throw await this.onError(l),s}}return{...i,id:i.id,name:r}})}async list(){return this.instrumentOperation("list",async()=>{const t={followSymlinks:!1,includeDirs:!1,includeFiles:!0,skip:["*.META$"]},r=[],{directory:i}=this,n=R(s=>s.replaceAll("\\","/"),"toPosix"),a=n(i);for await(const s of k(i,t)){const{suffix:l}=this.meta,{path:u}=s;if(!u.includes(l)){const{birthtime:m,ctime:d,mtime:c}=await C(u),o=n(u),f=o.startsWith(a)?o.slice(a.length):o;r.push({createdAt:m||d,id:f,modifiedAt:c})}}return r})}getFilePath(t){return E.assertSafeId(t),Et(t)&&g(y.INVALID_FILE_NAME,`Invalid file id: "${t}"`),K(this.directory,t)}lazyWrite(t){return new Promise((r,i)=>{const n=ut(this.getFilePath(t.name),{flags:"r+",start:t.start}),a=new Ce(t.contentLength||t.size-t.start),s=Le(t.checksum,t.checksumAlgorithm),l=!t.checksum,{signal:u}=t,m=R(()=>{n.close(),a.destroy(),s.destroy()},"cleanupStreams"),d=R(c=>{m(),r([Number.NaN,c])},"failWithCode");if(a.on("error",()=>{d(y.FILE_CONFLICT)}),s.on("error",()=>{d(y.CHECKSUM_MISMATCH)}),t.body.on("aborted",()=>{d(l?void 0:y.REQUEST_ABORTED)}),t.body.on("error",c=>{m(),i(c)}),u?.aborted){d(l?void 0:y.REQUEST_ABORTED);return}u&&u.addEventListener("abort",()=>{m(),n.destroy(),a.destroy(),s.destroy(),t.body.destroy(),r([Number.NaN,l?void 0:y.REQUEST_ABORTED])}),ht(t.body,a,s,n,c=>{if(c){if(m(),u?.aborted){r([Number.NaN,l?void 0:y.REQUEST_ABORTED]);return}r([Number.NaN,y.FILE_ERROR]);return}r([t.start+n.bytesWritten])})})}async accessCheck(){await H(this.directory)}}export{E as f,Ce as m,Le as s,x as y};
@@ -1,4 +1,4 @@
1
- import { F as File, M as MetaStorage, D as DiskStorageOptions, H as HttpError, e as FileInit, f as FilePart, g as FileQuery, a as FileReturn, E as ERRORS, B as BaseStorage, h as DiskStorageWithChecksumOptions } from "./storage.d-RteRC-cG.js";
1
+ import { F as File, M as MetaStorage, D as DiskStorageOptions, H as HttpError, e as FileInit, f as FilePart, g as FileQuery, a as FileReturn, E as ERRORS, B as BaseStorage, h as DiskStorageWithChecksumOptions } from "./storage.d-BoJgdi1n.js";
2
2
  import { Readable } from 'node:stream';
3
3
  /**
4
4
  * Local disk-based storage implementation.
@@ -1,4 +1,4 @@
1
- import { F as Files } from "./index.d-C4Fivh4I.js";
1
+ import { F as Files } from "./index.d-DSZjPbvW.js";
2
2
  import { C as CopyFileInput, D as DeleteFileInput, a as DownloadFileInput, G as GetFileMetadataInput, b as GetFileUrlInput, L as ListFilesInput, S as SignUploadUrlInput, U as UploadFileInput } from "./approval.d-CMAYH9GF.js";
3
3
  interface CopyFileResult {
4
4
  copied: true;
@@ -1 +1 @@
1
- var g=Object.defineProperty;var o=(s,t)=>g(s,"name",{value:t,configurable:!0});import{randomUUID as y}from"node:crypto";import{request as f}from"gaxios";import{GoogleAuth as C}from"google-auth-library";import v from"./MetaStorage-Y4m1dWgd.js";import{stringifyMetadata as R,parseMetadata as E}from"./Metadata-B6Ir0KO7.js";import n from"./GCSConfig-BQ0OpVhe.js";import{o as $}from"./has-content-Bx2p8Okx.js";var I="@visulima/storage",P="1.0.0-alpha.29";const i={name:I,version:P};var A=Object.defineProperty,u=o((s,t)=>A(s,"name",{value:t,configurable:!0}),"n");const T=u(s=>{const t=s.match(/(\d+)-(\d+)/),e=t?.[2]?+t[2]:0;return e>0?e+1:0},"getRangeEnd"),G=u(s=>{if($(s)){const t=s.contentLength?s.start+s.contentLength-1:"*";return`bytes ${s.start}-${t}/${s.size??"*"}`}return`bytes */${s.size??"*"}`},"buildContentRange"),U=u(s=>{if(s.response!==void 0){const{response:t}=s;return t?.data?.error?.errors?.map(({reason:e=""})=>e==="rateLimitExceeded"||e==="userRateLimitExceeded"?!0:!!(e&&e.includes("EAI_AGAIN"))).includes(!0)}return!1},"shouldRetry"),w={retry:3,shouldRetry:U,statusCodesToRetry:[[408,429,500,502,503,504],[100,199],[429],[500,599]]};var b=Object.defineProperty,j=o((s,t)=>b(s,"name",{value:t,configurable:!0}),"p");class N extends v{static{o(this,"E")}constructor(t){super(t),this.config=t;const{authClient:e,...a}=t,r=a.bucket||process.env.GCS_BUCKET;if(e===void 0){if(!r)throw new Error("GCS bucket is not defined");if(!a.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");a.scopes||=n.authScopes,this.authClient=new C(a)}else this.authClient=e;this.storageBaseURI=`${a.storageAPI||n.storageAPI}/${r}/o`,this.uploadBaseURI=`${a.uploadAPI||n.uploadAPI}/${r}/o`;const h=["storage.googleapis.com"],d=new URL(this.storageBaseURI).hostname;this.isCustomEndpoint=!h.includes(d);const{retryOptions:m,useAuthWithCustomEndpoint:p,userProject:l}=t;this.userProject=l,this.useAuthWithCustomEndpoint=p||!1,this.retryOptions={...w,...m},e===void 0&&this.accessCheck().catch(c=>{throw c.code==="404"?new Error(`Bucket ${r} does not exist`):c})}config;static{j(this,"GCSMetaStorage")}authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;async save(t,e){const a={...e};return a.metadata&&(a.metadata=R(e.metadata)),await this.makeRequest({body:JSON.stringify(a),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:a}=await this.makeRequest({params:{alt:"media"},url:e});return a.metadata&&typeof a.metadata=="string"&&(a.metadata=E(a.metadata)),a}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":`${i.name}/${i.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${i.version} gccl-invocation-id/${y()}`},params:{...this.userProject===void 0?{}:{userProject:this.userProject}},retry:!0,retryConfig:this.retryOptions,timeout:6e4},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?f(t):this.authClient.request(t)}}export{N as E,G as b,i as d,T as g,w as r};
1
+ var g=Object.defineProperty;var o=(s,t)=>g(s,"name",{value:t,configurable:!0});import{randomUUID as y}from"node:crypto";import{request as f}from"gaxios";import{GoogleAuth as C}from"google-auth-library";import v from"./MetaStorage-Y4m1dWgd.js";import{stringifyMetadata as R,parseMetadata as E}from"./Metadata-B6Ir0KO7.js";import n from"./GCSConfig-BQ0OpVhe.js";import{o as $}from"./has-content-Bx2p8Okx.js";var I="@visulima/storage",P="1.0.0-alpha.30";const i={name:I,version:P};var A=Object.defineProperty,u=o((s,t)=>A(s,"name",{value:t,configurable:!0}),"n");const T=u(s=>{const t=s.match(/(\d+)-(\d+)/),e=t?.[2]?+t[2]:0;return e>0?e+1:0},"getRangeEnd"),G=u(s=>{if($(s)){const t=s.contentLength?s.start+s.contentLength-1:"*";return`bytes ${s.start}-${t}/${s.size??"*"}`}return`bytes */${s.size??"*"}`},"buildContentRange"),U=u(s=>{if(s.response!==void 0){const{response:t}=s;return t?.data?.error?.errors?.map(({reason:e=""})=>e==="rateLimitExceeded"||e==="userRateLimitExceeded"?!0:!!(e&&e.includes("EAI_AGAIN"))).includes(!0)}return!1},"shouldRetry"),w={retry:3,shouldRetry:U,statusCodesToRetry:[[408,429,500,502,503,504],[100,199],[429],[500,599]]};var b=Object.defineProperty,j=o((s,t)=>b(s,"name",{value:t,configurable:!0}),"p");class N extends v{static{o(this,"E")}constructor(t){super(t),this.config=t;const{authClient:e,...a}=t,r=a.bucket||process.env.GCS_BUCKET;if(e===void 0){if(!r)throw new Error("GCS bucket is not defined");if(!a.projectId)throw new Error("Sorry, we cannot connect to Cloud Services without a project ID.");a.scopes||=n.authScopes,this.authClient=new C(a)}else this.authClient=e;this.storageBaseURI=`${a.storageAPI||n.storageAPI}/${r}/o`,this.uploadBaseURI=`${a.uploadAPI||n.uploadAPI}/${r}/o`;const h=["storage.googleapis.com"],d=new URL(this.storageBaseURI).hostname;this.isCustomEndpoint=!h.includes(d);const{retryOptions:m,useAuthWithCustomEndpoint:p,userProject:l}=t;this.userProject=l,this.useAuthWithCustomEndpoint=p||!1,this.retryOptions={...w,...m},e===void 0&&this.accessCheck().catch(c=>{throw c.code==="404"?new Error(`Bucket ${r} does not exist`):c})}config;static{j(this,"GCSMetaStorage")}authClient;storageBaseURI;uploadBaseURI;isCustomEndpoint=!1;retryOptions={};useAuthWithCustomEndpoint;userProject;async save(t,e){const a={...e};return a.metadata&&(a.metadata=R(e.metadata)),await this.makeRequest({body:JSON.stringify(a),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:a}=await this.makeRequest({params:{alt:"media"},url:e});return a.metadata&&typeof a.metadata=="string"&&(a.metadata=E(a.metadata)),a}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":`${i.name}/${i.version}`,"x-goog-api-client":`gl-node/${process.versions.node} gccl/${i.version} gccl-invocation-id/${y()}`},params:{...this.userProject===void 0?{}:{userProject:this.userProject}},retry:!0,retryConfig:this.retryOptions,timeout:6e4},this.isCustomEndpoint&&!this.useAuthWithCustomEndpoint?f(t):this.authClient.request(t)}}export{N as E,G as b,i as d,T as g,w as r};