@visulima/storage 1.0.0-alpha.2 → 1.0.0-alpha.21

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 (307) hide show
  1. package/CHANGELOG.md +263 -0
  2. package/LICENSE.md +1256 -512
  3. package/README.md +4 -4
  4. package/dist/adapter/nuxt/module.d.ts +41 -34
  5. package/dist/adapter/nuxt/module.js +1 -93
  6. package/dist/handler/http/fetch/index.d.ts +297 -4
  7. package/dist/handler/http/fetch/index.js +1 -4
  8. package/dist/handler/http/hono/index.d.ts +1474 -58
  9. package/dist/handler/http/hono/index.js +1 -65
  10. package/dist/handler/http/nextjs/index.d.ts +66 -58
  11. package/dist/handler/http/nextjs/index.js +1 -37
  12. package/dist/handler/http/node/index.d.ts +361 -4
  13. package/dist/handler/http/node/index.js +1 -4
  14. package/dist/handler/http/solid-start/index.d.ts +66 -57
  15. package/dist/handler/http/solid-start/index.js +1 -44
  16. package/dist/index.d.ts +376 -17
  17. package/dist/index.js +1 -13
  18. package/dist/openapi/index.d.ts +24 -5
  19. package/dist/openapi/index.js +1 -5
  20. package/dist/packem_shared/AwsLightFile-BTLiRxXj.js +1 -0
  21. package/dist/packem_shared/AwsLightMetaStorage-DHz1nf_H.js +1 -0
  22. package/dist/packem_shared/AwsLightStorage-CA9cdfJ6.js +1 -0
  23. package/dist/packem_shared/AzureFile-BKHru1zB.js +1 -0
  24. package/dist/packem_shared/AzureSMetaStorage-BqA4jUDJ.js +1 -0
  25. package/dist/packem_shared/AzureStorage-BKUjCymW.js +1 -0
  26. package/dist/packem_shared/BaseTransformer-D68eLyz1.js +1 -0
  27. package/dist/packem_shared/DiskStorage-DNjpDMX9.js +1 -0
  28. package/dist/packem_shared/DiskStorageWithChecksum-Bb6JX_tC.js +1 -0
  29. package/dist/packem_shared/ERRORS-B9jkvKwx.js +1 -0
  30. package/dist/packem_shared/File-alcSNpLq.js +1 -0
  31. package/dist/packem_shared/GCSConfig-BQ0OpVhe.js +1 -0
  32. package/dist/packem_shared/GCSFile-CHjX_fJk.js +1 -0
  33. package/dist/packem_shared/GCSMetaStorage-BRDiGnC1.js +1 -0
  34. package/dist/packem_shared/GCStorage-BPkZ9tex.js +1 -0
  35. package/dist/packem_shared/LocalMetaStorage-BWuFvWn4.js +1 -0
  36. package/dist/packem_shared/MediaTransformer-2C8MJeAg.js +1 -0
  37. package/dist/packem_shared/MetaStorage-Y4m1dWgd.js +1 -0
  38. package/dist/packem_shared/Metadata-B6Ir0KO7.js +1 -0
  39. package/dist/packem_shared/Multipart-Bd9YFFn0.js +1 -0
  40. package/dist/packem_shared/Multipart-D5bcEvga.js +1 -0
  41. package/dist/packem_shared/NetlifyBlobFile-CpzkMKng.js +1 -0
  42. package/dist/packem_shared/NetlifyBlobMetaStorage-dD0oBLom.js +1 -0
  43. package/dist/packem_shared/NetlifyBlobStorage-ByTwCN-h.js +1 -0
  44. package/dist/packem_shared/NoOpMetrics-Dky06sf1.js +1 -0
  45. package/dist/packem_shared/OpenTelemetryMetrics-9uxQMSlg.js +1 -0
  46. package/dist/packem_shared/Rest-CYEBbtCD.js +1 -0
  47. package/dist/packem_shared/Rest-DoonVU7B.js +1 -0
  48. package/dist/packem_shared/S3Client.d-CZ62Jztg.d.ts +20357 -0
  49. package/dist/packem_shared/S3File-Du6wP0Sz.js +1 -0
  50. package/dist/packem_shared/S3MetaStorage-vcriiosn.js +1 -0
  51. package/dist/packem_shared/S3Storage-Fx6-OSc-.js +1 -0
  52. package/dist/packem_shared/TUS_RESUMABLE-B7KtPVeC.js +1 -0
  53. package/dist/packem_shared/Tus-Bd_2Ki2G.js +1 -0
  54. package/dist/packem_shared/Tus-CUBCkuPE.js +1 -0
  55. package/dist/packem_shared/ValidationError-D8KKJiKA.js +1 -0
  56. package/dist/packem_shared/VercelBlobFile-CL9MjKcY.js +1 -0
  57. package/dist/packem_shared/VercelBlobMetaStorage-BsOTx-Su.js +1 -0
  58. package/dist/packem_shared/VercelBlobStorage-kNkk5Cn4.js +1 -0
  59. package/dist/packem_shared/_commonjsHelpers-D6W6KoPK.js +1 -0
  60. package/dist/packem_shared/aws-light-meta-storage-TPyQwLvk.js +4 -0
  61. package/dist/packem_shared/backblaze-DEflv87m.js +1 -0
  62. package/dist/packem_shared/base-handler-core-DaggCVsq.js +1 -0
  63. package/dist/packem_shared/base-handler-fetch-DnarP64X.js +1 -0
  64. package/dist/packem_shared/base-handler-node-BTes6sql.js +1 -0
  65. package/dist/packem_shared/cache-qV_5Umeq.js +1 -0
  66. package/dist/packem_shared/cloudflare-DLAeQvgD.js +1 -0
  67. package/dist/packem_shared/defaultCloudStorageFileNameValidation-yiM9GxHr.js +1 -0
  68. package/dist/packem_shared/digitalOcean-nhZUds87.js +1 -0
  69. package/dist/packem_shared/disk-storage-BvdK4bqF.js +5 -0
  70. package/dist/packem_shared/disk-storage-with-checksum.d-CaMptIUg.d.ts +148 -0
  71. package/dist/packem_shared/gcs-meta-storage-DZMf4IHn.js +1 -0
  72. package/dist/packem_shared/has-content-Bx2p8Okx.js +1 -0
  73. package/dist/packem_shared/headers-DC2MEOrK.js +27 -0
  74. package/dist/packem_shared/is-expired-1JuZjDtb.js +1 -0
  75. package/dist/packem_shared/isRetryableError-DQNSZiBc.js +1 -0
  76. package/dist/packem_shared/isValidMediaType-B-2UKjZx.js +1 -0
  77. package/dist/packem_shared/local-meta-storage-Bkwqi_gi.js +1 -0
  78. package/dist/packem_shared/local-meta-storage.d-CGSVabni.d.ts +20 -0
  79. package/dist/packem_shared/media-transformer.d-CLxm_69K.d.ts +331 -0
  80. package/dist/packem_shared/minio-BWwgGXeE.js +1 -0
  81. package/dist/packem_shared/multipart-base-C6OjBwMS.js +1 -0
  82. package/dist/packem_shared/part-match-DqD5U7An.js +1 -0
  83. package/dist/packem_shared/path-D7rMc9nq-B718mbm6.js +1 -0
  84. package/dist/packem_shared/response-builder-Wdo_fvcF.js +1 -0
  85. package/dist/packem_shared/rest-base-B2Dv7esY.js +1 -0
  86. package/dist/packem_shared/restOpenApiSpec-PaIVbESh.js +1 -0
  87. package/dist/packem_shared/s3-base-storage-xHZNtsGe.js +1 -0
  88. package/dist/packem_shared/s3-base-storage.d-BkRmde_Q.d.ts +251 -0
  89. package/dist/packem_shared/sharedGet-Ce7WGAsc.js +1 -0
  90. package/dist/packem_shared/storage-m_Cxgiih.js +1 -0
  91. package/dist/packem_shared/storage.d-Cxs42eEK.d.ts +939 -0
  92. package/dist/packem_shared/tigris-DZoyrMNd.js +1 -0
  93. package/dist/packem_shared/transformOpenApiSpec-C0vEbDTO.js +1 -0
  94. package/dist/packem_shared/tus-base.d-dim7udrK.d.ts +99 -0
  95. package/dist/packem_shared/tusOpenApiSpec-DF0-hlWV.js +1 -0
  96. package/dist/packem_shared/types.d-76N78ehR.d.ts +708 -0
  97. package/dist/packem_shared/types.d-LqXtPPaF.d.ts +49 -0
  98. package/dist/packem_shared/update-size-DANV7aa2.js +1 -0
  99. package/dist/packem_shared/validator-DK41xp8N.js +1 -0
  100. package/dist/packem_shared/waitForStorage-ChSBLhLc.js +1 -0
  101. package/dist/packem_shared/wasabi-Dmce4x9s.js +1 -0
  102. package/dist/packem_shared/xhrOpenApiSpec-nyoboz83.js +1 -0
  103. package/dist/storage/aws/clients/index.d.ts +166 -6
  104. package/dist/storage/aws/clients/index.js +1 -6
  105. package/dist/storage/aws/index.d.ts +320 -4
  106. package/dist/storage/aws/index.js +1 -3
  107. package/dist/storage/aws-light/index.d.ts +252 -4
  108. package/dist/storage/aws-light/index.js +1 -3
  109. package/dist/storage/azure/index.d.ts +10422 -4
  110. package/dist/storage/azure/index.js +1 -3
  111. package/dist/storage/gcs/index.d.ts +4107 -5
  112. package/dist/storage/gcs/index.js +1 -4
  113. package/dist/storage/local/index.d.ts +7 -4
  114. package/dist/storage/local/index.js +1 -3
  115. package/dist/storage/netlify-blob/index.d.ts +142 -4
  116. package/dist/storage/netlify-blob/index.js +1 -3
  117. package/dist/storage/vercel-blob/index.d.ts +129 -4
  118. package/dist/storage/vercel-blob/index.js +1 -3
  119. package/dist/transformer/audio-transformer.d.ts +127 -125
  120. package/dist/transformer/audio-transformer.js +1 -278
  121. package/dist/transformer/image-transformer.d.ts +569 -568
  122. package/dist/transformer/image-transformer.js +1 -1100
  123. package/dist/transformer/index.d.ts +62 -5
  124. package/dist/transformer/index.js +1 -4
  125. package/dist/transformer/video-transformer.d.ts +144 -142
  126. package/dist/transformer/video-transformer.js +1 -310
  127. package/package.json +45 -45
  128. package/dist/handler/base/base-handler-core.d.ts +0 -91
  129. package/dist/handler/base/base-handler-fetch.d.ts +0 -76
  130. package/dist/handler/base/base-handler-node.d.ts +0 -137
  131. package/dist/handler/multipart/multipart-base.d.ts +0 -84
  132. package/dist/handler/multipart/multipart-fetch.d.ts +0 -64
  133. package/dist/handler/multipart/multipart.d.ts +0 -49
  134. package/dist/handler/rest/rest-base.d.ts +0 -106
  135. package/dist/handler/rest/rest-fetch.d.ts +0 -88
  136. package/dist/handler/rest/rest.d.ts +0 -93
  137. package/dist/handler/tus/tus-base.d.ts +0 -152
  138. package/dist/handler/tus/tus-fetch.d.ts +0 -72
  139. package/dist/handler/tus/tus.d.ts +0 -78
  140. package/dist/handler/types.d.ts +0 -53
  141. package/dist/handler/utils/request-parser.d.ts +0 -72
  142. package/dist/handler/utils/response-builder.d.ts +0 -83
  143. package/dist/handler/utils/storage-utils.d.ts +0 -10
  144. package/dist/handler/utils/stream-utils.d.ts +0 -29
  145. package/dist/handler/utils/upload-handlers.d.ts +0 -76
  146. package/dist/metrics/index.d.ts +0 -2
  147. package/dist/metrics/no-op-metrics.d.ts +0 -15
  148. package/dist/metrics/opentelemetry-metrics.d.ts +0 -55
  149. package/dist/openapi/rest.d.ts +0 -7
  150. package/dist/openapi/shared.d.ts +0 -13
  151. package/dist/openapi/transform.d.ts +0 -3
  152. package/dist/openapi/tus.d.ts +0 -7
  153. package/dist/openapi/xhr.d.ts +0 -7
  154. package/dist/packem_shared/AwsLightFile-tTneXZgG.js +0 -11
  155. package/dist/packem_shared/AwsLightMetaStorage-BWSOtVaN.js +0 -4
  156. package/dist/packem_shared/AwsLightStorage-Cwkkc-z3.js +0 -133
  157. package/dist/packem_shared/AzureFile-CesgFzps.js +0 -8
  158. package/dist/packem_shared/AzureSMetaStorage-CFs-OYJT.js +0 -88
  159. package/dist/packem_shared/AzureStorage-9MoV2W8q.js +0 -357
  160. package/dist/packem_shared/BaseTransformer-C2gLib6v.js +0 -82
  161. package/dist/packem_shared/DiskStorage-CJtTzMQ3.js +0 -12
  162. package/dist/packem_shared/DiskStorageWithChecksum-BgrG8pvC.js +0 -238
  163. package/dist/packem_shared/ERRORS-D0apMqnc.js +0 -97
  164. package/dist/packem_shared/File-Bb3P23dr.js +0 -69
  165. package/dist/packem_shared/GCSConfig-vPP22kN6.js +0 -11
  166. package/dist/packem_shared/GCSFile-BIEunhAN.js +0 -8
  167. package/dist/packem_shared/GCSMetaStorage-sYiSjLUx.js +0 -7
  168. package/dist/packem_shared/GCStorage-DPl1_DAm.js +0 -406
  169. package/dist/packem_shared/LocalMetaStorage-CZHhKkMd.js +0 -7
  170. package/dist/packem_shared/MediaTransformer-D6658DL1.js +0 -1197
  171. package/dist/packem_shared/MetaStorage-pECeFOad.js +0 -46
  172. package/dist/packem_shared/Metadata-DRLXeJ0F.js +0 -89
  173. package/dist/packem_shared/Multipart-CNFK_Okz.js +0 -163
  174. package/dist/packem_shared/Multipart-CtUL7BQw.js +0 -128
  175. package/dist/packem_shared/NetlifyBlobFile-CXzyjqrD.js +0 -14
  176. package/dist/packem_shared/NetlifyBlobMetaStorage-DxZ5aDvD.js +0 -9
  177. package/dist/packem_shared/NetlifyBlobStorage-C6AX-X0P.js +0 -376
  178. package/dist/packem_shared/NoOpMetrics-DhAk5rXc.js +0 -10
  179. package/dist/packem_shared/OpenTelemetryMetrics-BnxhqIaH.js +0 -67
  180. package/dist/packem_shared/Rest-CAOAEkOj.js +0 -267
  181. package/dist/packem_shared/Rest-DNuLwBrK.js +0 -228
  182. package/dist/packem_shared/S3File-DZiyk9Qt.js +0 -11
  183. package/dist/packem_shared/S3MetaStorage-Dz9aDabA.js +0 -76
  184. package/dist/packem_shared/S3Storage-CgheE2yH.js +0 -316
  185. package/dist/packem_shared/TUS_RESUMABLE-GJzZ9R-f.js +0 -434
  186. package/dist/packem_shared/Tus-B8PmlMgR.js +0 -200
  187. package/dist/packem_shared/Tus-C4F1aYOl.js +0 -195
  188. package/dist/packem_shared/ValidationError-BfF1aE4h.js +0 -26
  189. package/dist/packem_shared/VercelBlobFile-BCg4aTEq.js +0 -18
  190. package/dist/packem_shared/VercelBlobMetaStorage-Bd9F-VFm.js +0 -9
  191. package/dist/packem_shared/VercelBlobStorage-BbuEYhOz.js +0 -261
  192. package/dist/packem_shared/_commonjsHelpers-B85MJLTf.js +0 -5
  193. package/dist/packem_shared/aws-light-meta-storage-DKJBgbR6.js +0 -446
  194. package/dist/packem_shared/backblaze-BlMnIcBC.js +0 -20
  195. package/dist/packem_shared/base-handler-core-BKuf4YLT.js +0 -303
  196. package/dist/packem_shared/base-handler-fetch-Cr0hLiqg.js +0 -291
  197. package/dist/packem_shared/base-handler-node-gk5aN9Cx.js +0 -730
  198. package/dist/packem_shared/cache-B88MXQ_2.js +0 -18
  199. package/dist/packem_shared/cloudflare-Bi1q8wXE.js +0 -21
  200. package/dist/packem_shared/defaultCloudStorageFileNameValidation-oVDgf-Sw.js +0 -11
  201. package/dist/packem_shared/digitalOcean-CWQRJM3L.js +0 -21
  202. package/dist/packem_shared/disk-storage-DkDoHnKB.js +0 -810
  203. package/dist/packem_shared/gcs-meta-storage-etw4wuh5.js +0 -158
  204. package/dist/packem_shared/has-content-CY66ehMK.js +0 -3
  205. package/dist/packem_shared/headers-DoS5nwM-.js +0 -3220
  206. package/dist/packem_shared/is-expired-CTThU1q5.js +0 -8
  207. package/dist/packem_shared/isRetryableError-Dycp7127.js +0 -82
  208. package/dist/packem_shared/isValidMediaType-BeDgiObq.js +0 -35
  209. package/dist/packem_shared/local-meta-storage-By-3SNBI.js +0 -649
  210. package/dist/packem_shared/minio-C2YBZQOw.js +0 -22
  211. package/dist/packem_shared/multipart-base-B3i67SSX.js +0 -102
  212. package/dist/packem_shared/part-match-BMNqHDYD.js +0 -96
  213. package/dist/packem_shared/path-CR6YkPXX-7R1-9CMk.js +0 -161
  214. package/dist/packem_shared/response-builder-BtnRiBUI.js +0 -45
  215. package/dist/packem_shared/rest-base-GRCcnan7.js +0 -457
  216. package/dist/packem_shared/restOpenApiSpec-CwcHHY2C.js +0 -800
  217. package/dist/packem_shared/s3-base-storage-xw6NJFX7.js +0 -510
  218. package/dist/packem_shared/sharedGet-Cpo7QUyu.js +0 -1019
  219. package/dist/packem_shared/storage-BwdYUHs3.js +0 -864
  220. package/dist/packem_shared/tigris-Hac8TKnX.js +0 -21
  221. package/dist/packem_shared/transformOpenApiSpec-DWM5WtnN.js +0 -975
  222. package/dist/packem_shared/tusOpenApiSpec-6ohiToBy.js +0 -740
  223. package/dist/packem_shared/update-size-CCGm6i1J.js +0 -8
  224. package/dist/packem_shared/validator-BeX_lJet.js +0 -78
  225. package/dist/packem_shared/waitForStorage-Cscw85sx.js +0 -18
  226. package/dist/packem_shared/wasabi-DIyflHSd.js +0 -21
  227. package/dist/packem_shared/xhrOpenApiSpec-DS17brnx.js +0 -264
  228. package/dist/storage/aws/clients/backblaze.d.ts +0 -12
  229. package/dist/storage/aws/clients/cloudflare.d.ts +0 -13
  230. package/dist/storage/aws/clients/digital-ocean.d.ts +0 -12
  231. package/dist/storage/aws/clients/minio.d.ts +0 -13
  232. package/dist/storage/aws/clients/tigris.d.ts +0 -12
  233. package/dist/storage/aws/clients/types.d.ts +0 -95
  234. package/dist/storage/aws/clients/wasabi.d.ts +0 -12
  235. package/dist/storage/aws/s3-base-storage.d.ts +0 -248
  236. package/dist/storage/aws/s3-client-adapter.d.ts +0 -110
  237. package/dist/storage/aws/s3-file.d.ts +0 -10
  238. package/dist/storage/aws/s3-meta-storage.d.ts +0 -15
  239. package/dist/storage/aws/s3-storage.d.ts +0 -70
  240. package/dist/storage/aws/types.d.ts +0 -119
  241. package/dist/storage/aws-light/aws-light-api-adapter.d.ts +0 -130
  242. package/dist/storage/aws-light/aws-light-file.d.ts +0 -10
  243. package/dist/storage/aws-light/aws-light-meta-storage.d.ts +0 -19
  244. package/dist/storage/aws-light/aws-light-storage.d.ts +0 -65
  245. package/dist/storage/aws-light/types.d.ts +0 -37
  246. package/dist/storage/azure/azure-file.d.ts +0 -6
  247. package/dist/storage/azure/azure-meta-storage.d.ts +0 -15
  248. package/dist/storage/azure/azure-storage.d.ts +0 -69
  249. package/dist/storage/azure/types.d.ts +0 -62
  250. package/dist/storage/gcs/fetch-error.d.ts +0 -11
  251. package/dist/storage/gcs/gcs-config.d.ts +0 -2
  252. package/dist/storage/gcs/gcs-file.d.ts +0 -6
  253. package/dist/storage/gcs/gcs-meta-storage.d.ts +0 -27
  254. package/dist/storage/gcs/gcs-storage.d.ts +0 -91
  255. package/dist/storage/gcs/types.d.ts +0 -55
  256. package/dist/storage/gcs/utils.d.ts +0 -7
  257. package/dist/storage/local/disk-storage-with-checksum.d.ts +0 -15
  258. package/dist/storage/local/disk-storage.d.ts +0 -135
  259. package/dist/storage/local/local-meta-storage.d.ts +0 -32
  260. package/dist/storage/meta-storage.d.ts +0 -30
  261. package/dist/storage/netlify-blob/netlify-blob-file.d.ts +0 -12
  262. package/dist/storage/netlify-blob/netlify-blob-meta-storage.d.ts +0 -7
  263. package/dist/storage/netlify-blob/netlify-blob-storage.d.ts +0 -93
  264. package/dist/storage/netlify-blob/types.d.ts +0 -30
  265. package/dist/storage/storage.d.ts +0 -353
  266. package/dist/storage/types.d.ts +0 -221
  267. package/dist/storage/utils/file/file.d.ts +0 -25
  268. package/dist/storage/utils/file/get-file-status.d.ts +0 -9
  269. package/dist/storage/utils/file/has-content.d.ts +0 -9
  270. package/dist/storage/utils/file/index.d.ts +0 -10
  271. package/dist/storage/utils/file/is-expired.d.ts +0 -8
  272. package/dist/storage/utils/file/metadata.d.ts +0 -18
  273. package/dist/storage/utils/file/part-match.d.ts +0 -11
  274. package/dist/storage/utils/file/types.d.ts +0 -37
  275. package/dist/storage/utils/file/update-metadata.d.ts +0 -10
  276. package/dist/storage/utils/file/update-size.d.ts +0 -10
  277. package/dist/storage/vercel-blob/types.d.ts +0 -32
  278. package/dist/storage/vercel-blob/vercel-blob-file.d.ts +0 -16
  279. package/dist/storage/vercel-blob/vercel-blob-meta-storage.d.ts +0 -7
  280. package/dist/storage/vercel-blob/vercel-blob-storage.d.ts +0 -76
  281. package/dist/transformer/base-transformer.d.ts +0 -63
  282. package/dist/transformer/media-transformer.d.ts +0 -332
  283. package/dist/transformer/types.d.ts +0 -652
  284. package/dist/transformer/utils.d.ts +0 -33
  285. package/dist/transformer/validation-error.d.ts +0 -23
  286. package/dist/utils/cache.d.ts +0 -32
  287. package/dist/utils/chunked-upload.d.ts +0 -65
  288. package/dist/utils/detect-file-type.d.ts +0 -28
  289. package/dist/utils/errors.d.ts +0 -74
  290. package/dist/utils/file-path-url-matcher.d.ts +0 -18
  291. package/dist/utils/headers.d.ts +0 -111
  292. package/dist/utils/http.d.ts +0 -92
  293. package/dist/utils/locker.d.ts +0 -26
  294. package/dist/utils/pipes/stream-checksum.d.ts +0 -47
  295. package/dist/utils/pipes/stream-length.d.ts +0 -22
  296. package/dist/utils/primitives/get-last-one.d.ts +0 -3
  297. package/dist/utils/primitives/is-record.d.ts +0 -2
  298. package/dist/utils/primitives/map-values.d.ts +0 -9
  299. package/dist/utils/primitives/pick.d.ts +0 -2
  300. package/dist/utils/primitives/to-milliseconds.d.ts +0 -12
  301. package/dist/utils/primitives/to-seconds.d.ts +0 -12
  302. package/dist/utils/range-checksum.d.ts +0 -33
  303. package/dist/utils/range-hasher.d.ts +0 -46
  304. package/dist/utils/retry.d.ts +0 -64
  305. package/dist/utils/types.d.ts +0 -108
  306. package/dist/utils/validation-error.d.ts +0 -22
  307. package/dist/utils/validator.d.ts +0 -36
@@ -0,0 +1,939 @@
1
+ import { Transform, Readable } from 'node:stream';
2
+ import { BinaryToTextEncoding, Hash } from 'node:crypto';
3
+ import { IncomingMessage } from 'node:http';
4
+ import { LRUCache } from 'lru-cache';
5
+ /**
6
+ * Transform that computes a rolling checksum for a stream while passing
7
+ * data through unchanged.
8
+ */
9
+ interface RangeChecksum extends Transform {
10
+ /** Return the current digest in the selected encoding. */
11
+ digest: (encoding: BinaryToTextEncoding) => string;
12
+ hash: Hash;
13
+ path: string;
14
+ reset: () => void;
15
+ }
16
+ /**
17
+ * LRU-backed map of rolling hashers keyed by file path. Used to compute
18
+ * hex/base64 digests and resume hashing from an offset.
19
+ */
20
+ interface RangeHasher extends LRUCache<string, Hash> {
21
+ algorithm: "md5" | "sha1";
22
+ base64: (path: string) => string;
23
+ digester: (path: string) => RangeChecksum;
24
+ hex: (path: string) => string;
25
+ init: (path: string, start: number) => Promise<Hash>;
26
+ updateFromFs: (path: string, start: number, initial?: Hash) => Promise<Hash>;
27
+ }
28
+ /**
29
+ * Normalized HTTP error payload returned by handlers and storage backends.
30
+ */
31
+ interface HttpErrorBody {
32
+ code: string;
33
+ detail?: Record<string, unknown> | string;
34
+ message: string;
35
+ name?: string;
36
+ retryable?: boolean;
37
+ UploadErrorCode?: string;
38
+ }
39
+ /**
40
+ * Rich HTTP error including status code and optional headers/body.
41
+ */
42
+ interface HttpError<T = HttpErrorBody> extends UploadResponse<T> {
43
+ statusCode: number;
44
+ }
45
+ /**
46
+ * Node.js IncomingMessage with an optional parsed body attached.
47
+ */
48
+ interface IncomingMessageWithBody<T = unknown> extends IncomingMessage {
49
+ _body?: boolean;
50
+ body?: T;
51
+ }
52
+ type Header = string[] | number | string;
53
+ type Headers = Record<string, Header>;
54
+ type ResponseBody = Record<string, unknown> | string | Buffer | Uint8Array;
55
+ type ResponseBodyType = "json" | "text";
56
+ /**
57
+ * Tuple form for quick response definitions: [status, body, headers].
58
+ */
59
+ type ResponseTuple<T = ResponseBody> = [statusCode: number, body?: T, headers?: Headers];
60
+ /**
61
+ * Structured response used across handlers and storage operations.
62
+ */
63
+ interface UploadResponse<T = ResponseBody> extends Record<string, unknown> {
64
+ body?: T;
65
+ headers?: Headers;
66
+ statusCode?: number;
67
+ }
68
+ /**
69
+ * Declarative validator configuration for a single rule.
70
+ */
71
+ interface ValidatorConfig<T> {
72
+ isValid?: (t: T) => Promise<boolean> | boolean;
73
+ response?: HttpError | ResponseTuple;
74
+ value?: unknown;
75
+ }
76
+ /** Map of rule-name -> validator configuration. */
77
+ type Validation<T> = Record<string, ValidatorConfig<T>>;
78
+ /** Narrowed error response shape for validation failures. */
79
+ interface ValidationError extends HttpError {
80
+ code: string;
81
+ }
82
+ /**
83
+ * Metrics interface for observability.
84
+ * Provides counters, timers, and gauges for tracking storage operations.
85
+ */
86
+ interface Metrics {
87
+ /**
88
+ * Set a gauge metric value.
89
+ * @param name Metric name (e.g., "storage.files.size")
90
+ * @param value Gauge value
91
+ * @param attributes Optional attributes/labels
92
+ */
93
+ gauge: (name: string, value: number, attributes?: Record<string, string | number>) => void;
94
+ /**
95
+ * Increment a counter metric.
96
+ * @param name Metric name (e.g., "storage.operations.create.count")
97
+ * @param value Increment value (default: 1)
98
+ * @param attributes Optional attributes/labels (e.g., { storage: "s3", operation: "create" })
99
+ */
100
+ increment: (name: string, value?: number, attributes?: Record<string, string | number>) => void;
101
+ /**
102
+ * Record a duration/timing metric in milliseconds.
103
+ * @param name Metric name (e.g., "storage.operations.write.duration")
104
+ * @param duration Duration in milliseconds
105
+ * @param attributes Optional attributes/labels
106
+ */
107
+ timing: (name: string, duration: number, attributes?: Record<string, string | number>) => void;
108
+ }
109
+ /**
110
+ * Canonical error codes used across handlers and storage adapters.
111
+ * These codes map to standardized HTTP status codes and error messages.
112
+ */
113
+ declare enum ERRORS {
114
+ BAD_REQUEST = "BadRequest",
115
+ CHECKSUM_MISMATCH = "ChecksumMismatch",
116
+ FILE_CONFLICT = "FileConflict",
117
+ FILE_ERROR = "FileError",
118
+ FILE_LOCKED = "FileLocked",
119
+ FILE_NOT_ALLOWED = "FileNotAllowed",
120
+ FILE_NOT_FOUND = "FileNotFound",
121
+ FORBIDDEN = "Forbidden",
122
+ GONE = "Gone",
123
+ INVALID_FILE_NAME = "InvalidFileName",
124
+ INVALID_FILE_SIZE = "InvalidFileSize",
125
+ INVALID_RANGE = "InvalidRange",
126
+ INVALID_TYPE = "Invalidtype",
127
+ METHOD_NOT_ALLOWED = "MethodNotAllowed",
128
+ REQUEST_ABORTED = "RequestAborted",
129
+ REQUEST_ENTITY_TOO_LARGE = "RequestEntityTooLarge",
130
+ STORAGE_BUSY = "StorageBusy",
131
+ STORAGE_ERROR = "StorageError",
132
+ TOO_MANY_REQUESTS = "TooManyRequests",
133
+ UNKNOWN_ERROR = "UnknownError",
134
+ UNPROCESSABLE_ENTITY = "UnprocessableEntity",
135
+ UNSUPPORTED_CHECKSUM_ALGORITHM = "UnsupportedChecksumAlgorithm",
136
+ UNSUPPORTED_MEDIA_TYPE = "UnsupportedMediaType",
137
+ }
138
+ /**
139
+ * Type mapping of error codes to standardized HTTP error responses.
140
+ * @template T - The error code type (defaults to string)
141
+ */
142
+ type ErrorResponses<T extends string = string> = { [K in T]: HttpError };
143
+ /**
144
+ * Mapping of error codes to HttpError response objects.
145
+ * @returns Map of error codes to standardized HTTP error responses
146
+ */
147
+ declare const ErrorMap: ErrorResponses<ERRORS>;
148
+ /**
149
+ * Error subclass carrying a stable error code and optional detail.
150
+ * Provides structured error information for upload operations.
151
+ */
152
+ declare class UploadError extends Error {
153
+ override name: string;
154
+ /** The standardized error code from the ERRORS enum */
155
+ UploadErrorCode: ERRORS;
156
+ /** Optional additional error details */
157
+ detail?: unknown;
158
+ /**
159
+ * Creates a new UploadError instance.
160
+ * @param code Standardized error code (defaults to UNKNOWN_ERROR)
161
+ * @param message Human-readable error message (defaults to the code)
162
+ * @param detail Optional additional error details
163
+ */
164
+ constructor(code?: ERRORS, message?: string, detail?: unknown);
165
+ }
166
+ /**
167
+ * Type guard to check if an error is an UploadError instance.
168
+ * @param error Error to check
169
+ * @returns True if the error is an UploadError with a valid error code
170
+ */
171
+ declare const isUploadError: (error: unknown) => error is UploadError;
172
+ /**
173
+ * Convenience function to throw an UploadError from a string error code.
174
+ * Looks up the appropriate error message from ErrorMap.
175
+ * @param UploadErrorCode String error code to convert to UploadError
176
+ * @param detail Optional additional error details
177
+ * @throws UploadError with the specified code and message
178
+ */
179
+ declare const throwErrorCode: (UploadErrorCode: ERRORS | string, detail?: string) => never;
180
+ interface MetaStorageOptions {
181
+ logger?: Console;
182
+ prefix?: string;
183
+ suffix?: string;
184
+ }
185
+ interface LocalMetaStorageOptions extends MetaStorageOptions {
186
+ /**
187
+ * Where the upload metadata should be stored
188
+ */
189
+ directory?: string;
190
+ }
191
+ declare class Metadata {
192
+ [key: string]: unknown;
193
+ psize?: number | string;
194
+ pname?: string;
195
+ pfiletype?: string;
196
+ ptype?: string;
197
+ pmimeType?: string;
198
+ pcontentType?: string;
199
+ ptitle?: string;
200
+ pfilename?: string;
201
+ poriginalName?: string;
202
+ plastModified?: number | string;
203
+ }
204
+ interface FileInit {
205
+ contentType?: string;
206
+ expiredAt?: Date | number | string;
207
+ metadata: Metadata;
208
+ originalName?: string;
209
+ size?: number | string;
210
+ storageClass?: string;
211
+ ttl?: number | string;
212
+ }
213
+ interface FileReturn extends Omit<Required<FileInit>, "storageClass" | "ttl" | "expiredAt"> {
214
+ content: Buffer;
215
+ ETag?: string;
216
+ expiredAt?: Date | number | string;
217
+ id: string;
218
+ modifiedAt?: Date | number | string;
219
+ name: string;
220
+ storageClass?: string;
221
+ }
222
+ type UploadEventTypeValue = "completed" | "created" | "deleted" | "part" | "updated";
223
+ type UploadEventType = UploadEventTypeValue;
224
+ interface FileQuery {
225
+ id: string;
226
+ name?: string;
227
+ size?: number;
228
+ }
229
+ interface Checksum {
230
+ checksum?: string;
231
+ checksumAlgorithm?: string;
232
+ }
233
+ interface FilePart extends Checksum, FileQuery {
234
+ body: Readable;
235
+ contentLength?: number;
236
+ start: number;
237
+ }
238
+ type DateType = Date | number | string;
239
+ declare class File implements FileInit {
240
+ bytesWritten: number;
241
+ contentType: string;
242
+ originalName: string;
243
+ id: string;
244
+ metadata: Metadata;
245
+ name: string;
246
+ size?: number;
247
+ status?: UploadEventType;
248
+ expiredAt?: DateType;
249
+ createdAt?: DateType;
250
+ modifiedAt?: DateType;
251
+ hash?: {
252
+ algorithm: string;
253
+ value: string;
254
+ };
255
+ content?: Buffer;
256
+ ETag?: string;
257
+ constructor({
258
+ contentType,
259
+ expiredAt,
260
+ metadata,
261
+ originalName,
262
+ size
263
+ }: FileInit);
264
+ }
265
+ type UploadFile = Readonly<File>;
266
+ /**
267
+ * Stores upload metadata.
268
+ */
269
+ declare class MetaStorage<T extends File = File> {
270
+ prefix: string;
271
+ suffix: string;
272
+ protected readonly logger?: Console;
273
+ constructor(config?: MetaStorageOptions);
274
+ /**
275
+ * Saves upload metadata.
276
+ */
277
+ save(_id: string, file: T): Promise<T>;
278
+ /**
279
+ * Deletes an upload metadata.
280
+ */
281
+ delete(_id: string): Promise<void>;
282
+ /**
283
+ * Retrieves upload metadata.
284
+ */
285
+ get(_id: string): Promise<T>;
286
+ /**
287
+ * Marks upload active.
288
+ */
289
+ touch(_id: string, _file: T): Promise<T>;
290
+ getMetaName(id: string): string;
291
+ getIdFromMetaName(name: string): string;
292
+ }
293
+ /**
294
+ * Simple cache interface that any cache implementation can follow
295
+ */
296
+ interface Cache<K = string, V = unknown> {
297
+ /** Clear all cache entries */
298
+ clear: () => void | Promise<void>;
299
+ /** Delete a value from cache */
300
+ delete: (key: K) => boolean | Promise<boolean>;
301
+ /** Get a value from cache */
302
+ get: (key: K) => V | undefined | Promise<V | undefined>;
303
+ /** Check if a key exists in cache */
304
+ has: (key: K) => boolean | Promise<boolean>;
305
+ /** Set a value in cache */
306
+ set: (key: K, value: V, options?: CacheOptions) => boolean | Promise<boolean>;
307
+ }
308
+ /**
309
+ * Options for cache operations
310
+ */
311
+ interface CacheOptions {
312
+ /** TTL in milliseconds */
313
+ ttl?: number;
314
+ }
315
+ /**
316
+ * A simple lock map keyed by strings, backed by LRUCache. Locks
317
+ * automatically expire according to the configured TTL preventing deadlocks.
318
+ */
319
+ declare class Locker<K extends string = string, V extends string = string> extends LRUCache<K, V, number> {
320
+ /**
321
+ * Creates a new Locker instance with configurable TTL and cache options.
322
+ * @param options LRU cache configuration options
323
+ */
324
+ constructor(options?: LRUCache.Options<K, V, number>);
325
+ /**
326
+ * Acquires a lock for the specified key.
327
+ * Throws an error if the key is already locked.
328
+ * @param key The key to lock
329
+ * @returns The lock token (same as the key)
330
+ * @throws Error if the key is already locked
331
+ */
332
+ lock(key: K): string;
333
+ /**
334
+ * Releases the lock for the specified key.
335
+ * @param key The key to unlock
336
+ */
337
+ unlock(key: K): void;
338
+ }
339
+ /**
340
+ * Configurable validation system for file upload constraints.
341
+ * Supports multiple validation rules with custom error responses.
342
+ * @template T - The type being validated
343
+ */
344
+ declare class Validator<T> {
345
+ private prefix;
346
+ private validators;
347
+ /**
348
+ * Creates a new Validator instance.
349
+ * @param prefix Prefix for generated error codes (default: "ValidationError")
350
+ */
351
+ constructor(prefix?: string);
352
+ /**
353
+ * Adds validation rules to the validator.
354
+ * Each rule must include an `isValid` function.
355
+ * @param config Validation configuration object
356
+ * @throws TypeError if any validator is missing the isValid function
357
+ */
358
+ add(config: Validation<T>): void;
359
+ /**
360
+ * Verifies an object against all configured validation rules.
361
+ * Throws ValidationError on first validation failure.
362
+ * @param t Object to validate
363
+ * @throws ValidationError if validation fails
364
+ */
365
+ verify(t: T): Promise<never | void>;
366
+ }
367
+ /**
368
+ * Retry configuration options for storage operations
369
+ */
370
+ interface RetryConfig {
371
+ /**
372
+ * Multiplier for exponential backoff (e.g., 2 means delays double each retry)
373
+ * @default 2
374
+ */
375
+ backoffMultiplier?: number;
376
+ /**
377
+ * Custom function to calculate delay for a specific retry attempt
378
+ * @param attempt The current retry attempt (0-indexed)
379
+ * @param error The error that occurred
380
+ * @returns Delay in milliseconds, or undefined to use default exponential backoff
381
+ */
382
+ calculateDelay?: (attempt: number, error: unknown) => number | undefined;
383
+ /**
384
+ * Initial delay in milliseconds before first retry
385
+ * @default 1000
386
+ */
387
+ initialDelay?: number;
388
+ /**
389
+ * Maximum delay in milliseconds between retries
390
+ * @default 30000
391
+ */
392
+ maxDelay?: number;
393
+ /**
394
+ * Maximum number of retry attempts
395
+ * @default 3
396
+ */
397
+ maxRetries?: number;
398
+ /**
399
+ * HTTP status codes that should trigger a retry
400
+ * @default [408, 429, 500, 502, 503, 504]
401
+ */
402
+ retryableStatusCodes?: number[];
403
+ /**
404
+ * Custom function to determine if an error should be retried
405
+ * @param error The error that occurred
406
+ * @returns true if the error should be retried, false otherwise
407
+ */
408
+ shouldRetry?: (error: unknown) => boolean;
409
+ }
410
+ /**
411
+ * Determines if an error is retryable based on common patterns
412
+ * @param error The error to check
413
+ * @param retryableStatusCodes HTTP status codes that should trigger retry
414
+ * @returns true if the error is retryable
415
+ */
416
+ declare const isRetryableError: (error: unknown, retryableStatusCodes?: number[]) => boolean;
417
+ /**
418
+ * Retry an async operation with exponential backoff
419
+ * @param fn The async function to retry
420
+ * @param config Retry configuration
421
+ * @returns The result of the function
422
+ * @throws The last error if all retries are exhausted
423
+ */
424
+ declare const retry: <T>(function_: () => Promise<T>, config?: RetryConfig) => Promise<T>;
425
+ /**
426
+ * Create a retry wrapper function with pre-configured settings.
427
+ * @param config Retry configuration
428
+ * @returns A function that wraps async operations with retry logic
429
+ */
430
+ declare const createRetryWrapper: (config?: RetryConfig) => <T>(function_: () => Promise<T>) => Promise<T>;
431
+ type OnCreate<TFile extends File = File> = (file: TFile) => Promise<void> | void;
432
+ type OnUpdate<TFile extends File = File> = (file: TFile) => Promise<void> | void;
433
+ type OnComplete<TFile extends File = File, TResponse = unknown, TRequest = unknown> = (file: TFile, response: TResponse, request?: TRequest) => Promise<void> | void;
434
+ type OnDelete<TFile extends File = File> = (file: TFile) => Promise<void> | void;
435
+ type OnError<TBody = HttpErrorBody> = (error: HttpError<TBody>) => Promise<void> | void;
436
+ interface PurgeList {
437
+ items: UploadFile[];
438
+ maxAgeMs: number;
439
+ }
440
+ interface ExpirationOptions {
441
+ /**
442
+ * Age of the upload, after which it is considered expired and can be deleted
443
+ */
444
+ maxAge: number | string;
445
+ /**
446
+ * Auto purging interval for expired upload
447
+ */
448
+ purgeInterval?: number | string;
449
+ /**
450
+ * Auto prolong expiring upload
451
+ */
452
+ rolling?: boolean;
453
+ }
454
+ interface BaseStorageOptions<T extends File = File> extends GenericStorageConfig {
455
+ /** Allowed MIME types */
456
+ allowMIME?: string[];
457
+ /** The full path of the folder where the uploaded asset will be stored. */
458
+ assetFolder?: string;
459
+ /** Cache instance to use for caching */
460
+ cache?: Cache;
461
+ /**
462
+ * Automatic cleaning of abandoned and completed upload
463
+ * @example
464
+ * ```ts
465
+ * app.use(
466
+ * '/upload',
467
+ * Upload.upload({
468
+ * directory: 'upload',
469
+ * expiration: { maxAge: '6h', purgeInterval: '30min' },
470
+ * onComplete
471
+ * })
472
+ * );
473
+ * ```
474
+ */
475
+ expiration?: ExpirationOptions;
476
+ /** File naming function */
477
+ filename?: (file: T) => string;
478
+ /**
479
+ * File name validation function.
480
+ * Returns true if the filename is valid, false otherwise.
481
+ * @default Cloud storage platforms: permissive (only blocks path traversal and null bytes)
482
+ * @default DiskStorage: strict (blocks filesystem-incompatible characters)
483
+ * @example
484
+ * ```ts
485
+ * fileNameValidation: (name: string) => {
486
+ * // Custom validation logic
487
+ * return name.length > 0 && !name.includes('../');
488
+ * }
489
+ * ```
490
+ */
491
+ fileNameValidation?: (name: string) => boolean;
492
+ /** Logger injection */
493
+ logger?: Console;
494
+ /** Limiting the size of custom metadata */
495
+ maxMetadataSize?: number | string;
496
+ /** File size limit */
497
+ maxUploadSize?: number | string;
498
+ /** Provide custom meta storage */
499
+ metaStorage?: MetaStorage<T>;
500
+ /** Metrics injection for observability */
501
+ metrics?: Metrics;
502
+ /** Callback function that is called when an upload is completed */
503
+ onComplete?: OnComplete<T>;
504
+ /** Callback function that is called when a new upload is created */
505
+ onCreate?: OnCreate<T>;
506
+ /** Callback function that is called when an upload is cancelled */
507
+ onDelete?: OnDelete<T>;
508
+ /** Customize error response */
509
+ onError?: OnError;
510
+ /** Callback function that is called when an upload is updated */
511
+ onUpdate?: OnUpdate<T>;
512
+ /** Force relative URI in Location header */
513
+ useRelativeLocation?: boolean;
514
+ /** Upload validation options */
515
+ validation?: Validation<T>;
516
+ }
517
+ type DiskStorageOptions<T extends File> = BaseStorageOptions<T> & {
518
+ /**
519
+ * Uploads directory.
520
+ */
521
+ directory: string;
522
+ /**
523
+ * Configuring metafile storage on the local disk
524
+ * @example
525
+ * ```ts
526
+ * const storage = new DiskStorage({
527
+ * directory: 'upload',
528
+ * metaStorageConfig: { directory: '/tmp/upload-metafiles', prefix: '.' }
529
+ * });
530
+ * ```
531
+ */
532
+ metaStorageConfig?: LocalMetaStorageOptions;
533
+ };
534
+ type DiskStorageWithChecksumOptions<T extends File> = DiskStorageOptions<T> & {
535
+ /**
536
+ * Enable/disable file/range checksum calculation
537
+ */
538
+ checksum?: boolean | "md5" | "sha1";
539
+ };
540
+ /**
541
+ * Unified storage configuration
542
+ */
543
+ interface GenericStorageConfig {
544
+ /** Allow additional properties for specific storage backends */
545
+ [key: string]: unknown;
546
+ /** Base path/prefix for all operations */
547
+ basePath?: string;
548
+ /** Cache TTL */
549
+ cacheTTL?: number;
550
+ /** Supported checksum algorithms */
551
+ checksumTypes?: string[];
552
+ /** Logger instance */
553
+ logger?: Console;
554
+ /** Maximum file size */
555
+ maxFileSize?: number | string;
556
+ /** Metrics instance for observability */
557
+ metrics?: Metrics;
558
+ /** Retry configuration for transient failures */
559
+ retryConfig?: RetryConfig;
560
+ }
561
+ /**
562
+ * Batch operation result for a single file
563
+ */
564
+ interface BatchOperationResult<T extends File = File> {
565
+ /** Error message if operation failed */
566
+ error?: string;
567
+ /** File that was successfully operated on */
568
+ file?: T;
569
+ /** File ID */
570
+ id: string;
571
+ /** Whether the operation was successful */
572
+ success: boolean;
573
+ }
574
+ /**
575
+ * Response from batch operations (deleteBatch, copyBatch, moveBatch)
576
+ */
577
+ interface BatchOperationResponse<T extends File = File> {
578
+ /** Failed operations with error details */
579
+ failed: {
580
+ error: string;
581
+ id: string;
582
+ }[];
583
+ /** Total number of failed operations */
584
+ failedCount: number;
585
+ /** Successfully processed files */
586
+ successful: T[];
587
+ /** Total number of successful operations */
588
+ successfulCount: number;
589
+ }
590
+ /**
591
+ * Default filename validation for cloud storage platforms.
592
+ * Permissive validation that only blocks dangerous patterns (path traversal, null bytes).
593
+ * Cloud storage platforms (S3, Azure, GCS) accept most special characters and handle URL encoding automatically.
594
+ */
595
+ declare const defaultCloudStorageFileNameValidation: (name: string) => boolean;
596
+ /**
597
+ * Default filename validation for local filesystems.
598
+ * Stricter validation that blocks filesystem-incompatible characters.
599
+ */
600
+ declare const defaultFilesystemFileNameValidation: (name: string) => boolean;
601
+ /**
602
+ * Abstract base class for all storage backends.
603
+ * @template TFile The file type used by this storage backend.
604
+ * @template TFileReturn The return type for file retrieval operations.
605
+ * @remarks
606
+ * ## Error Handling
607
+ *
608
+ * All storage operations follow consistent error handling patterns:
609
+ * - Operations throw `UploadError` with specific error codes (see ERRORS enum)
610
+ * - Common error codes: FILE_NOT_FOUND, GONE (expired), FILE_LOCKED, STORAGE_BUSY
611
+ * - Errors are normalized with storage class context via `normalizeError()`
612
+ * - Batch operations capture individual failures without stopping the batch
613
+ *
614
+ * ## Retry Behavior
615
+ *
616
+ * Storage implementations handle retries differently:
617
+ *
618
+ * ### Cloud Storage (S3, GCS, Azure, Netlify Blob)
619
+ * - Use configurable retry wrappers via `retryConfig` option
620
+ * - Default retryable status codes: 408, 429, 500, 502, 503, 504
621
+ * - Retry logic handles transient network errors and rate limiting
622
+ * - Custom `shouldRetry` functions can be provided for advanced retry logic
623
+ *
624
+ * ### Local Storage (DiskStorage)
625
+ * - No automatic retries (filesystem operations are typically immediate)
626
+ * - Errors are thrown directly for immediate feedback
627
+ *
628
+ * ## Operation Instrumentation
629
+ *
630
+ * All public operations are automatically instrumented via `instrumentOperation()`:
631
+ * - Metrics are recorded for operation count, duration, and errors
632
+ * - File sizes are tracked for operations that return file objects
633
+ * - Error metrics include error messages for debugging
634
+ *
635
+ * ## Metadata Caching
636
+ *
637
+ * File metadata is automatically cached to reduce storage API calls:
638
+ * - Cache is updated on save, delete, and get operations
639
+ * - Cache is invalidated when metadata is deleted
640
+ * - Implementations can override caching behavior if needed
641
+ */
642
+ declare abstract class BaseStorage<TFile extends File = File, TFileReturn extends FileReturn = FileReturn> {
643
+ /**
644
+ * Hook called when a new file is created.
645
+ * @param file The newly created file object.
646
+ * @remarks This hook is called after file metadata is saved but before returning the file.
647
+ * Can be used for side effects like logging, notifications, or custom processing.
648
+ */
649
+ onCreate: (file: TFile) => Promise<void> | void;
650
+ /**
651
+ * Hook called when file metadata is updated.
652
+ * @param file The updated file object.
653
+ * @remarks This hook is called after metadata is updated and saved.
654
+ * Can be used for side effects like logging or custom processing.
655
+ */
656
+ onUpdate: (file: TFile) => Promise<void> | void;
657
+ /**
658
+ * Hook called when a file upload is completed.
659
+ * @param file The completed file object.
660
+ * @param response The response object that can be modified in place (headers, statusCode, body).
661
+ * @param request Optional request object for additional context.
662
+ * @remarks This hook is called when file status becomes "completed".
663
+ * The response object can be modified directly to add headers or change the status code.
664
+ */
665
+ onComplete: (file: TFile, response: unknown, request?: unknown) => Promise<void> | void;
666
+ /**
667
+ * Hook called when a file is deleted.
668
+ * @param file The deleted file object.
669
+ * @remarks This hook is called after the file is deleted but before returning.
670
+ * Can be used for side effects like cleanup or logging.
671
+ */
672
+ onDelete: (file: TFile) => Promise<void> | void;
673
+ /**
674
+ * Hook called when an error occurs during storage operations.
675
+ * @param error The HTTP error object that can be modified in place.
676
+ * @remarks This hook allows customizing error responses by modifying the error object.
677
+ * The error object can be modified to change headers, statusCode, or body properties.
678
+ * Error formatting happens in handlers after this hook is called.
679
+ */
680
+ onError: (error: HttpError) => Promise<void> | void;
681
+ isReady: boolean;
682
+ errorResponses: ErrorResponses;
683
+ cache: Cache<string, TFile>;
684
+ readonly logger?: Console;
685
+ readonly metrics: Metrics;
686
+ readonly genericConfig: BaseStorageOptions<TFile>;
687
+ maxMetadataSize: number;
688
+ checksumTypes: string[];
689
+ maxUploadSize: number;
690
+ protected expiration?: {
691
+ maxAge?: string | number;
692
+ purgeInterval?: string | number;
693
+ rolling?: boolean;
694
+ };
695
+ protected locker: Locker;
696
+ protected namingFunction: (file: TFile) => string;
697
+ protected validation: Validator<TFile>;
698
+ protected abstract meta: MetaStorage<TFile>;
699
+ protected assetFolder: string | undefined;
700
+ /**
701
+ * Limits the number of concurrent upload requests
702
+ */
703
+ protected concurrency?: number;
704
+ protected constructor(config: BaseStorageOptions<TFile>);
705
+ get tusExtension(): string[];
706
+ /**
707
+ * Validates a file against configured validation rules.
708
+ * @param file File object to validate.
709
+ * @returns Promise resolving to undefined if file is valid, throws ValidationError otherwise.
710
+ * @throws {ValidationError} If validation fails
711
+ */
712
+ validate(file: TFile): Promise<void>;
713
+ /**
714
+ * Checks if a file exists by querying its metadata.
715
+ * @param query File query containing the file ID to check.
716
+ * @param query.id File ID to check.
717
+ * @returns Promise resolving to true if file exists, false otherwise.
718
+ * @remarks This method does not throw errors - it returns false if the file is not found.
719
+ */
720
+ exists(query: FileQuery): Promise<boolean>;
721
+ /**
722
+ * Normalizes errors with storage-specific context.
723
+ * @param error The error to normalize.
724
+ * @returns Normalized HTTP error with storage class context added to the message.
725
+ * @remarks Errors are enhanced with the storage class name for better debugging.
726
+ */
727
+ normalizeError(error: Error): HttpError;
728
+ /**
729
+ * Gets the storage configuration.
730
+ * @returns The current storage configuration options.
731
+ */
732
+ get config(): BaseStorageOptions<TFile>;
733
+ /**
734
+ * Saves upload metadata to the metadata storage.
735
+ * @param file File object containing metadata to save.
736
+ * @returns Promise resolving to the saved file object.
737
+ * @remarks Updates timestamps and caches the file metadata.
738
+ */
739
+ saveMeta(file: TFile): Promise<TFile>;
740
+ /**
741
+ * Deletes upload metadata from the metadata storage.
742
+ * @param id File ID whose metadata should be deleted.
743
+ * @returns Promise resolving when metadata is deleted.
744
+ * @remarks Also removes the file from the cache.
745
+ */
746
+ deleteMeta(id: string): Promise<void>;
747
+ /**
748
+ * Retrieves upload metadata by file ID.
749
+ * @param id File ID to retrieve metadata for.
750
+ * @returns Promise resolving to the file metadata object.
751
+ * @throws {UploadError} If the file metadata cannot be found (ERRORS.FILE_NOT_FOUND).
752
+ * @remarks Caches the retrieved metadata for faster subsequent access.
753
+ */
754
+ getMeta(id: string): Promise<TFile>;
755
+ /**
756
+ * Checks if a file has expired and deletes it if so.
757
+ * @param file File object to check for expiration.
758
+ * @returns Promise resolving to the file object if not expired.
759
+ * @throws {UploadError} If the file has expired (ERRORS.GONE).
760
+ * @remarks If the file is expired, it is automatically deleted and the metadata is removed.
761
+ */
762
+ checkIfExpired(file: TFile): Promise<TFile>;
763
+ /**
764
+ * Searches for and purges expired uploads.
765
+ * @param maxAge Maximum age of files to keep (files older than this will be purged).
766
+ * Can be a number (milliseconds) or string (e.g., "1h", "30m", "7d").
767
+ * If not provided, uses the expiration.maxAge from configuration.
768
+ * @returns Promise resolving to a list of purged files.
769
+ * @remarks
770
+ * Errors during individual file deletions are logged but do not stop the purge process.
771
+ * Files with corrupted metadata are skipped with a warning.
772
+ * Uses rolling expiration if configured (based on modifiedAt) or fixed expiration (based on createdAt).
773
+ */
774
+ purge(maxAge?: number | string): Promise<PurgeList>;
775
+ /**
776
+ * Gets an uploaded file by ID.
777
+ * @param query File query containing the file ID to retrieve.
778
+ * @param query.id File ID to retrieve.
779
+ * @returns Promise resolving to the file data including content.
780
+ * @throws {UploadError} If the file cannot be found (ERRORS.FILE_NOT_FOUND) or has expired (ERRORS.GONE).
781
+ * @remarks This method loads the entire file content into memory. For large files, use getStream() instead.
782
+ */
783
+ abstract get({
784
+ id
785
+ }: FileQuery): Promise<TFileReturn>;
786
+ /**
787
+ * Gets an uploaded file as a readable stream for efficient large file handling.
788
+ * @param query File query containing the file ID to stream.
789
+ * @param query.id File ID to stream.
790
+ * @returns Promise resolving to an object containing the stream, headers, and size.
791
+ * @throws {UploadError} If the file cannot be found (ERRORS.FILE_NOT_FOUND) or has expired (ERRORS.GONE).
792
+ * @remarks
793
+ * Default implementation falls back to get() and creates a stream from the buffer.
794
+ * Storage implementations should override this for better streaming performance.
795
+ * Headers include Content-Type, Content-Length, ETag, and Last-Modified.
796
+ */
797
+ getStream({
798
+ id
799
+ }: FileQuery): Promise<{
800
+ headers?: Record<string, string>;
801
+ size?: number;
802
+ stream: Readable;
803
+ }>;
804
+ /**
805
+ * Retrieves a list of uploaded files.
806
+ * @param _limit Maximum number of files to return (default: 1000).
807
+ * @returns Promise resolving to an array of file metadata objects.
808
+ * @throws {Error} If not implemented by the storage backend.
809
+ * @remarks Storage implementations must override this method.
810
+ */
811
+ list(_limit?: number): Promise<TFile[]>;
812
+ /**
813
+ * Updates file metadata with user-provided key-value pairs.
814
+ * @param query File query containing the file ID to update.
815
+ * @param query.id File ID to update.
816
+ * @param metadata Partial file object containing fields to update.
817
+ * @returns Promise resolving to the updated file object.
818
+ * @throws {UploadError} If the file cannot be found (ERRORS.FILE_NOT_FOUND).
819
+ * @remarks
820
+ * Supports TTL (time-to-live) option: if metadata contains a 'ttl' field,
821
+ * it will be converted to an 'expiredAt' timestamp.
822
+ * TTL can be a number (milliseconds) or string (e.g., "1h", "30m", "7d").
823
+ */
824
+ update({
825
+ id
826
+ }: FileQuery, metadata: Partial<File>): Promise<TFile>;
827
+ /**
828
+ * Creates a new upload and saves its metadata.
829
+ * @param file File initialization configuration.
830
+ * @returns Promise resolving to the created file object.
831
+ */
832
+ abstract create(file: FileInit): Promise<TFile>;
833
+ /**
834
+ * Writes part and/or returns status of an upload.
835
+ * @param part File part, query, or full file object to write.
836
+ * @returns Promise resolving to the updated file object.
837
+ */
838
+ abstract write(part: FilePart | FileQuery | TFile): Promise<TFile>;
839
+ /**
840
+ * Deletes an upload and its metadata.
841
+ * @param query File query containing the file ID to delete.
842
+ * @param query.id File ID to delete.
843
+ * @returns Promise resolving to the deleted file object with status: "deleted".
844
+ * @throws {UploadError} If the file metadata cannot be found.
845
+ */
846
+ abstract delete(query: FileQuery): Promise<TFile>;
847
+ /**
848
+ * Copies an upload file to a new location.
849
+ * @param name Source file name/ID.
850
+ * @param destination Destination file name/ID.
851
+ * @param options Optional copy options including storage class.
852
+ * @returns Promise resolving to the copied file object.
853
+ * @throws {UploadError} If the source file cannot be found.
854
+ */
855
+ abstract copy(name: string, destination: string, options?: {
856
+ storageClass?: string;
857
+ }): Promise<TFile>;
858
+ /**
859
+ * Moves an upload file to a new location.
860
+ * @param name Source file name/ID.
861
+ * @param destination Destination file name/ID.
862
+ * @returns Promise resolving to the moved file object.
863
+ * @throws {UploadError} If the source file cannot be found.
864
+ */
865
+ abstract move(name: string, destination: string): Promise<TFile>;
866
+ /**
867
+ * Deletes multiple files in a single batch operation.
868
+ * @param ids Array of file IDs to delete.
869
+ * @returns Promise resolving to batch operation response with successful and failed deletions.
870
+ * @remarks
871
+ * Processes all deletions in parallel using Promise.allSettled.
872
+ * Individual failures do not stop the batch operation.
873
+ * Each deletion is wrapped in error handling to capture failures.
874
+ * Metrics are recorded for the batch operation and individual failures.
875
+ * Returns both successful and failed operations with detailed error information.
876
+ */
877
+ deleteBatch(ids: string[]): Promise<BatchOperationResponse<TFile>>;
878
+ /**
879
+ * Copies multiple files in a single batch operation.
880
+ * @param operations Array of copy operations, each containing:
881
+ * source: Source file ID.
882
+ * destination: Destination file ID or path.
883
+ * options: Optional copy options including storage class.
884
+ * @returns Promise resolving to batch operation response with successful and failed copies.
885
+ * @remarks
886
+ * Processes all copies in parallel using Promise.allSettled.
887
+ * Individual failures do not stop the batch operation.
888
+ * Each copy operation is wrapped in error handling to capture failures.
889
+ * Metrics are recorded for the batch operation and individual failures.
890
+ * Returns both successful and failed operations with detailed error information.
891
+ */
892
+ copyBatch(operations: {
893
+ destination: string;
894
+ options?: {
895
+ storageClass?: string;
896
+ };
897
+ source: string;
898
+ }[]): Promise<BatchOperationResponse<TFile>>;
899
+ /**
900
+ * Moves multiple files in a single batch operation.
901
+ * @param operations Array of move operations, each containing:
902
+ * source: Source file ID.
903
+ * destination: Destination file ID or path.
904
+ * @returns Promise resolving to batch operation response with successful and failed moves.
905
+ * @remarks
906
+ * Processes all moves in parallel using Promise.allSettled.
907
+ * Individual failures do not stop the batch operation.
908
+ * Each move operation is wrapped in error handling to capture failures.
909
+ * Metrics are recorded for the batch operation and individual failures.
910
+ * Returns both successful and failed operations with detailed error information.
911
+ */
912
+ moveBatch(operations: {
913
+ destination: string;
914
+ source: string;
915
+ }[]): Promise<BatchOperationResponse<TFile>>;
916
+ /**
917
+ * Prevent upload from being accessed by multiple requests
918
+ */
919
+ protected lock(key: string): Promise<string>;
920
+ protected unlock(key: string): Promise<void>;
921
+ protected isUnsupportedChecksum(algorithm?: string): boolean;
922
+ protected startAutoPurge(purgeInterval: number): void;
923
+ protected updateTimestamps(file: TFile): TFile;
924
+ /**
925
+ * Instruments a storage operation with metrics and error tracking.
926
+ * @param operation Operation name (e.g., "create", "delete", "copy").
927
+ * @param function_ The operation function to execute.
928
+ * @param attributes Additional attributes to include in metrics.
929
+ * @returns Promise resolving to the operation result.
930
+ * @throws Re-throws any errors from the operation function.
931
+ * @remarks
932
+ * Records operation count, duration, and error metrics.
933
+ * Tracks file sizes for operations returning file objects.
934
+ * Error metrics include error messages for debugging.
935
+ * All public methods should use this wrapper for consistent instrumentation.
936
+ */
937
+ protected instrumentOperation<T>(operation: string, function_: () => Promise<T>, attributes?: Record<string, string | number>): Promise<T>;
938
+ }
939
+ export { RangeChecksum as A, BaseStorage as B, Cache as C, DiskStorageOptions as D, ERRORS as E, File as F, RangeHasher as G, HttpError as H, IncomingMessageWithBody as I, ResponseBody as J, ResponseTuple as K, LocalMetaStorageOptions as L, MetaStorage as M, ValidationError as N, OnComplete as O, PurgeList as P, ValidatorConfig as Q, RetryConfig as R, defaultCloudStorageFileNameValidation as S, defaultFilesystemFileNameValidation as T, UploadFile as U, Validation as V, isRetryableError as W, isUploadError as X, retry as Y, throwErrorCode as Z, FileReturn as a, UploadError as b, UploadEventType as c, createRetryWrapper as d, FileInit as e, FilePart as f, FileQuery as g, DiskStorageWithChecksumOptions as h, ResponseBodyType as i, ErrorResponses as j, BaseStorageOptions as k, UploadResponse as l, MetaStorageOptions as m, Metrics as n, BatchOperationResponse as o, BatchOperationResult as p, ErrorMap as q, ExpirationOptions as r, Header as s, Headers as t, HttpErrorBody as u, Metadata as v, OnCreate as w, OnDelete as x, OnError as y, OnUpdate as z };