@visulima/storage 1.0.0-alpha.9 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (424) hide show
  1. package/CHANGELOG.md +555 -0
  2. package/LICENSE.md +237 -568
  3. package/README.md +82 -466
  4. package/dist/adapter/nuxt/module.d.ts +41 -34
  5. package/dist/adapter/nuxt/module.js +1 -93
  6. package/dist/adapter/nuxt/package.json +0 -6
  7. package/dist/ai/ai-sdk/index.d.ts +113 -0
  8. package/dist/ai/ai-sdk/index.js +1 -0
  9. package/dist/ai/claude/index.d.ts +177 -0
  10. package/dist/ai/claude/index.js +1 -0
  11. package/dist/ai/openai/index.d.ts +205 -0
  12. package/dist/ai/openai/index.js +1 -0
  13. package/dist/ai/tanstack/index.d.ts +115 -0
  14. package/dist/ai/tanstack/index.js +1 -0
  15. package/dist/handler/http/fetch/index.d.ts +303 -4
  16. package/dist/handler/http/fetch/index.js +1 -4
  17. package/dist/handler/http/hono/index.d.ts +73 -64
  18. package/dist/handler/http/hono/index.js +1 -65
  19. package/dist/handler/http/nextjs/index.d.ts +66 -58
  20. package/dist/handler/http/nextjs/index.js +1 -37
  21. package/dist/handler/http/node/index.d.ts +368 -4
  22. package/dist/handler/http/node/index.js +1 -8
  23. package/dist/handler/http/solid-start/index.d.ts +66 -57
  24. package/dist/handler/http/solid-start/index.js +1 -44
  25. package/dist/index.d.ts +106 -17
  26. package/dist/index.js +1 -13
  27. package/dist/openapi/index.d.ts +24 -5
  28. package/dist/openapi/index.js +1 -5
  29. package/dist/packem_shared/AbstractBaseStorage-Ba7cLu-t.js +1 -0
  30. package/dist/packem_shared/AwsLightFile-CpZrubaV.js +1 -0
  31. package/dist/packem_shared/AwsLightMetaStorage-DPqJ9LTr.js +1 -0
  32. package/dist/packem_shared/AwsLightStorage-DTBVxHXO.js +1 -0
  33. package/dist/packem_shared/AzureFile-DFSaVe25.js +1 -0
  34. package/dist/packem_shared/AzureSMetaStorage-ByzM6Aix.js +1 -0
  35. package/dist/packem_shared/AzureStorage-BFsD4qbF.js +1 -0
  36. package/dist/packem_shared/BaseTransformer-Buw5lX_3.js +1 -0
  37. package/dist/packem_shared/BoxFile-CseIoPW1.js +1 -0
  38. package/dist/packem_shared/BoxMetaStorage-DFwhEI9C.js +1 -0
  39. package/dist/packem_shared/BoxStorage-B_t-OVzf.js +1 -0
  40. package/dist/packem_shared/BunS3File-BcYmsz1n.js +1 -0
  41. package/dist/packem_shared/BunS3MetaStorage-DFwhEI9C.js +1 -0
  42. package/dist/packem_shared/BunS3Storage-CB_pZWlV.js +1 -0
  43. package/dist/packem_shared/BunnyFile-BgEOlcYI.js +1 -0
  44. package/dist/packem_shared/BunnyMetaStorage-DFwhEI9C.js +1 -0
  45. package/dist/packem_shared/BunnyStorage-CILSK4_Z.js +1 -0
  46. package/dist/packem_shared/CloudinaryFile-Bo5B-vM1.js +1 -0
  47. package/dist/packem_shared/CloudinaryMetaStorage-D_vNzewL.js +1 -0
  48. package/dist/packem_shared/CloudinaryStorage-DiCbdAi_.js +1 -0
  49. package/dist/packem_shared/DiskStorage-Kp5t3vnF.js +1 -0
  50. package/dist/packem_shared/DiskStorageWithChecksum-Bh6w-Iu8.js +1 -0
  51. package/dist/packem_shared/DropboxFile-BFb7eOzy.js +1 -0
  52. package/dist/packem_shared/DropboxMetaStorage-DFwhEI9C.js +1 -0
  53. package/dist/packem_shared/DropboxStorage-H8bd8hEz.js +1 -0
  54. package/dist/packem_shared/ERRORS-BIBxE2oR.js +1 -0
  55. package/dist/packem_shared/File-W8aOo15X.js +1 -0
  56. package/dist/packem_shared/Files-BA3mpDwz.js +1 -0
  57. package/dist/packem_shared/FirebaseFile-BLaBxa2A.js +1 -0
  58. package/dist/packem_shared/FirebaseMetaStorage-D_vNzewL.js +1 -0
  59. package/dist/packem_shared/FirebaseStorage-Dgk4XyMr.js +2 -0
  60. package/dist/packem_shared/FtpFile-ClWDYnt2.js +1 -0
  61. package/dist/packem_shared/FtpMetaStorage-DFwhEI9C.js +1 -0
  62. package/dist/packem_shared/FtpStorage-g_DjiR-C.js +1 -0
  63. package/dist/packem_shared/GCSConfig-BQ0OpVhe.js +1 -0
  64. package/dist/packem_shared/GCSFile-Cero7qZN.js +1 -0
  65. package/dist/packem_shared/GCSMetaStorage-3fLTlRd4.js +1 -0
  66. package/dist/packem_shared/GCStorage-DUfwVFd3.js +1 -0
  67. package/dist/packem_shared/GoogleDriveFile-DHpLhzg9.js +1 -0
  68. package/dist/packem_shared/GoogleDriveMetaStorage-DqkgoE46.js +1 -0
  69. package/dist/packem_shared/GoogleDriveStorage-D0-5egHE.js +1 -0
  70. package/dist/packem_shared/LocalMetaStorage-Bp5mVc76.js +1 -0
  71. package/dist/packem_shared/MediaTransformer-D2kUsklW.js +1 -0
  72. package/dist/packem_shared/MemoryMetaStorage-Ksgh9pe7.js +1 -0
  73. package/dist/packem_shared/MemoryStorage-DzSTdlAq.js +1 -0
  74. package/dist/packem_shared/MetaStorage-DPEUyWgN.js +1 -0
  75. package/dist/packem_shared/Metadata-B7CcBueg.js +1 -0
  76. package/dist/packem_shared/Multipart-Btj2mo9r.js +1 -0
  77. package/dist/packem_shared/Multipart-C4GpuHMU.js +1 -0
  78. package/dist/packem_shared/NetlifyBlobFile-DoFhkzaH.js +1 -0
  79. package/dist/packem_shared/NetlifyBlobMetaStorage-D_vNzewL.js +1 -0
  80. package/dist/packem_shared/NetlifyBlobStorage-DZdCmOVW.js +1 -0
  81. package/dist/packem_shared/NoOpMetrics-BLo6u4NY.js +1 -0
  82. package/dist/packem_shared/OneDriveFile-CNNJYI43.js +1 -0
  83. package/dist/packem_shared/OneDriveMetaStorage-DqkgoE46.js +1 -0
  84. package/dist/packem_shared/OneDriveStorage-CvJetV7_.js +1 -0
  85. package/dist/packem_shared/OpenTelemetryMetrics-DJDQsNKp.js +1 -0
  86. package/dist/packem_shared/PocketBaseFile-DpJpxl3e.js +1 -0
  87. package/dist/packem_shared/PocketBaseMetaStorage-CpvDRnSu.js +1 -0
  88. package/dist/packem_shared/PocketBaseStorage-BPil-koe.js +1 -0
  89. package/dist/packem_shared/Rest-BehVaxbl.js +1 -0
  90. package/dist/packem_shared/Rest-ymPCZkKR.js +1 -0
  91. package/dist/packem_shared/S3File-CpZrubaV.js +1 -0
  92. package/dist/packem_shared/S3MetaStorage-CMonflzp.js +1 -0
  93. package/dist/packem_shared/S3Storage-wslqssvr.js +1 -0
  94. package/dist/packem_shared/SftpFile-ClWDYnt2.js +1 -0
  95. package/dist/packem_shared/SftpMetaStorage-DFwhEI9C.js +1 -0
  96. package/dist/packem_shared/SftpStorage-BVbMtS2b.js +1 -0
  97. package/dist/packem_shared/SharePointFile-Blz9FS4h.js +1 -0
  98. package/dist/packem_shared/SharePointMetaStorage-DFwhEI9C.js +1 -0
  99. package/dist/packem_shared/SharePointStorage-DWjvR5oZ.js +1 -0
  100. package/dist/packem_shared/SupabaseFile-Bo5B-vM1.js +1 -0
  101. package/dist/packem_shared/SupabaseMetaStorage-DqkgoE46.js +1 -0
  102. package/dist/packem_shared/SupabaseStorage-BiKmYKb6.js +1 -0
  103. package/dist/packem_shared/TUS_RESUMABLE-CyTSRvPU.js +1 -0
  104. package/dist/packem_shared/Tus-BgbON_wQ.js +1 -0
  105. package/dist/packem_shared/Tus-v6jzkaIO.js +1 -0
  106. package/dist/packem_shared/UploadControl-DZJhI9Wh.js +1 -0
  107. package/dist/packem_shared/UploadThingFile-BTFMpcIA.js +1 -0
  108. package/dist/packem_shared/UploadThingMetaStorage-D_vNzewL.js +1 -0
  109. package/dist/packem_shared/UploadThingStorage-jrEnANC5.js +1 -0
  110. package/dist/packem_shared/ValidationError-3B06DFyE.js +1 -0
  111. package/dist/packem_shared/VercelBlobFile-CVQwKlZk.js +1 -0
  112. package/dist/packem_shared/VercelBlobMetaStorage-DFwhEI9C.js +1 -0
  113. package/dist/packem_shared/VercelBlobStorage-Y-cDgH30.js +1 -0
  114. package/dist/packem_shared/_commonjsHelpers-CWAkuNXM.js +1 -0
  115. package/dist/packem_shared/agentsCopyFile-Dl5iffdH.js +1 -0
  116. package/dist/packem_shared/akamai-DthkaFul.js +1 -0
  117. package/dist/packem_shared/alibaba-BEi25O1g.js +1 -0
  118. package/dist/packem_shared/approval-fVHwBp7u.js +1 -0
  119. package/dist/packem_shared/approval.d-CMAYH9GF.d.ts +75 -0
  120. package/dist/packem_shared/aws-light-meta-storage-DGrn72VJ.js +4 -0
  121. package/dist/packem_shared/azure-meta-storage-ClbEsfI4.js +1 -0
  122. package/dist/packem_shared/backblaze-m1N5NZ9q.js +1 -0
  123. package/dist/packem_shared/base-handler-core-EeV8gZck.js +1 -0
  124. package/dist/packem_shared/base-handler-fetch-CHzsgb7C.js +1 -0
  125. package/dist/packem_shared/base-handler-node-BjpW8pGi.js +1 -0
  126. package/dist/packem_shared/cache-Cw3QjoVN.js +1 -0
  127. package/dist/packem_shared/claudeCopyFile-BX9O4ORk.js +1 -0
  128. package/dist/packem_shared/cloudflare-CdUTErlo.js +1 -0
  129. package/dist/packem_shared/copyFile-49FtxXcm.js +1 -0
  130. package/dist/packem_shared/copyFile-BUPezT_c.js +1 -0
  131. package/dist/packem_shared/createResponsesFileTools-6Tvt2PNr.js +1 -0
  132. package/dist/packem_shared/createRetryWrapper-CxgiV_hH.js +1 -0
  133. package/dist/packem_shared/detect-file-type-BA7UBLKA.js +1 -0
  134. package/dist/packem_shared/digitalOcean-B2uB6pgz.js +1 -0
  135. package/dist/packem_shared/disk-storage-DIn-VnCh.js +1 -0
  136. package/dist/packem_shared/disk-storage-with-checksum.d-B-VGEsfl.d.ts +156 -0
  137. package/dist/packem_shared/executors-BDzMjc4y.js +1 -0
  138. package/dist/packem_shared/executors.d-BZP2rWo3.d.ts +69 -0
  139. package/dist/packem_shared/exoscale-BDa1Gjth.js +1 -0
  140. package/dist/packem_shared/filebase-CsFYJIwB.js +1 -0
  141. package/dist/packem_shared/files.d-CH0iLBNC.d.ts +655 -0
  142. package/dist/packem_shared/gcs-meta-storage-Dy37wCjI.js +1 -0
  143. package/dist/packem_shared/get-file-status-y3wTtDQs.js +1 -0
  144. package/dist/packem_shared/getFormatFromContentType-DCTTPQHm.js +1 -0
  145. package/dist/packem_shared/has-content-50BsqrWw.js +1 -0
  146. package/dist/packem_shared/headers-BAiAKekR.js +26 -0
  147. package/dist/packem_shared/hetzner-BGGFiRGD.js +1 -0
  148. package/dist/packem_shared/ibmCos-j-3TfJ5p.js +1 -0
  149. package/dist/packem_shared/idriveE2-C6pQ5pQ0.js +1 -0
  150. package/dist/packem_shared/index-nZWCQrSe.js +5 -0
  151. package/dist/packem_shared/internal-D_cZIFwI.js +1 -0
  152. package/dist/packem_shared/is-expired-CBEk6XBi.js +1 -0
  153. package/dist/packem_shared/local-meta-storage-C2T92TYb.js +11 -0
  154. package/dist/packem_shared/local-meta-storage.d-D9PBfkn6.d.ts +21 -0
  155. package/dist/packem_shared/media-transformer.d-Quf4ai47.d.ts +331 -0
  156. package/dist/packem_shared/memory-storage.d-4EU1cMt1.d.ts +101 -0
  157. package/dist/packem_shared/minio-NKquuBfS.js +1 -0
  158. package/dist/packem_shared/multipart-base-BOzY19lb.js +1 -0
  159. package/dist/packem_shared/oauth-refresh-EdGzlcOZ.js +1 -0
  160. package/dist/packem_shared/oracleCloud-DslqNpn6.js +1 -0
  161. package/dist/packem_shared/ovhCloud-CMHE6uLV.js +1 -0
  162. package/dist/packem_shared/part-match-D-9dGX42.js +1 -0
  163. package/dist/packem_shared/path-0oTTdkvl-BVg7lYf5.js +1 -0
  164. package/dist/packem_shared/posix-dirname-CfpH5wZi.js +1 -0
  165. package/dist/packem_shared/response-builder-CbSA8qPa.js +1 -0
  166. package/dist/packem_shared/rest-base-CynUg0mH.js +1 -0
  167. package/dist/packem_shared/restOpenApiSpec-Csv513qf.js +1 -0
  168. package/dist/packem_shared/s3-base-storage-DXZYN24h.js +1 -0
  169. package/dist/packem_shared/s3-base-storage.d-BQgP5B-t.d.ts +287 -0
  170. package/dist/packem_shared/scaleway-U1In3v70.js +1 -0
  171. package/dist/packem_shared/sharedErrorSchemaObject-YN65aAKj.js +1 -0
  172. package/dist/packem_shared/storage-Cyy73Y6r.js +1 -0
  173. package/dist/packem_shared/storage.d-CEM1upWM.d.ts +1176 -0
  174. package/dist/packem_shared/storj-Cb59q9kF.js +1 -0
  175. package/dist/packem_shared/sync-DhR3536K.js +1 -0
  176. package/dist/packem_shared/tencent-Q1y2GENc.js +1 -0
  177. package/dist/packem_shared/tigris-BELKoyyp.js +1 -0
  178. package/dist/packem_shared/transformOpenApiSpec-CIEAgpBD.js +1 -0
  179. package/dist/packem_shared/tus-base.d-DLzKE54M.d.ts +106 -0
  180. package/dist/packem_shared/tusOpenApiSpec-D96B03t5.js +1 -0
  181. package/dist/packem_shared/types.d-Bon9GVVe.d.ts +104 -0
  182. package/dist/packem_shared/types.d-CggTCgXr.d.ts +49 -0
  183. package/dist/packem_shared/types.d-CrUWY4On.d.ts +720 -0
  184. package/dist/packem_shared/update-size-DuNuLyxj.js +1 -0
  185. package/dist/packem_shared/vultr-B491cQ4e.js +1 -0
  186. package/dist/packem_shared/waitForStorage-ByQmG4xF.js +1 -0
  187. package/dist/packem_shared/wasabi-DFrwIoab.js +1 -0
  188. package/dist/packem_shared/xhrOpenApiSpec-DQR4h6M8.js +1 -0
  189. package/dist/packem_shared/yandex-CwzHuEKP.js +1 -0
  190. package/dist/storage/aws/clients/index.d.ts +612 -6
  191. package/dist/storage/aws/clients/index.js +1 -6
  192. package/dist/storage/aws/index.d.ts +332 -4
  193. package/dist/storage/aws/index.js +1 -3
  194. package/dist/storage/aws-light/index.d.ts +259 -4
  195. package/dist/storage/aws-light/index.js +1 -3
  196. package/dist/storage/azure/index.d.ts +236 -4
  197. package/dist/storage/azure/index.js +1 -3
  198. package/dist/storage/box/index.d.ts +189 -0
  199. package/dist/storage/box/index.js +1 -0
  200. package/dist/storage/bun-s3/index.d.ts +200 -0
  201. package/dist/storage/bun-s3/index.js +1 -0
  202. package/dist/storage/bunny/index.d.ts +119 -0
  203. package/dist/storage/bunny/index.js +1 -0
  204. package/dist/storage/cloudinary/index.d.ts +121 -0
  205. package/dist/storage/cloudinary/index.js +1 -0
  206. package/dist/storage/dropbox/index.d.ts +132 -0
  207. package/dist/storage/dropbox/index.js +1 -0
  208. package/dist/storage/firebase/index.d.ts +192 -0
  209. package/dist/storage/firebase/index.js +1 -0
  210. package/dist/storage/ftp/index.d.ts +91 -0
  211. package/dist/storage/ftp/index.js +1 -0
  212. package/dist/storage/gcs/index.d.ts +195 -5
  213. package/dist/storage/gcs/index.js +1 -4
  214. package/dist/storage/google-drive/index.d.ts +148 -0
  215. package/dist/storage/google-drive/index.js +1 -0
  216. package/dist/storage/local/index.d.ts +7 -4
  217. package/dist/storage/local/index.js +1 -3
  218. package/dist/storage/memory/index.d.ts +6 -0
  219. package/dist/storage/memory/index.js +1 -0
  220. package/dist/storage/netlify-blob/index.d.ts +147 -4
  221. package/dist/storage/netlify-blob/index.js +1 -3
  222. package/dist/storage/onedrive/index.d.ts +103 -0
  223. package/dist/storage/onedrive/index.js +1 -0
  224. package/dist/storage/pocketbase/index.d.ts +172 -0
  225. package/dist/storage/pocketbase/index.js +1 -0
  226. package/dist/storage/sftp/index.d.ts +92 -0
  227. package/dist/storage/sftp/index.js +1 -0
  228. package/dist/storage/sharepoint/index.d.ts +180 -0
  229. package/dist/storage/sharepoint/index.js +1 -0
  230. package/dist/storage/supabase/index.d.ts +115 -0
  231. package/dist/storage/supabase/index.js +1 -0
  232. package/dist/storage/uploadthing/index.d.ts +95 -0
  233. package/dist/storage/uploadthing/index.js +1 -0
  234. package/dist/storage/vercel-blob/index.d.ts +189 -4
  235. package/dist/storage/vercel-blob/index.js +1 -3
  236. package/dist/transformer/audio-transformer.d.ts +127 -125
  237. package/dist/transformer/audio-transformer.js +1 -278
  238. package/dist/transformer/image-transformer.d.ts +573 -568
  239. package/dist/transformer/image-transformer.js +1 -1100
  240. package/dist/transformer/index.d.ts +62 -5
  241. package/dist/transformer/index.js +1 -4
  242. package/dist/transformer/video-transformer.d.ts +144 -142
  243. package/dist/transformer/video-transformer.js +1 -310
  244. package/package.json +202 -51
  245. package/dist/handler/base/base-handler-core.d.ts +0 -91
  246. package/dist/handler/base/base-handler-fetch.d.ts +0 -76
  247. package/dist/handler/base/base-handler-node.d.ts +0 -137
  248. package/dist/handler/multipart/multipart-base.d.ts +0 -84
  249. package/dist/handler/multipart/multipart-fetch.d.ts +0 -64
  250. package/dist/handler/multipart/multipart.d.ts +0 -49
  251. package/dist/handler/rest/rest-base.d.ts +0 -106
  252. package/dist/handler/rest/rest-fetch.d.ts +0 -88
  253. package/dist/handler/rest/rest.d.ts +0 -93
  254. package/dist/handler/tus/tus-base.d.ts +0 -152
  255. package/dist/handler/tus/tus-fetch.d.ts +0 -72
  256. package/dist/handler/tus/tus.d.ts +0 -78
  257. package/dist/handler/types.d.ts +0 -53
  258. package/dist/handler/utils/request-parser.d.ts +0 -72
  259. package/dist/handler/utils/response-builder.d.ts +0 -83
  260. package/dist/handler/utils/storage-utils.d.ts +0 -10
  261. package/dist/handler/utils/stream-utils.d.ts +0 -29
  262. package/dist/handler/utils/upload-handlers.d.ts +0 -76
  263. package/dist/metrics/index.d.ts +0 -2
  264. package/dist/metrics/no-op-metrics.d.ts +0 -15
  265. package/dist/metrics/opentelemetry-metrics.d.ts +0 -55
  266. package/dist/openapi/rest.d.ts +0 -7
  267. package/dist/openapi/shared.d.ts +0 -13
  268. package/dist/openapi/transform.d.ts +0 -3
  269. package/dist/openapi/tus.d.ts +0 -7
  270. package/dist/openapi/xhr.d.ts +0 -7
  271. package/dist/packem_shared/AwsLightFile-tTneXZgG.js +0 -11
  272. package/dist/packem_shared/AwsLightMetaStorage-BWSOtVaN.js +0 -4
  273. package/dist/packem_shared/AwsLightStorage-Blv-GP4v.js +0 -133
  274. package/dist/packem_shared/AzureFile-CesgFzps.js +0 -8
  275. package/dist/packem_shared/AzureSMetaStorage-CFs-OYJT.js +0 -88
  276. package/dist/packem_shared/AzureStorage-B0v048hG.js +0 -357
  277. package/dist/packem_shared/BaseTransformer-C2gLib6v.js +0 -82
  278. package/dist/packem_shared/DiskStorage-Ck5yGQsq.js +0 -12
  279. package/dist/packem_shared/DiskStorageWithChecksum-BRl-V5x2.js +0 -238
  280. package/dist/packem_shared/ERRORS-D0apMqnc.js +0 -97
  281. package/dist/packem_shared/File-Bb3P23dr.js +0 -69
  282. package/dist/packem_shared/GCSConfig-vPP22kN6.js +0 -11
  283. package/dist/packem_shared/GCSFile-BIEunhAN.js +0 -8
  284. package/dist/packem_shared/GCSMetaStorage-CHZKMe7N.js +0 -7
  285. package/dist/packem_shared/GCStorage-C-gAuP0j.js +0 -406
  286. package/dist/packem_shared/LocalMetaStorage-CZHhKkMd.js +0 -7
  287. package/dist/packem_shared/MediaTransformer-D6658DL1.js +0 -1197
  288. package/dist/packem_shared/MetaStorage-pECeFOad.js +0 -46
  289. package/dist/packem_shared/Metadata-DRLXeJ0F.js +0 -89
  290. package/dist/packem_shared/Multipart-CRV21AUU.js +0 -128
  291. package/dist/packem_shared/Multipart-D2ryPMjD.js +0 -163
  292. package/dist/packem_shared/NetlifyBlobFile-CXzyjqrD.js +0 -14
  293. package/dist/packem_shared/NetlifyBlobMetaStorage-DxZ5aDvD.js +0 -9
  294. package/dist/packem_shared/NetlifyBlobStorage-CLPtjHqd.js +0 -376
  295. package/dist/packem_shared/NoOpMetrics-DhAk5rXc.js +0 -10
  296. package/dist/packem_shared/OpenTelemetryMetrics-BnxhqIaH.js +0 -67
  297. package/dist/packem_shared/Rest-DcxBMBjU.js +0 -228
  298. package/dist/packem_shared/Rest-DjwU3puo.js +0 -267
  299. package/dist/packem_shared/S3File-DZiyk9Qt.js +0 -11
  300. package/dist/packem_shared/S3MetaStorage-Dz9aDabA.js +0 -76
  301. package/dist/packem_shared/S3Storage-DHmTk-hU.js +0 -316
  302. package/dist/packem_shared/TUS_RESUMABLE-Dtfsffnj.js +0 -434
  303. package/dist/packem_shared/Tus-DFVlZHaX.js +0 -200
  304. package/dist/packem_shared/Tus-DaN0FmOy.js +0 -195
  305. package/dist/packem_shared/ValidationError-BfF1aE4h.js +0 -26
  306. package/dist/packem_shared/VercelBlobFile-BCg4aTEq.js +0 -18
  307. package/dist/packem_shared/VercelBlobMetaStorage-Bd9F-VFm.js +0 -9
  308. package/dist/packem_shared/VercelBlobStorage-DD9LMOS6.js +0 -261
  309. package/dist/packem_shared/_commonjsHelpers-BqLXS_qQ.js +0 -5
  310. package/dist/packem_shared/aws-light-meta-storage-DKJBgbR6.js +0 -446
  311. package/dist/packem_shared/backblaze-BlMnIcBC.js +0 -20
  312. package/dist/packem_shared/base-handler-core-BoAqTyz7.js +0 -303
  313. package/dist/packem_shared/base-handler-fetch-D4u2xits.js +0 -291
  314. package/dist/packem_shared/base-handler-node-DGzcHHAy.js +0 -730
  315. package/dist/packem_shared/cache-B88MXQ_2.js +0 -18
  316. package/dist/packem_shared/cloudflare-Bi1q8wXE.js +0 -21
  317. package/dist/packem_shared/defaultCloudStorageFileNameValidation-DUuacjWv.js +0 -11
  318. package/dist/packem_shared/digitalOcean-CWQRJM3L.js +0 -21
  319. package/dist/packem_shared/disk-storage-CD47QI30.js +0 -810
  320. package/dist/packem_shared/gcs-meta-storage-CJ8Uts_d.js +0 -158
  321. package/dist/packem_shared/has-content-CY66ehMK.js +0 -3
  322. package/dist/packem_shared/headers-YLRp1dLo.js +0 -1318
  323. package/dist/packem_shared/is-expired-CTThU1q5.js +0 -8
  324. package/dist/packem_shared/isRetryableError-Dycp7127.js +0 -82
  325. package/dist/packem_shared/isValidMediaType-BeDgiObq.js +0 -35
  326. package/dist/packem_shared/local-meta-storage-By-3SNBI.js +0 -649
  327. package/dist/packem_shared/minio-C2YBZQOw.js +0 -22
  328. package/dist/packem_shared/multipart-base-C994naBi.js +0 -102
  329. package/dist/packem_shared/part-match-BMNqHDYD.js +0 -96
  330. package/dist/packem_shared/path-CR6YkPXX-7R1-9CMk.js +0 -161
  331. package/dist/packem_shared/response-builder-BtnRiBUI.js +0 -45
  332. package/dist/packem_shared/rest-base-D9URIFkc.js +0 -457
  333. package/dist/packem_shared/restOpenApiSpec-D1JC_Jto.js +0 -800
  334. package/dist/packem_shared/s3-base-storage-C1DIHTYY.js +0 -510
  335. package/dist/packem_shared/sharedGet-Cpo7QUyu.js +0 -1019
  336. package/dist/packem_shared/storage-C6NSXb8h.js +0 -1175
  337. package/dist/packem_shared/tigris-Hac8TKnX.js +0 -21
  338. package/dist/packem_shared/transformOpenApiSpec-DWM5WtnN.js +0 -975
  339. package/dist/packem_shared/tusOpenApiSpec-mBZkl7he.js +0 -740
  340. package/dist/packem_shared/update-size-CCGm6i1J.js +0 -8
  341. package/dist/packem_shared/validator-BeX_lJet.js +0 -78
  342. package/dist/packem_shared/waitForStorage-Cscw85sx.js +0 -18
  343. package/dist/packem_shared/wasabi-DIyflHSd.js +0 -21
  344. package/dist/packem_shared/xhrOpenApiSpec-B1V5Dxrj.js +0 -264
  345. package/dist/storage/aws/clients/backblaze.d.ts +0 -12
  346. package/dist/storage/aws/clients/cloudflare.d.ts +0 -13
  347. package/dist/storage/aws/clients/digital-ocean.d.ts +0 -12
  348. package/dist/storage/aws/clients/minio.d.ts +0 -13
  349. package/dist/storage/aws/clients/tigris.d.ts +0 -12
  350. package/dist/storage/aws/clients/types.d.ts +0 -95
  351. package/dist/storage/aws/clients/wasabi.d.ts +0 -12
  352. package/dist/storage/aws/s3-base-storage.d.ts +0 -248
  353. package/dist/storage/aws/s3-client-adapter.d.ts +0 -110
  354. package/dist/storage/aws/s3-file.d.ts +0 -10
  355. package/dist/storage/aws/s3-meta-storage.d.ts +0 -15
  356. package/dist/storage/aws/s3-storage.d.ts +0 -70
  357. package/dist/storage/aws/types.d.ts +0 -119
  358. package/dist/storage/aws-light/aws-light-api-adapter.d.ts +0 -130
  359. package/dist/storage/aws-light/aws-light-file.d.ts +0 -10
  360. package/dist/storage/aws-light/aws-light-meta-storage.d.ts +0 -19
  361. package/dist/storage/aws-light/aws-light-storage.d.ts +0 -65
  362. package/dist/storage/aws-light/types.d.ts +0 -37
  363. package/dist/storage/azure/azure-file.d.ts +0 -6
  364. package/dist/storage/azure/azure-meta-storage.d.ts +0 -15
  365. package/dist/storage/azure/azure-storage.d.ts +0 -69
  366. package/dist/storage/azure/types.d.ts +0 -62
  367. package/dist/storage/gcs/fetch-error.d.ts +0 -11
  368. package/dist/storage/gcs/gcs-config.d.ts +0 -2
  369. package/dist/storage/gcs/gcs-file.d.ts +0 -6
  370. package/dist/storage/gcs/gcs-meta-storage.d.ts +0 -27
  371. package/dist/storage/gcs/gcs-storage.d.ts +0 -91
  372. package/dist/storage/gcs/types.d.ts +0 -55
  373. package/dist/storage/gcs/utils.d.ts +0 -7
  374. package/dist/storage/local/disk-storage-with-checksum.d.ts +0 -15
  375. package/dist/storage/local/disk-storage.d.ts +0 -135
  376. package/dist/storage/local/local-meta-storage.d.ts +0 -32
  377. package/dist/storage/meta-storage.d.ts +0 -30
  378. package/dist/storage/netlify-blob/netlify-blob-file.d.ts +0 -12
  379. package/dist/storage/netlify-blob/netlify-blob-meta-storage.d.ts +0 -7
  380. package/dist/storage/netlify-blob/netlify-blob-storage.d.ts +0 -93
  381. package/dist/storage/netlify-blob/types.d.ts +0 -30
  382. package/dist/storage/storage.d.ts +0 -353
  383. package/dist/storage/types.d.ts +0 -221
  384. package/dist/storage/utils/file/file.d.ts +0 -25
  385. package/dist/storage/utils/file/get-file-status.d.ts +0 -9
  386. package/dist/storage/utils/file/has-content.d.ts +0 -9
  387. package/dist/storage/utils/file/index.d.ts +0 -10
  388. package/dist/storage/utils/file/is-expired.d.ts +0 -8
  389. package/dist/storage/utils/file/metadata.d.ts +0 -18
  390. package/dist/storage/utils/file/part-match.d.ts +0 -11
  391. package/dist/storage/utils/file/types.d.ts +0 -37
  392. package/dist/storage/utils/file/update-metadata.d.ts +0 -10
  393. package/dist/storage/utils/file/update-size.d.ts +0 -10
  394. package/dist/storage/vercel-blob/types.d.ts +0 -32
  395. package/dist/storage/vercel-blob/vercel-blob-file.d.ts +0 -16
  396. package/dist/storage/vercel-blob/vercel-blob-meta-storage.d.ts +0 -7
  397. package/dist/storage/vercel-blob/vercel-blob-storage.d.ts +0 -76
  398. package/dist/transformer/base-transformer.d.ts +0 -63
  399. package/dist/transformer/media-transformer.d.ts +0 -332
  400. package/dist/transformer/types.d.ts +0 -652
  401. package/dist/transformer/utils.d.ts +0 -33
  402. package/dist/transformer/validation-error.d.ts +0 -23
  403. package/dist/utils/cache.d.ts +0 -32
  404. package/dist/utils/chunked-upload.d.ts +0 -65
  405. package/dist/utils/detect-file-type.d.ts +0 -28
  406. package/dist/utils/errors.d.ts +0 -74
  407. package/dist/utils/file-path-url-matcher.d.ts +0 -18
  408. package/dist/utils/headers.d.ts +0 -111
  409. package/dist/utils/http.d.ts +0 -92
  410. package/dist/utils/locker.d.ts +0 -26
  411. package/dist/utils/pipes/stream-checksum.d.ts +0 -47
  412. package/dist/utils/pipes/stream-length.d.ts +0 -22
  413. package/dist/utils/primitives/get-last-one.d.ts +0 -3
  414. package/dist/utils/primitives/is-record.d.ts +0 -2
  415. package/dist/utils/primitives/map-values.d.ts +0 -9
  416. package/dist/utils/primitives/pick.d.ts +0 -2
  417. package/dist/utils/primitives/to-milliseconds.d.ts +0 -12
  418. package/dist/utils/primitives/to-seconds.d.ts +0 -12
  419. package/dist/utils/range-checksum.d.ts +0 -33
  420. package/dist/utils/range-hasher.d.ts +0 -46
  421. package/dist/utils/retry.d.ts +0 -64
  422. package/dist/utils/types.d.ts +0 -108
  423. package/dist/utils/validation-error.d.ts +0 -22
  424. package/dist/utils/validator.d.ts +0 -36
@@ -0,0 +1 @@
1
+ import{Readable as D}from"node:stream";import{drive as C}from"@googleapis/drive";import{JWT as g,GoogleAuth as T,OAuth2Client as b}from"google-auth-library";import{throwErrorCode as u,ERRORS as p,wrapStorageError as E}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-Cyy73Y6r.js";import m from"./GoogleDriveFile-DHpLhzg9.js";import F from"./GoogleDriveMetaStorage-DqkgoE46.js";import{t as I}from"./get-file-status-y3wTtDQs.js";import{t as _}from"./update-size-DuNuLyxj.js";import{i as L}from"./part-match-D-9dGX42.js";import{e as G}from"./has-content-50BsqrWw.js";const f="https://www.googleapis.com/auth/drive",A=1024,h="fsdkKey",y="fsdkContentType",O="id, name, size, mimeType, md5Checksum, modifiedTime, appProperties",v=r=>{const e=r.lastIndexOf("/");return e===-1?r:r.slice(e+1)},w=r=>r.replaceAll("\\","\\\\").replaceAll("'",String.raw`\'`);class R{#t;#e=new Map;constructor(e){this.#t=Math.max(1,e)}delete(e){this.#e.delete(e)}get(e){const i=this.#e.get(e);if(i!==void 0)return this.#e.delete(e),this.#e.set(e,i),i}set(e,i){if(this.#e.has(e)&&this.#e.delete(e),this.#e.set(e,i),this.#e.size>this.#t){const t=this.#e.keys().next().value;t!==void 0&&this.#e.delete(t)}}}const P=r=>{const e=r.subject??process.env.GOOGLE_DRIVE_SUBJECT;if(r.credentials)return new g({email:r.credentials.client_email,key:r.credentials.private_key,scopes:[f],...e&&{subject:e}});if(r.keyFilename)return new T({keyFile:r.keyFilename,scopes:[f],...e&&{clientOptions:{subject:e}}});if(r.oauth){const s=new b({clientId:r.oauth.clientId,clientSecret:r.oauth.clientSecret});return s.setCredentials({refresh_token:r.oauth.refreshToken}),s}const i=process.env.GOOGLE_DRIVE_CLIENT_EMAIL,t=process.env.GOOGLE_DRIVE_PRIVATE_KEY;if(i&&t)return new g({email:i,key:t,scopes:[f],...e&&{subject:e}});const o=process.env.GOOGLE_DRIVE_KEY_FILE;if(o)return new T({keyFile:o,scopes:[f],...e&&{clientOptions:{subject:e}}})},B=async r=>{const e=[];for await(const i of r)e.push(Buffer.from(i));return Buffer.concat(e)},U=r=>{if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(Buffer.isBuffer(r))return new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(ArrayBuffer.isView(r)){const e=r;return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof r=="string")return new TextEncoder().encode(r);throw new Error("Google Drive: unexpected response payload shape")};class H extends k{static name="google-drive";checksumTypes=[];meta;authForTokens;driveClient;fileIdCache;publicByDefault;rootFolderId;sharedDriveParams;constructor(e){if(super(e),e.client)this.driveClient=e.client,this.authForTokens=void 0;else{const t=P(e);if(!t)throw new Error("Google Drive storage: missing auth. Pass `client`, `credentials`, `keyFilename`, or `oauth`. Env fallbacks: GOOGLE_DRIVE_CLIENT_EMAIL + GOOGLE_DRIVE_PRIVATE_KEY, or GOOGLE_DRIVE_KEY_FILE.");this.authForTokens=t,this.driveClient=C({auth:t,version:"v3"})}const i=e.driveId??process.env.GOOGLE_DRIVE_ID;this.rootFolderId=e.rootFolderId??process.env.GOOGLE_DRIVE_ROOT_FOLDER_ID??i??"root",this.publicByDefault=e.publicByDefault??!1,this.fileIdCache=new R(e.fileIdCacheSize??A),this.sharedDriveParams={includeItemsFromAllDrives:!0,supportsAllDrives:!0,...i&&{corpora:"drive",driveId:i}},this.meta=e.metaStorage??new F(e.metaStorageConfig),this.isReady=!0}get raw(){return this.driveClient}async create(e,i){return this.instrumentOperation("create",async()=>{const t=new m(e);t.name=this.namingFunction(t),await this.validate(t);try{const o=await this.getMeta(t.id);if(o.bytesWritten>=0)return o}catch{}return t.bytesWritten=0,t.status=I(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,i){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&_(t,e.size),!L(e,t))throw new Error("File part does not match");const o=await this.lock(e.id);try{if(G(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const s=await B(e.body),n=t.name||t.id,a={[y]:t.contentType,[h]:n},l=await this.runOperation(i,()=>this.driveClient.files.create({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum, modifiedTime",media:{body:D.from(s),mimeType:t.contentType},requestBody:{appProperties:a,mimeType:t.contentType,name:v(n),parents:[this.rootFolderId]}})),{data:d}=l,c=d.id??void 0;c&&(this.fileIdCache.set(n,c),this.publicByDefault&&await this.runOperation(i,()=>this.driveClient.permissions.create({...this.sharedDriveParams,fileId:c,requestBody:{role:"reader",type:"anyone"}}))),t.bytesWritten=s.length,t.size=s.length,t.driveFileId=c,t.mimeType=d.mimeType??t.contentType,t.ETag=d.md5Checksum??void 0}return t.status=I(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,o)}})}async delete({id:e},i){return this.instrumentOperation("delete",async()=>{let t;const o=e;try{t=await this.getMeta(e)}catch{}try{const s=t?.driveFileId??await this.resolveFileId(o,i);await this.runOperation(i,()=>this.driveClient.files.delete({...this.sharedDriveParams,fileId:s})),this.fileIdCache.delete(o)}catch(s){if(!z(s))throw s;this.fileIdCache.delete(o)}return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new m({contentType:"application/octet-stream",metadata:{},originalName:e}),{id:e,name:e,status:"deleted"})})}async get({id:e},i){return this.instrumentOperation("get",async()=>{let t,o;try{t=await this.checkIfExpired(await this.getMeta(e)),o=t.driveFileId??await this.resolveFileId(t.name??e,i)}catch{o=await this.resolveFileId(e,i)}const[s,n]=await Promise.all([this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,fields:O,fileId:o})),this.runOperation(i,()=>this.driveClient.files.get({...this.sharedDriveParams,alt:"media",fileId:o},{responseType:"arraybuffer"}))]),{data:a}=s,l=U(n.data),d=Buffer.from(l.buffer,l.byteOffset,l.byteLength),c=a.appProperties??{};return{content:d,contentType:t?.contentType??c[y]??a.mimeType??"application/octet-stream",ETag:t?.ETag??a.md5Checksum??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt??a.modifiedTime??void 0,name:t?.name??a.name??e,originalName:t?.originalName??a.name??e,size:t?.size??Number(a.size??d.length)}})}async copy(e,i,t){return this.instrumentOperation("copy",async()=>{const o=await this.resolveFileId(e,t),s=await this.runOperation(t,()=>this.driveClient.files.copy({...this.sharedDriveParams,fields:"id, size, mimeType, md5Checksum",fileId:o,requestBody:{appProperties:{[h]:i},name:v(i),parents:[this.rootFolderId]}})),n=s.data.id??void 0;n&&this.fileIdCache.set(i,n);const a=new m({contentType:s.data.mimeType??"application/octet-stream",metadata:{},originalName:i});return a.id=i,a.name=i,a.driveFileId=n,a.mimeType=s.data.mimeType??void 0,a.ETag=s.data.md5Checksum??void 0,a.size=Number(s.data.size??0),a})}async move(e,i,t){return this.instrumentOperation("move",async()=>{const o=await this.copy(e,i,t);return await this.delete({id:e},t),o})}async list(e=1e3,i){return this.instrumentOperation("list",async()=>{const t=`'${w(this.rootFolderId)}' in parents and trashed=false`,o=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:`nextPageToken, files(${O})`,pageSize:e,q:t}))).data.files??[],s=[];for(const n of o){const a=n.appProperties??{},l=a[h];if(!l)continue;n.id&&this.fileIdCache.set(l,n.id);const d=new m({contentType:a[y]??n.mimeType??"application/octet-stream",metadata:{},originalName:n.name??l});d.id=l,d.name=l,d.driveFileId=n.id??void 0,d.mimeType=n.mimeType??void 0,d.size=Number(n.size??0),d.modifiedAt=n.modifiedTime??void 0,d.ETag=n.md5Checksum??void 0,s.push(d)}return s},{limit:e})}async getReadUrl(e,i){return i?.responseContentDisposition!==void 0||i?.responseContentType!==void 0?u(p.METHOD_NOT_ALLOWED,"Google Drive: `responseContentDisposition`/`responseContentType` are not supported — Drive's webContentLink has no Content-Disposition/Content-Type override."):this.publicByDefault?`https://drive.google.com/uc?export=download&id=${await this.resolveFileId(e)}`:u(p.METHOD_NOT_ALLOWED,"Google Drive: getReadUrl() requires the adapter to be constructed with `publicByDefault: true`. Drive has no signed URL primitive — use get() for private files.")}async getUploadUrl(e,i){if(i?.contentLength!==void 0)return u(p.BAD_REQUEST,"Google Drive: `contentLength` is not supported for upload URLs. A Drive resumable upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");if(!this.authForTokens)return u(p.METHOD_NOT_ALLOWED,"Google Drive: getUploadUrl() requires `credentials`, `keyFilename`, or `oauth` — not the pre-built `client` escape hatch.");const t=await this.authForTokens.getAccessToken(),o=typeof t=="string"?t:t?.token;if(!o)throw new Error("Google Drive: failed to mint access token for resumable upload session");const s={Authorization:`Bearer ${o}`,"Content-Type":"application/json; charset=UTF-8"};i?.contentType&&(s["X-Upload-Content-Type"]=i.contentType);const n={appProperties:{[h]:e},name:v(e),parents:[this.rootFolderId]},a=await fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",{body:JSON.stringify(n),headers:s,method:"POST"});if(!a.ok){const d=await a.text().catch(()=>"");throw E(new Error(`${a.statusText} ${d}`.trim()||a.statusText),{adapter:"Google Drive",operation:"resumable upload session",status:a.status})}const l=a.headers.get("location")??a.headers.get("Location");if(!l)throw E(new Error("response missing Location header"),{adapter:"Google Drive",code:p.STORAGE_ERROR,operation:"resumable upload session"});return l}async resolveFileId(e,i){const t=this.fileIdCache.get(e);if(t)return t;const o=`appProperties has { key='${h}' and value='${w(e)}' } and '${w(this.rootFolderId)}' in parents and trashed=false`,s=(await this.runOperation(i,()=>this.driveClient.files.list({...this.sharedDriveParams,fields:"files(id)",pageSize:2,q:o}))).data.files??[];if(s.length===0)throw new Error(`Google Drive: not found: ${e}`);if(s.length>1)throw new Error(`Google Drive: multiple files share virtual key '${e}'. Resolve via storage.raw.`);const n=s[0]?.id;if(!n)throw new Error(`Google Drive: list returned no fileId for ${e}`);return this.fileIdCache.set(e,n),n}internalOnComplete=e=>this.deleteMeta(e.id)}const z=r=>{if(r===null||typeof r!="object")return!1;const e=r;return typeof e.code=="number"&&e.code===404||typeof e.status=="number"&&e.status===404?!0:typeof e.response?.status=="number"&&e.response.status===404};export{H as default};
@@ -0,0 +1 @@
1
+ import"node:fs/promises";import"node:os";import{y as f}from"./local-meta-storage-C2T92TYb.js";import"./path-0oTTdkvl-BVg7lYf5.js";import"./ERRORS-BIBxE2oR.js";import"./MetaStorage-DPEUyWgN.js";import"./Metadata-B7CcBueg.js";export{f as default};
@@ -0,0 +1 @@
1
+ import{createHash as l}from"node:crypto";import{Readable as f}from"node:stream";import d from"mime";import{N as p}from"./cache-Cw3QjoVN.js";import{isKnownContentType as u}from"./getFormatFromContentType-DCTTPQHm.js";import s from"./ValidationError-3B06DFyE.js";class T{constructor(e,t={}){if(this.storage=e,this.logger=t.logger||this.storage.logger,this.config={audioBitrate:128e3,audioCodec:"aac",cache:t.cache??new p,cacheTtl:3600,maxAudioSize:100*1024*1024,maxImageSize:10*1024*1024,maxVideoSize:500*1024*1024,saveTransformedFiles:!1,supportedAudioFormats:[],supportedImageFormats:[],supportedVideoFormats:[],videoBitrate:2e6,videoCodec:"avc",...t},t.ImageTransformer&&((!Array.isArray(this.config.supportedImageFormats)||this.config.supportedImageFormats.length===0)&&(this.config.supportedImageFormats=["jpeg","png","webp","avif","tiff","gif","svg"]),this.imageTransformer=new t.ImageTransformer(this.storage,{cache:this.config.cache,cacheTtl:this.config.cacheTtl,logger:this.logger,maxImageSize:this.config.maxImageSize,supportedFormats:this.config.supportedImageFormats})),t.VideoTransformer&&((!Array.isArray(this.config.supportedVideoFormats)||this.config.supportedVideoFormats.length===0)&&(this.config.supportedVideoFormats=["mp4","webm","mkv","avi","mov","flv","wmv"]),this.videoTransformer=new t.VideoTransformer(this.storage,{cache:this.config.cache,cacheTtl:this.config.cacheTtl,defaultBitrate:this.config.videoBitrate,defaultCodec:this.config.videoCodec,logger:this.logger,maxVideoSize:this.config.maxVideoSize,supportedFormats:this.config.supportedVideoFormats})),t.AudioTransformer&&((!Array.isArray(this.config.supportedAudioFormats)||this.config.supportedAudioFormats.length===0)&&(this.config.supportedAudioFormats=["mp3","wav","ogg","aac","flac","m4a","wma","aiff"]),this.audioTransformer=new t.AudioTransformer(this.storage,{cache:this.config.cache,cacheTtl:this.config.cacheTtl,defaultBitrate:this.config.audioBitrate,defaultCodec:this.config.audioCodec,logger:this.logger,maxAudioSize:this.config.maxAudioSize,supportedFormats:this.config.supportedAudioFormats})),t.AudioTransformer===void 0&&t.ImageTransformer===void 0&&t.VideoTransformer===void 0)throw new Error("MediaTransformer initialization failed: No transformers are configured. At least one transformer (AudioTransformer, ImageTransformer, or VideoTransformer) must be provided in the configuration to enable media processing functionality.")}storage;imageTransformer;videoTransformer;audioTransformer;config;logger;supportedFormats(){return[...this.config.supportedAudioFormats,...this.config.supportedImageFormats,...this.config.supportedVideoFormats]}async handle(e,t){const a=this.parseQuery(t),r={id:e},o=await this.storage.get(r),n=this.detectMediaType(o.contentType);if(this.validateQueryParameters(a,n),this.config.saveTransformedFiles&&this.hasTransformations(a)){const h=this.generateTransformedFileId(e,a,n);try{const m=await this.storage.get({id:h});return this.logger?.debug?.(`Serving cached transformed file: ${h}`),this.createMediaTransformResult(m,n,o)}catch{this.logger?.debug?.(`Transformed file not found, processing: ${h}`)}}let i;switch(n){case"audio":{if(!this.audioTransformer)throw new Error("Audio transformer not available. Please install audio transformation dependencies or provide an audio transformer instance.");i=await this.handleAudioTransformation(e,a);break}case"image":{if(!this.imageTransformer)throw new Error("Image transformer not available. Please install image transformation dependencies or provide an image transformer instance.");i=await this.handleImageTransformation(e,a);break}case"video":{if(!this.videoTransformer)throw new Error("Video transformer not available. Please install video transformation dependencies or provide a video transformer instance.");i=await this.handleVideoTransformation(e,a);break}default:throw new Error(`Unsupported media type: ${o.contentType}`)}return this.config.saveTransformedFiles&&this.hasTransformations(a)&&await this.saveTransformedFile(i,e,a,n),i}async fetch(e,t){const a=new URLSearchParams(t);return this.handle(e,a)}clearCache(e){this.imageTransformer?.clearCache(e),this.videoTransformer?.clearCache(e),this.audioTransformer?.clearCache(e)}async clearSavedTransformedFiles(){if(this.config.saveTransformedFiles)try{this.logger?.warn?.("clearSavedTransformedFiles requires custom storage implementation to find and delete transformed files")}catch(e){this.logger?.error?.(`Failed to clear saved transformed files: ${e}`)}}async clearSavedTransformedFilesForFile(e){if(this.config.saveTransformedFiles)try{this.logger?.warn?.("clearSavedTransformedFilesForFile requires custom storage implementation")}catch(t){this.logger?.error?.(`Failed to clear saved transformed files for ${e}: ${t}`)}}getCacheStats(){const e={audio:this.audioTransformer?.getCacheStats(),image:this.imageTransformer?.getCacheStats(),video:this.videoTransformer?.getCacheStats()};return e.image===void 0&&delete e.image,e.video===void 0&&delete e.video,e.audio===void 0&&delete e.audio,e}validateQueryParameters(e,t){switch(t){case"audio":{this.validateAudioQueryParameters(e);break}case"image":{this.validateImageQueryParameters(e);break}case"video":{this.validateVideoQueryParameters(e);break}}}validateImageQueryParameters(e){const t=new Set(["alphaQuality","angle","background","bandbool","blur","boolean","brightness","channel","clahe","colourspace","compressionLevel","convolve","cropHeight","cropWidth","delay","dilate","effort","erode","extractChannel","fastShrinkOnLoad","fit","flatten","flip","flop","format","frameRate","gamma","grayscale","greyscale","height","hue","joinChannel","kernel","left","lightness","linear","loop","maxSlope","median","modulate","negate","normalise","normalize","position","quality","recombine","saturation","sharpen","threshold","tint","top","unflatten","width","withoutEnlargement","withoutReduction"]),a=new Set(["bitrate","codec","frameRate","keyFrameInterval","numberOfChannels","sampleRate"]),r=[];for(const i of a)e[i]!==void 0&&r.push(i);if(r.length>0){const i=[...r].toSorted();throw new s(`Invalid query parameters for image transformation: ${i.join(", ")}. Images support: ${[...t].toSorted().join(", ")}. Video/audio parameters (${i.join(", ")}) are not supported for images.`,"INVALID_PARAMS_FOR_IMAGE","image",i,[...t].toSorted())}if(e.fit&&!["contain","cover","fill","inside","outside"].includes(e.fit))throw new s(`Invalid fit value: "${e.fit}". Supported values: "cover", "contain", "fill", "inside", "outside"`,"INVALID_FIT_VALUE","image",["fit"],["cover","contain","fill","inside","outside"]);if(e.format&&!["avif","gif","jpeg","png","tiff","webp"].includes(e.format))throw new s(`Invalid format for image: "${e.format}". Supported formats: jpeg, png, webp, avif, tiff, gif`,"INVALID_FORMAT","image",["format"],["jpeg","png","webp","avif","tiff","gif"]);const o=["left","top","cropWidth","cropHeight"],n=o.filter(i=>e[i]!==void 0);if(n.length>0&&n.length!==o.length)throw new s(`Incomplete crop parameters: ${n.join(", ")}. All crop parameters must be provided: left, top, cropWidth, cropHeight`,"INCOMPLETE_CROP_PARAMS","image",n,o)}validateVideoQueryParameters(e){const t=new Set(["angle","background","bitrate","codec","cropHeight","cropWidth","fit","format","frameRate","height","keyFrameInterval","left","position","quality","top","width","withoutEnlargement","withoutReduction"]),a=new Set(["numberOfChannels","sampleRate"]),r=[];for(const i of a)e[i]!==void 0&&r.push(i);if(r.length>0){const i=[...r].toSorted();throw new s(`Invalid query parameters for video transformation: ${i.join(", ")}. Videos support: ${[...t].toSorted().join(", ")}. Audio-only parameters (${i.join(", ")}) are not supported for videos.`,"INVALID_PARAMS_FOR_VIDEO","video",i,[...t].toSorted())}if(e.fit&&!["contain","cover","fill","inside","outside"].includes(e.fit))throw new s(`Invalid fit value: "${e.fit}". Supported values: "cover", "contain", "fill", "inside", "outside"`,"INVALID_FIT_VALUE","video",["fit"],["cover","contain","fill","inside","outside"]);if(e.codec&&!["av1","avc","hevc","vp8","vp9"].includes(e.codec))throw new s(`Invalid codec for video: "${e.codec}". Supported codecs: avc, hevc, vp8, vp9, av1`,"INVALID_VIDEO_CODEC","video",["codec"],["avc","hevc","vp8","vp9","av1"]);if(e.format&&!["mkv","mp4","ogg","webm"].includes(e.format))throw new s(`Invalid format for video: "${e.format}". Supported formats: mp4, webm, mkv, ogg`,"INVALID_VIDEO_FORMAT","video",["format"],["mp4","webm","mkv","ogg"]);const o=["left","top","cropWidth","cropHeight"],n=o.filter(i=>e[i]!==void 0);if(n.length>0&&n.length!==o.length)throw new s(`Incomplete crop parameters: ${n.join(", ")}. All crop parameters must be provided: left, top, cropWidth, cropHeight`,"INCOMPLETE_CROP_PARAMS","video",n,o);if(e.width!==void 0&&(typeof e.width!="number"||e.width<=0))throw new s(`Invalid width: ${e.width}. Must be a positive number.`,"INVALID_WIDTH","video",["width"],[]);if(e.height!==void 0&&(typeof e.height!="number"||e.height<=0))throw new s(`Invalid height: ${e.height}. Must be a positive number.`,"INVALID_HEIGHT","video",["height"],[]);if(e.bitrate!==void 0&&(typeof e.bitrate!="number"||e.bitrate<=0))throw new s(`Invalid bitrate: ${e.bitrate}. Must be a positive number.`,"INVALID_BITRATE","video",["bitrate"],[]);if(e.frameRate!==void 0&&(typeof e.frameRate!="number"||e.frameRate<=0))throw new s(`Invalid frameRate: ${e.frameRate}. Must be a positive number.`,"INVALID_FRAME_RATE","video",["frameRate"],[]);if(e.keyFrameInterval!==void 0&&(typeof e.keyFrameInterval!="number"||e.keyFrameInterval<=0))throw new s(`Invalid keyFrameInterval: ${e.keyFrameInterval}. Must be a positive number.`,"INVALID_KEY_FRAME_INTERVAL","video",["keyFrameInterval"],[])}generateTransformedFileId(e,t,a){const r=Object.keys(t).filter(i=>t[i]!==void 0).toSorted().map(i=>`${i}:${t[i]}`).join("|"),o=`${e}|${a}|${r}`,n=l("sha256").update(o).digest("hex").slice(0,32);return`${e}_transformed_${n}`}hasTransformations(e){return this.hasImageTransformations(e)||this.hasVideoTransformations(e)||this.hasAudioTransformations(e)}createMediaTransformResult(e,t,a){const r={buffer:e.content,format:this.getFormatFromContentType(e.contentType||""),mediaType:t,originalFile:a,size:e.content.length};switch(t){case"audio":return{...r,bitrate:e.bitrate,duration:e.duration,mediaType:"audio",numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate};case"image":return{...r,height:e.height,mediaType:"image",width:e.width};case"video":return{...r,bitrate:e.bitrate,duration:e.duration,height:e.height,mediaType:"video",width:e.width};default:return r}}getFormatFromContentType(e){return e?d.getExtension(e)||"application/octet-stream":""}async saveTransformedFile(e,t,a,r){try{const o=this.generateTransformedFileId(t,a,r),n={format:e.format,mediaType:r,originalFileId:t,size:e.size,transformation:a,transformedAt:new Date().toISOString()};r==="image"&&e.width&&e.height?(n.width=e.width,n.height=e.height):r==="video"&&e.width&&e.height?(n.width=e.width,n.height=e.height,n.duration=e.duration,n.bitrate=e.bitrate):r==="audio"&&(n.duration=e.duration,n.numberOfChannels=e.numberOfChannels,n.sampleRate=e.sampleRate,n.bitrate=e.bitrate);const i=await this.storage.create({contentType:d.getType(e.format)??void 0,id:o,metadata:n,originalName:`${o}.${e.format}`,size:e.size});await this.storage.write({body:f.from(e.buffer),contentLength:e.size,id:i.id,start:0}),this.logger?.debug?.(`Saved transformed file: ${o}`)}catch(o){this.logger?.error?.(`Failed to save transformed file: ${o}`)}}validateAudioQueryParameters(e){const t=new Set(["bitrate","codec","format","numberOfChannels","quality","sampleRate"]),a=new Set(["angle","background","cropHeight","cropWidth","fit","frameRate","height","keyFrameInterval","left","position","top","width","withoutEnlargement","withoutReduction"]),r=[];for(const o of a)e[o]!==void 0&&r.push(o);if(r.length>0){const o=[...r].toSorted();throw new s(`Invalid query parameters for audio transformation: ${o.join(", ")}. Audio supports: ${[...t].toSorted().join(", ")}. Video-only parameters (${o.join(", ")}) are not supported for audio.`,"INVALID_PARAMS_FOR_AUDIO","audio",o,[...t].toSorted())}if(e.codec&&!["aac","flac","mp3","opus","vorbis"].includes(e.codec))throw new s(`Invalid codec for audio: "${e.codec}". Supported codecs: aac, opus, mp3, vorbis, flac`,"INVALID_AUDIO_CODEC","audio",["codec"],["aac","opus","mp3","vorbis","flac"]);if(e.format&&!["aac","flac","mp3","ogg","wav"].includes(e.format))throw new s(`Invalid format for audio: "${e.format}". Supported formats: mp3, wav, ogg, aac, flac`,"INVALID_AUDIO_FORMAT","audio",["format"],["mp3","wav","ogg","aac","flac"]);if(e.bitrate!==void 0&&(typeof e.bitrate!="number"||e.bitrate<=0))throw new s(`Invalid bitrate: ${e.bitrate}. Must be a positive number.`,"INVALID_BITRATE","audio",["bitrate"],[]);if(e.numberOfChannels!==void 0&&(typeof e.numberOfChannels!="number"||e.numberOfChannels<=0||e.numberOfChannels>8))throw new s(`Invalid numberOfChannels: ${e.numberOfChannels}. Must be a number between 1 and 8.`,"INVALID_CHANNEL_COUNT","audio",["numberOfChannels"],["1","2","3","4","5","6","7","8"]);if(e.sampleRate!==void 0){const o=[8e3,11025,16e3,22050,32e3,44100,48e3,88200,96e3,192e3];if(typeof e.sampleRate!="number"||!o.includes(e.sampleRate))throw new s(`Invalid sampleRate: ${e.sampleRate}. Supported sample rates: ${o.join(", ")}`,"INVALID_SAMPLE_RATE","audio",["sampleRate"],o.map(String))}}async handleImageTransformation(e,t){const a=[];this.hasImageTransformations(t)&&((t.width||t.height||t.fit)&&a.push({options:{fit:t.fit,height:t.height,position:t.position,width:t.width,withoutEnlargement:t.withoutEnlargement,withoutReduction:t.withoutReduction},type:"resize"}),t.left!==void 0&&t.top!==void 0&&t.cropWidth&&t.cropHeight&&a.push({options:{height:t.cropHeight,left:t.left,top:t.top,width:t.cropWidth},type:"crop"}),t.angle&&a.push({options:{angle:t.angle,background:t.background},type:"rotate"}),t.format?a.push({options:{format:t.format,quality:t.quality},type:"format"}):t.quality&&a.push({options:{quality:t.quality},type:"quality"}));const r=a.length>0?await this.imageTransformer.transform(e,a):await this.imageTransformer.transform(e,[]);return this.convertImageResult(r)}async handleVideoTransformation(e,t){const a=[];this.hasVideoTransformations(t)&&((t.width||t.height||t.fit)&&a.push({options:{fit:t.fit,height:t.height,position:t.position,width:t.width,withoutEnlargement:t.withoutEnlargement,withoutReduction:t.withoutReduction},type:"resize"}),t.left!==void 0&&t.top!==void 0&&t.cropWidth&&t.cropHeight&&a.push({options:{height:Number(t.cropHeight),left:t.left,top:t.top,width:t.cropWidth},type:"crop"}),t.angle&&a.push({options:{angle:t.angle,background:t.background},type:"rotate"}),(t.codec||t.bitrate)&&a.push({options:{bitrate:t.bitrate||t.quality,codec:t.codec,frameRate:t.frameRate,keyFrameInterval:t.keyFrameInterval},type:"codec"}),t.format&&a.push({options:{format:t.format},type:"format"}));const r=a.length>0?await this.videoTransformer.transform(e,a):await this.videoTransformer.transform(e,[]);return this.convertVideoResult(r)}async handleAudioTransformation(e,t){const a=[];this.hasAudioTransformations(t)&&(t.sampleRate&&a.push({options:{sampleRate:t.sampleRate},type:"resample"}),t.numberOfChannels&&a.push({options:{numberOfChannels:t.numberOfChannels},type:"channels"}),(t.codec||t.bitrate)&&a.push({options:{bitrate:t.bitrate||t.quality,codec:t.codec},type:"codec"}),t.format&&a.push({options:{format:t.format},type:"format"}));const r=a.length>0?await this.audioTransformer.transform(e,a):await this.audioTransformer.transform(e,[]);return this.convertAudioResult(r)}parseQuery(e){if(typeof e=="string")return this.parseURLSearchParams(new URLSearchParams(e));if(e instanceof URLSearchParams)return this.parseURLSearchParams(e);const t=e;return e.left&&(t.left=Number.parseInt(e.left,10)),e.top&&(t.top=Number.parseInt(e.top,10)),e.cropWidth&&(t.cropWidth=Number.parseInt(e.cropWidth,10)),e.cropHeight&&(t.cropHeight=Number.parseInt(e.cropHeight,10)),e.angle&&(t.angle=Number.parseInt(e.angle,10)),e.quality&&(t.quality=Number.parseInt(e.quality,10)),e.width&&(t.width=Number.parseInt(e.width,10)),e.height&&(t.height=Number.parseInt(e.height,10)),e.bitrate&&(t.bitrate=Number.parseInt(e.bitrate,10)),e.frameRate&&(t.frameRate=Number.parseInt(e.frameRate,10)),e.keyFrameInterval&&(t.keyFrameInterval=Number.parseInt(e.keyFrameInterval,10)),e.numberOfChannels&&(t.numberOfChannels=Number.parseInt(e.numberOfChannels,10)),e.sampleRate&&(t.sampleRate=Number.parseInt(e.sampleRate,10)),t}parseBooleanParameter(e){if(e!==null)return e==="true"||e==="1"}parseURLSearchParams(e){const t={};if(e.has("format")&&(t.format=e.get("format")??void 0),e.has("quality")&&(t.quality=e.get("quality")?Number.parseInt(e.get("quality"),10):void 0),e.has("width")&&(t.width=e.get("width")?Number.parseInt(e.get("width"),10):void 0),e.has("height")&&(t.height=e.get("height")?Number.parseInt(e.get("height"),10):void 0),e.has("fit")){const a=e.get("fit");a&&["contain","cover","fill","inside","outside"].includes(a)&&(t.fit=a)}if(e.has("position")&&(t.position=e.get("position")??void 0),e.has("withoutEnlargement")){const a=e.get("withoutEnlargement");t.withoutEnlargement=a==="true"?!0:void 0}if(e.has("withoutReduction")){const a=e.get("withoutReduction");t.withoutReduction=a==="true"?!0:void 0}if(e.has("left")&&(t.left=e.get("left")?Number.parseInt(e.get("left"),10):void 0),e.has("top")&&(t.top=e.get("top")?Number.parseInt(e.get("top"),10):void 0),e.has("cropWidth")&&(t.cropWidth=e.get("cropWidth")?Number.parseInt(e.get("cropWidth"),10):void 0),e.has("cropHeight")&&(t.cropHeight=e.get("cropHeight")?Number.parseInt(e.get("cropHeight"),10):void 0),e.has("angle")){const a=e.get("angle")?Number.parseInt(e.get("angle"),10):void 0;a!==void 0&&(t.angle=a)}if(e.has("background")&&(t.background=e.get("background")??void 0),e.has("blur")&&(t.blur=this.parseBooleanParameter(e.get("blur"))),e.has("sharpen")&&(t.sharpen=this.parseBooleanParameter(e.get("sharpen"))),e.has("median")&&(t.median=e.get("median")?Number.parseInt(e.get("median"),10):void 0),e.has("clahe")&&(t.clahe=this.parseBooleanParameter(e.get("clahe"))),e.has("threshold")&&(t.threshold=e.get("threshold")?Number.parseInt(e.get("threshold"),10):void 0),e.has("gamma")&&(t.gamma=this.parseBooleanParameter(e.get("gamma"))),e.has("negate")&&(t.negate=this.parseBooleanParameter(e.get("negate"))),(e.has("normalise")||e.has("normalize"))&&(t.normalise=this.parseBooleanParameter(e.get("normalise"))||this.parseBooleanParameter(e.get("normalize"))),e.has("flatten")&&(t.flatten=this.parseBooleanParameter(e.get("flatten"))),e.has("unflatten")&&(t.unflatten=this.parseBooleanParameter(e.get("unflatten"))),e.has("flip")&&(t.flip=this.parseBooleanParameter(e.get("flip"))),e.has("flop")&&(t.flop=this.parseBooleanParameter(e.get("flop"))),e.has("affine")&&(t.affine=this.parseBooleanParameter(e.get("affine"))),e.has("dilate")&&(t.dilate=this.parseBooleanParameter(e.get("dilate"))),e.has("erode")&&(t.erode=this.parseBooleanParameter(e.get("erode"))),e.has("pipelineColourspace")&&(t.pipelineColourspace=this.parseBooleanParameter(e.get("pipelineColourspace"))),e.has("toColourspace")&&(t.toColourspace=this.parseBooleanParameter(e.get("toColourspace"))),e.has("removeAlpha")&&(t.removeAlpha=this.parseBooleanParameter(e.get("removeAlpha"))),e.has("ensureAlpha")&&(t.ensureAlpha=this.parseBooleanParameter(e.get("ensureAlpha"))),(e.has("greyscale")||e.has("grayscale"))&&(t.greyscale=this.parseBooleanParameter(e.get("greyscale"))||this.parseBooleanParameter(e.get("grayscale"))),e.has("modulate")&&(t.modulate=this.parseBooleanParameter(e.get("modulate"))),e.has("tint")&&(t.tint=this.parseBooleanParameter(e.get("tint"))),e.has("brightness")&&(t.brightness=e.get("brightness")?Number.parseFloat(e.get("brightness")):void 0),e.has("saturation")&&(t.saturation=e.get("saturation")?Number.parseFloat(e.get("saturation")):void 0),e.has("hue")&&(t.hue=e.get("hue")?Number.parseInt(e.get("hue"),10):void 0),e.has("lightness")&&(t.lightness=e.get("lightness")?Number.parseInt(e.get("lightness"),10):void 0),e.has("kernel")&&(t.kernel=e.get("kernel")??void 0),e.has("fastShrinkOnLoad")&&(t.fastShrinkOnLoad=e.get("fastShrinkOnLoad")==="true"),e.has("codec")){const a=e.get("codec");a&&["avc","hevc","vp8","vp9","av1","aac","opus","mp3","vorbis","flac"].includes(a)&&(t.codec=a)}return e.has("bitrate")&&(t.bitrate=e.get("bitrate")?Number.parseInt(e.get("bitrate"),10):void 0),e.has("frameRate")&&(t.frameRate=e.get("frameRate")?Number.parseInt(e.get("frameRate"),10):void 0),e.has("keyFrameInterval")&&(t.keyFrameInterval=e.get("keyFrameInterval")?Number.parseInt(e.get("keyFrameInterval"),10):void 0),e.has("numberOfChannels")&&(t.numberOfChannels=e.get("numberOfChannels")?Number.parseInt(e.get("numberOfChannels"),10):void 0),e.has("sampleRate")&&(t.sampleRate=e.get("sampleRate")?Number.parseInt(e.get("sampleRate"),10):void 0),t}detectMediaType(e){if(!e)throw new Error("Cannot detect media type: no content type provided");if(!u(e))throw new Error(`Unknown or invalid content type: ${e}`);if(e.startsWith("image/"))return"image";if(e.startsWith("video/"))return"video";if(e.startsWith("audio/"))return"audio";throw new Error(`Unsupported media type for content type: ${e}`)}hasImageTransformations(e){return!!(e.width||e.height||e.fit||e.position||e.withoutEnlargement||e.withoutReduction||e.left!==void 0||e.top!==void 0||e.cropWidth||e.cropHeight||e.angle!==void 0||e.background||e.blur||e.sharpen||e.median||e.clahe||e.threshold!==void 0||e.gamma||e.negate||e.normalise||e.flatten||e.unflatten||e.flip||e.flop||e.greyscale||e.modulate||e.tint||e.brightness!==void 0||e.saturation!==void 0||e.hue!==void 0||e.lightness!==void 0||e.kernel||e.fastShrinkOnLoad||e.affine||e.dilate||e.erode||e.pipelineColourspace||e.toColourspace||e.removeAlpha||e.ensureAlpha||e.format||e.quality)}hasVideoTransformations(e){return!!(e.width||e.height||e.fit||e.position||e.withoutEnlargement||e.withoutReduction||e.left!==void 0||e.top!==void 0||e.cropWidth||e.cropHeight||e.angle||e.background||e.codec||e.bitrate||e.frameRate||e.keyFrameInterval||e.format||e.quality)}hasAudioTransformations(e){return!!(e.sampleRate||e.numberOfChannels||e.codec||e.bitrate||e.format||e.quality)}convertImageResult(e){return{buffer:e.buffer,format:e.format,height:e.height,mediaType:"image",originalFile:e.originalFile,size:e.size,width:e.width}}convertVideoResult(e){return{bitrate:e.bitrate,buffer:e.buffer,duration:e.duration,format:e.format,height:e.height,mediaType:"video",originalFile:e.originalFile,size:e.size,width:e.width}}convertAudioResult(e){return{bitrate:e.bitrate,buffer:e.buffer,duration:e.duration,format:e.format,mediaType:"audio",numberOfChannels:e.numberOfChannels,originalFile:e.originalFile,sampleRate:e.sampleRate,size:e.size}}}export{T as default};
@@ -0,0 +1 @@
1
+ import s from"./MetaStorage-DPEUyWgN.js";class n extends s{store;constructor(t){super(t),this.store=t?.store??new Map}async save(t,e){return this.store.set(t,{...e}),{...e}}async get(t){const e=this.store.get(t);if(!e)throw new Error(`Meta not found for id: ${t}`);return{...e}}async delete(t){this.store.delete(t)}async touch(t,e){return this.save(t,e)}clear(){this.store.clear()}}export{n as default};
@@ -0,0 +1 @@
1
+ import{Readable as w}from"node:stream";import{F as p}from"./index-nZWCQrSe.js";import{throwErrorCode as f,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as c}from"./storage-Cyy73Y6r.js";import T from"./MemoryMetaStorage-Ksgh9pe7.js";import l from"./File-W8aOo15X.js";import{t as u}from"./get-file-status-y3wTtDQs.js";import{e as b}from"./has-content-50BsqrWw.js";import{t as A}from"./update-size-DuNuLyxj.js";class D extends c{static name="memory";checksumTypes=["md5"];supportsRange=!0;meta;store;constructor(e={}){if(super(e),this.store=new Map,this.meta=e.metaStorage??new T({...e.metaStorageConfig,logger:this.logger}),e.initial)for(const[s,t]of Object.entries(e.initial)){c.assertSafeId(s);const a=Buffer.from(t),r=new Date().toISOString(),n=p(a);this.store.set(s,{bytes:a,contentType:"application/octet-stream",createdAt:r,eTag:n,metadata:{},modifiedAt:r});const i=new l({contentType:"application/octet-stream",id:s,metadata:{name:s,size:a.length},originalName:s,size:a.length});i.name=s,i.bytesWritten=a.length,i.ETag=n,i.createdAt=r,i.modifiedAt=r,i.status=u(i),this.meta.save(s,i).catch(()=>{})}}get raw(){return this.store}async create(e,s){return this.instrumentOperation("create",async()=>{const t=new l(e);return t.name=this.namingFunction(t),c.assertSafeId(t.name),await this.validate(t),t.bytesWritten=0,t.status=u(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,s){return this.instrumentOperation("write",async()=>{const t=await this.getMeta(e.id);if(!b(e))return t;const{body:a,start:r}=e,n=[];for await(const o of a)Buffer.isBuffer(o)?n.push(o):typeof o=="string"?n.push(Buffer.from(o)):ArrayBuffer.isView(o)?n.push(Buffer.from(o.buffer,o.byteOffset,o.byteLength)):n.push(Buffer.from(o));const i=Buffer.concat(n),m=this.store.get(t.name)?.bytes,d=r===0||!m?i:Buffer.concat([m.subarray(0,r),i]),y=new Date().toISOString(),g={bytes:d,contentType:t.contentType,createdAt:this.store.get(t.name)?.createdAt??y,eTag:p(d),metadata:{...t.metadata},modifiedAt:y};return this.store.set(t.name,g),t.bytesWritten=d.length,t.ETag=g.eTag,t.modifiedAt=g.modifiedAt,A(t,d.length),t.status=u(t),await this.saveMeta(t),t.status==="completed"&&await this.onComplete(t,{}),t})}async get({id:e},s){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);if(i>m||i>=a.bytes.length)return f(h.BAD_REQUEST,`Invalid range ${i}-${n.end??""}`);r=a.bytes.subarray(i,m+1)}return{content:r,contentType:a.contentType,ETag:a.eTag,expiredAt:t.expiredAt,id:e,metadata:{...a.metadata},modifiedAt:a.modifiedAt,name:t.name,originalName:t.originalName,size:r.length}})}async getStream({id:e},s){return this.instrumentOperation("getStream",async()=>{const t=await this.checkIfExpired(await this.meta.get(e)),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);let r=a.bytes;const n=s?.range;if(n){const i=Math.max(0,n.start),m=n.end===void 0?a.bytes.length-1:Math.min(a.bytes.length-1,n.end);r=a.bytes.subarray(i,m+1)}return{headers:{"Content-Length":String(r.length),"Content-Type":a.contentType,ETag:a.eTag,"Last-Modified":a.modifiedAt},size:r.length,stream:w.from(r)}})}async exists({id:e}){return this.instrumentOperation("exists",async()=>{try{const s=await this.meta.get(e);return this.store.has(s.name)}catch{return!1}})}async delete({id:e}){return this.instrumentOperation("delete",async()=>{const s=await this.getMeta(e);this.store.delete(s.name),await this.deleteMeta(e);const t={...s,status:"deleted"};return await this.onDelete(t),t})}async copy(e,s){return this.instrumentOperation("copy",async()=>{c.assertSafeId(e),c.assertSafeId(s);const t=await this.getMeta(e),a=this.store.get(t.name);if(!a)return f(h.FILE_NOT_FOUND);const r=new Date().toISOString();this.store.set(s,{...a,bytes:Buffer.from(a.bytes),metadata:{...a.metadata},modifiedAt:r});const n={...t,ETag:a.eTag,id:s,modifiedAt:r,name:s};return await this.saveMeta(n),n})}async move(e,s){return this.instrumentOperation("move",async()=>{if(e===s)return this.getMeta(e);const t=await this.copy(e,s);return await this.delete({id:e}),t})}async list(){return this.instrumentOperation("list",async()=>{const e=[];for(const[s,t]of this.store)e.push({contentType:t.contentType,createdAt:t.createdAt,ETag:t.eTag,id:s,metadata:{...t.metadata},modifiedAt:t.modifiedAt,name:s,size:t.bytes.length});return e})}async getReadUrl(e){return c.assertSafeId(e),`memory://${e}`}async getUploadUrl(e){return c.assertSafeId(e),`memory://${e}`}}export{D as default};
@@ -0,0 +1 @@
1
+ class i{prefix="";suffix="";logger;constructor(e){this.prefix=e?.prefix??"",this.suffix=e?.suffix??".META",this.logger=e?.logger}async save(e,t){return t}async delete(e){throw new Error("Not implemented")}async get(e){throw new Error("Not implemented")}async touch(e,t){throw new Error("Not implemented")}getMetaName(e){return this.prefix+e+this.suffix}getIdFromMetaName(e){return e.slice(this.prefix.length,-this.suffix.length)}}export{i as default};
@@ -0,0 +1 @@
1
+ const l=" ".codePointAt(0)??32,f=",".codePointAt(0)??44,p=/^[\d+/A-Z]*={0,2}$/i,u=e=>{if(typeof e!="string")return!1;const t=Number.parseFloat(e);return!Number.isNaN(t)&&Number.isFinite(t)};class g{psize;pname;pfiletype;ptype;pmimeType;pcontentType;ptitle;pfilename;poriginalName;plastModified}const c=e=>{if(e.length===0)return!1;for(let t=0;t<e.length;t+=1){const r=e.codePointAt(t);if(r>127||r===l||r===f)return!1}return!0},d=e=>e.length%4!==0?!1:p.test(e),m=e=>Object.entries(e).map(([t,r])=>{if(r==null)return t;const n=typeof r=="object"?JSON.stringify(r):String(r),a=Buffer.from(n,"utf8").toString("base64");return`${t} ${a}`}).join(","),h=e=>{const t={};if(!e||e.trim().length===0)throw new Error("Metadata string is not valid");for(const r of e.split(",")){const n=r.split(" "),[a,s]=n;if((n.length===1||n.length===2)&&c(a)&&(n.length===1||d(s))&&!(a in t)){let i="";n.length===1?i=void 0:s&&(i=Buffer.from(s,"base64").toString("utf8"));let o=i;if(i!==void 0)try{o=JSON.parse(i)}catch{i==="true"?o=!0:i==="false"?o=!1:u(i)&&(o=Number(i))}t[a]=o}else throw new Error("Metadata string is not valid")}return t};export{g as Metadata,h as parseMetadata,m as stringifyMetadata,c as validateKey,d as validateValue};
@@ -0,0 +1 @@
1
+ import{Readable as s}from"node:stream";import{parseMultipartRequest as n,MaxFileSizeExceededError as d,MultipartParseError as l}from"@remix-run/multipart-parser/node";import{n as i}from"./headers-BAiAKekR.js";import{g as m}from"./base-handler-core-EeV8gZck.js";import{b as f}from"./storage-Cyy73Y6r.js";import{T as u}from"./base-handler-node-BjpW8pGi.js";import{p as h}from"./multipart-base-BOzY19lb.js";const c=/^multipart\/.+|application\/x-www-form-urlencoded$/i;class b extends u{static methods=["delete","download","get","options","post"];multipartBase;maxFileSize;maxHeaderSize;constructor(t){super(t),this.maxFileSize=t.maxFileSize??Math.min(this.storage.maxUploadSize,1024*1024*1024),this.maxHeaderSize=t.maxHeaderSize??64*1024;const e=this;this.multipartBase=new class extends h{get storage(){return e.storage}get maxFileSize(){return e.maxFileSize}get maxHeaderSize(){return e.maxHeaderSize}buildFileUrl(r,a){return e.buildFileUrl({url:r},a)}createStreamFromBytes(r){return r instanceof Uint8Array||Buffer.isBuffer(r)?s.from(Buffer.from(r)):typeof r=="number"?s.from(Buffer.alloc(0)):s.from(Buffer.from(String(r)))}createEmptyStream(){return s.from(new Uint8Array(0))}}}async post(t){if(!c.test(t.headers["content-type"]?.split(";")[0]??""))throw i(400,"Invalid content-type");try{const e=[];for await(const o of n(t,{maxFileSize:this.maxFileSize,maxHeaderSize:this.maxHeaderSize}))e.push(o);const r=e.find(o=>o.isFile);if(!r)throw i(400,"No file found in multipart request");const a=t.originalUrl||t.url||"";return this.multipartBase.handlePost(r,e,a)}catch(e){throw e instanceof d?i(413,"File size limit exceeded"):e instanceof l?i(400,"Invalid multipart request"):e instanceof f&&e.statusCode?i(e.statusCode,e.message||e.body||"Validation failed"):e}}async delete(t){try{const e=m(t);return this.multipartBase.handleDelete(e)}catch(e){throw this.checkForUndefinedIdOrPath(e),e.code==="ENOENT"?i(404,"File not found"):e}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}}export{b as default};
@@ -0,0 +1 @@
1
+ import{Readable as a}from"node:stream";import{parseMultipartRequest as m,MaxFileSizeExceededError as h,MultipartParseError as c}from"@remix-run/multipart-parser";import{n as i}from"./headers-BAiAKekR.js";import{b as u,B as f}from"./storage-Cyy73Y6r.js";import{C as p}from"./base-handler-fetch-CHzsgb7C.js";import{p as g}from"./multipart-base-BOzY19lb.js";const x=/^multipart\/.+|application\/x-www-form-urlencoded$/i,S=d=>{let t;try{const r=new URL(d).pathname.split("/").filter(Boolean);t=r[r.length-1]||void 0}catch{return}if(t){try{f.assertSafeId(t)}catch{throw i(400,`Invalid file id: "${t}"`)}return t}};class n extends p{static methods=["delete","download","get","options","post"];multipartBase;maxFileSize;maxHeaderSize;constructor(t){super(t),this.maxFileSize=t.maxFileSize??Math.min(this.storage.maxUploadSize,1024*1024*1024),this.maxHeaderSize=t.maxHeaderSize??64*1024;const r=this;this.multipartBase=new class extends g{get storage(){return r.storage}get maxFileSize(){return r.maxFileSize}get maxHeaderSize(){return r.maxHeaderSize}buildFileUrl(e,s){return r.buildFileUrl({url:e},s)}createStreamFromBytes(e){return e instanceof Uint8Array?a.from(Buffer.from(e)):e instanceof ArrayBuffer?a.from(Buffer.from(e)):a.from(new Uint8Array(0))}createEmptyStream(){return a.from(new Uint8Array(0))}}}async post(t){const r=t.headers.get("content-type")||"";if(!x.test(r.split(";")[0]||""))throw i(400,"Invalid content-type");try{const e=[];for await(const o of m(t,{maxFileSize:this.maxFileSize,maxHeaderSize:this.maxHeaderSize}))e.push(o);const s=e.find(o=>o.isFile);if(!s)throw i(400,"No file found in multipart request");const l=t.url;return this.multipartBase.handlePost(s,e,l)}catch(e){throw e instanceof h?i(413,"File size limit exceeded"):e instanceof c?i(400,"Invalid multipart request"):e instanceof u&&e.statusCode?i(e.statusCode,e.message||e.body||"Validation failed"):e}}async delete(t){const r=S(t.url);if(!r)throw i(404,"File not found");try{return this.multipartBase.handleDelete(r)}catch(e){throw e.code==="ENOENT"?i(404,"File not found"):e}}async options(t){return{headers:{"Access-Control-Allow-Methods":(this.constructor.methods||n.methods).map(r=>r.toUpperCase()).join(", ")},statusCode:204}}async get(t){throw i(500,"GET requests should be handled via fetch() method")}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}}export{n as default};
@@ -0,0 +1 @@
1
+ import e from"./File-W8aOo15X.js";class r extends e{url;pathname}export{r as default};
@@ -0,0 +1 @@
1
+ import{y as s}from"./local-meta-storage-C2T92TYb.js";class o extends s{constructor(r){super(r)}}export{o as default};
@@ -0,0 +1 @@
1
+ import{getStore as u}from"@netlify/blobs";import{a as p}from"./detect-file-type-BA7UBLKA.js";import{B as y,c as h,e as d}from"./storage-Cyy73Y6r.js";import{y as w}from"./local-meta-storage-C2T92TYb.js";import f from"./NetlifyBlobFile-DoFhkzaH.js";import{t as m}from"./get-file-status-y3wTtDQs.js";import{t as g}from"./update-size-DuNuLyxj.js";import{i as b}from"./part-match-D-9dGX42.js";import{e as O}from"./has-content-50BsqrWw.js";class C extends y{static name="netlify-blob";checksumTypes=["md5"];get raw(){return this.store}meta;storeName;siteID;token;store;resolvedRetryConfig;constructor(e){super(e),this.storeName=e.storeName||"default",this.siteID=e.siteID||process.env.NETLIFY_SITE_ID,this.token=e.token||process.env.NETLIFY_TOKEN,this.store=u({name:this.storeName,...this.siteID&&{siteID:this.siteID},...this.token&&{token:this.token}});const n={backoffMultiplier:2,initialDelay:1e3,maxDelay:3e4,maxRetries:3,retryableStatusCodes:[408,429,500,502,503,504],shouldRetry:r=>{if(r instanceof Error){const i=r.code;if(i==="ECONNRESET"||i==="ETIMEDOUT"||i==="ENOTFOUND"||i==="ECONNREFUSED")return!0}const s=r;return!!(s.status&&[408,429,500,502,503,504].includes(s.status))},...e.retryConfig};this.resolvedRetryConfig=n;const{metaStorage:t,metaStorageConfig:a}=e;this.meta=t||new w(a),this.isReady=!0}getRetryConfig(){return this.resolvedRetryConfig}async create(e,n){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const r=typeof e.ttl=="string"?h(e.ttl):e.ttl;t.expiredAt=r===void 0?void 0:Date.now()+r}const a=new f(t);a.name=this.namingFunction(a),await this.validate(a);try{const r=await this.getMeta(a.id);if(r.bytesWritten>=0)return r}catch{}return a.bytesWritten=0,a.status=m(a),await this.saveMeta(a),await this.onCreate(a),a})}async write(e,n){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&g(t,e.size),!b(e,t))throw new Error("File part does not match");const a=await this.lock(e.id);try{if(O(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=[],s=e.body;for await(const o of s)r.push(Buffer.from(o));const i=Buffer.concat(r);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await p(i);o?.mime&&(t.contentType=o.mime)}catch{}await this.runOperation(n,()=>this.store.set(t.name,i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),{metadata:{...t.metadata,contentType:t.contentType}})),t.pathname=t.name,t.url=this.getBlobUrl(t.name),t.bytesWritten=i.length}return t.status=m(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,a)}})}async delete({id:e},n){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.pathname)throw new Error(`File ${e} does not have a valid pathname`);t.status="deleted";try{await this.runOperation(n,()=>this.store.delete(t.pathname))}catch(r){this.logger?.error("Failed to delete blob from Netlify Blob:",r);const s=this.normalizeError(r instanceof Error?r:new Error(String(r)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},n){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);return!t.pathname||t.pathname.length<=0?!1:await this.runOperation(n,()=>this.store.get(t.pathname,{type:"blob"}))!=null}catch{return!1}})}async get({id:e},n){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.pathname||t.pathname.length<=0)throw new Error("File pathname not found");const a=await this.runOperation(n,()=>this.store.get(t.pathname,{type:"blob"}));if(!a)throw new Error("File not found in Netlify Blob");let r;if(typeof a=="string")r=Buffer.from(a,"utf8").buffer;else if(a&&typeof a=="object"&&"arrayBuffer"in a&&typeof a.arrayBuffer=="function")r=await this.runOperation(n,()=>a.arrayBuffer());else throw new Error("Invalid blob type returned from Netlify Blob");const s=Buffer.from(r);let i=null;try{i=await this.store.getMetadata?.(t.pathname)??null}catch{}return{content:s,contentType:i?.contentType||t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:{...t.metadata,...i?.metadata},modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||s.length}})}async copy(e,n,t){return this.instrumentOperation("copy",async()=>{const a=await this.getMeta(e);if(!a.pathname)throw new Error("Source file pathname not found");const r=await this.runOperation(t,()=>this.store.get(a.pathname,{type:"blob"}));if(!r)throw new Error("Source file not found in Netlify Blob");let s=null;try{const l=this.store;l.getMetadata&&a.pathname&&(s=await l.getMetadata(a.pathname))}catch{}let i;if(typeof r=="string")i=Buffer.from(r,"utf8").buffer;else if(r&&typeof r=="object"&&"arrayBuffer"in r){const l=r;i=await this.runOperation(t,()=>l.arrayBuffer())}else throw new Error("Invalid blob type returned from Netlify Blob");const o=Buffer.from(i);await this.runOperation(t,()=>this.store.set(n,o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength),{metadata:s||{contentType:a.contentType,...a.metadata}}));const c={...a,id:n,name:n,pathname:n,url:this.getBlobUrl(n)};return await this.saveMeta(c),c})}async move(e,n,t){return this.instrumentOperation("move",async()=>{const a=await this.copy(e,n,t);return await this.delete({id:e},t),a})}async update({id:e},n,t){return this.instrumentOperation("update",async()=>{const a=await this.getMeta(e),r={...n};if("ttl"in r&&r.ttl!==void 0){const i=r.ttl,o=typeof i=="string"?h(i):i;o!==void 0&&(r.expiredAt=Date.now()+o),delete r.ttl}d(a,r),await this.saveMeta(a);const s={...a,status:"updated"};return await this.onUpdate(s),s})}async list(e=1e3,n){return this.instrumentOperation("list",async()=>{const t=await this.runOperation(n,()=>this.store.list()),a=[];for await(const r of t.blobs){let s=null;try{s=await this.store.getMetadata?.(r.key)??null}catch{}const i=new f({contentType:s?.contentType||"application/octet-stream",metadata:s?.metadata||{},originalName:r.key}),o=r;if(i.createdAt=o.createdAt?.toISOString(),i.id=r.key,i.modifiedAt=o.updatedAt?.toISOString(),i.name=r.key,i.pathname=r.key,i.size=o.size,i.url=this.getBlobUrl(r.key),a.push(i),a.length>=e)break}return a},{limit:e})}internalOnComplete=e=>this.deleteMeta(e.id);getBlobUrl(e){return`/api/blobs/${this.storeName}/${e}`}}export{C as default};
@@ -0,0 +1 @@
1
+ class i{increment(e,t,r){}timing(e,t,r){}gauge(e,t,r){}}export{i as default};
@@ -0,0 +1 @@
1
+ import e from"./File-W8aOo15X.js";let a=class extends e{driveItemId;eTag;webUrl};export{a as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-C2T92TYb.js";class o extends r{constructor(t){super(t)}}export{o as default};
@@ -0,0 +1 @@
1
+ import{ResponseType as g,Client as U,GraphError as b}from"@microsoft/microsoft-graph-client";import{wrapStorageError as p,ERRORS as m,throwErrorCode as E}from"./ERRORS-BIBxE2oR.js";import{c as D}from"./oauth-refresh-EdGzlcOZ.js";import{B as _}from"./storage-Cyy73Y6r.js";import u from"./OneDriveFile-CNNJYI43.js";import A from"./OneDriveMetaStorage-DqkgoE46.js";import{t as T}from"./get-file-status-y3wTtDQs.js";import{t as N}from"./update-size-DuNuLyxj.js";import{i as S}from"./part-match-D-9dGX42.js";import{e as L}from"./has-content-50BsqrWw.js";const P="https://graph.microsoft.com/.default",M=250*1024*1024,F=16*320*1024,B=1e3,d=o=>{let t=0,i=o.length;for(;t<i&&o[t]==="/";)t+=1;for(;i>t&&o[i-1]==="/";)i-=1;return t===0&&i===o.length?o:o.slice(t,i)},w=(o,t)=>{if(d(o).split("/").filter(Boolean).some(i=>i==="."||i===".."))throw new Error(`OneDrive storage: ${t} must not contain "." or ".." path segments.`)},y=o=>o.split("/").map(t=>encodeURIComponent(t)).join("/"),x=async o=>{const t=[];for await(const i of o)t.push(Buffer.from(i));return Buffer.concat(t)},I=o=>({getAccessToken:()=>Promise.resolve(o)}),$=o=>({getAccessToken:async()=>o()}),O=o=>D({buildBody:()=>new URLSearchParams({client_id:o.clientId,client_secret:o.clientSecret,grant_type:"client_credentials",scope:P}),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(o.tenantId)}/oauth2/v2.0/token`}),v=o=>D({buildBody:()=>new URLSearchParams({client_id:o.clientId,grant_type:"refresh_token",refresh_token:o.refreshToken,scope:P,...o.clientSecret&&{client_secret:o.clientSecret}}),provider:"OneDrive",tokenUrl:`https://login.microsoftonline.com/${encodeURIComponent(o.tenantId??"common")}/oauth2/v2.0/token`}),V=o=>({getAccessToken:()=>o.getAccessToken()}),C=o=>{if(o.client)return o.client;const t=o.accessToken!==void 0,i=o.clientCredentials!==void 0,e=o.oauth!==void 0;if([t,i,e].filter(Boolean).length>1)throw new Error("OneDrive storage: pass exactly one of `accessToken`, `clientCredentials`, or `oauth`.");let n;if(o.accessToken!==void 0?n=typeof o.accessToken=="function"?$(o.accessToken):I(o.accessToken):o.clientCredentials?n=O(o.clientCredentials):o.oauth&&(n=v({clientId:o.oauth.clientId,refreshToken:o.oauth.refreshToken,...o.oauth.clientSecret&&{clientSecret:o.oauth.clientSecret},...o.oauth.tenantId&&{tenantId:o.oauth.tenantId}})),!n){const a=process.env.ONEDRIVE_ACCESS_TOKEN;if(a)n=I(a);else{const r=process.env.ONEDRIVE_CLIENT_ID,s=process.env.ONEDRIVE_CLIENT_SECRET,c=process.env.ONEDRIVE_TENANT_ID,h=process.env.ONEDRIVE_REFRESH_TOKEN;h&&r?n=v({clientId:r,refreshToken:h,...s&&{clientSecret:s},...c&&{tenantId:c}}):r&&s&&c&&(n=O({clientId:r,clientSecret:s,tenantId:c}))}}if(!n)throw new Error("OneDrive storage: missing auth. Pass `client`, `accessToken`, `clientCredentials`, or `oauth`. Env fallbacks: ONEDRIVE_ACCESS_TOKEN; or ONEDRIVE_REFRESH_TOKEN + ONEDRIVE_CLIENT_ID (+ optional ONEDRIVE_CLIENT_SECRET, ONEDRIVE_TENANT_ID); or ONEDRIVE_CLIENT_ID + ONEDRIVE_CLIENT_SECRET + ONEDRIVE_TENANT_ID.");return U.initWithMiddleware({authProvider:V(n)})},z=o=>{if(o instanceof b)return o.statusCode===404||o.code==="itemNotFound";if(o&&typeof o=="object"){const t=o;return t.statusCode===404||t.status===404||t.code==="itemNotFound"}return!1};class Z extends _{static name="onedrive";checksumTypes=[];meta;basePath;client;copyTimeoutMs;publicByDefault;rootFolderPath;constructor(t){if(super(t),[t.driveId,t.siteId,t.userId].filter(i=>i!==void 0).length>1)throw new Error("OneDrive storage: pass at most one of `driveId`, `siteId`, or `userId`.");if(t.driveId)this.basePath=`/drives/${encodeURIComponent(t.driveId)}`;else if(t.siteId)this.basePath=`/sites/${encodeURIComponent(t.siteId)}/drive`;else if(t.userId)this.basePath=`/users/${encodeURIComponent(t.userId)}/drive`;else{if(t.clientCredentials)throw new Error("OneDrive storage: `clientCredentials` (app-only) auth requires `driveId`, `siteId`, or `userId`.");this.basePath="/me/drive"}w(t.rootFolderPath??"","rootFolderPath"),this.rootFolderPath=d(t.rootFolderPath??""),this.publicByDefault=t.publicByDefault??!1,this.copyTimeoutMs=t.copyTimeoutMs??6e4,this.client=C(t),this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,i){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),await this.validate(e);try{const n=await this.getMeta(e.id);if(n.bytesWritten>=0)return n}catch{}return e.bytesWritten=0,e.status=T(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,i){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&N(e,t.size),!S(t,e))throw new Error("File part does not match");const n=await this.lock(t.id);try{if(L(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=await x(t.body),r=e.name||e.id,s=a.byteLength<=M?await this.uploadSimple(r,a,e.contentType,i):await this.uploadSession(r,a,e.contentType,i);e.bytesWritten=a.length,e.size=a.length,e.driveItemId=s.id,e.webUrl=s.webUrl,e.eTag=s.eTag,e.ETag=s.eTag}return e.status=T(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,n)}})}async delete({id:t},i){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const n=e?.name??t;try{await this.runOperation(i,()=>this.client.api(this.itemApiPath(n)).delete())}catch(a){if(!z(a))throw a}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{id:t,name:t,status:"deleted"})})}async get({id:t},i){return this.instrumentOperation("get",async()=>{let e,n=t;try{e=await this.checkIfExpired(await this.getMeta(t)),n=e.name??t}catch{}const a=await this.runOperation(i,()=>this.client.api(this.itemApiPath(n)).get()),r=await this.runOperation(i,()=>this.client.api(this.itemActionPath(n,"content")).responseType(g.ARRAYBUFFER).get()),s=Buffer.from(r);return{content:s,contentType:e?.contentType??a.file?.mimeType??"application/octet-stream",ETag:e?.ETag??a.eTag,expiredAt:e?.expiredAt,id:t,metadata:e?.metadata??{},modifiedAt:e?.modifiedAt??a.lastModifiedDateTime,name:e?.name??a.name,originalName:e?.originalName??a.name,size:e?.size??a.size??s.length}})}async copy(t,i,e){return this.instrumentOperation("copy",async()=>{const n=this.parentReferencePath(i),a={name:R(i),parentReference:{path:n}},r=await this.runOperation(e,()=>this.client.api(this.itemActionPath(t,"copy")).responseType(g.RAW).post(a));if(r.status!==202){const f=await r.text().catch(()=>"");throw p(new Error(f||r.statusText),{adapter:"OneDrive",operation:"copy",status:r.status})}const s=r.headers.get("Location");if(!s)throw p(new Error("response missing Location monitor URL"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});const c=await this.pollCopyMonitor(s,e),h=new u({contentType:"application/octet-stream",metadata:{},originalName:i});return h.id=i,h.name=i,h.driveItemId=c,h})}async move(t,i,e){return this.instrumentOperation("move",async()=>{const n=this.parentReferencePath(i),a=R(i),r=await this.runOperation(e,()=>this.client.api(this.itemApiPath(t)).patch({name:a,parentReference:{path:n}})),s=new u({contentType:"application/octet-stream",metadata:{},originalName:i});s.id=i,s.name=i,s.driveItemId=r.id,s.webUrl=r.webUrl,s.eTag=r.eTag,s.ETag=r.eTag;try{await this.deleteMeta(t)}catch{}return s})}async list(t=1e3,i){return this.instrumentOperation("list",async()=>{const e=[];let n=`${this.folderListChildrenPath()}?$top=${Math.min(t,1e3)}`;for(;n&&e.length<t;){const a=await this.runOperation(i,()=>this.client.api(n).get());for(const r of a.value){if(!r.file)continue;const s=this.itemPathToKey(r);if(!s)continue;const c=new u({contentType:r.file.mimeType??"application/octet-stream",metadata:{},originalName:r.name});if(c.id=s,c.name=s,c.driveItemId=r.id,c.webUrl=r.webUrl,c.eTag=r.eTag,c.ETag=r.eTag,c.size=r.size??0,c.modifiedAt=r.lastModifiedDateTime,e.push(c),e.length>=t)break}n=a["@odata.nextLink"]??null}return e},{limit:t})}async getReadUrl(t,i){if(i?.responseContentDisposition||i?.responseContentType)return E(m.METHOD_NOT_ALLOWED,"OneDrive: `responseContentDisposition` / `responseContentType` are not supported — Graph download URLs have no overrides.");if(this.publicByDefault){const n=(await this.client.api(this.itemActionPath(t,"createLink")).post({scope:"anonymous",type:"view"})).link?.webUrl;if(!n)throw new Error("OneDrive: createLink response missing webUrl");return n}const e=(await this.client.api(this.itemApiPath(t)).select("@microsoft.graph.downloadUrl").get())["@microsoft.graph.downloadUrl"];if(!e)throw new Error("OneDrive: item has no `@microsoft.graph.downloadUrl` — it may be a folder or have no content.");return e}async getUploadUrl(t,i){if(i?.contentLength!==void 0)return E(m.BAD_REQUEST,"OneDrive: `contentLength` is not supported for upload URLs. A Graph upload session does not enforce a server-side content-length policy, so the cap would not bind; enforce size limits at your application gateway/proxy before issuing the session URL.");const e=await this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...i?.contentType&&{file:{mimeType:i.contentType}}}});if(!e.uploadUrl)throw p(new Error("createUploadSession response missing uploadUrl"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"getUploadUrl"});return e.uploadUrl}keyParts(t){w(t,"key");const i=d(t),e=[];return this.rootFolderPath&&e.push(this.rootFolderPath),i&&e.push(i),e}itemApiPath(t){const i=this.keyParts(t);return i.length===0?`${this.basePath}/root`:`${this.basePath}/root:/${y(i.join("/"))}`}itemActionPath(t,i){const e=this.keyParts(t);return e.length===0?`${this.basePath}/root/${i}`:`${this.basePath}/root:/${y(e.join("/"))}:/${i}`}folderListChildrenPath(){return this.itemActionPath("","children")}parentReferencePath(t){w(t,"key");const i=d(t),e=[];this.rootFolderPath&&e.push(this.rootFolderPath);const n=i.lastIndexOf("/");if(n!==-1){const a=i.slice(0,n);a&&e.push(a)}return e.length===0?"/drive/root:":`/drive/root:/${y(e.join("/"))}`}itemPathToKey(t){const i=t.parentReference?.path??"",e="/root:",n=i.indexOf(e);let a=n===-1?"":i.slice(n+e.length);a=d(decodeURIComponent(a));const r=this.rootFolderPath&&a.startsWith(this.rootFolderPath)?a.slice(this.rootFolderPath.length):a,s=d(r);return s?`${s}/${t.name}`:t.name}async uploadSimple(t,i,e,n){return await this.runOperation(n,()=>this.client.api(`${this.itemActionPath(t,"content")}?@microsoft.graph.conflictBehavior=replace`).header("Content-Type",e??"application/octet-stream").put(i))}async uploadSession(t,i,e,n){const a=await this.runOperation(n,()=>this.client.api(this.itemActionPath(t,"createUploadSession")).post({item:{"@microsoft.graph.conflictBehavior":"replace",...e&&{file:{mimeType:e}}}})),r=i.byteLength;let s=0,c;for(;s<r;){const h=Math.min(s+F,r),f=i.subarray(s,h),l=await this.runOperation(n,()=>fetch(a.uploadUrl,{body:new Uint8Array(f),headers:{"Content-Length":String(f.byteLength),"Content-Range":`bytes ${s}-${h-1}/${r}`},method:"PUT"}));if(l.status===200||l.status===201)c=await l.json();else if(l.status!==202){const k=await l.text().catch(()=>"");throw p(new Error(k||l.statusText),{adapter:"OneDrive",operation:"upload-session chunk",status:l.status})}s=h}if(!c)throw p(new Error("upload-session terminated without a final DriveItem response"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"write"});return c}async pollCopyMonitor(t,i){const e=Date.now()+this.copyTimeoutMs;for(;;){const n=await this.runOperation(i,()=>fetch(t));if(!n.ok)throw p(new Error(n.statusText),{adapter:"OneDrive",operation:"copy monitor",status:n.status});const a=await n.json();if(a.status==="completed")return a.resourceId;if(a.status==="failed")throw p(new Error(a.error?.message??"unknown error"),{adapter:"OneDrive",code:m.STORAGE_ERROR,operation:"copy"});if(Date.now()>=e)throw new Error(`OneDrive: copy timed out after ${this.copyTimeoutMs}ms (status: ${a.status??"unknown"})`);await new Promise(r=>{setTimeout(r,B)})}}internalOnComplete=t=>this.deleteMeta(t.id)}const R=o=>{const t=d(o),i=t.lastIndexOf("/");return i===-1?t:t.slice(i+1)},tt=o=>C(o);export{tt as buildGraphClient,Z as default};
@@ -0,0 +1 @@
1
+ import{metrics as i}from"@opentelemetry/api";class c{meter;counters=new Map;histograms=new Map;gauges=new Map;constructor(e){this.meter=e||i.getMeter("@visulima/storage","1.0.0")}increment(e,r=1,t){if(!this.counters.has(e)){const o={description:`Counter for ${e}`};this.counters.set(e,this.meter.createCounter(e,o))}const s=this.counters.get(e);if(!s)throw new Error(`Counter ${e} was not created`);s.add(r,t)}timing(e,r,t){if(!this.histograms.has(e)){const o={description:`Duration histogram for ${e}`,unit:"ms"};this.histograms.set(e,this.meter.createHistogram(e,o))}const s=this.histograms.get(e);if(!s)throw new Error(`Histogram ${e} was not created`);s.record(r,t)}gauge(e,r,t){if(!this.gauges.has(e)){const o={description:`Gauge for ${e}`};this.gauges.set(e,this.meter.createUpDownCounter(e,o))}const s=this.gauges.get(e);if(!s)throw new Error(`Gauge ${e} was not created`);s.add(r,t)}}export{c as default};
@@ -0,0 +1 @@
1
+ import t from"./File-W8aOo15X.js";class c extends t{bucket;path;publicUrl}export{c as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-C2T92TYb.js";class e extends r{constructor(o){super(o)}}export{e as default};
@@ -0,0 +1 @@
1
+ import g,{ClientResponseError as O}from"pocketbase";import{throwErrorCode as p,ERRORS as m}from"./ERRORS-BIBxE2oR.js";import{B as k}from"./storage-Cyy73Y6r.js";import u from"./PocketBaseFile-DpJpxl3e.js";import A from"./PocketBaseMetaStorage-CpvDRnSu.js";import{t as y}from"./get-file-status-y3wTtDQs.js";import{t as E}from"./update-size-DuNuLyxj.js";import{i as T}from"./part-match-D-9dGX42.js";import{e as B}from"./has-content-50BsqrWw.js";const N=async o=>{const t=[];for await(const a of o)t.push(Buffer.from(a));return Buffer.concat(t)},d=o=>(o instanceof O||!!o&&typeof o=="object")&&o.status===404,f=(o,t,a,e)=>{const i=o.files.getURL??o.files.getUrl;return i?i(t,a,e):p(m.METHOD_NOT_ALLOWED,"PocketBase: client has no files.getURL()")};class P extends k{static name="pocketbase";checksumTypes=[];meta;client;collectionName;defaultUrlExpiresIn;fileField;keyField;publicBaseUrl;ensureAuth;constructor(t){if(super(t),!t.collection)throw new Error("PocketBase storage: `collection` is required.");if(this.collectionName=t.collection,this.keyField=t.keyField??"key",this.fileField=t.fileField??"file",this.publicBaseUrl=t.publicBaseUrl,this.defaultUrlExpiresIn=t.defaultUrlExpiresIn??3600,t.client)this.client=t.client,this.ensureAuth=async()=>{};else{const a=t.url??process.env.POCKETBASE_URL;if(!a)throw new Error("PocketBase storage: `url` is required (or set POCKETBASE_URL).");const e=new g(a);this.client=e;const i=t.authToken??process.env.POCKETBASE_AUTH_TOKEN,n=t.adminEmail??process.env.POCKETBASE_ADMIN_EMAIL,s=t.adminPassword??process.env.POCKETBASE_ADMIN_PASSWORD;i?(e.authStore.save(i,null),this.ensureAuth=async()=>{}):n&&s?this.ensureAuth=async()=>{e.authStore.isValid||await e.collection("_superusers").authWithPassword(n,s)}:this.ensureAuth=async()=>{}}this.meta=t.metaStorage??new A(t.metaStorageConfig),this.isReady=!0}get raw(){return this.client}async create(t,a){return this.instrumentOperation("create",async()=>{const e=new u(t);e.name=this.namingFunction(e),e.bucket=this.collectionName,e.path=e.name,await this.validate(e);try{const i=await this.getMeta(e.id);if(i.bytesWritten>=0)return i}catch{}return e.bytesWritten=0,e.status=y(e),await this.saveMeta(e),await this.onCreate(e),e})}async write(t,a){return this.instrumentOperation("write",async()=>{let e;if("contentType"in t&&"metadata"in t&&!("body"in t)&&!("start"in t)?e=t:(e=await this.getMeta(t.id),await this.checkIfExpired(e)),e.status==="completed")return e;if(t.size!==void 0&&E(e,t.size),!T(t,e))throw new Error("File part does not match");const i=await this.lock(t.id);try{if(B(t)){if(this.isUnsupportedChecksum(t.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await N(t.body),s=e.path??e.name;await this.putRecord(s,n,e.contentType,a),e.bytesWritten=n.length,e.size=n.length,e.path=s}return e.status=y(e),e.status==="completed"&&await this.internalOnComplete(e),await this.saveMeta(e),e}finally{await this.unlock(t.id,i)}})}async delete({id:t},a){return this.instrumentOperation("delete",async()=>{let e;try{e=await this.getMeta(t)}catch{}const i=e?.path??e?.name??t;await this.ensureAuth();try{const n=await this.findRecord(i,a);await this.runOperation(a,()=>this.client.collection(this.collectionName).delete(n.id))}catch(n){if(!d(n))throw n}return e?(e.status="deleted",await this.deleteMeta(e.id),await this.onDelete(e),e):Object.assign(new u({contentType:"application/octet-stream",metadata:{},originalName:t}),{bucket:this.collectionName,id:t,name:t,path:i,status:"deleted"})})}async exists({id:t},a){return this.instrumentOperation("exists",async()=>{let e=t;try{e=(await this.getMeta(t)).path??t}catch{}await this.ensureAuth();try{return await this.findRecord(e,a),!0}catch(i){if(d(i))return!1;throw i}})}async get({id:t},a){return this.instrumentOperation("get",async()=>{let e=t,i;try{i=await this.checkIfExpired(await this.getMeta(t)),e=i.path??i.name??t}catch{}await this.ensureAuth();const n=await this.findRecord(e,a),s=String(n[this.fileField]??""),r=f(this.client,n,s),c=await this.runOperation(a,()=>fetch(r));if(!c.ok)return p(m.FILE_NOT_FOUND,`PocketBase: object not found at "${e}"`);const l=Buffer.from(await c.arrayBuffer());return{content:l,contentType:i?.contentType??c.headers.get("content-type")??"application/octet-stream",ETag:i?.ETag,expiredAt:i?.expiredAt,id:t,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt,name:i?.name??e,originalName:i?.originalName??e,size:i?.size??l.length}})}async copy(t,a,e){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(t))?.path??t;await this.ensureAuth();const n=await this.findRecord(i,e),s=String(n[this.fileField]??""),r=f(this.client,n,s),c=await this.runOperation(e,()=>fetch(r));if(!c.ok)return p(m.FILE_NOT_FOUND,`PocketBase: object not found at "${i}"`);const l=Buffer.from(await c.arrayBuffer()),w=c.headers.get("content-type")??"application/octet-stream";await this.putRecord(a,l,w,e);const h=new u({contentType:w,metadata:{},originalName:a});return h.id=a,h.name=a,h.path=a,h.bucket=this.collectionName,h.size=l.length,h})}async move(t,a,e){return this.instrumentOperation("move",async()=>{const i=await this.copy(t,a,e),n=(await this.getMetaSafe(t))?.path??t;await this.ensureAuth();try{const s=await this.findRecord(n,e);await this.runOperation(e,()=>this.client.collection(this.collectionName).delete(s.id))}catch(s){if(!d(s))throw s}try{await this.deleteMeta(t)}catch{}return i})}async list(t=1e3,a){return this.instrumentOperation("list",async()=>{await this.ensureAuth();const{items:e}=await this.runOperation(a,()=>this.client.collection(this.collectionName).getList(1,t));return(e??[]).map(i=>{const n=String(i[this.keyField]??i.id),s=String(i[this.fileField]??""),r=new u({contentType:"application/octet-stream",metadata:{},originalName:n});return r.id=n,r.name=n,r.path=n,r.bucket=this.collectionName,r.ETag=s||void 0,r.createdAt=typeof i.created=="string"?i.created:void 0,r.modifiedAt=typeof i.updated=="string"?i.updated:void 0,r})},{limit:t})}async getReadUrl(t,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return p(m.METHOD_NOT_ALLOWED,"PocketBase: `responseContentDisposition`/`responseContentType` are not supported — PocketBase file URLs have no Content-Disposition/Content-Type override.");if(this.publicBaseUrl)return`${this.publicBaseUrl.replace(/\/+$/,"")}/${t}`;await this.ensureAuth();let e=t;const i=await this.getMetaSafe(t);i?.path&&(e=i.path);const n=await this.findRecord(e),s=String(n[this.fileField]??""),r=await this.client.files.getToken();return f(this.client,n,s,{token:r})}async findRecord(t,a){const e=this.client.filter(`${this.keyField} = {:k}`,{k:t});return this.runOperation(a,()=>this.client.collection(this.collectionName).getFirstListItem(e))}async putRecord(t,a,e,i){await this.ensureAuth();const n=new FormData;n.append(this.keyField,t),n.append(this.fileField,new Blob([new Uint8Array(a)],{type:e}),t);try{const s=await this.findRecord(t,i);await this.runOperation(i,()=>this.client.collection(this.collectionName).update(s.id,n))}catch(s){if(!d(s))throw s;await this.runOperation(i,()=>this.client.collection(this.collectionName).create(n))}}async getMetaSafe(t){try{return await this.getMeta(t)}catch{return}}internalOnComplete=t=>this.deleteMeta(t.id)}export{P as default};
@@ -0,0 +1 @@
1
+ import{n as i}from"./headers-BAiAKekR.js";import{hasBody as p}from"type-is";import{b as n,a as c,g as l,r as y}from"./base-handler-core-EeV8gZck.js";import{T as b}from"./base-handler-node-BjpW8pGi.js";import{X as U,v as w,a as F,e as B,b as O,c as N}from"./rest-base-CynUg0mH.js";class g extends b{static methods=["delete","download","get","head","options","patch","post","put"];restBase;constructor(t){super(t);const s=this;this.restBase=new class extends U{get storage(){return s.storage}buildFileUrl(e,r){return s.buildFileUrlForRest(e,r)}}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PUT",this.put.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}buildFileUrlForRest(t,s){return this.buildFileUrl({url:t},s)}async post(t){const s=n(t,"x-chunked-upload",!0)==="true";w(t,!0);const e=F(t,!0,this.storage.maxUploadSize),r=n(t,"content-type")||"application/octet-stream",a=B(t,e,r),o=t.originalUrl||t.url||"",d=c(t);return this.restBase.handlePost(a,s,o,d,e)}async put(t){let s;try{s=l(t)}catch(u){throw this.checkForUndefinedIdOrPath(u),u}if(!p(t))throw i(400,"Request body is required");const e=Number.parseInt(n(t,"content-length")||"0",10);if(e===0)throw i(400,"Content-Length is required and must be greater than 0");if(e>this.storage.maxUploadSize)throw i(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`);const r=n(t,"content-type")||"application/octet-stream",a=n(t,"x-file-metadata",!0);let o;if(a)try{o=JSON.parse(a)}catch{}const d=O(t),h={contentType:r,metadata:o||{},originalName:d,size:e},f=t.originalUrl||t.url||"",m=c(t);return this.restBase.handlePut(s,h,f,m,e,o)}async delete(t){const s=new URL(t.url||"","http://localhost").searchParams.get("ids");if(s){const e=s.split(",").map(r=>r.trim()).filter(Boolean);if(e.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(e)}if((n(t,"content-type")||"").includes("application/json"))try{const e=await y(t,"utf8",1048576),r=JSON.parse(e);if(Array.isArray(r)){if(r.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(r)}if(typeof r=="object"&&r!==null&&"ids"in r&&Array.isArray(r.ids)){const a=r.ids;if(a.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(a)}}catch(e){if(e.statusCode===400)throw e}try{const e=l(t);return this.restBase.deleteSingle(e)}catch(e){throw this.checkForUndefinedIdOrPath(e),e.code==="ENOENT"||e.UploadErrorCode==="FILE_NOT_FOUND"?i(404,"File not found"):e}}async patch(t){let s;try{s=l(t)}catch(h){throw this.checkForUndefinedIdOrPath(h),h}if(!p(t))throw i(400,"Request body is required");const e=Number.parseInt(n(t,"content-length")||"0",10);if(e===0)throw i(400,"Content-Length is required and must be greater than 0");const{chunkOffset:r}=N(t);if(r===void 0)throw i(400,"X-Chunk-Offset header is required");const a=n(t,"x-chunk-checksum",!0),o=t.originalUrl||t.url||"",d=c(t);return this.restBase.handlePatch(s,r,e,a,o,d)}async head(t){try{const s=l(t);return this.restBase.handleHead(s)}catch(s){throw this.checkForUndefinedIdOrPath(s),s.UploadErrorCode==="FILE_NOT_FOUND"||s.code==="ENOENT"?i(404,"File not found"):s}}async options(){return this.restBase.handleOptions(g.methods,this.storage.maxUploadSize)}async get(t,s){return super.get(t,s)}}export{g as default};
@@ -0,0 +1 @@
1
+ import{n as i}from"./headers-BAiAKekR.js";import{B as b}from"./storage-Cyy73Y6r.js";import{ERRORS as p}from"./ERRORS-BIBxE2oR.js";import{a as u}from"./base-handler-core-EeV8gZck.js";import{C as w}from"./base-handler-fetch-CHzsgb7C.js";import{X as N,p as f}from"./rest-base-CynUg0mH.js";class g extends w{static methods=["delete","download","get","head","options","patch","post","put"];restBase;constructor(e){super(e);const r=this;this.restBase=new class extends N{get storage(){return r.storage}buildFileUrl(s,t){return r.buildFileUrl({url:s},t)}}}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PUT",this.put.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}async post(e){const r=e.headers.get("x-chunked-upload")==="true",s=e.headers.get("content-length"),t=s?Number.parseInt(s,10):0;if(!r){if(!s||Number.isNaN(t)||t===0)throw i(400,"Content-Length is required and must be greater than 0");if(e.body===null)throw i(400,"Request body is required")}if(t>this.storage.maxUploadSize)throw i(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`);const o=e.headers.get("content-type")||"application/octet-stream",n=B(e,t,o),a=e.url,h=e.body?u(e):void 0;return this.restBase.handlePost(n,r,a,h,t)}async put(e){const r=l(e.url);if(!r)throw i(400,"File ID is required in URL path");if(e.body===null)throw i(400,"Request body is required");const s=e.headers.get("content-length"),t=s?Number.parseInt(s,10):0;if(t===0)throw i(400,"Content-Length is required and must be greater than 0");if(t>this.storage.maxUploadSize)throw i(413,`File size exceeds maximum allowed size of ${this.storage.maxUploadSize} bytes`);const o=e.headers.get("content-type")||"application/octet-stream",n=e.headers.get("x-file-metadata");let a;if(n)try{a=JSON.parse(n)}catch{}const h=f(e.headers.get("content-disposition")),c={contentType:o,metadata:a||{},originalName:h,size:t},m=e.url,y=u(e);return this.restBase.handlePut(r,c,m,y,t,a)}async delete(e){const r=new URL(e.url).searchParams.get("ids");if(r){const t=r.split(",").map(o=>o.trim()).filter(Boolean);if(t.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(t)}if((e.headers.get("content-type")||"").includes("application/json"))try{const t=Number.parseInt(e.headers.get("content-length")??"",10);if(Number.isFinite(t)&&t>1048576)throw i(413,"Batch delete body exceeds 1 MiB");const o=await e.text();if(Buffer.byteLength(o,"utf8")>1048576)throw i(413,"Batch delete body exceeds 1 MiB");const n=JSON.parse(o);if(Array.isArray(n)){if(n.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(n)}if(typeof n=="object"&&n!==null&&"ids"in n&&Array.isArray(n.ids)){const a=n.ids;if(a.length===0)throw i(400,"No file IDs provided");return this.restBase.deleteBatch(a)}}catch(t){if(t.statusCode===400)throw t}const s=l(e.url);if(!s)throw i(404,"File not found");try{return this.restBase.deleteSingle(s)}catch(t){const o=t;throw o.UploadErrorCode===p.FILE_NOT_FOUND||o.code==="ENOENT"?i(404,"File not found"):t}}async patch(e){const r=l(e.url);if(!r)throw i(404,"File not found");if(e.body===null)throw i(400,"Request body is required");const s=e.headers.get("content-length"),t=s?Number.parseInt(s,10):0;if(t===0)throw i(400,"Content-Length is required and must be greater than 0");const o=e.headers.get("x-chunk-offset"),n=o?Number.parseInt(o,10):void 0;if(n===void 0)throw i(400,"X-Chunk-Offset header is required");const a=e.headers.get("x-chunk-checksum")||void 0,h=e.url,c=u(e);return this.restBase.handlePatch(r,n,t,a,h,c)}async head(e){const r=l(e.url);if(!r)throw i(404,"File not found");try{return this.restBase.handleHead(r)}catch(s){const t=s;throw t.UploadErrorCode===p.FILE_NOT_FOUND||t.code==="ENOENT"?i(404,"File not found"):s}}async options(e){return this.restBase.handleOptions(g.methods,this.storage.maxUploadSize)}async get(e){throw i(500,"GET requests should be handled via fetch() method")}}const B=(d,e,r)=>{const s=d.headers.get("x-total-size"),t=s?Number.parseInt(s,10):e,o=d.headers.get("x-file-metadata");let n={};if(o)try{n=JSON.parse(o)}catch{}const a=f(d.headers.get("content-disposition"));return{contentType:r,metadata:n,originalName:a,size:t}},l=d=>{let e;try{const r=new URL(d).pathname.split("/").filter(Boolean),s=r[r.length-1];if(!s)return null;e=s.replace(/\.[^.]+$/,"")||void 0}catch{return null}if(!e)return null;try{b.assertSafeId(e)}catch{throw i(400,`Invalid file id: "${e}"`)}return e};export{g as default};
@@ -0,0 +1 @@
1
+ import r from"./File-W8aOo15X.js";class s extends r{Parts;UploadId;uri;partsUrls;partSize}export{s as default};
@@ -0,0 +1 @@
1
+ import{S3Client as c,HeadObjectCommand as o,DeleteObjectCommand as r,PutObjectCommand as d,waitUntilBucketExists as m}from"@aws-sdk/client-s3";import{fromIni as h}from"@aws-sdk/credential-providers";import f from"./MetaStorage-DPEUyWgN.js";import{parseMetadata as l,stringifyMetadata as u}from"./Metadata-B7CcBueg.js";import{t as p}from"./is-expired-CBEk6XBi.js";class M extends f{constructor(t){super(t),this.config=t;const{client:e,...a}=t,i=a.bucket||process.env.S3_BUCKET;if(e===void 0){if(!i)throw new Error("S3 bucket is not defined");const n=a.keyFile||process.env.S3_KEYFILE;n&&(a.credentials=h({configFilepath:n})),this.client=new c(a),this.accessCheck(i).catch(s=>{throw s})}else this.client=e;this.bucket=i}config;bucket;client;async get(t){const e=this.getMetaName(t),a={Bucket:this.bucket,Key:e},{Expires:i,Metadata:n}=await this.client.send(new o(a));if(i&&p({expiredAt:i}))throw await this.delete(e),new Error(`Metafile ${t} not found`);if(n?.metadata!==void 0){const s=JSON.parse(decodeURIComponent(n.metadata));return s.metadata&&typeof s.metadata=="string"&&(s.metadata=l(s.metadata)),s}throw new Error(`Metafile ${t} not found`)}async touch(t,e){return this.save(t,e)}async delete(t){const e={Bucket:this.bucket,Key:this.getMetaName(t)};await this.client.send(new r(e))}async save(t,e){const a={...e};a.metadata&&(a.metadata=u(e.metadata));const i=encodeURIComponent(JSON.stringify(a)),n={Bucket:this.bucket,ContentLength:0,Key:this.getMetaName(t),Metadata:{metadata:i}};return await this.client.send(new d(n)),e}async accessCheck(t,e=30){await m({client:this.client,maxWaitTime:e},{Bucket:t})}}export{M as default};
@@ -0,0 +1 @@
1
+ import{CreateMultipartUploadCommand as f,UploadPartCommand as g,CompleteMultipartUploadCommand as w,AbortMultipartUploadCommand as k,ListPartsCommand as B,GetObjectCommand as C,HeadObjectCommand as b,DeleteObjectCommand as S,CopyObjectCommand as T,ListObjectsV2Command as E,waitUntilBucketExists as x,S3Client as U,PutObjectCommand as K}from"@aws-sdk/client-s3";import{fromIni as L}from"@aws-sdk/credential-providers";import{getSignedUrl as m}from"@aws-sdk/s3-request-presigner";import{S as P,b as I}from"./s3-base-storage-DXZYN24h.js";import{Readable as u}from"node:stream";import{ReadableStream as y}from"node:stream/web";import M from"./S3File-CpZrubaV.js";import A from"./S3MetaStorage-CMonflzp.js";const r=p=>p?.signal?{abortSignal:p.signal}:void 0;class O{constructor(e,t){this.client=e}client;async createMultipartUpload(e,t){const a=new f({ACL:e.ACL,Bucket:e.Bucket,ContentType:e.ContentType,Key:e.Key,Metadata:e.Metadata}),n=await this.client.send(a,r(t));if(!n.UploadId)throw new Error("Failed to create multipart upload");return{UploadId:n.UploadId}}async uploadPart(e,t){const a=e.Body instanceof y?u.fromWeb(e.Body):e.Body,n=new g({Body:a,Bucket:e.Bucket,ContentLength:e.ContentLength,ContentMD5:e.ContentMD5,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId}),o=await this.client.send(n,r(t));if(!o.ETag)throw new Error("Failed to upload part");return{ETag:o.ETag}}async completeMultipartUpload(e,t){const a=new w({Bucket:e.Bucket,Key:e.Key,MultipartUpload:{Parts:e.Parts.map(({ETag:o,PartNumber:i})=>({ETag:o,PartNumber:i}))},UploadId:e.UploadId}),n=await this.client.send(a,r(t));if(!n.Location)throw new Error("Failed to complete multipart upload");return{ETag:n.ETag,Location:n.Location}}async abortMultipartUpload(e,t){const a=new k({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId});await this.client.send(a,r(t))}async listParts(e,t){const a=new B({Bucket:e.Bucket,Key:e.Key,UploadId:e.UploadId}),n=await this.client.send(a,r(t)),o=[];if(n.Parts)for(const i of n.Parts)i.ETag&&i.PartNumber&&o.push({ETag:i.ETag,PartNumber:i.PartNumber,Size:i.Size});return{Parts:o.length>0?o:void 0}}async getObject(e,t){const a=new C({Bucket:e.Bucket,Key:e.Key,...e.Range!==void 0&&{Range:e.Range}}),n=await this.client.send(a,r(t));let o;if(n.Body){const i=n.Body;i instanceof u||typeof i=="object"&&"transform"in i&&i instanceof y?o=i:o=u.from(i)}return{Body:o,ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified,Metadata:n.Metadata}}async headObject(e,t){const a=new b({Bucket:e.Bucket,Key:e.Key}),n=await this.client.send(a,r(t));return{ContentLength:n.ContentLength,ContentType:n.ContentType,ETag:n.ETag,Expires:n.Expires,LastModified:n.LastModified}}async deleteObject(e,t){const a=new S({Bucket:e.Bucket,Key:e.Key});await this.client.send(a,r(t))}async copyObject(e,t){const a={Bucket:e.Bucket,CopySource:e.CopySource,Key:e.Key};e.StorageClass&&(a.StorageClass=e.StorageClass);const n=new T(a);await this.client.send(n,r(t))}async listObjectsV2(e,t){const a=new E({Bucket:e.Bucket,ContinuationToken:e.ContinuationToken,Delimiter:e.Delimiter,MaxKeys:e.MaxKeys,Prefix:e.Prefix}),n=await this.client.send(a,r(t));return{CommonPrefixes:n.CommonPrefixes?.map(o=>({Prefix:o.Prefix})),Contents:n.Contents?.map(o=>({Key:o.Key,LastModified:o.LastModified})),IsTruncated:n.IsTruncated,NextContinuationToken:n.NextContinuationToken}}async getPresignedUrl(e){const t=new g({Bucket:e.Bucket,Key:e.Key,PartNumber:e.PartNumber,UploadId:e.UploadId});return m(this.client,t,{expiresIn:e.expiresIn})}async checkBucketAccess(e){await x({client:this.client,maxWaitTime:30},{Bucket:e.Bucket})}}class _ extends P{static name="s3";s3Api;rawClient;constructor(e){const{bucket:t=process.env.S3_BUCKET,region:a=process.env.S3_REGION}=e;if(!t)throw new Error("S3 bucket is not defined");if(!a)throw new Error("S3 region is not defined");e.region=a;const n=e.keyFile||process.env.S3_KEYFILE;n&&(e.credentials=L({configFilepath:n}));const o=new U(e);super({bucket:t,clientDirectUpload:e.clientDirectUpload,expiration:e.expiration?.maxAge?{maxAge:String(e.expiration.maxAge)}:void 0,filename:e.filename,logger:e.logger,metaStorage:e.metaStorage,metaStorageConfig:e.metaStorageConfig?{...e.metaStorageConfig,...e}:{...e},partSize:e.partSize,retryConfig:{...e.retryConfig,shouldRetry:c=>{const s=c;if(s.$metadata){const d=s.$metadata.httpStatusCode;if(d&&[408,429,500,502,503,504].includes(d)||s.$fault==="server")return!0}return s.retryable??!1}}}),this.s3Api=new O(o,t),this.rawClient=o;const{metaStorage:i,metaStorageConfig:l}=e;if(!i){const c={...e,...l,logger:this.logger};"directory"in c||(this.meta=new A(c))}this.config.clientDirectUpload&&(this.onCreate=async()=>{})}normalizeError(e){return e.$metadata?{code:e.Code||e.name,message:e.message,name:e.name,statusCode:e.$metadata.httpStatusCode||500}:super.normalizeError(e)}async update({id:e},t){if(this.config.clientDirectUpload){const a=await this.getMeta(e);return this.buildPresigned({...a,...t})}return super.update({id:e},t)}async getStream({id:e},t){return this.instrumentOperation("getStream",async()=>{const a=this.getS3Api(),n=I(t?.range),{Body:o,ContentLength:i,ContentType:l,ETag:c,Expires:s,LastModified:d}=await this.runOperation(t,h=>a.getObject({Bucket:this.bucket,Key:e,...n!==void 0&&{Range:n}},{signal:h}));return await this.checkIfExpired({expiredAt:s}),{headers:{"Content-Length":i?.toString()??"0","Content-Type":l,...c&&{ETag:c},...s&&{"X-Upload-Expires":s.toString()},...d&&{"Last-Modified":d.toString()}},size:Number(i),stream:o}})}get raw(){return this.rawClient}async getReadUrl(e,t){const a=new C({Bucket:this.bucket,Key:e,...t?.responseContentDisposition&&{ResponseContentDisposition:t.responseContentDisposition},...t?.responseContentType&&{ResponseContentType:t.responseContentType}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}async getUploadUrl(e,t){const a=new K({Bucket:this.bucket,Key:e,...t?.contentType&&{ContentType:t.contentType},...t?.contentLength!==void 0&&{ContentLength:t.contentLength}});return m(this.rawClient,a,{expiresIn:t?.expiresIn??3600})}getS3Api(){return this.s3Api}getFileClass(){return M}getAcl(){return this.config.acl}async accessCheck(e=30){await this.s3Api.checkBucketAccess({Bucket:this.bucket})}}export{_ as default};
@@ -0,0 +1 @@
1
+ import e from"./File-W8aOo15X.js";class s extends e{path}export{s as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-C2T92TYb.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -0,0 +1 @@
1
+ import{F as T}from"./index-nZWCQrSe.js";import P from"ssh2-sftp-client";import{throwErrorCode as d,ERRORS as p}from"./ERRORS-BIBxE2oR.js";import{B as O}from"./storage-Cyy73Y6r.js";import k from"./SftpFile-ClWDYnt2.js";import F from"./SftpMetaStorage-DFwhEI9C.js";import{r as y,t as b,e as l}from"./posix-dirname-CfpH5wZi.js";import{t as E}from"./get-file-status-y3wTtDQs.js";import{t as M}from"./update-size-DuNuLyxj.js";import{i as v}from"./part-match-D-9dGX42.js";import{e as S}from"./has-content-50BsqrWw.js";const f=c=>{const a=c?.code,e=c instanceof Error?c.message:String(c);return a===2||a==="ENOENT"||/no such file|not exist|no such path/i.test(e)},g=c=>{if(c instanceof Error&&c.name==="AbortError")return c;const a=new Error(c instanceof Error&&c.message?c.message:"The operation was aborted",{cause:c});return a.name="AbortError",a};class U extends O{static name="sftp";checksumTypes=[];supportsRange=!0;meta;connection;rootFolderPath;constructor(a){super(a),this.connection=a.connection,this.rootFolderPath=y(a.rootFolderPath??""),this.meta=a.metaStorage??new F(a.metaStorageConfig),this.isReady=!0}async create(a,e){return this.instrumentOperation("create",async()=>{const t=new k(a);t.name=this.namingFunction(t),t.path=this.keyToPath(t.name),await this.validate(t);try{const i=await this.getMeta(t.id);if(i.status==="completed")return i}catch{}return t.bytesWritten=0,t.status=E(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&&M(t,a.size),!v(a,t))return d(p.FILE_CONFLICT);const i=await this.lock(a.id);try{if(S(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 n=await b(a.body),r=t.path??this.keyToPath(t.name||t.id);await this.runOperation(e,s=>this.run(s,async o=>{const h=l(r);h&&await o.mkdir(h,!0),await o.put(n,r)})),t.bytesWritten=n.length,t.size=n.length,t.path=r,t.ETag=T(n)}return t.status=E(t),await this.saveMeta(t),t}finally{await this.unlock(a.id,i)}})}async get({id:a},e){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(a)),i=t.path??this.keyToPath(t.name||a),{range:n}=e??{},r=await this.runOperation(e,s=>this.run(s,async o=>{try{const h=n?{readStreamOptions:{start:n.start,...n.end===void 0?{}:{end:n.end}}}:void 0;return await o.get(i,void 0,h)}catch(h){if(f(h))return d(p.FILE_NOT_FOUND);throw h}}));return{content:r,contentType:t.contentType,ETag:t.ETag??T(r),expiredAt:t.expiredAt,id:a,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:n?r.length:t.size??r.length}})}async delete({id:a},e){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(a),i=t.path??this.keyToPath(t.name||a);await this.runOperation(e,r=>this.run(r,async s=>{try{await s.delete(i)}catch(o){if(!f(o))throw o}})),await this.deleteMeta(a);const n={...t,status:"deleted"};return await this.onDelete(n),n})}async copy(a,e,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(a),n=i.path??this.keyToPath(i.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async h=>{const u=await h.get(n),m=l(r);m&&await h.mkdir(m,!0),await h.put(u,r)}));const s={...i,id:e,name:e,path:r};return await this.saveMeta(s),s})}async move(a,e,t){return this.instrumentOperation("move",async()=>{const i=await this.getMeta(a),n=i.path??this.keyToPath(i.name||a),r=this.keyToPath(e);await this.runOperation(t,o=>this.run(o,async h=>{const u=l(r);u&&await h.mkdir(u,!0);try{await h.rename(n,r)}catch(m){try{const w=await h.get(n);await h.put(w,r),await h.delete(n)}catch(w){throw new AggregateError([m,w],`SFTP move failed: rename and copy+delete fallback both failed for "${n}" → "${r}"`)}}}));const s={...i,id:e,name:e,path:r};await this.saveMeta(s);try{await this.deleteMeta(a)}catch{}return s})}async list(a=1e3,e){return this.instrumentOperation("list",async()=>{const t=this.keyToPath("");return this.runOperation(e,i=>this.run(i,async n=>{const r=[];return await this.walkList(n,t,r),r}))})}async exists({id:a},e){return this.instrumentOperation("exists",async()=>{let t;try{t=await this.getMeta(a)}catch{return!1}const i=t.path??this.keyToPath(t.name||a);return this.runOperation(e,n=>this.run(n,async r=>{const s=await r.exists(i);return s==="-"||s==="l"}))})}async walkList(a,e,t){let i;try{i=await a.list(e||".")}catch(n){if(f(n))return;throw n}for(const n of i){const r=e?`${e}/${n.name}`:n.name;if(n.type==="d"){await this.walkList(a,r,t);continue}if(n.type!=="-")continue;const s=this.pathToKey(r);if(!s)continue;const o=new k({contentType:"application/octet-stream",metadata:{},originalName:n.name});o.id=s,o.name=s,o.path=r,o.size=n.size,o.modifiedAt=new Date(n.modifyTime).toISOString(),t.push(o)}}async run(a,e){const t=new P;if(a?.aborted)throw g(a.reason);const i=()=>{t.end()};a?.addEventListener("abort",i,{once:!0});try{if(await t.connect(this.connection),a?.aborted)throw g(a.reason);return await e(t)}catch(n){throw a?.aborted?g(n):n}finally{a?.removeEventListener("abort",i),await t.end()}}keyToPath(a){const e=y(a);e&&O.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=y(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{U as default};
@@ -0,0 +1 @@
1
+ import e from"./OneDriveFile-CNNJYI43.js";class a extends e{}export{a as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-C2T92TYb.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -0,0 +1 @@
1
+ import{throwErrorCode as c,ERRORS as d}from"./ERRORS-BIBxE2oR.js";import h,{buildGraphClient as l}from"./OneDriveStorage-CvJetV7_.js";import{B as I}from"./storage-Cyy73Y6r.js";import u from"./SharePointMetaStorage-DFwhEI9C.js";const g=a=>{if(!a)return;const e=a.replace(/\/+$/,"").split("/").pop();if(e)try{return decodeURIComponent(e)}catch{return e}},v=a=>{let e;try{e=new URL(a)}catch{return c(d.BAD_REQUEST,`SharePoint storage: invalid \`siteUrl\` "${a}".`)}const t=e.pathname.replace(/\/+$/,"");return{hostname:e.host,sitePath:t===""?"/":t}};class T extends I{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 n=process.env.SHAREPOINT_TENANT_ID??process.env.ONEDRIVE_TENANT_ID,o=process.env.SHAREPOINT_CLIENT_ID??process.env.ONEDRIVE_CLIENT_ID,i=process.env.SHAREPOINT_CLIENT_SECRET??process.env.ONEDRIVE_CLIENT_SECRET;if(n&&o&&i)return{clientId:o,clientSecret:i,tenantId:n}})();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=l(this.oneDriveAuth),this.meta=e.metaStorage??new u(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:n,sitePath:o,siteUrl:i,...s}=this.genericConfig;return new h({...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 n=await this.client.api(`/sites/${t}/drives`).get(),o=e.documentLibrary.toLowerCase(),i=(n.value??[]).find(s=>s.name===e.documentLibrary)??(n.value??[]).find(s=>s.name?.toLowerCase()===o||g(s.webUrl)?.toLowerCase()===o);return i?i.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}=v(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 n=r==="/"?"":r.replace(/^\/+/,""),o=n?`/sites/${t}:/${n}`:`/sites/${t}`;let i;try{i=await this.client.api(o).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 i?.id?i.id:c(d.FILE_NOT_FOUND,`SharePoint storage: site not found for "${e.siteUrl??`${t}${r}`}".`)}}export{T as default};
@@ -0,0 +1 @@
1
+ import t from"./File-W8aOo15X.js";class a extends t{bucket;path;publicUrl}export{a as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-C2T92TYb.js";class o extends r{constructor(t){super(t)}}export{o as default};
@@ -0,0 +1 @@
1
+ import{StorageClient as l}from"@supabase/storage-js";import{throwErrorCode as h,ERRORS as u}from"./ERRORS-BIBxE2oR.js";import{B as f}from"./storage-Cyy73Y6r.js";import c from"./SupabaseFile-Bo5B-vM1.js";import g from"./SupabaseMetaStorage-DqkgoE46.js";import{t as p}from"./get-file-status-y3wTtDQs.js";import{t as w}from"./update-size-DuNuLyxj.js";import{i as y}from"./part-match-D-9dGX42.js";import{e as b}from"./has-content-50BsqrWw.js";const d=3600*24*7,E=o=>{if(!o||!/^attachment(\s*;|\s*$)/i.test(o.trim()))return;const e=o.match(/filename\*?=(?:UTF-8'')?(?:"([^"]+)"|([^;]+))/i),a=e?.[1]??e?.[2];if(!a)return!0;try{return decodeURIComponent(a.trim())}catch{return a.trim()}},S=async o=>{const e=[];for await(const a of o)e.push(Buffer.from(a));return Buffer.concat(e)};class R extends f{static name="supabase";checksumTypes=[];meta;bucket;defaultUrlExpiresIn;storageClient;constructor(e){if(super(e),this.bucket=e.bucket,this.defaultUrlExpiresIn=Math.min(e.defaultUrlExpiresIn??3600,d),e.client)this.storageClient=e.client;else{const a=e.url??process.env.SUPABASE_URL,t=e.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(!t)throw new Error("Supabase storage: `serviceKey` is required (or set SUPABASE_SERVICE_ROLE_KEY / SUPABASE_KEY).");const i=a.replace(/\/+$/,"")+(a.endsWith("/storage/v1")?"":"/storage/v1");this.storageClient=new l(i,{apikey:t,Authorization:`Bearer ${t}`},e.fetch)}this.meta=e.metaStorage??new g(e.metaStorageConfig),this.isReady=!0}get raw(){return this.storageClient}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new c(e);t.name=this.namingFunction(t),t.bucket=this.bucket,t.path=t.name,await this.validate(t);try{const i=await this.getMeta(t.id);if(i.bytesWritten>=0)return i}catch{}return t.bytesWritten=0,t.status=p(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,a){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&w(t,e.size),!y(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(b(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const r=await S(e.body),n=t.path??t.name,{data:s,error:m}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).upload(n,r,{contentType:t.contentType,upsert:!0}));if(m)throw m;t.bytesWritten=r.length,t.size=r.length,t.path=s?.path??n,t.ETag=s?.id}return t.status=p(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const i=t?.path??t?.name??e,{error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).remove([i]));if(r&&r.message&&!/not.*found/i.test(r.message))throw r;return t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new c({contentType:"application/octet-stream",metadata:{},originalName:e}),{bucket:this.bucket,id:e,name:e,path:i,status:"deleted"})})}async exists({id:e},a){return this.instrumentOperation("exists",async()=>{let t=e;try{t=(await this.getMeta(e)).path??e}catch{}const{data:i,error:r}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).exists(t));return r?!1:!!i})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t=e,i;try{i=await this.checkIfExpired(await this.getMeta(e)),t=i.path??i.name??e}catch{}const{data:r,error:n}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).download(t));if(n||!r)throw n??new Error(`Supabase: object not found at "${t}"`);const s=Buffer.from(await this.runOperation(a,()=>r.arrayBuffer()));return{content:s,contentType:i?.contentType??r.type??"application/octet-stream",ETag:i?.ETag,expiredAt:i?.expiredAt,id:e,metadata:i?.metadata??{},modifiedAt:i?.modifiedAt,name:i?.name??t,originalName:i?.originalName??t,size:i?.size??s.length}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const i=(await this.getMetaSafe(e))?.path??e,r=a,{error:n}=await this.runOperation(t,()=>this.storageClient.from(this.bucket).copy(i,r));if(n)throw n;const s=new c({contentType:"application/octet-stream",metadata:{},originalName:a});return s.id=a,s.name=a,s.path=r,s.bucket=this.bucket,s})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const i=(await this.getMetaSafe(e))?.path??e,{error:r}=await this.runOperation(t,()=>this.storageClient.from(this.bucket).move(i,a));if(r)throw r;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(e)}catch{}return n})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>{const{data:t,error:i}=await this.runOperation(a,()=>this.storageClient.from(this.bucket).list("",{limit:e}));if(i)throw i;return(t??[]).map(r=>{const n=new c({contentType:r.metadata?.mimetype??"application/octet-stream",metadata:r.metadata??{},originalName:r.name});return n.id=r.name,n.name=r.name,n.path=r.name,n.bucket=this.bucket,n.size=typeof r.metadata?.size=="number"?r.metadata.size:void 0,n.createdAt=r.created_at??void 0,n.modifiedAt=r.updated_at??void 0,n.ETag=r.metadata?.eTag??r.id??void 0,n})},{limit:e})}async getReadUrl(e,a){const t=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,d),{data:i,error:r}=await this.storageClient.from(this.bucket).createSignedUrl(e,t,{download:E(a?.responseContentDisposition)});return r||!i?h(u.METHOD_NOT_ALLOWED,r?.message??"Supabase: createSignedUrl failed"):i.signedUrl}async getUploadUrl(e,a){if(a?.contentType!==void 0||a?.contentLength!==void 0)return h(u.BAD_REQUEST,"Supabase: `contentType`/`contentLength` are not supported for upload URLs. A Supabase signed upload URL does not bind the request Content-Type into the signature and cannot enforce a size limit; validate both at your application gateway/proxy before issuing the URL.");const{data:t,error:i}=await this.storageClient.from(this.bucket).createSignedUploadUrl(e);return i||!t?h(u.METHOD_NOT_ALLOWED,i?.message??"Supabase: createSignedUploadUrl failed"):t.signedUrl}async getMetaSafe(e){try{return await this.getMeta(e)}catch{return}}internalOnComplete=e=>this.deleteMeta(e.id)}export{R as default};
@@ -0,0 +1 @@
1
+ import{n as s,H as v}from"./headers-BAiAKekR.js";import{Metadata as N}from"./Metadata-B7CcBueg.js";const T="1.0.0",S="1.0.0",x=(m="")=>{const t=m.split(",").map(o=>o.split(" ")),e=Object.create(N.prototype);return Object.values(t).forEach(([o,r])=>{o&&(e[o]=r?Buffer.from(r,"base64").toString():"")}),e},O=m=>!m||Object.keys(m).length===0?"":Object.entries(m).map(([t,e])=>e===void 0?t:`${t} ${Buffer.from(String(e)).toString("base64")}`).toString();class H{get storage(){throw new Error("storage must be implemented")}buildFileUrl(t,e){throw new Error("buildFileUrl must be implemented")}handleOptions(t){return{headers:{"Access-Control-Allow-Headers":"Authorization, Content-Type, Location, Tus-Extension, Tus-Max-Size, Tus-Resumable, Tus-Version, Upload-Concat, Upload-Defer-Length, Upload-Length, Upload-Metadata, Upload-Offset, X-HTTP-Method-Override, X-Requested-With","Access-Control-Allow-Methods":t.map(e=>e.toUpperCase()).join(", "),"Access-Control-Max-Age":86400,"Tus-Checksum-Algorithm":this.storage.checksumTypes.join(","),"Tus-Extension":this.storage.tusExtension.toString(),"Tus-Max-Size":this.storage.maxUploadSize,"Tus-Version":S},statusCode:204}}async handlePost(t,e,o,r,u,g,p,U){if(e!==void 0){if(!this.storage.tusExtension.includes("creation-defer-length"))throw s(501,"creation-defer-length extension is not (yet) supported.");if(t===void 0){const l={metadata:r?x(r):{}};let i=await this.storage.create(l);U==="application/offset+octet-stream"&&p>0&&(i=await this.storage.write({...i,body:g,contentLength:p,start:0}));let a={};this.storage.tusExtension.includes("expiration")&&typeof i.expiredAt=="number"&&i.size===void 0&&(a={"Upload-Expires":new Date(i.expiredAt).toUTCString()});const c=this.buildFileUrl(u,i);a={...a,...this.buildHeaders(i,{Location:c})},a.Location||(a.Location=c),i.bytesWritten>0&&(a["Upload-Offset"]=i.bytesWritten.toString()),a["Upload-Defer-Length"]="1";const b=i.bytesWritten>0?200:201;return{...i,headers:a,statusCode:b}}}if(o){if(!this.storage.tusExtension.includes("concatenation"))throw s(501,"Concatenation extension is not (yet) supported. Disable parallel upload in the tus client.");const l=r?x(r):{};if(o==="partial"){const i={metadata:{...l,uploadConcat:"partial"},size:t};let a=await this.storage.create(i);U==="application/offset+octet-stream"&&p>0&&(a=await this.storage.write({...a,body:g,contentLength:p,start:0}));let c={};this.storage.tusExtension.includes("expiration")&&typeof a.expiredAt=="number"&&a.bytesWritten!==(a.size??0)&&(c={"Upload-Expires":new Date(a.expiredAt).toUTCString()});const b=this.buildFileUrl(u,a);c={...c,...this.buildHeaders(a,{Location:b})},c.Location||(c.Location=b),a.bytesWritten>0&&(c["Upload-Offset"]=a.bytesWritten.toString()),c["Upload-Concat"]="partial";const w=a.bytesWritten>0?200:201;return{...a,headers:c,statusCode:w}}if(o.startsWith("final;")){const i=o.slice(6).trim().split(/\s+/).filter(Boolean);if(i.length===0)throw s(400,"Upload-Concat final must include at least one partial upload ID");let a=0;const c=[];for(const C of i)try{const f=await this.storage.getMeta(C);if(await this.storage.checkIfExpired(f),f.metadata?.uploadConcat!=="partial")throw s(400,`Upload ${C} is not a partial upload`);if(f.status!=="completed"||f.size===void 0)throw s(409,`Partial upload ${C} is not completed`);c.push(f),a+=f.size}catch(f){const L=f;throw L.statusCode===404||L.statusCode===410?s(409,`Partial upload ${C} not found or expired`):f}const b={metadata:{...l,partialIds:i,uploadConcat:`final;${i.join(" ")}`},size:a},w=await this.storage.create(b);await this.concatenateFiles(w,c);const z=this.buildFileUrl(u,w),A={...this.buildHeaders(w,{Location:z}),"Upload-Concat":o};return{...w,headers:A,statusCode:201}}throw s(400,"Invalid Upload-Concat header format")}if(t===void 0&&e===void 0)throw s(400,"Either upload-length or upload-defer-length must be specified.");if(t!==void 0&&Number.isNaN(Number(t)))throw s(400,"Invalid upload-length");const E={metadata:r?x(r):{},size:t};let n=await this.storage.create(E);U==="application/offset+octet-stream"&&p>0&&(n=await this.storage.write({...n,body:g,contentLength:p,start:0}));let h={};this.storage.tusExtension.includes("expiration")&&typeof n.expiredAt=="number"&&n.bytesWritten!==Number.parseInt(t,10)&&(h={"Upload-Expires":new Date(n.expiredAt).toUTCString()});const y=this.buildFileUrl(u,n);h={...h,...this.buildHeaders(n,{Location:y})},h.Location||(h.Location=y),n.bytesWritten>0&&(h["Upload-Offset"]=n.bytesWritten.toString());const d=n.bytesWritten>0?200:201;return{...n,headers:h,statusCode:d}}async handlePatch(t,e,o,r,u,g,p,U,E){const n=r?x(r):void 0;if(n)try{await this.storage.update({id:t},{id:t,metadata:n})}catch(l){throw l.UploadErrorCode==="FILE_NOT_FOUND"?s(410,"Upload expired"):l}let h;try{h=await this.storage.getMeta(t),await this.storage.checkIfExpired(h)}catch(l){const i=l;throw i.UploadErrorCode==="GONE"||i.UploadErrorCode==="FILE_NOT_FOUND"?s(410,"Upload expired"):l}const y=h.metadata?.uploadConcat;if(typeof y=="string"&&y.startsWith("final;"))throw s(403,"Cannot PATCH a final concatenation upload");let d=await this.storage.write({body:U,checksum:u,checksumAlgorithm:g,contentLength:E,id:t,start:e});if(o!==void 0){if(!this.storage.tusExtension.includes("creation-defer-length"))throw s(501,"creation-defer-length extension is not (yet) supported.");if(d.size!==void 0&&!Number.isNaN(d.size))throw s(412,"Upload-Length has already been set for this upload");const l=Number.parseInt(o,10);if(Number.isNaN(l))throw s(400,"Invalid Upload-Length value");if(l<d.bytesWritten)throw s(400,"Upload-Length is smaller than the current offset");d=await this.storage.update({id:t},{size:l}),d.bytesWritten===d.size&&(d={...d,status:"completed"})}return{...d,headers:this.buildHeaders(d,{"Upload-Offset":d.bytesWritten}),statusCode:d.status==="completed"?200:204}}async handleHead(t){const e=await this.storage.getMeta(t);await this.storage.checkIfExpired(e);const o={...typeof e.size=="number"&&!Number.isNaN(e.size)?{"Upload-Length":e.size}:{"Upload-Defer-Length":"1"},...this.buildHeaders(e,{"Cache-Control":v.createCacheControlPreset("no-store"),"Upload-Metadata":O(e.metadata),"Upload-Offset":e.bytesWritten})},r=e.metadata?.uploadConcat;return typeof r=="string"&&(o["Upload-Concat"]=r),{headers:o,statusCode:200}}async handleGet(t){const e=await this.storage.getMeta(t);return{...e,body:e,headers:this.buildHeaders(e,{"Content-Type":v.createContentType({mediaType:"application/json"})}),statusCode:200}}async handleDelete(t){if(this.disableTerminationForFinishedUploads&&(await this.storage.getMeta(t)).status==="completed")throw s(400,"Termination of finished uploads is disabled");const e=await this.storage.delete({id:t});if(e.status===void 0)throw s(404,"File not found");return{...e,headers:this.buildHeaders(e),statusCode:204}}buildHeaders(t,e={}){return e["Tus-Resumable"]=T,this.storage.tusExtension.includes("expiration")&&t.expiredAt!==void 0&&(e["Upload-Expires"]=new Date(t.expiredAt).toUTCString()),e}extractChecksum(t){if(!t)return{checksum:void 0,checksumAlgorithm:void 0};const[e,o]=t.split(/\s+/).filter(Boolean);return{checksum:o,checksumAlgorithm:e}}validateTusResumableHeader(t){if(!t)throw s(412,"Missing Tus-Resumable header");if(t!==T)throw s(412,`Unsupported TUS version: ${t}. Server supports: ${T}`)}async concatenateFiles(t,e){let o=0;for(const r of e){if(!this.storage.getStream)throw s(501,"getStream is not supported by this storage backend");const{size:u,stream:g}=await this.storage.getStream({id:r.id});if(u===void 0)throw s(500,"Partial upload size is undefined");const p=await this.storage.write({...t,body:g,contentLength:u,start:o});Object.assign(t,p),o+=u}}}const k=T,F=S;export{k as TUS_RESUMABLE,F as TUS_VERSION,H as TusBase,x as parseMetadata,O as serializeMetadata};
@@ -0,0 +1 @@
1
+ import{format as b}from"node:url";import{n as d}from"./headers-BAiAKekR.js";import{b as a,a as c,g as n}from"./base-handler-core-EeV8gZck.js";import{T as f}from"./base-handler-node-BjpW8pGi.js";import{TusBase as U,TUS_RESUMABLE as T}from"./TUS_RESUMABLE-CyTSRvPU.js";import{TUS_VERSION as R}from"./TUS_RESUMABLE-CyTSRvPU.js";class p extends f{static methods=["delete","download","get","head","options","patch","post"];disableTerminationForFinishedUploads=!1;tusBase;constructor(e){super(e),this.disableTerminationForFinishedUploads=e.disableTerminationForFinishedUploads??!1;const t=this;this.tusBase=new class extends U{get storage(){return t.storage}get disableTerminationForFinishedUploads(){return t.disableTerminationForFinishedUploads}buildFileUrl(s,r){return t.buildFileUrlForTus(s,r)}}}async options(){return this.tusBase.handleOptions(p.methods)}async post(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));const t=e.headers["upload-length"],s=e.headers["upload-defer-length"],r=e.headers["upload-concat"],o=a(e,"upload-metadata",!0),i=a(e,"content-type")||"",h=Number.parseInt(a(e,"content-length")||"0",10),l=e.originalUrl||e.url||"",u=c(e);return this.tusBase.handlePost(t,s,r,o,l,u,h,i)}async patch(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);if(e.headers["upload-offset"]===void 0)throw d(412,"Missing Upload-Offset header");if(e.headers["content-type"]===void 0)throw d(412,"Content-Type header required");if(e.headers["content-type"]!=="application/offset+octet-stream")throw d(415,"Unsupported Media Type");const s=Number.parseInt(a(e,"upload-offset"),10),r=e.headers["upload-length"],o=a(e,"upload-metadata",!0),i=Number(a(e,"content-length")),h=a(e,"upload-checksum"),{checksum:l,checksumAlgorithm:u}=this.tusBase.extractChecksum(h),m=e.originalUrl||e.url||"",g=c(e);return this.tusBase.handlePatch(t,s,r,o,l,u,m,g,i)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async head(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleHead(t)}catch(t){this.checkForUndefinedIdOrPath(t);const s=t;throw s.UploadErrorCode==="GONE"||s.UploadErrorCode==="FILE_NOT_FOUND"?d(410,"Upload expired"):t}}async get(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleGet(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.UploadErrorCode==="GONE"?d(410,"Upload expired"):t}}async delete(e){this.tusBase.validateTusResumableHeader(a(e,"tus-resumable"));try{const t=n(e);return this.tusBase.handleDelete(t)}catch(t){throw this.checkForUndefinedIdOrPath(t),t.code==="ENOENT"?d(404,"File not found"):t}}send(e,{body:t="",headers:s={},statusCode:r=200}){const o={body:t,headers:{...s,"Access-Control-Expose-Headers":"location,upload-expires,upload-offset,upload-length,upload-metadata,upload-defer-length,tus-resumable,tus-extension,tus-max-size,tus-version,tus-checksum-algorithm,cache-control","Tus-Resumable":T},statusCode:r||200};super.send(e,o)}compose(){this.registeredHandlers.set("POST",this.post.bind(this)),this.registeredHandlers.set("PATCH",this.patch.bind(this)),this.registeredHandlers.set("HEAD",this.head.bind(this)),this.registeredHandlers.set("GET",this.get.bind(this)),this.registeredHandlers.set("DELETE",this.delete.bind(this)),this.registeredHandlers.set("OPTIONS",this.options.bind(this)),this.logger?.debug("Registered handler: %s",[...this.registeredHandlers.keys()].join(", "))}buildFileUrlForTus(e,t){const s=new URL(e,"http://localhost"),{pathname:r}=s,o=Object.fromEntries(s.searchParams.entries()),i=b({pathname:`${r}/${t.id}`,query:o});return this.storage.config.useRelativeLocation?i:(/^https?:\/\//iu.test(e)?s.origin:"")+i}}export{T as TUS_RESUMABLE,R as TUS_VERSION,p as Tus};
@@ -0,0 +1 @@
1
+ import{n as a}from"./headers-BAiAKekR.js";import{B as y}from"./storage-Cyy73Y6r.js";import{C as v}from"./base-handler-fetch-CHzsgb7C.js";import{TusBase as E,TUS_RESUMABLE as w}from"./TUS_RESUMABLE-CyTSRvPU.js";import{TUS_VERSION as C}from"./TUS_RESUMABLE-CyTSRvPU.js";const h=f=>{let e;try{const t=new URL(f).pathname.split("/").filter(Boolean);e=t[t.length-1]||void 0}catch{return}if(e){try{y.assertSafeId(e)}catch{throw a(400,`Invalid file id: "${e}"`)}return e}};class m extends v{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 E{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",w),new Response(t.body,{headers:s,status:t.status,statusText:t.statusText})}async options(){return this.tusBase.handleOptions(m.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,l=e.headers.get("content-type")||"",i=e.headers.get("content-length"),n=i?Number.parseInt(i,10):0,u=e.url,c=e.body;return this.tusBase.handlePost(s,r,o,d,u,c,n,l)}async patch(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=h(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),l=e.headers.get("upload-length")||void 0,i=e.headers.get("upload-metadata")||void 0,n=e.headers.get("content-length"),u=n?Number.parseInt(n,10):0,c=e.headers.get("upload-checksum")||void 0,{checksum:b,checksumAlgorithm:T}=this.tusBase.extractChecksum(c),U=e.url,F=e.body;try{return this.tusBase.handlePatch(s,d,l,i,b,T,U,F,u)}catch(p){const g=p;throw g.UploadErrorCode==="GONE"||g.UploadErrorCode==="FILE_NOT_FOUND"?a(410,"Upload expired"):p}}async head(e){const t=e.headers.get("tus-resumable");this.tusBase.validateTusResumableHeader(t||void 0);const s=h(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=h(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=h(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{w as TUS_RESUMABLE,C as TUS_VERSION,m as Tus};
@@ -0,0 +1 @@
1
+ class a{key;controller=new AbortController;internalState="idle";loadedBytes;startPaused=!1;boundStream;constructor(t){this.loadedBytes=t?.loaded??0,this.key=t?.key}static from(t){const e=typeof t=="string"?JSON.parse(t):t;return new a({key:e.key,loaded:e.loaded})}get signal(){return this.controller.signal}get state(){return this.internalState}get loaded(){return this.loadedBytes}pause(){(this.internalState==="uploading"||this.internalState==="idle")&&(this.internalState="paused",this.startPaused=!0,this.boundStream?.pause())}resume(){this.internalState==="paused"&&(this.internalState="uploading",this.startPaused=!1,this.boundStream?.resume())}abort(t){this.internalState!=="completed"&&this.internalState!=="aborted"&&(this.internalState="aborted",this.controller.abort(t))}serialize(){return{key:this.key,loaded:this.loadedBytes,version:1}}_bind(t,e){this.boundStream=t,this.key??=e,this.internalState!=="aborted"&&(this.internalState=this.startPaused?"paused":"uploading"),this.startPaused&&t.pause()}_progress(t){this.loadedBytes=t}_complete(){this.internalState!=="aborted"&&(this.internalState="completed"),this.boundStream=void 0}}export{a as UploadControl};
@@ -0,0 +1 @@
1
+ import s from"./File-W8aOo15X.js";class t extends s{customId;fileHash;ufsKey;url}export{t as default};
@@ -0,0 +1 @@
1
+ import{y as s}from"./local-meta-storage-C2T92TYb.js";class o extends s{constructor(r){super(r)}}export{o as default};
@@ -0,0 +1 @@
1
+ import{UTApi as w,UTFile as u}from"uploadthing/server";import{throwErrorCode as l,ERRORS as h}from"./ERRORS-BIBxE2oR.js";import{B as g}from"./storage-Cyy73Y6r.js";import d from"./UploadThingFile-BTFMpcIA.js";import T from"./UploadThingMetaStorage-D_vNzewL.js";import{t as m}from"./get-file-status-y3wTtDQs.js";import{t as U}from"./update-size-DuNuLyxj.js";import{i as I}from"./part-match-D-9dGX42.js";import{e as O}from"./has-content-50BsqrWw.js";const f=3600*24*7,E=p=>{let e;try{e=typeof atob=="function"?atob(p):Buffer.from(p,"base64").toString("utf8")}catch(t){throw new Error(`UploadThing: token is not valid base64: ${t.message}`)}let a;try{a=JSON.parse(e)}catch(t){throw new Error(`UploadThing: token does not decode to JSON: ${t.message}`)}if(!a||typeof a!="object"||typeof a.apiKey!="string"||typeof a.appId!="string")throw new Error("UploadThing: token missing `apiKey` or `appId`");return a},k=async p=>{const e=[];for await(const a of p)e.push(Buffer.from(a));return Buffer.concat(e)},y=p=>{const e=p.lastIndexOf("/");return e===-1?p:p.slice(e+1)};class S extends g{static name="uploadthing";checksumTypes=[];meta;acl;appId;defaultUrlExpiresIn;utapi;constructor(e){super(e);const a=e.token??process.env.UPLOADTHING_TOKEN;if(e.client)this.utapi=e.client;else{if(!a)throw new Error("UploadThing: missing token. Pass `token` or set UPLOADTHING_TOKEN.");this.utapi=new w({defaultKeyType:"customId",token:a})}if(!a)throw new Error("UploadThing: `token` is required even when passing `client` so the adapter can derive `appId` for CDN URLs.");this.appId=E(a).appId,this.acl=e.acl??"public-read",this.defaultUrlExpiresIn=Math.min(e.defaultUrlExpiresIn??3600,f),this.meta=e.metaStorage??new T(e.metaStorageConfig),this.isReady=!0}get raw(){return this.utapi}async create(e,a){return this.instrumentOperation("create",async()=>{const t=new d(e);t.name=this.namingFunction(t),t.customId=t.name,await this.validate(t);try{const i=await this.getMeta(t.id);if(i.bytesWritten>=0)return i}catch{}return t.bytesWritten=0,t.status=m(t),await this.saveMeta(t),await this.onCreate(t),t})}async write(e,a){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&U(t,e.size),!I(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(O(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const n=await k(e.body),o=new Blob([new Uint8Array(n)],{type:t.contentType}),s=new u([o],y(t.name||t.id),{customId:t.name||t.id,type:t.contentType}),r=await this.runOperation(a,()=>this.utapi.uploadFiles(s,{acl:this.acl}));if(r.error)throw new Error(r.error.message);const{data:c}=r;t.bytesWritten=n.length,t.size=n.length,t.ufsKey=c.key,t.url=c.ufsUrl??c.url,t.ETag=c.fileHash,t.fileHash=c.fileHash}return t.status=m(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},a){return this.instrumentOperation("delete",async()=>{let t;try{t=await this.getMeta(e)}catch{}const i=t?.customId??t?.name??e;return await this.runOperation(a,()=>this.utapi.deleteFiles(i)),t?(t.status="deleted",await this.deleteMeta(t.id),await this.onDelete(t),t):Object.assign(new d({contentType:"application/octet-stream",metadata:{},originalName:e}),{customId:i,id:e,name:e,status:"deleted"})})}async get({id:e},a){return this.instrumentOperation("get",async()=>{let t,i=e;try{t=await this.checkIfExpired(await this.getMeta(e)),i=t.customId??t.name??e}catch{}const n=await this.resolveFetchUrl(i,a),o=await this.runOperation(a,()=>fetch(n));if(!o.ok)throw new Error(`UploadThing: fetch failed: ${o.status} ${o.statusText} for ${i}`);const s=Buffer.from(await o.arrayBuffer());return{content:s,contentType:t?.contentType??o.headers.get("content-type")??"application/octet-stream",ETag:t?.ETag??o.headers.get("etag")??void 0,expiredAt:t?.expiredAt,id:e,metadata:t?.metadata??{},modifiedAt:t?.modifiedAt,name:t?.name??i,originalName:t?.originalName??i,size:t?.size??s.length}})}async copy(e,a,t){return this.instrumentOperation("copy",async()=>{const i=await this.get({id:e},t),n=new Blob([new Uint8Array(i.content)],{type:i.contentType}),o=new u([n],y(a),{customId:a,type:i.contentType}),s=await this.runOperation(t,()=>this.utapi.uploadFiles(o,{acl:this.acl}));if(s.error)throw new Error(s.error.message);const r=new d({contentType:i.contentType,metadata:{},originalName:a});return r.id=a,r.name=a,r.customId=a,r.size=typeof i.size=="string"?Number(i.size):i.size,r.ufsKey=s.data.key,r.url=s.data.ufsUrl??s.data.url,r.ETag=s.data.fileHash,r})}async move(e,a,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,a,t);return await this.delete({id:e},t),i})}async list(e=1e3,a){return this.instrumentOperation("list",async()=>(await this.runOperation(a,()=>this.utapi.listFiles({limit:e}))).files.map(t=>{const i=t.customId??t.key,n=new d({contentType:"application/octet-stream",metadata:{},originalName:i});return n.id=i,n.name=i,n.customId=t.customId??void 0,n.ufsKey=t.key,n.size=t.size,n.modifiedAt=t.uploadedAt?new Date(t.uploadedAt).toISOString():void 0,n}),{limit:e})}async getReadUrl(e,a){if(a?.responseContentDisposition!==void 0||a?.responseContentType!==void 0)return l(h.METHOD_NOT_ALLOWED,"UploadThing: `responseContentDisposition`/`responseContentType` are not supported — no override exists on UploadThing CDN/signed URLs.");if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(e)}`;const t=Math.min(a?.expiresIn??this.defaultUrlExpiresIn,f),{ufsUrl:i}=await this.utapi.generateSignedURL(e,{expiresIn:t,keyType:"customId"});return i}async getUploadUrl(e,a){return l(h.METHOD_NOT_ALLOWED,"UploadThing: presigned PUT URLs require the UFS ingest signing scheme — use the file-router pattern via `storage.raw` instead.")}async resolveFetchUrl(e,a){if(this.acl==="public-read")return`https://${this.appId}.ufs.sh/f/${encodeURIComponent(e)}`;const{ufsUrl:t}=await this.runOperation(a,()=>this.utapi.generateSignedURL(e,{expiresIn:this.defaultUrlExpiresIn,keyType:"customId"}));return t}internalOnComplete=e=>this.deleteMeta(e.id)}export{S as default};
@@ -0,0 +1 @@
1
+ class o extends Error{code;details;constructor(s,a,e,i,r,t){super(s),this.name="ValidationError",this.code=a,this.details={invalidParams:i,mediaType:e,suggestions:t,validParams:r}}}export{o as default};
@@ -0,0 +1 @@
1
+ import a from"./File-W8aOo15X.js";class o extends a{url;downloadUrl;pathname}export{o as default};
@@ -0,0 +1 @@
1
+ import{y as r}from"./local-meta-storage-C2T92TYb.js";class o extends r{constructor(e){super(e)}}export{o as default};
@@ -0,0 +1 @@
1
+ import{put as l,list as u,del as d,copy as h}from"@vercel/blob";import{a as y}from"./detect-file-type-BA7UBLKA.js";import{B as O,c as E}from"./storage-Cyy73Y6r.js";import{y as g}from"./local-meta-storage-C2T92TYb.js";import m from"./VercelBlobFile-CVQwKlZk.js";import{t as p}from"./get-file-status-y3wTtDQs.js";import{t as T}from"./update-size-DuNuLyxj.js";import{i as b}from"./part-match-D-9dGX42.js";import{e as v}from"./has-content-50BsqrWw.js";class f extends O{static name="vercel-blob";checksumTypes=["md5"];get raw(){return{copy:h,credentials:this.credentials,del:d,list:u,put:l}}meta;credentials;multipart;access;constructor(e){super(e),this.credentials=f.resolveCredentials(e),this.multipart=e.multipart??!1,this.access=e.access??"public";const{metaStorage:r,metaStorageConfig:t}=e;this.meta=r||new g(t),this.isReady=!0}static resolveCredentials(e){if(e.token)return{token:e.token};const r=e.oidcToken??process.env.VERCEL_OIDC_TOKEN,t=e.storeId??process.env.BLOB_STORE_ID,i=t?.startsWith("store_")?t.slice(6):t;if(r&&i)return{oidcToken:r,storeId:i};if(r||i)throw new Error(`Vercel Blob OIDC auth requires both \`oidcToken\` and \`storeId\` (or \`VERCEL_OIDC_TOKEN\` and \`BLOB_STORE_ID\` env vars). Got: oidcToken=${r?"set":"missing"}, storeId=${i?"set":"missing"}.`);const a=process.env.BLOB_READ_WRITE_TOKEN||process.env.VERCEL_BLOB_TOKEN;if(a)return{token:a};throw new Error("Vercel Blob credentials are required. Provide `token`, an `oidcToken`+`storeId` pair, or set BLOB_READ_WRITE_TOKEN / (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) env vars.")}async create(e,r){return this.instrumentOperation("create",async()=>{const t={...e};if(e.ttl){const a=typeof e.ttl=="string"?E(e.ttl):e.ttl;t.expiredAt=a===void 0?void 0:Date.now()+a}const i=new m(t);i.name=this.namingFunction(i),await this.validate(i);try{const a=await this.getMeta(i.id);if(a.bytesWritten>=0)return a}catch{}return i.bytesWritten=0,i.status=p(i),await this.saveMeta(i),await this.onCreate(i),i})}async write(e,r){return this.instrumentOperation("write",async()=>{let t;if("contentType"in e&&"metadata"in e&&!("body"in e)&&!("start"in e)?t=e:(t=await this.getMeta(e.id),await this.checkIfExpired(t)),t.status==="completed")return t;if(e.size!==void 0&&T(t,e.size),!b(e,t))throw new Error("File part does not match");const i=await this.lock(e.id);try{if(v(e)){if(this.isUnsupportedChecksum(e.checksumAlgorithm))throw new Error("Unsupported checksum algorithm");const a=[],n=e.body;for await(const o of n)a.push(Buffer.from(o));const s=Buffer.concat(a);if((t.bytesWritten===0||Number.isNaN(t.bytesWritten))&&(!t.contentType||t.contentType==="application/octet-stream"))try{const o=await y(s);o?.mime&&(t.contentType=o.mime)}catch{}const w=new Blob([s],{type:t.contentType}),c=await this.runOperation(r,()=>l(t.name,w,{access:this.access,multipart:this.shouldUseMultipart(t),...this.credentials}));t.url=c.url,t.pathname=c.pathname,t.downloadUrl=c.downloadUrl,t.bytesWritten=s.length}return t.status=p(t),t.status==="completed"&&await this.internalOnComplete(t),await this.saveMeta(t),t}finally{await this.unlock(e.id,i)}})}async delete({id:e},r){return this.instrumentOperation("delete",async()=>{const t=await this.getMeta(e);if(!t.url)throw new Error(`File ${e} does not have a valid URL`);const{url:i}=t;t.status="deleted";try{await this.runOperation(r,()=>d(i,{...this.credentials}))}catch(n){this.logger?.error("Failed to delete blob from Vercel Blob:",n);const s=this.normalizeError(n instanceof Error?n:new Error(String(n)));await this.onError(s)}await this.deleteMeta(t.id);const a={...t};return await this.onDelete(a),a})}async exists({id:e},r){return this.instrumentOperation("exists",async()=>{try{const t=await this.getMeta(e);if(!t.url||t.url.length===0)return!1;const{url:i}=t;return(await this.runOperation(r,()=>fetch(i,{method:"HEAD"}))).ok}catch{return!1}})}async get({id:e},r){return this.instrumentOperation("get",async()=>{const t=await this.checkIfExpired(await this.getMeta(e));if(!t.url||t.url.length===0)throw new Error("File URL not found");const{url:i}=t,a=await this.runOperation(r,()=>fetch(i)),n=Buffer.from(await this.runOperation(r,()=>a.arrayBuffer()));return{content:n,contentType:t.contentType,ETag:t.ETag,expiredAt:t.expiredAt,id:e,metadata:t.metadata,modifiedAt:t.modifiedAt,name:t.name,originalName:t.originalName,size:t.size||n.length}})}async copy(e,r,t){return this.instrumentOperation("copy",async()=>{const i=await this.getMeta(e);if(!i.url)throw new Error("Source file URL not found");const a=i.url,n=await this.runOperation(t,()=>h(a,r,{access:"public",...this.credentials}));return{...i,id:r,name:r,pathname:n.pathname,url:n.url}})}async move(e,r,t){return this.instrumentOperation("move",async()=>{const i=await this.copy(e,r,t);return await this.delete({id:e},t),i})}async list(e=1e3,r){return this.instrumentOperation("list",async()=>(await this.runOperation(r,()=>u({limit:e,...this.credentials}))).blobs.map(t=>{const i=new m({contentType:"application/octet-stream",metadata:{},originalName:t.pathname});return i.createdAt=t.uploadedAt?.toISOString(),i.id=t.pathname,i.modifiedAt=t.uploadedAt?.toISOString(),i.name=t.pathname,i.pathname=t.pathname,i.size=t.size,i.url=t.url,i.downloadUrl=t.downloadUrl,i}),{limit:e})}internalOnComplete=e=>this.deleteMeta(e.id);shouldUseMultipart(e){return typeof this.multipart=="boolean"?this.multipart:typeof this.multipart=="number"&&e.size!==void 0?e.size>=this.multipart:!1}}export{f as default};
@@ -0,0 +1 @@
1
+ function o(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}export{o as g};
@@ -0,0 +1 @@
1
+ import{tool as a}from"@openai/agents";import{r as c}from"./approval-fVHwBp7u.js";import{T as t,e as r,W as u}from"./executors-BDzMjc4y.js";const g=e=>a({description:t.listFiles.description,execute:i=>r.listFiles(e,i),name:"listFiles",parameters:t.listFiles.input}),m=e=>a({description:t.getFileMetadata.description,execute:i=>r.getFileMetadata(e,i),name:"getFileMetadata",parameters:t.getFileMetadata.input}),U=e=>a({description:t.downloadFile.description,execute:i=>r.downloadFile(e,i),name:"downloadFile",parameters:t.downloadFile.input}),A=e=>a({description:t.getFileUrl.description,execute:i=>r.getFileUrl(e,i),name:"getFileUrl",parameters:t.getFileUrl.input}),v=(e,{needsApproval:i=!0}={})=>a({description:t.uploadFile.description,execute:l=>r.uploadFile(e,l),name:"uploadFile",needsApproval:i,parameters:t.uploadFile.input}),f=(e,{needsApproval:i=!0}={})=>a({description:t.deleteFile.description,execute:l=>r.deleteFile(e,l),name:"deleteFile",needsApproval:i,parameters:t.deleteFile.input}),x=(e,{needsApproval:i=!0}={})=>a({description:t.copyFile.description,execute:l=>r.copyFile(e,l),name:"copyFile",needsApproval:i,parameters:t.copyFile.input}),O=(e,{needsApproval:i=!0}={})=>a({description:t.signUploadUrl.description,execute:l=>r.signUploadUrl(e,l),name:"signUploadUrl",needsApproval:i,parameters:t.signUploadUrl.input});function T({files:e,overrides:i,readOnly:l=!1,requireApproval:F=!0}){const p=o=>({needsApproval:c(o,F)}),s={copyFile:x(e,p("copyFile")),deleteFile:f(e,p("deleteFile")),downloadFile:U(e),getFileMetadata:m(e),getFileUrl:A(e),listFiles:g(e),signUploadUrl:O(e,p("signUploadUrl")),uploadFile:v(e,p("uploadFile"))};if(i){for(const[o,n]of Object.entries(i))if(o in s&&n){const d=o;Object.assign(s,{[d]:{...s[d],...n}})}}return l?Object.fromEntries(Object.entries(s).filter(([o])=>!u.has(o))):s}export{x as agentsCopyFile,f as agentsDeleteFile,U as agentsDownloadFile,m as agentsGetFileMetadata,A as agentsGetFileUrl,g as agentsListFiles,O as agentsSignUploadUrl,v as agentsUploadFile,T as createAgentsFileTools};
@@ -0,0 +1 @@
1
+ const o=e=>{const r=e?.accessKeyId??process.env.AWS_ACCESS_KEY_ID??process.env.AKAMAI_ACCESS_KEY_ID,c=e?.secretAccessKey??process.env.AWS_SECRET_ACCESS_KEY??process.env.AKAMAI_SECRET_ACCESS_KEY,s=e?.region??process.env.AKAMAI_REGION;if(!r||!c||!s)throw new Error("Missing required parameters for Akamai Cloud Object Storage client.");return{credentials:{accessKeyId:r,secretAccessKey:c},endpoint:e?.endpoint??`https://${s}.linodeobjects.com`,forcePathStyle:!1,region:s}};export{o as default};
@@ -0,0 +1 @@
1
+ const o=e=>{const r=e?.accessKeyId??process.env.AWS_ACCESS_KEY_ID??process.env.ALIBABA_ACCESS_KEY_ID,n=e?.endpoint??process.env.ALIBABA_ENDPOINT,s=e?.region??process.env.ALIBABA_REGION,c=e?.secretAccessKey??process.env.AWS_SECRET_ACCESS_KEY??process.env.ALIBABA_ACCESS_KEY_SECRET;if(!s||!r||!c)throw new Error("Missing required parameters for Alibaba Cloud OSS client.");return{credentials:{accessKeyId:r,secretAccessKey:c},endpoint:n??`https://s3.oss-${s}.aliyuncs.com`,forcePathStyle:!1,region:s}};export{o as default};
@@ -0,0 +1 @@
1
+ const e=(r,o)=>typeof o=="boolean"?o:o[r]??!0;export{e as r};