@dimah-s3/server 1.7.1 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/README.md +72 -16
  2. package/dist/adapters/express.d.ts +7 -7
  3. package/dist/adapters/express.d.ts.map +1 -1
  4. package/dist/adapters/express.js +94 -94
  5. package/dist/adapters/express.js.map +1 -1
  6. package/dist/adapters/fastify.d.ts +11 -5
  7. package/dist/adapters/fastify.d.ts.map +1 -1
  8. package/dist/adapters/fastify.js +94 -94
  9. package/dist/adapters/fastify.js.map +1 -1
  10. package/dist/adapters/node.d.ts +20 -3
  11. package/dist/adapters/node.d.ts.map +1 -1
  12. package/dist/adapters/node.js +92 -92
  13. package/dist/adapters/node.js.map +1 -1
  14. package/dist/api/context.d.ts +8 -4
  15. package/dist/api/context.d.ts.map +1 -1
  16. package/dist/api/{routes/index.d.ts → core-endpoints.d.ts} +43 -68
  17. package/dist/api/core-endpoints.d.ts.map +1 -0
  18. package/dist/api/create-s3-endpoint.d.ts +70 -48
  19. package/dist/api/create-s3-endpoint.d.ts.map +1 -1
  20. package/dist/api/create-s3-middleware.d.ts +19 -16
  21. package/dist/api/create-s3-middleware.d.ts.map +1 -1
  22. package/dist/api/router-context.d.ts +23 -0
  23. package/dist/api/router-context.d.ts.map +1 -0
  24. package/dist/api/router.d.ts +15 -5
  25. package/dist/api/router.d.ts.map +1 -1
  26. package/dist/config/feature-toggle.d.ts +16 -0
  27. package/dist/config/feature-toggle.d.ts.map +1 -0
  28. package/dist/config/resolve-config.d.ts +9 -0
  29. package/dist/config/resolve-config.d.ts.map +1 -0
  30. package/dist/config/resolve-routes.d.ts +37 -0
  31. package/dist/config/resolve-routes.d.ts.map +1 -0
  32. package/dist/dimah-s3.d.ts +22 -32
  33. package/dist/dimah-s3.d.ts.map +1 -1
  34. package/dist/helpers/authorize-download.d.ts +25 -0
  35. package/dist/helpers/authorize-download.d.ts.map +1 -0
  36. package/dist/helpers/aws-errors.d.ts +16 -0
  37. package/dist/helpers/aws-errors.d.ts.map +1 -0
  38. package/dist/helpers/best-effort.d.ts +22 -3
  39. package/dist/helpers/best-effort.d.ts.map +1 -1
  40. package/dist/helpers/checksum-config.d.ts +13 -0
  41. package/dist/helpers/checksum-config.d.ts.map +1 -0
  42. package/dist/helpers/constraints.d.ts +17 -12
  43. package/dist/helpers/constraints.d.ts.map +1 -1
  44. package/dist/helpers/error-boundary.d.ts +28 -0
  45. package/dist/helpers/error-boundary.d.ts.map +1 -0
  46. package/dist/helpers/finalize-confirmed.d.ts +42 -13
  47. package/dist/helpers/finalize-confirmed.d.ts.map +1 -1
  48. package/dist/helpers/head-object.d.ts +6 -9
  49. package/dist/helpers/head-object.d.ts.map +1 -1
  50. package/dist/helpers/hooks.d.ts +29 -15
  51. package/dist/helpers/hooks.d.ts.map +1 -1
  52. package/dist/helpers/inline-types.d.ts +24 -7
  53. package/dist/helpers/inline-types.d.ts.map +1 -1
  54. package/dist/helpers/list-parts.d.ts +4 -6
  55. package/dist/helpers/list-parts.d.ts.map +1 -1
  56. package/dist/helpers/metadata-encoding.d.ts +15 -0
  57. package/dist/helpers/metadata-encoding.d.ts.map +1 -0
  58. package/dist/helpers/object-meta.d.ts +39 -0
  59. package/dist/helpers/object-meta.d.ts.map +1 -0
  60. package/dist/helpers/object-s3.d.ts +5 -2
  61. package/dist/helpers/object-s3.d.ts.map +1 -1
  62. package/dist/helpers/open-target.d.ts +89 -0
  63. package/dist/helpers/open-target.d.ts.map +1 -0
  64. package/dist/helpers/part-layout.d.ts +19 -0
  65. package/dist/helpers/part-layout.d.ts.map +1 -0
  66. package/dist/helpers/presign.d.ts +54 -0
  67. package/dist/helpers/presign.d.ts.map +1 -0
  68. package/dist/helpers/request.d.ts +6 -11
  69. package/dist/helpers/request.d.ts.map +1 -1
  70. package/dist/helpers/resolve-target.d.ts +28 -20
  71. package/dist/helpers/resolve-target.d.ts.map +1 -1
  72. package/dist/helpers/sniff-object.d.ts +22 -0
  73. package/dist/helpers/sniff-object.d.ts.map +1 -0
  74. package/dist/helpers/ticket.d.ts +75 -0
  75. package/dist/helpers/ticket.d.ts.map +1 -0
  76. package/dist/index.d.ts +4 -12
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +2647 -1579
  79. package/dist/index.js.map +1 -1
  80. package/dist/operations/catalog.d.ts +16 -0
  81. package/dist/operations/catalog.d.ts.map +1 -0
  82. package/dist/operations/confirm.d.ts +19 -0
  83. package/dist/operations/confirm.d.ts.map +1 -0
  84. package/dist/operations/delete-many.d.ts +18 -0
  85. package/dist/operations/delete-many.d.ts.map +1 -0
  86. package/dist/operations/delete.d.ts +14 -0
  87. package/dist/operations/delete.d.ts.map +1 -0
  88. package/dist/operations/download.d.ts +20 -0
  89. package/dist/operations/download.d.ts.map +1 -0
  90. package/dist/operations/file.d.ts +38 -0
  91. package/dist/operations/file.d.ts.map +1 -0
  92. package/dist/operations/multipart/abort.d.ts +20 -0
  93. package/dist/operations/multipart/abort.d.ts.map +1 -0
  94. package/dist/operations/multipart/complete.d.ts +21 -0
  95. package/dist/operations/multipart/complete.d.ts.map +1 -0
  96. package/dist/operations/multipart/init.d.ts +19 -0
  97. package/dist/operations/multipart/init.d.ts.map +1 -0
  98. package/dist/operations/multipart/list-parts.d.ts +11 -0
  99. package/dist/operations/multipart/list-parts.d.ts.map +1 -0
  100. package/dist/operations/multipart/open-multipart.d.ts +25 -0
  101. package/dist/operations/multipart/open-multipart.d.ts.map +1 -0
  102. package/dist/operations/multipart/sign-part.d.ts +20 -0
  103. package/dist/operations/multipart/sign-part.d.ts.map +1 -0
  104. package/dist/operations/put.d.ts +18 -0
  105. package/dist/operations/put.d.ts.map +1 -0
  106. package/dist/operations/run-operation.d.ts +18 -0
  107. package/dist/operations/run-operation.d.ts.map +1 -0
  108. package/dist/operations/s3-api.d.ts +12 -0
  109. package/dist/operations/s3-api.d.ts.map +1 -0
  110. package/dist/operations/upload.d.ts +19 -0
  111. package/dist/operations/upload.d.ts.map +1 -0
  112. package/dist/plugin/apply-plugins.d.ts +9 -11
  113. package/dist/plugin/apply-plugins.d.ts.map +1 -1
  114. package/dist/plugin/chain-hooks.d.ts +12 -9
  115. package/dist/plugin/chain-hooks.d.ts.map +1 -1
  116. package/dist/plugin/define-plugin.d.ts +11 -4
  117. package/dist/plugin/define-plugin.d.ts.map +1 -1
  118. package/dist/plugin/index.d.ts +1 -2
  119. package/dist/plugin/index.d.ts.map +1 -1
  120. package/dist/plugin/types.d.ts +52 -56
  121. package/dist/plugin/types.d.ts.map +1 -1
  122. package/dist/plugins.d.ts +10 -8
  123. package/dist/plugins.d.ts.map +1 -1
  124. package/dist/plugins.js +325 -1627
  125. package/dist/plugins.js.map +1 -1
  126. package/dist/route.d.ts +0 -1
  127. package/dist/route.d.ts.map +1 -1
  128. package/dist/types/config.d.ts +171 -172
  129. package/dist/types/config.d.ts.map +1 -1
  130. package/dist/types/hook-contexts.d.ts +139 -147
  131. package/dist/types/hook-contexts.d.ts.map +1 -1
  132. package/dist/types/index.d.ts +3 -3
  133. package/dist/types/index.d.ts.map +1 -1
  134. package/dist/types/locals.d.ts +37 -0
  135. package/dist/types/locals.d.ts.map +1 -0
  136. package/dist/types/resolved.d.ts +118 -0
  137. package/dist/types/resolved.d.ts.map +1 -0
  138. package/package.json +8 -12
  139. package/dist/api/bind-endpoints.d.ts +0 -12
  140. package/dist/api/bind-endpoints.d.ts.map +0 -1
  141. package/dist/api/index.d.ts +0 -6
  142. package/dist/api/index.d.ts.map +0 -1
  143. package/dist/api/index.js +0 -1353
  144. package/dist/api/index.js.map +0 -1
  145. package/dist/api/routes/catalog.d.ts +0 -9
  146. package/dist/api/routes/catalog.d.ts.map +0 -1
  147. package/dist/api/routes/confirm.d.ts +0 -13
  148. package/dist/api/routes/confirm.d.ts.map +0 -1
  149. package/dist/api/routes/delete-batch.d.ts +0 -14
  150. package/dist/api/routes/delete-batch.d.ts.map +0 -1
  151. package/dist/api/routes/delete.d.ts +0 -26
  152. package/dist/api/routes/delete.d.ts.map +0 -1
  153. package/dist/api/routes/download.d.ts +0 -21
  154. package/dist/api/routes/download.d.ts.map +0 -1
  155. package/dist/api/routes/file.d.ts +0 -20
  156. package/dist/api/routes/file.d.ts.map +0 -1
  157. package/dist/api/routes/index.d.ts.map +0 -1
  158. package/dist/api/routes/multipart/abort.d.ts +0 -16
  159. package/dist/api/routes/multipart/abort.d.ts.map +0 -1
  160. package/dist/api/routes/multipart/complete.d.ts +0 -22
  161. package/dist/api/routes/multipart/complete.d.ts.map +0 -1
  162. package/dist/api/routes/multipart/init.d.ts +0 -22
  163. package/dist/api/routes/multipart/init.d.ts.map +0 -1
  164. package/dist/api/routes/multipart/list-parts.d.ts +0 -17
  165. package/dist/api/routes/multipart/list-parts.d.ts.map +0 -1
  166. package/dist/api/routes/multipart/part.d.ts +0 -20
  167. package/dist/api/routes/multipart/part.d.ts.map +0 -1
  168. package/dist/api/routes/upload.d.ts +0 -22
  169. package/dist/api/routes/upload.d.ts.map +0 -1
  170. package/dist/errors.d.ts +0 -23
  171. package/dist/errors.d.ts.map +0 -1
  172. package/dist/helpers/expires.d.ts +0 -21
  173. package/dist/helpers/expires.d.ts.map +0 -1
  174. package/dist/helpers/features.d.ts +0 -17
  175. package/dist/helpers/features.d.ts.map +0 -1
  176. package/dist/helpers/index.d.ts +0 -19
  177. package/dist/helpers/index.d.ts.map +0 -1
  178. package/dist/helpers/is-aws-not-found.d.ts +0 -5
  179. package/dist/helpers/is-aws-not-found.d.ts.map +0 -1
  180. package/dist/helpers/previous-key.d.ts +0 -5
  181. package/dist/helpers/previous-key.d.ts.map +0 -1
  182. package/dist/helpers/resolve-route.d.ts +0 -33
  183. package/dist/helpers/resolve-route.d.ts.map +0 -1
  184. package/dist/plugin/hook-registry.d.ts +0 -21
  185. package/dist/plugin/hook-registry.d.ts.map +0 -1
  186. package/dist/put.d.ts +0 -15
  187. package/dist/put.d.ts.map +0 -1
package/README.md CHANGED
@@ -1,14 +1,26 @@
1
1
  # @dimah-s3/server
2
2
 
3
- Presigned S3 handlers with HTTP `handler`, direct `api`, and an optional `plugins` array.
3
+ **2.0 beta.** Install with `@beta`. `@latest` stays on 1.x, and betas can include breaking changes until 2.0.0.
4
4
 
5
- Full documentation: [s3.dimah.dev/docs/server](https://s3.dimah.dev/docs/server) ·
6
- [llms.txt](https://s3.dimah.dev/llms.txt)
5
+ Presigned S3 upload, download, and delete handlers with route policies,
6
+ guards, and lifecycle hooks. One instance gives you an HTTP `handler`, an
7
+ in-process `api`, and `put` for server-side uploads.
8
+
9
+ Full documentation: [v2.s3.dimah.dev/docs/server](https://v2.s3.dimah.dev/docs/server) ·
10
+ [llms.txt](https://v2.s3.dimah.dev/llms.txt)
7
11
 
8
12
  ## Install
9
13
 
10
14
  ```bash
11
- pnpm add @dimah-s3/server @aws-sdk/client-s3
15
+ pnpm add @dimah-s3/server@beta @aws-sdk/client-s3
16
+ ```
17
+
18
+ Set the upload ticket secret, at least 32 characters and the same on every
19
+ instance:
20
+
21
+ ```bash
22
+ # .env — generate with: openssl rand -base64 32
23
+ DIMAH_S3_SECRET="…"
12
24
  ```
13
25
 
14
26
  ## Minimal setup
@@ -17,44 +29,88 @@ pnpm add @dimah-s3/server @aws-sdk/client-s3
17
29
  import { S3Client } from "@aws-sdk/client-s3";
18
30
  import { dimahS3, route } from "@dimah-s3/server";
19
31
 
20
- export const awsS3 = new S3Client({/* env */});
32
+ export const awsS3 = new S3Client({
33
+ region: process.env.S3_REGION,
34
+ // Required: presigned browser uploads cannot match SDK checksums.
35
+ requestChecksumCalculation: "WHEN_REQUIRED",
36
+ });
21
37
 
22
38
  export const s3 = dimahS3({
23
39
  client: awsS3,
24
40
  bucket: process.env.S3_BUCKET!,
25
41
  routes: {
26
42
  uploads: route({
27
- upload: { fileTypes: ["image/*"] },
43
+ upload: { fileTypes: ["image/*"], maxFileSize: 5 * 1024 * 1024 },
44
+ download: true,
45
+ delete: true,
28
46
  }),
29
47
  },
30
48
  });
31
49
  ```
32
50
 
33
- Mount with a framework adapter:
51
+ Mount it with a framework adapter:
34
52
 
35
53
  ```ts
36
- // Next.js
54
+ // Next.js: app/api/s3/[...s3]/route.ts
37
55
  import { toNextJsHandler } from "@dimah-s3/server/next";
38
56
  export const { GET, POST, PUT, PATCH, DELETE } = toNextJsHandler(s3);
39
57
 
40
- // Express — @dimah-s3/server/express → toExpressHandler
41
- // Hono — @dimah-s3/server/hono → toHonoHandler
42
- // Fastify — @dimah-s3/server/fastify → toFastifyHandler
43
- // Elysia — @dimah-s3/server/elysia → toElysiaHandler
58
+ // Express — @dimah-s3/server/express → toExpressHandler
59
+ // Hono — @dimah-s3/server/hono → toHonoHandler
60
+ // Fastify — @dimah-s3/server/fastify → toFastifyHandler
61
+ // Elysia — @dimah-s3/server/elysia → toElysiaHandler
44
62
  // SvelteKit — @dimah-s3/server/svelte-kit → toSvelteKitHandler
45
- // Node http — @dimah-s3/server/node → toNodeHandler
63
+ // Node http — @dimah-s3/server/node → toNodeHandler
64
+ // Any Fetch runtime: s3.handler(request)
46
65
  ```
47
66
 
48
- See [Server Setup](https://s3.dimah.dev/docs/server/setup) for full examples.
67
+ See [Server Setup](https://v2.s3.dimah.dev/docs/server/setup) for every adapter.
49
68
 
50
- Server-side (no HTTP):
69
+ ## Guards and hooks
70
+
71
+ Guards return nothing to allow, `{ locals }` to pass values on, and throw
72
+ `s3Error(code)` to reject:
51
73
 
52
74
  ```ts
53
- await s3.api.download({ query: { route, key }, headers: await headers() });
75
+ import { s3Error } from "@dimah-s3/server";
76
+
77
+ declare module "@dimah-s3/server" {
78
+ interface DimahS3Locals {
79
+ userId?: string;
80
+ }
81
+ }
82
+
83
+ export const s3 = dimahS3({
84
+ // ...
85
+ guard: async ({ request }) => {
86
+ const session = await getSession(request);
87
+ if (!session) throw s3Error("UNAUTHORIZED");
88
+ return { locals: { userId: session.userId } };
89
+ },
90
+ });
91
+ ```
92
+
93
+ `upload.onStart` runs once an upload can begin, and `upload.onConfirmed` runs
94
+ after HeadObject verifies the stored object. `onConfirmed` runs at least once:
95
+ dedupe on `uploadToken`.
96
+
97
+ ## In process
98
+
99
+ `s3.api` has the browser client's shape, with `{ headers, request, locals }`
100
+ last:
101
+
102
+ ```ts
103
+ await s3.api.download({ route: "uploads", key }, { headers: await headers() });
104
+
105
+ await s3.put({ route: "uploads", name: "report.pdf", body: pdfBytes });
54
106
  ```
55
107
 
56
108
  Optional persistence: add `db()` from [`@dimah-s3/db`](../db) to `plugins`.
57
109
 
110
+ ## Upgrading from 1.7
111
+
112
+ See [Upgrade to 2.0 beta](https://v2.s3.dimah.dev/docs/migration-2-0).
113
+
58
114
  ## License
59
115
 
60
116
  MIT
@@ -1,10 +1,13 @@
1
- import { fromNodeHeaders } from "./node";
1
+ import { fromNodeHeaders, type NodeHandlerOptions } from "./node";
2
2
  import type { DimahS3HandlerSource } from "./types";
3
- export { fromNodeHeaders };
3
+ export { fromNodeHeaders, type NodeHandlerOptions };
4
4
  /**
5
5
  * Adapt a dimah-s3 instance to an Express / Connect handler.
6
6
  *
7
7
  * Mount **before** `express.json()` so the request body is not consumed early.
8
+ * A route (`app.all`) and a mount (`app.use("/api/s3", …)`) both work: the
9
+ * request URL is read from `req.originalUrl`. Takes the same options as
10
+ * `toNodeHandler`, such as `{ trustProxy: true }` behind a proxy.
8
11
  *
9
12
  * @example
10
13
  * ```ts
@@ -13,12 +16,9 @@ export { fromNodeHeaders };
13
16
  * import { s3 } from "./s3";
14
17
  *
15
18
  * const app = express();
16
- * // Express 4
17
- * app.all("/api/s3/*", toExpressHandler(s3));
18
- * // Express 5 — named wildcard
19
- * // app.all("/api/s3/*splat", toExpressHandler(s3));
19
+ * app.use("/api/s3", toExpressHandler(s3));
20
20
  * app.use(express.json());
21
21
  * ```
22
22
  */
23
- export declare function toExpressHandler(s3: DimahS3HandlerSource): (req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => Promise<void>;
23
+ export declare function toExpressHandler(s3: DimahS3HandlerSource, options?: NodeHandlerOptions): (req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => Promise<void>;
24
24
  //# sourceMappingURL=express.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"express.d.ts","sourceRoot":"","sources":["../../src/adapters/express.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAiB,MAAM,QAAQ,CAAC;AACxD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD,OAAO,EAAE,eAAe,EAAE,CAAC;AAE3B;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,oBAAoB,wGAExD"}
1
+ {"version":3,"file":"express.d.ts","sourceRoot":"","sources":["../../src/adapters/express.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EAEf,KAAK,kBAAkB,EACxB,MAAM,QAAQ,CAAC;AAChB,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD,OAAO,EAAE,eAAe,EAAE,KAAK,kBAAkB,EAAE,CAAC;AAEpD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAC9B,EAAE,EAAE,oBAAoB,EACxB,OAAO,CAAC,EAAE,kBAAkB,wGAG7B"}
@@ -1,71 +1,24 @@
1
+ import { Readable } from 'stream';
2
+ import { s3Error } from '@dimah-s3/core';
1
3
  import { toResponse } from 'better-call';
2
- import { S3_ERROR_CODES, APIError } from '@dimah-s3/core';
3
4
 
4
5
  // src/adapters/node.ts
5
- var errors = {
6
- notFound: () => APIError.from("NOT_FOUND", S3_ERROR_CODES.NOT_FOUND),
7
- unauthorized: () => APIError.from("UNAUTHORIZED", S3_ERROR_CODES.UNAUTHORIZED),
8
- forbidden: () => APIError.from("FORBIDDEN", S3_ERROR_CODES.FORBIDDEN),
9
- conflict: () => APIError.from("CONFLICT", S3_ERROR_CODES.CONFLICT),
10
- internalError: () => APIError.from("INTERNAL_SERVER_ERROR", S3_ERROR_CODES.INTERNAL_ERROR),
11
- objectNotFound: () => APIError.from("NOT_FOUND", S3_ERROR_CODES.OBJECT_NOT_FOUND),
12
- featureDisabled: (feature) => APIError.from("NOT_FOUND", {
13
- code: S3_ERROR_CODES.FEATURE_DISABLED.code,
14
- message: S3_ERROR_CODES.FEATURE_DISABLED.message.replaceAll(
15
- "{feature}",
16
- feature
17
- ),
18
- params: { feature }
19
- }),
20
- invalidKey: () => APIError.from("BAD_REQUEST", S3_ERROR_CODES.INVALID_KEY),
21
- unknownRoute: (route) => APIError.from("NOT_FOUND", {
22
- code: S3_ERROR_CODES.UNKNOWN_ROUTE.code,
23
- message: S3_ERROR_CODES.UNKNOWN_ROUTE.message,
24
- params: { route }
25
- }),
26
- fileTypeNotAllowed: (fileName, contentType) => APIError.from("BAD_REQUEST", {
27
- code: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.code,
28
- message: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.message,
29
- params: {
30
- fileName,
31
- ...contentType ? { contentType } : {}
32
- }
33
- }),
34
- s3NetworkError: (code) => APIError.from("BAD_GATEWAY", {
35
- code: S3_ERROR_CODES.S3_NETWORK_ERROR.code,
36
- message: S3_ERROR_CODES.S3_NETWORK_ERROR.message.replaceAll(
37
- "{code}",
38
- code
39
- ),
40
- params: { code }
41
- }),
42
- multipartPartMissing: (partNumber) => APIError.from("BAD_REQUEST", {
43
- code: S3_ERROR_CODES.MULTIPART_PART_MISSING.code,
44
- message: S3_ERROR_CODES.MULTIPART_PART_MISSING.message.replaceAll(
45
- "{partNumber}",
46
- String(partNumber)
47
- ),
48
- params: { partNumber }
49
- }),
50
- payloadTooLarge: (message = S3_ERROR_CODES.PAYLOAD_TOO_LARGE.message) => APIError.from("PAYLOAD_TOO_LARGE", {
51
- ...S3_ERROR_CODES.PAYLOAD_TOO_LARGE,
52
- message
53
- }),
54
- quotaExceeded: (message = S3_ERROR_CODES.QUOTA_EXCEEDED.message) => APIError.from("PAYLOAD_TOO_LARGE", {
55
- ...S3_ERROR_CODES.QUOTA_EXCEEDED,
56
- message
57
- }),
58
- validationError: (message) => APIError.from("BAD_REQUEST", {
59
- code: S3_ERROR_CODES.VALIDATION_ERROR.code,
60
- message
61
- })
6
+
7
+ // src/helpers/logger.ts
8
+ var defaultLogger = {
9
+ error: (message, ...args) => {
10
+ console.error("[dimah-s3]", message, ...args);
11
+ },
12
+ warn: (message, ...args) => {
13
+ console.warn("[dimah-s3]", message, ...args);
14
+ }
62
15
  };
63
16
 
64
17
  // src/adapters/node.ts
65
18
  function fromNodeHeaders(nodeHeaders) {
66
19
  const headers = new Headers();
67
20
  for (const [key, value] of Object.entries(nodeHeaders)) {
68
- if (value == null) continue;
21
+ if (value == null || key.startsWith(":")) continue;
69
22
  if (Array.isArray(value)) {
70
23
  for (const v of value) headers.append(key, v);
71
24
  } else {
@@ -74,56 +27,103 @@ function fromNodeHeaders(nodeHeaders) {
74
27
  }
75
28
  return headers;
76
29
  }
77
- function collectBody(req) {
78
- const { promise, resolve, reject } = Promise.withResolvers();
79
- const chunks = [];
80
- req.on("data", (chunk) => {
81
- chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
82
- });
83
- req.on("end", () => resolve(Buffer.concat(chunks)));
84
- req.on("error", reject);
85
- return promise;
30
+ function toNodeHandler(s3, options = {}) {
31
+ return async (req, res) => {
32
+ const controller = new AbortController();
33
+ res.once("close", () => {
34
+ if (!res.writableFinished) controller.abort();
35
+ });
36
+ try {
37
+ const request = toWebRequest(req, controller.signal, options);
38
+ await writeWebResponse(res, await s3.handler(request));
39
+ } catch (error) {
40
+ if (controller.signal.aborted) return;
41
+ defaultLogger.error?.("Node adapter failed", error);
42
+ if (res.headersSent) {
43
+ res.destroy();
44
+ } else {
45
+ await writeWebResponse(res, toResponse(s3Error("INTERNAL_ERROR")));
46
+ }
47
+ }
48
+ };
86
49
  }
87
- function toWebRequest(req, body) {
88
- const host = req.headers.host ?? "localhost";
89
- const protocol = req.socket.encrypted === true ? "https" : "http";
90
- const url = new URL(req.url ?? "/", `${protocol}://${host}`);
91
- const headers = fromNodeHeaders(req.headers);
50
+ function toWebRequest(req, signal, options) {
92
51
  const method = (req.method ?? "GET").toUpperCase();
93
- const init = { method, headers };
94
- if (method !== "GET" && method !== "HEAD") {
95
- init.body = new Uint8Array(body);
52
+ const hasBody = method !== "GET" && method !== "HEAD";
53
+ const init = {
54
+ method,
55
+ headers: fromNodeHeaders(req.headers),
56
+ signal
57
+ };
58
+ if (hasBody) {
59
+ init.body = Readable.toWeb(req);
96
60
  init.duplex = "half";
97
61
  }
98
- return new Request(url, init);
62
+ return new Request(requestURL(req, options), init);
63
+ }
64
+ function requestURL(req, options) {
65
+ const encrypted = req.socket.encrypted === true;
66
+ let protocol = encrypted ? "https" : "http";
67
+ let host = req.headers.host ?? "localhost";
68
+ if (options.trustProxy) {
69
+ const forwardedProto = firstHeaderValue(req.headers["x-forwarded-proto"]);
70
+ if (forwardedProto === "http" || forwardedProto === "https") {
71
+ protocol = forwardedProto;
72
+ }
73
+ host = firstHeaderValue(req.headers["x-forwarded-host"]) || host;
74
+ }
75
+ const path = req.originalUrl ?? req.url;
76
+ return new URL(path ?? "/", `${protocol}://${host}`);
77
+ }
78
+ function firstHeaderValue(value) {
79
+ const raw = Array.isArray(value) ? value[0] : value;
80
+ return raw?.split(",")[0]?.trim().toLowerCase() ?? "";
99
81
  }
100
82
  async function writeWebResponse(res, response) {
101
83
  res.statusCode = response.status;
102
84
  for (const [key, value] of response.headers) {
85
+ if (key === "set-cookie") continue;
103
86
  res.setHeader(key, value);
104
87
  }
105
- const buffer = Buffer.from(await response.arrayBuffer());
106
- res.end(buffer);
107
- }
108
- function toNodeHandler(s3) {
109
- return async (req, res) => {
110
- try {
111
- const body = await collectBody(req);
112
- const request = toWebRequest(req, body);
113
- const response = await s3.handler(request);
114
- await writeWebResponse(res, response);
115
- } catch (err) {
116
- console.error("[S3 API]", err);
117
- if (!res.headersSent) {
118
- await writeWebResponse(res, toResponse(errors.internalError()));
88
+ const cookies = response.headers.getSetCookie();
89
+ if (cookies.length > 0) res.setHeader("set-cookie", cookies);
90
+ if (response.body === null) {
91
+ res.end();
92
+ return;
93
+ }
94
+ const reader = response.body.getReader();
95
+ try {
96
+ for (; ; ) {
97
+ const { done, value } = await reader.read();
98
+ if (done) break;
99
+ if (res.destroyed || res.writableEnded) {
100
+ await reader.cancel();
101
+ return;
119
102
  }
103
+ if (!value?.byteLength) continue;
104
+ if (!res.write(value)) await waitForDrain(res);
120
105
  }
121
- };
106
+ if (!res.destroyed && !res.writableEnded) res.end();
107
+ } catch (error) {
108
+ await reader.cancel(error).catch(() => void 0);
109
+ throw error;
110
+ }
111
+ }
112
+ function waitForDrain(res) {
113
+ return new Promise((resolve) => {
114
+ const done = () => {
115
+ res.off("drain", done);
116
+ res.off("close", done);
117
+ resolve();
118
+ };
119
+ res.once("drain", done);
120
+ res.once("close", done);
121
+ });
122
122
  }
123
123
 
124
124
  // src/adapters/express.ts
125
- function toExpressHandler(s3) {
126
- return toNodeHandler(s3);
125
+ function toExpressHandler(s3, options) {
126
+ return toNodeHandler(s3, options);
127
127
  }
128
128
 
129
129
  export { fromNodeHeaders, toExpressHandler };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/errors.ts","../../src/adapters/node.ts","../../src/adapters/express.ts"],"names":[],"mappings":";;;;AAWO,IAAM,MAAA,GAAS;AAAA,EACpB,UAAU,MAAM,QAAA,CAAS,IAAA,CAAK,WAAA,EAAa,eAAe,SAAS,CAAA;AAAA,EAEnE,cAAc,MACZ,QAAA,CAAS,IAAA,CAAK,cAAA,EAAgB,eAAe,YAAY,CAAA;AAAA,EAE3D,WAAW,MAAM,QAAA,CAAS,IAAA,CAAK,WAAA,EAAa,eAAe,SAAS,CAAA;AAAA,EAEpE,UAAU,MAAM,QAAA,CAAS,IAAA,CAAK,UAAA,EAAY,eAAe,QAAQ,CAAA;AAAA,EAEjE,eAAe,MACb,QAAA,CAAS,IAA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,EACF,CAAA;AACF;;;AC9EO,SAAS,iBAAiB,EAAA,EAA0B;AACzD,EAAA,OAAO,cAAc,EAAE,CAAA;AACzB","file":"express.js","sourcesContent":["import {\n APIError,\n S3_ERROR_CODES,\n isAPIError,\n isS3ErrorCode,\n} from \"@dimah-s3/core\";\nimport type { RouteOperation } from \"@/types/config\";\n\nexport { APIError, S3_ERROR_CODES, isAPIError, isS3ErrorCode };\n\n/** English API errors with stable codes for client-side localization. */\nexport const errors = {\n notFound: () => APIError.from(\"NOT_FOUND\", S3_ERROR_CODES.NOT_FOUND),\n\n unauthorized: () =>\n APIError.from(\"UNAUTHORIZED\", S3_ERROR_CODES.UNAUTHORIZED),\n\n forbidden: () => APIError.from(\"FORBIDDEN\", S3_ERROR_CODES.FORBIDDEN),\n\n conflict: () => APIError.from(\"CONFLICT\", S3_ERROR_CODES.CONFLICT),\n\n internalError: () =>\n APIError.from(\"INTERNAL_SERVER_ERROR\", S3_ERROR_CODES.INTERNAL_ERROR),\n\n objectNotFound: () =>\n APIError.from(\"NOT_FOUND\", S3_ERROR_CODES.OBJECT_NOT_FOUND),\n\n featureDisabled: (feature: RouteOperation) =>\n APIError.from(\"NOT_FOUND\", {\n code: S3_ERROR_CODES.FEATURE_DISABLED.code,\n message: S3_ERROR_CODES.FEATURE_DISABLED.message.replaceAll(\n \"{feature}\",\n feature,\n ),\n params: { feature },\n }),\n\n invalidKey: () => APIError.from(\"BAD_REQUEST\", S3_ERROR_CODES.INVALID_KEY),\n\n unknownRoute: (route: string) =>\n APIError.from(\"NOT_FOUND\", {\n code: S3_ERROR_CODES.UNKNOWN_ROUTE.code,\n message: S3_ERROR_CODES.UNKNOWN_ROUTE.message,\n params: { route },\n }),\n\n fileTypeNotAllowed: (fileName: string, contentType?: string) =>\n APIError.from(\"BAD_REQUEST\", {\n code: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.code,\n message: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.message,\n params: {\n fileName,\n ...(contentType ? { contentType } : {}),\n },\n }),\n\n s3NetworkError: (code: string) =>\n APIError.from(\"BAD_GATEWAY\", {\n code: S3_ERROR_CODES.S3_NETWORK_ERROR.code,\n message: S3_ERROR_CODES.S3_NETWORK_ERROR.message.replaceAll(\n \"{code}\",\n code,\n ),\n params: { code },\n }),\n\n multipartPartMissing: (partNumber: number) =>\n APIError.from(\"BAD_REQUEST\", {\n code: S3_ERROR_CODES.MULTIPART_PART_MISSING.code,\n message: S3_ERROR_CODES.MULTIPART_PART_MISSING.message.replaceAll(\n \"{partNumber}\",\n String(partNumber),\n ),\n params: { partNumber },\n }),\n\n payloadTooLarge: (\n message: string = S3_ERROR_CODES.PAYLOAD_TOO_LARGE.message,\n ) =>\n APIError.from(\"PAYLOAD_TOO_LARGE\", {\n ...S3_ERROR_CODES.PAYLOAD_TOO_LARGE,\n message,\n }),\n\n quotaExceeded: (message: string = S3_ERROR_CODES.QUOTA_EXCEEDED.message) =>\n APIError.from(\"PAYLOAD_TOO_LARGE\", {\n ...S3_ERROR_CODES.QUOTA_EXCEEDED,\n message,\n }),\n\n validationError: (message: string) =>\n APIError.from(\"BAD_REQUEST\", {\n code: S3_ERROR_CODES.VALIDATION_ERROR.code,\n message,\n }),\n} as const;\n\nexport type ServerErrors = typeof errors;\n","import { toResponse } from \"better-call\";\nimport type {\n IncomingHttpHeaders,\n IncomingMessage,\n ServerResponse,\n} from \"node:http\";\nimport { errors } from \"@/errors\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\n/**\n * Convert Node.js / Express request headers into a Web {@link Headers} object.\n * Useful when calling `s3.api.*` from a Node handler.\n *\n * @example\n * ```ts\n * import { fromNodeHeaders } from \"@dimah-s3/server/node\";\n *\n * await s3.api.download({ query: { route, key }, headers: fromNodeHeaders(req.headers) });\n * ```\n */\nexport function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(nodeHeaders)) {\n if (value == null) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n return headers;\n}\n\nfunction collectBody(req: IncomingMessage): Promise<Buffer> {\n const { promise, resolve, reject } = Promise.withResolvers<Buffer>();\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer | string) => {\n chunks.push(typeof chunk === \"string\" ? Buffer.from(chunk) : chunk);\n });\n req.on(\"end\", () => resolve(Buffer.concat(chunks)));\n req.on(\"error\", reject);\n return promise;\n}\n\nfunction toWebRequest(req: IncomingMessage, body: Buffer): Request {\n const host = req.headers.host ?? \"localhost\";\n const protocol =\n (req.socket as { encrypted?: boolean }).encrypted === true\n ? \"https\"\n : \"http\";\n const url = new URL(req.url ?? \"/\", `${protocol}://${host}`);\n\n const headers = fromNodeHeaders(req.headers);\n const method = (req.method ?? \"GET\").toUpperCase();\n const init: RequestInit = { method, headers };\n if (method !== \"GET\" && method !== \"HEAD\") {\n init.body = new Uint8Array(body);\n // @ts-expect-error Node fetch duplex for streaming bodies\n init.duplex = \"half\";\n }\n\n return new Request(url, init);\n}\n\nasync function writeWebResponse(\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n res.statusCode = response.status;\n for (const [key, value] of response.headers) {\n res.setHeader(key, value);\n }\n const buffer = Buffer.from(await response.arrayBuffer());\n res.end(buffer);\n}\n\n/**\n * Adapt a dimah-s3 instance to Node.js `http` / Express-style handlers.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { toNodeHandler } from \"@dimah-s3/server/node\";\n * import { s3 } from \"./s3\";\n *\n * createServer(toNodeHandler(s3)).listen(3000);\n * ```\n */\nexport function toNodeHandler(s3: DimahS3HandlerSource) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n try {\n const body = await collectBody(req);\n const request = toWebRequest(req, body);\n const response = await s3.handler(request);\n await writeWebResponse(res, response);\n } catch (err) {\n console.error(\"[S3 API]\", err);\n if (!res.headersSent) {\n await writeWebResponse(res, toResponse(errors.internalError()));\n }\n }\n };\n}\n","import { fromNodeHeaders, toNodeHandler } from \"./node\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\nexport { fromNodeHeaders };\n\n/**\n * Adapt a dimah-s3 instance to an Express / Connect handler.\n *\n * Mount **before** `express.json()` so the request body is not consumed early.\n *\n * @example\n * ```ts\n * import express from \"express\";\n * import { toExpressHandler } from \"@dimah-s3/server/express\";\n * import { s3 } from \"./s3\";\n *\n * const app = express();\n * // Express 4\n * app.all(\"/api/s3/*\", toExpressHandler(s3));\n * // Express 5 — named wildcard\n * // app.all(\"/api/s3/*splat\", toExpressHandler(s3));\n * app.use(express.json());\n * ```\n */\nexport function toExpressHandler(s3: DimahS3HandlerSource) {\n return toNodeHandler(s3);\n}\n"]}
1
+ {"version":3,"sources":["../../src/helpers/logger.ts","../../src/adapters/node.ts","../../src/adapters/express.ts"],"names":[],"mappings":";;;;;;;AAEO,IAAM,aAAA,GAA+B;AAAA,EAC1C,KAAA,EAAO,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC3B,IAAA,OAAA,CAAQ,KAAA,CAAM,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC9C,CAAA;AAAA,EACA,IAAA,EAAM,CAAC,OAAA,EAAA,GAAY,IAAA,KAAS;AAC1B,IAAA,OAAA,CAAQ,IAAA,CAAK,YAAA,EAAc,OAAA,EAAS,GAAG,IAAI,CAAA;AAAA,EAC7C;AACF,CAAA;;;ACwBO,SAAS,gBAAgB,WAAA,EAA2C;AACzE,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,EAAQ;AAC5B,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,WAAW,CAAA,EAAG;AACtD,IAAA,IAAI,KAAA,IAAS,IAAA,IAAQ,GAAA,CAAI,UAAA,CAAW,GAAG,CAAA,EAAG;AAC1C,IAAA,IAAI,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAA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AAG,MAAM,aAAa,GAAG,CAAA;AAAA,IAC/C;AACA,IAAA,IAAI,CAAC,GAAA,CAAI,SAAA,IAAa,CAAC,GAAA,CAAI,aAAA,MAAmB,GAAA,EAAI;AAAA,EACpD,SAAS,KAAA,EAAO;AACd,IAAA,MAAM,OAAO,MAAA,CAAO,KAAK,CAAA,CAAE,KAAA,CAAM,MAAM,MAAS,CAAA;AAChD,IAAA,MAAM,KAAA;AAAA,EACR;AACF;AAGA,SAAS,aAAa,GAAA,EAAoC;AACxD,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,KAAY;AAC9B,IAAA,MAAM,OAAO,MAAM;AACjB,MAAA,GAAA,CAAI,GAAA,CAAI,SAAS,IAAI,CAAA;AACrB,MAAA,GAAA,CAAI,GAAA,CAAI,SAAS,IAAI,CAAA;AACrB,MAAA,OAAA,EAAQ;AAAA,IACV,CAAA;AACA,IAAA,GAAA,CAAI,IAAA,CAAK,SAAS,IAAI,CAAA;AACtB,IAAA,GAAA,CAAI,IAAA,CAAK,SAAS,IAAI,CAAA;AAAA,EACxB,CAAC,CAAA;AACH;;;ACjKO,SAAS,gBAAA,CACd,IACA,OAAA,EACA;AACA,EAAA,OAAO,aAAA,CAAc,IAAI,OAAO,CAAA;AAClC","file":"express.js","sourcesContent":["import type { DimahS3Logger } from \"@/types\";\n\nexport const defaultLogger: DimahS3Logger = {\n error: (message, ...args) => {\n console.error(\"[dimah-s3]\", message, ...args);\n },\n warn: (message, ...args) => {\n console.warn(\"[dimah-s3]\", message, ...args);\n },\n};\n\nexport function resolveLogger(\n logger: DimahS3Logger | false | undefined,\n): DimahS3Logger {\n if (logger === false) return {};\n if (!logger) return defaultLogger;\n return logger;\n}\n","import type {\n IncomingHttpHeaders,\n IncomingMessage,\n ServerResponse,\n} from \"node:http\";\nimport { Readable } from \"node:stream\";\nimport { s3Error } from \"@dimah-s3/core\";\nimport { toResponse } from \"better-call\";\nimport { defaultLogger } from \"@/helpers/logger\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\n/** Options of the Node, Express and Fastify adapters. */\nexport type NodeHandlerOptions = {\n /**\n * Build the request URL from `X-Forwarded-Proto` and `X-Forwarded-Host`.\n * Turn it on only behind a proxy that sets them, since clients can send\n * them too. Default `false`.\n */\n trustProxy?: boolean;\n};\n\n/**\n * Convert Node.js / Express request headers into a Web {@link Headers} object.\n * Useful when calling `s3.api.*` from a Node handler. HTTP/2 pseudo-headers\n * (`:path`) are left out.\n *\n * @example\n * ```ts\n * import { fromNodeHeaders } from \"@dimah-s3/server/node\";\n *\n * await s3.api.download({ route, key }, { headers: fromNodeHeaders(req.headers) });\n * ```\n */\nexport function fromNodeHeaders(nodeHeaders: IncomingHttpHeaders): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(nodeHeaders)) {\n if (value == null || key.startsWith(\":\")) continue;\n if (Array.isArray(value)) {\n for (const v of value) headers.append(key, v);\n } else {\n headers.set(key, value);\n }\n }\n return headers;\n}\n\n/**\n * Adapt a dimah-s3 instance to Node.js `http` / Express-style handlers.\n *\n * The request body streams from `req`, so the body cap is counted as bytes\n * arrive. When the client disconnects before the response finishes, the\n * request signal aborts and so does the S3 call behind it. Response bodies,\n * such as a `/file` download, stream to `res`.\n *\n * @example\n * ```ts\n * import { createServer } from \"node:http\";\n * import { toNodeHandler } from \"@dimah-s3/server/node\";\n * import { s3 } from \"./s3\";\n *\n * createServer(toNodeHandler(s3)).listen(3000);\n * // Behind a proxy that sets X-Forwarded-Proto / X-Forwarded-Host:\n * // createServer(toNodeHandler(s3, { trustProxy: true }));\n * ```\n */\nexport function toNodeHandler(\n s3: DimahS3HandlerSource,\n options: NodeHandlerOptions = {},\n) {\n return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {\n const controller = new AbortController();\n res.once(\"close\", () => {\n if (!res.writableFinished) controller.abort();\n });\n\n try {\n const request = toWebRequest(req, controller.signal, options);\n await writeWebResponse(res, await s3.handler(request));\n } catch (error) {\n // The client went away; there is no one to answer.\n if (controller.signal.aborted) return;\n defaultLogger.error?.(\"Node adapter failed\", error);\n if (res.headersSent) {\n res.destroy();\n } else {\n await writeWebResponse(res, toResponse(s3Error(\"INTERNAL_ERROR\")));\n }\n }\n };\n}\n\nfunction toWebRequest(\n req: IncomingMessage,\n signal: AbortSignal,\n options: NodeHandlerOptions,\n): Request {\n const method = (req.method ?? \"GET\").toUpperCase();\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n const init: RequestInit & { duplex?: \"half\" } = {\n method,\n headers: fromNodeHeaders(req.headers),\n signal,\n };\n if (hasBody) {\n // The DOM and Node typings of ReadableStream differ; the runtime object is the same.\n init.body = Readable.toWeb(req) as ReadableStream<Uint8Array<ArrayBuffer>>;\n // Node's fetch needs `duplex` for a streaming body.\n init.duplex = \"half\";\n }\n return new Request(requestURL(req, options), init);\n}\n\n/**\n * The absolute request URL, from the socket or the trusted proxy headers.\n * Express sets `originalUrl`, which keeps the mount path that\n * `app.use(\"/api/s3\", …)` strips from `url`.\n */\nfunction requestURL(req: IncomingMessage, options: NodeHandlerOptions): URL {\n const encrypted = (req.socket as { encrypted?: boolean }).encrypted === true;\n let protocol = encrypted ? \"https\" : \"http\";\n let host = req.headers.host ?? \"localhost\";\n\n if (options.trustProxy) {\n const forwardedProto = firstHeaderValue(req.headers[\"x-forwarded-proto\"]);\n if (forwardedProto === \"http\" || forwardedProto === \"https\") {\n protocol = forwardedProto;\n }\n host = firstHeaderValue(req.headers[\"x-forwarded-host\"]) || host;\n }\n const path = (req as { originalUrl?: string }).originalUrl ?? req.url;\n return new URL(path ?? \"/\", `${protocol}://${host}`);\n}\n\n/** The first entry of a header that proxies may append to (`a, b`). */\nfunction firstHeaderValue(value: string | string[] | undefined): string {\n const raw = Array.isArray(value) ? value[0] : value;\n return raw?.split(\",\")[0]?.trim().toLowerCase() ?? \"\";\n}\n\nasync function writeWebResponse(\n res: ServerResponse,\n response: Response,\n): Promise<void> {\n res.statusCode = response.status;\n for (const [key, value] of response.headers) {\n if (key === \"set-cookie\") continue;\n res.setHeader(key, value);\n }\n const cookies = response.headers.getSetCookie();\n if (cookies.length > 0) res.setHeader(\"set-cookie\", cookies);\n\n if (response.body === null) {\n res.end();\n return;\n }\n // `Readable.fromWeb` piped into `res` deadlocks once the body is larger\n // than the stream buffer: each side waits for the other to pull. Read\n // the web stream and write it, waiting for `drain` when Node's buffer\n // is full.\n const reader = response.body.getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (res.destroyed || res.writableEnded) {\n await reader.cancel();\n return;\n }\n if (!value?.byteLength) continue;\n if (!res.write(value)) await waitForDrain(res);\n }\n if (!res.destroyed && !res.writableEnded) res.end();\n } catch (error) {\n await reader.cancel(error).catch(() => undefined);\n throw error;\n }\n}\n\n/** Resolves when `res` accepts more data, or when the client has gone. */\nfunction waitForDrain(res: ServerResponse): Promise<void> {\n return new Promise((resolve) => {\n const done = () => {\n res.off(\"drain\", done);\n res.off(\"close\", done);\n resolve();\n };\n res.once(\"drain\", done);\n res.once(\"close\", done);\n });\n}\n","import {\n fromNodeHeaders,\n toNodeHandler,\n type NodeHandlerOptions,\n} from \"./node\";\nimport type { DimahS3HandlerSource } from \"./types\";\n\nexport { fromNodeHeaders, type NodeHandlerOptions };\n\n/**\n * Adapt a dimah-s3 instance to an Express / Connect handler.\n *\n * Mount **before** `express.json()` so the request body is not consumed early.\n * A route (`app.all`) and a mount (`app.use(\"/api/s3\", …)`) both work: the\n * request URL is read from `req.originalUrl`. Takes the same options as\n * `toNodeHandler`, such as `{ trustProxy: true }` behind a proxy.\n *\n * @example\n * ```ts\n * import express from \"express\";\n * import { toExpressHandler } from \"@dimah-s3/server/express\";\n * import { s3 } from \"./s3\";\n *\n * const app = express();\n * app.use(\"/api/s3\", toExpressHandler(s3));\n * app.use(express.json());\n * ```\n */\nexport function toExpressHandler(\n s3: DimahS3HandlerSource,\n options?: NodeHandlerOptions,\n) {\n return toNodeHandler(s3, options);\n}\n"]}
@@ -1,5 +1,7 @@
1
1
  import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { type NodeHandlerOptions } from "./node";
2
3
  import type { DimahS3HandlerSource } from "./types";
4
+ export type { NodeHandlerOptions };
3
5
  /** Structural Fastify request/reply — avoids a hard dependency on `fastify`. */
4
6
  type FastifyRequestLike = {
5
7
  raw: IncomingMessage;
@@ -12,8 +14,9 @@ type FastifyReplyLike = {
12
14
  * Adapt a dimah-s3 instance to a Fastify route handler.
13
15
  *
14
16
  * Uses `reply.hijack()` and the Node adapter so Fastify does not touch the
15
- * response stream. Mount this route **before** body parsers (or disable JSON
16
- * parsing for `/api/s3/*`) so the request body stays readable.
17
+ * response stream. Turn Fastify's body parsing off for these routes, as
18
+ * below, so the adapter can stream the raw body. Takes the same options as
19
+ * `toNodeHandler`.
17
20
  *
18
21
  * @example
19
22
  * ```ts
@@ -22,9 +25,12 @@ type FastifyReplyLike = {
22
25
  * import { s3 } from "./s3";
23
26
  *
24
27
  * const app = Fastify();
25
- * app.all("/api/s3/*", toFastifyHandler(s3));
28
+ * app.register(async (scope) => {
29
+ * scope.removeAllContentTypeParsers();
30
+ * scope.addContentTypeParser("*", (_request, _payload, done) => done(null));
31
+ * scope.all("/api/s3/*", toFastifyHandler(s3));
32
+ * });
26
33
  * ```
27
34
  */
28
- export declare function toFastifyHandler(s3: DimahS3HandlerSource): (req: FastifyRequestLike, reply: FastifyReplyLike) => Promise<void>;
29
- export {};
35
+ export declare function toFastifyHandler(s3: DimahS3HandlerSource, options?: NodeHandlerOptions): (req: FastifyRequestLike, reply: FastifyReplyLike) => Promise<void>;
30
36
  //# sourceMappingURL=fastify.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.d.ts","sourceRoot":"","sources":["../../src/adapters/fastify.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD,gFAAgF;AAChF,KAAK,kBAAkB,GAAG;IACxB,GAAG,EAAE,eAAe,CAAC;CACtB,CAAC;AAEF,KAAK,gBAAgB,GAAG;IACtB,GAAG,EAAE,cAAc,CAAC;IACpB,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,oBAAoB,SAEpC,kBAAkB,SAAS,gBAAgB,mBAI/D"}
1
+ {"version":3,"file":"fastify.d.ts","sourceRoot":"","sources":["../../src/adapters/fastify.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,EAAiB,KAAK,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAChE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAC;AAEpD,YAAY,EAAE,kBAAkB,EAAE,CAAC;AAEnC,gFAAgF;AAChF,KAAK,kBAAkB,GAAG;IACxB,GAAG,EAAE,eAAe,CAAC;CACtB,CAAC;AAEF,KAAK,gBAAgB,GAAG;IACtB,GAAG,EAAE,cAAc,CAAC;IACpB,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,gBAAgB,CAC9B,EAAE,EAAE,oBAAoB,EACxB,OAAO,CAAC,EAAE,kBAAkB,SAGT,kBAAkB,SAAS,gBAAgB,mBAI/D"}