@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/dist/plugins.js CHANGED
@@ -1,1710 +1,408 @@
1
- import { S3_API_ROUTES, isAPIError, APIError, S3_ERROR_CODES, confirmBodySchema, deleteQuerySchema, deleteBatchBodySchema, downloadQuerySchema, fileQuerySchema, multipartAbortBodySchema, multipartCompleteBodySchema, multipartInitBodySchema, multipartListPartsQuerySchema, multipartSignPartBodySchema, uploadBodySchema, buildContentDisposition, S3_MAX_EXPIRES_IN, S3_MAX_POST_OBJECT_BYTES, resolveStoredFileName, resolveInlineDisposition, fileNameFromKey, S3_DEFAULT_EXPIRES_IN, matchesFileTypes, ROUTE_NAME_PATTERN, normalizeObjectKey, sanitizeFileName } from '@dimah-s3/core';
2
- import { DeleteObjectCommand, GetObjectCommand, CreateMultipartUploadCommand, UploadPartCommand, PutObjectCommand, HeadObjectCommand, ListPartsCommand, AbortMultipartUploadCommand, CompleteMultipartUploadCommand } from '@aws-sdk/client-s3';
1
+ import { S3_API_ROUTES, s3Error, APIError, base64UrlDecode } from '@dimah-s3/core';
3
2
  import { createMiddleware, createEndpoint } from 'better-call';
4
3
  import * as z from 'zod';
5
- import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
6
- import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
4
+ import { statusCodes, APIError as APIError$1 } from 'better-call/error';
5
+ import { DeleteObjectCommand } from '@aws-sdk/client-s3';
7
6
 
8
- // src/plugin/apply-plugins.ts
9
- async function deleteObjectBestEffort(client, bucket, key) {
10
- try {
11
- await client.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
12
- } catch {
13
- }
14
- }
15
- async function abortMultipartBestEffort(client, bucket, key, uploadId) {
16
- try {
17
- await client.send(
18
- new AbortMultipartUploadCommand({
19
- Bucket: bucket,
20
- Key: key,
21
- UploadId: uploadId
22
- })
23
- );
24
- } catch {
7
+ // src/api/create-s3-endpoint.ts
8
+ var NETWORK_CODES = /* @__PURE__ */ new Set([
9
+ "EAI_AGAIN",
10
+ "ECONNREFUSED",
11
+ "ECONNRESET",
12
+ "EHOSTUNREACH",
13
+ "ENETUNREACH",
14
+ "ENOTFOUND",
15
+ "EPIPE",
16
+ "ETIMEDOUT",
17
+ "UND_ERR_CONNECT_TIMEOUT",
18
+ "UND_ERR_SOCKET"
19
+ ]);
20
+ var STATUS_NAMES = new Map(
21
+ Object.entries(statusCodes).map(([name, status]) => [status, name])
22
+ );
23
+ var ConfigError = class extends Error {
24
+ constructor(message) {
25
+ super(message);
26
+ this.name = "ConfigError";
25
27
  }
26
- }
27
- var errors = {
28
- notFound: () => APIError.from("NOT_FOUND", S3_ERROR_CODES.NOT_FOUND),
29
- unauthorized: () => APIError.from("UNAUTHORIZED", S3_ERROR_CODES.UNAUTHORIZED),
30
- forbidden: () => APIError.from("FORBIDDEN", S3_ERROR_CODES.FORBIDDEN),
31
- conflict: () => APIError.from("CONFLICT", S3_ERROR_CODES.CONFLICT),
32
- internalError: () => APIError.from("INTERNAL_SERVER_ERROR", S3_ERROR_CODES.INTERNAL_ERROR),
33
- objectNotFound: () => APIError.from("NOT_FOUND", S3_ERROR_CODES.OBJECT_NOT_FOUND),
34
- featureDisabled: (feature) => APIError.from("NOT_FOUND", {
35
- code: S3_ERROR_CODES.FEATURE_DISABLED.code,
36
- message: S3_ERROR_CODES.FEATURE_DISABLED.message.replaceAll(
37
- "{feature}",
38
- feature
39
- ),
40
- params: { feature }
41
- }),
42
- invalidKey: () => APIError.from("BAD_REQUEST", S3_ERROR_CODES.INVALID_KEY),
43
- unknownRoute: (route) => APIError.from("NOT_FOUND", {
44
- code: S3_ERROR_CODES.UNKNOWN_ROUTE.code,
45
- message: S3_ERROR_CODES.UNKNOWN_ROUTE.message,
46
- params: { route }
47
- }),
48
- fileTypeNotAllowed: (fileName, contentType) => APIError.from("BAD_REQUEST", {
49
- code: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.code,
50
- message: S3_ERROR_CODES.FILE_TYPE_NOT_ALLOWED.message,
51
- params: {
52
- fileName,
53
- ...contentType ? { contentType } : {}
54
- }
55
- }),
56
- s3NetworkError: (code) => APIError.from("BAD_GATEWAY", {
57
- code: S3_ERROR_CODES.S3_NETWORK_ERROR.code,
58
- message: S3_ERROR_CODES.S3_NETWORK_ERROR.message.replaceAll(
59
- "{code}",
60
- code
61
- ),
62
- params: { code }
63
- }),
64
- multipartPartMissing: (partNumber) => APIError.from("BAD_REQUEST", {
65
- code: S3_ERROR_CODES.MULTIPART_PART_MISSING.code,
66
- message: S3_ERROR_CODES.MULTIPART_PART_MISSING.message.replaceAll(
67
- "{partNumber}",
68
- String(partNumber)
69
- ),
70
- params: { partNumber }
71
- }),
72
- payloadTooLarge: (message = S3_ERROR_CODES.PAYLOAD_TOO_LARGE.message) => APIError.from("PAYLOAD_TOO_LARGE", {
73
- ...S3_ERROR_CODES.PAYLOAD_TOO_LARGE,
74
- message
75
- }),
76
- quotaExceeded: (message = S3_ERROR_CODES.QUOTA_EXCEEDED.message) => APIError.from("PAYLOAD_TOO_LARGE", {
77
- ...S3_ERROR_CODES.QUOTA_EXCEEDED,
78
- message
79
- }),
80
- validationError: (message) => APIError.from("BAD_REQUEST", {
81
- code: S3_ERROR_CODES.VALIDATION_ERROR.code,
82
- message
83
- })
84
28
  };
85
-
86
- // src/helpers/is-aws-not-found.ts
87
- function isAwsNotFound(err) {
88
- const e = err;
89
- return e?.name === "NoSuchKey" || e?.name === "NotFound" || e?.name === "NoSuchUpload" || e?.Code === "NoSuchKey" || e?.Code === "NotFound" || e?.Code === "NoSuchUpload" || e?.$metadata?.httpStatusCode === 404;
90
- }
91
- async function sendOrObjectNotFound(send) {
29
+ function toAPIError(error, env, request, operation) {
30
+ if (isHttpError(error)) return normalizeAPIError(error);
31
+ const networkCode = socketErrorCode(error);
32
+ const result = networkCode ? s3Error("S3_NETWORK_ERROR", { code: networkCode }, { cause: error }) : s3Error("INTERNAL_ERROR", void 0, { cause: error });
33
+ if (!request.signal.aborted) {
34
+ report(error, result, env, { request, operation });
35
+ }
36
+ return result;
37
+ }
38
+ function report(error, result, env, context) {
39
+ env.logger.error?.(logMessage(error, result), error);
40
+ const failed = (hookError) => {
41
+ env.logger.error?.("onError threw", hookError);
42
+ };
92
43
  try {
93
- return await send();
94
- } catch (err) {
95
- if (isAwsNotFound(err)) throw errors.objectNotFound();
96
- throw err;
97
- }
98
- }
99
- function normalizeExpiresIn(value, maxExpiresIn = S3_MAX_EXPIRES_IN) {
100
- const n = Number(value);
101
- const expires = Number.isFinite(n) && n > 0 ? Math.floor(n) : S3_DEFAULT_EXPIRES_IN;
102
- const max = Number.isFinite(maxExpiresIn) && maxExpiresIn > 0 ? Math.floor(maxExpiresIn) : S3_MAX_EXPIRES_IN;
103
- return Math.min(expires, max);
104
- }
105
- function clampDownloadExpiresIn(options) {
106
- const max = options.maxExpiresIn;
107
- if (options.resolvedExpiresIn != null) {
108
- return normalizeExpiresIn(options.resolvedExpiresIn, max);
44
+ void Promise.resolve(env.onError?.(error, context)).catch(failed);
45
+ } catch (hookError) {
46
+ failed(hookError);
109
47
  }
110
- const cap = normalizeExpiresIn(options.routeExpiresIn, max);
111
- if (options.requested == null) return cap;
112
- return Math.min(normalizeExpiresIn(options.requested, max), cap);
113
48
  }
114
-
115
- // src/helpers/logger.ts
116
- var defaultLogger = {
117
- error: (message, ...args) => {
118
- console.error("[dimah-s3]", message, ...args);
119
- },
120
- warn: (message, ...args) => {
121
- console.warn("[dimah-s3]", message, ...args);
49
+ function isHttpError(error) {
50
+ if (error instanceof APIError || error instanceof APIError$1) {
51
+ return true;
122
52
  }
123
- };
124
- function resolveLogger(logger) {
125
- if (logger === false) return {};
126
- if (!logger) return defaultLogger;
127
- return logger;
53
+ const candidate = error;
54
+ return candidate?.name === "APIError" && typeof candidate.statusCode === "number" && typeof candidate.body?.code === "string";
55
+ }
56
+ function logMessage(error, result) {
57
+ if (error instanceof ConfigError) return `Config error: ${error.message}`;
58
+ if (result.code === "S3_NETWORK_ERROR") return result.message;
59
+ return error instanceof Error ? error.message : String(error);
60
+ }
61
+ function socketErrorCode(error) {
62
+ const candidates = [error, error?.cause];
63
+ for (const candidate of candidates) {
64
+ const code = candidate?.code;
65
+ if (typeof code === "string" && NETWORK_CODES.has(code)) return code;
66
+ }
67
+ return void 0;
68
+ }
69
+ function normalizeAPIError(error) {
70
+ if (error instanceof APIError) return error;
71
+ const body = error.body ?? {};
72
+ const status = typeof error.statusCode === "number" ? error.statusCode : 500;
73
+ const message = typeof body.message === "string" ? body.message : error.message;
74
+ const code = typeof body.code === "string" ? body.code : STATUS_NAMES.get(status) ?? "INTERNAL_ERROR";
75
+ switch (code) {
76
+ case "UNSUPPORTED_MEDIA_TYPE":
77
+ return s3Error("UNSUPPORTED_MEDIA_TYPE", void 0, { cause: error });
78
+ case "BAD_REQUEST":
79
+ case "VALIDATION_ERROR":
80
+ return s3Error("VALIDATION_ERROR", { issue: message }, { cause: error });
81
+ case "INTERNAL_SERVER_ERROR":
82
+ return s3Error("INTERNAL_ERROR", void 0, { cause: error });
83
+ }
84
+ return new APIError(
85
+ status,
86
+ {
87
+ code,
88
+ message,
89
+ ...body.params !== void 0 ? { params: body.params } : {},
90
+ cause: error
91
+ },
92
+ error.headers
93
+ );
128
94
  }
129
95
 
130
96
  // src/helpers/hooks.ts
131
- function mapGuardError(err) {
132
- if (isAPIError(err)) throw err;
133
- if (err instanceof Error && err.message.trim()) {
134
- throw new APIError("FORBIDDEN", {
135
- message: err.message,
136
- cause: err
137
- });
138
- }
139
- throw errors.forbidden();
140
- }
141
- async function runHook(hook, context) {
142
- if (!hook) return;
143
- try {
144
- await hook(context);
145
- } catch (err) {
146
- mapGuardError(err);
147
- }
148
- }
149
- async function runObjectHook(hook, context) {
150
- if (!hook) return;
151
- try {
152
- return await hook(context);
153
- } catch (err) {
154
- mapGuardError(err);
97
+ function createLocals(seed) {
98
+ const locals = /* @__PURE__ */ Object.create(null);
99
+ return locals;
100
+ }
101
+ async function runGuards(guards, context) {
102
+ for (const { plugin, hook } of guards) {
103
+ const result = await hook(context);
104
+ if (result === void 0) continue;
105
+ if (!isGuardResult(result)) {
106
+ throw new ConfigError(
107
+ `${guardName(plugin)} for "${context.operation}" returned ${describeValue(result)}. Return nothing or { locals } to allow, and throw to reject.`
108
+ );
109
+ }
110
+ mergeLocals(context.locals, result.locals);
155
111
  }
156
112
  }
157
- async function runLifecycleHook(hook, context, config) {
158
- if (!hook) return;
159
- try {
160
- await hook(context);
161
- } catch (err) {
162
- if (isAPIError(err)) throw err;
163
- resolveLogger(config?.logger).error?.("lifecycle hook failed", err);
164
- config?.onError?.(err, { request: context.request });
165
- throw errors.internalError();
113
+ function mergeLocals(target, source) {
114
+ for (const [key, value] of Object.entries(source)) {
115
+ target[key] = value;
166
116
  }
167
117
  }
168
-
169
- // src/helpers/previous-key.ts
170
- var DIMAH_PREVIOUS_KEY_META = "dimah-previous-key";
171
- function stripPreviousKeyMeta(metadata) {
172
- if (!metadata) return {};
173
- const { [DIMAH_PREVIOUS_KEY_META]: _omit, ...rest } = metadata;
174
- return rest;
175
- }
176
- function previousKeyFromMetadata(metadata) {
177
- const value = metadata?.[DIMAH_PREVIOUS_KEY_META]?.trim();
178
- return value || void 0;
118
+ function isGuardResult(value) {
119
+ if (!isPlainObject(value)) return false;
120
+ const keys = Object.keys(value);
121
+ return keys.length === 1 && keys[0] === "locals" && typeof value.locals === "object" && value.locals !== null && !Array.isArray(value.locals);
179
122
  }
180
-
181
- // src/helpers/object-s3.ts
182
- var MAX_S3_TAGS = 10;
183
- var MAX_TAG_KEY_CHARS = 128;
184
- var MAX_TAG_VALUE_CHARS = 256;
185
- function present(value) {
186
- const trimmed = value?.trim();
187
- return trimmed ? trimmed : void 0;
123
+ function isPlainObject(value) {
124
+ if (typeof value !== "object" || value === null) return false;
125
+ const proto = Object.getPrototypeOf(value);
126
+ return proto === Object.prototype || proto === null;
188
127
  }
189
- function assertTagEntry(key, value) {
190
- if (key.length === 0) {
191
- throw errors.validationError("S3 object tag keys cannot be empty");
192
- }
193
- if (key.length > MAX_TAG_KEY_CHARS) {
194
- throw errors.validationError(
195
- `S3 object tag keys cannot exceed ${MAX_TAG_KEY_CHARS} characters`
196
- );
197
- }
198
- if (value.length > MAX_TAG_VALUE_CHARS) {
199
- throw errors.validationError(
200
- `S3 object tag values cannot exceed ${MAX_TAG_VALUE_CHARS} characters`
201
- );
202
- }
128
+ function guardName(plugin) {
129
+ return plugin === void 0 ? "A guard" : `The "${plugin}" plugin guard`;
203
130
  }
204
- function encodeObjectTagging(tagging) {
205
- const entries = Object.entries(tagging);
206
- if (entries.length > MAX_S3_TAGS) {
207
- throw errors.validationError(
208
- `S3 object tagging allows at most ${MAX_S3_TAGS} tags`
209
- );
131
+ function describeValue(value) {
132
+ switch (typeof value) {
133
+ case "string":
134
+ return "a string";
135
+ case "function":
136
+ return "a function";
137
+ case "object":
138
+ if (value === null) return "null";
139
+ return Array.isArray(value) ? "an array" : "an object other than { locals }";
140
+ default:
141
+ return String(value);
210
142
  }
211
- return entries.map(([key, value]) => {
212
- assertTagEntry(key, value);
213
- return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
214
- }).join("&");
215
- }
216
- function taggingHeader(tagging) {
217
- if (!tagging || Object.keys(tagging).length === 0) return void 0;
218
- return encodeObjectTagging(tagging);
219
- }
220
- function normalizeObjectS3(info) {
221
- const storageClass = present(info?.storageClass);
222
- const cacheControl = present(info?.cacheControl);
223
- const tagging = info?.tagging && Object.keys(info.tagging).length > 0 ? info.tagging : void 0;
224
- if (tagging) encodeObjectTagging(tagging);
225
- return {
226
- ...storageClass ? { storageClass } : {},
227
- ...cacheControl ? { cacheControl } : {},
228
- ...tagging ? { tagging } : {}
229
- };
230
- }
231
- function objectCommandExtras(opts) {
232
- const tagging = taggingHeader(opts.tagging);
233
- return {
234
- ...opts.storageClass ? { StorageClass: opts.storageClass } : {},
235
- ...opts.cacheControl ? { CacheControl: opts.cacheControl } : {},
236
- ...tagging ? { Tagging: tagging } : {}
237
- };
238
- }
239
- function objectPutHeaders(opts) {
240
- const tagging = taggingHeader(opts.tagging);
241
- return {
242
- ...opts.cacheControl ? { "Cache-Control": opts.cacheControl } : {},
243
- ...opts.storageClass ? { "x-amz-storage-class": opts.storageClass } : {},
244
- ...tagging ? { "x-amz-tagging": tagging } : {}
245
- };
246
143
  }
247
144
 
248
- // src/helpers/resolve-target.ts
249
- function assertSafeObjectKey(key) {
250
- const normalized = normalizeObjectKey(key);
251
- if (!normalized) throw errors.invalidKey();
252
- return normalized;
253
- }
254
- function applyPrefix(prefix, key) {
255
- const p = assertSafeObjectKey(prefix);
256
- const k = assertSafeObjectKey(key);
257
- if (k.startsWith(`${p}/`)) return k;
258
- if (k === p) throw errors.invalidKey();
259
- return `${p}/${k}`;
260
- }
261
- function nestKeyUnderPrefix(keyPrefix, key) {
262
- const safe = assertSafeObjectKey(key);
263
- if (keyPrefix === false) return safe;
264
- return applyPrefix(keyPrefix, safe);
265
- }
266
- function assertStoredKey(key, keyPrefix) {
267
- const safe = assertSafeObjectKey(key);
268
- if (keyPrefix === false) return safe;
269
- const root = assertSafeObjectKey(keyPrefix);
270
- if (safe.startsWith(`${root}/`)) return safe;
271
- throw errors.invalidKey();
272
- }
273
- function objectKeyFileName(fileName) {
274
- const sanitized = sanitizeFileName(fileName);
275
- const leaf = sanitized.split("/").findLast((part) => part.length > 0);
276
- if (!leaf || leaf === "." || leaf === "..") return "file";
277
- return leaf;
278
- }
279
- function generateObjectKey(folder, fileName) {
280
- const leaf = `${crypto.randomUUID()}/${objectKeyFileName(fileName)}`;
281
- if (folder === false) return assertSafeObjectKey(leaf);
282
- return applyPrefix(folder, leaf);
283
- }
284
- function resolveAcl(info, route) {
285
- return info?.acl ?? route.upload.acl ?? "private";
286
- }
287
- async function resolveUploadTarget(route, context) {
288
- const bucket = route.bucket;
289
- const objectContext = {
290
- ...context,
291
- bucket,
292
- keyPrefix: route.keyPrefix
293
- };
294
- const info = await runObjectHook(route.upload.object, objectContext) ?? void 0;
295
- const key = info?.key ? nestKeyUnderPrefix(route.keyPrefix, info.key) : generateObjectKey(
296
- info?.folder != null && info.folder !== "" ? nestKeyUnderPrefix(route.keyPrefix, info.folder) : route.keyPrefix === false ? false : route.keyPrefix,
297
- context.file.name
298
- );
299
- const metadata = { ...info?.metadata };
300
- if (info?.previousKey) {
301
- metadata[DIMAH_PREVIOUS_KEY_META] = nestKeyUnderPrefix(
302
- route.keyPrefix,
303
- info.previousKey
304
- );
305
- }
306
- return {
307
- key,
308
- bucket,
309
- metadata: Object.keys(metadata).length > 0 ? metadata : info?.metadata,
310
- acl: resolveAcl(info, route),
311
- ...normalizeObjectS3(info)
312
- };
313
- }
314
- function resolveStoredTarget(route, key) {
315
- return {
316
- key: assertStoredKey(key, route.keyPrefix),
317
- bucket: route.bucket
318
- };
319
- }
320
- function assertRouteName(name) {
321
- if (!ROUTE_NAME_PATTERN.test(name)) {
322
- throw new Error(
323
- `dimahS3 route "${name}" is invalid. Use a letter followed by up to 63 letters, digits, underscores, or hyphens.`
324
- );
325
- }
145
+ // src/helpers/request.ts
146
+ function syntheticRequest(config, init = {}) {
147
+ return new Request(config.baseURL ?? `http://localhost${config.basePath}`, {
148
+ headers: init.headers,
149
+ signal: init.signal
150
+ });
326
151
  }
327
152
 
328
- // src/helpers/features.ts
329
- function isEnabled(feature) {
330
- return feature.enabled;
331
- }
332
- function resolveKeyPrefix(name, value) {
333
- if (value === false) return false;
334
- const normalized = normalizeObjectKey(value ?? name);
335
- if (!normalized) {
153
+ // src/api/router-context.ts
154
+ var RESOLVED_CONFIG = /* @__PURE__ */ Symbol.for("dimah-s3.resolved-config");
155
+ function resolvedConfig(context) {
156
+ const resolved = context[RESOLVED_CONFIG];
157
+ if (!resolved) {
336
158
  throw new Error(
337
- `dimahS3 route "${name}": keyPrefix is not a valid object-key prefix.`
159
+ "createS3Endpoint needs the dimahS3 router context. Mount the endpoint as a plugin endpoint and call it through the HTTP handler."
338
160
  );
339
161
  }
340
- return normalized;
341
- }
342
- function isFeatureOn(value, defaultOn = false) {
343
- if (value === false) return false;
344
- if (value === void 0) return defaultOn;
345
- if (value === true) return true;
346
- if ("enabled" in value && typeof value.enabled === "boolean") {
347
- return value.enabled;
348
- }
349
- return true;
350
- }
351
- function normalizeFeature(value, defaultOn = false) {
352
- if (value === false) return { enabled: false };
353
- if (value === void 0) {
354
- if (!defaultOn) return { enabled: false };
355
- return { enabled: true };
356
- }
357
- if (value === true) return { enabled: true };
358
- return { ...value, enabled: true };
162
+ return resolved;
359
163
  }
360
- function skippedPluginIds(plugins) {
361
- const ids = /* @__PURE__ */ new Set();
362
- if (!plugins) return ids;
363
- for (const [id, enabled] of Object.entries(plugins)) {
364
- if (!enabled) ids.add(id);
365
- }
366
- return ids;
367
- }
368
- function splitUpload(upload2) {
369
- if (upload2 === void 0 || typeof upload2 === "boolean") {
370
- return { upload: upload2, multipart: void 0 };
371
- }
372
- const { multipart, ...rest } = upload2;
373
- return { upload: rest, multipart };
374
- }
375
- function normalizeRoute(name, route, instance) {
376
- assertRouteName(name);
377
- const client = route.client ?? instance.client;
378
- const bucket = route.bucket ?? instance.bucket;
379
- if (!client) {
380
- throw new Error(
381
- `dimahS3 route "${name}": set client on the route or on dimahS3().`
382
- );
383
- }
384
- if (!bucket) {
385
- throw new Error(
386
- `dimahS3 route "${name}": set bucket on the route or on dimahS3().`
387
- );
388
- }
389
- const { upload: uploadInput, multipart: multipartInput } = splitUpload(
390
- route.upload
391
- );
392
- const upload2 = normalizeFeature(uploadInput);
393
- const download2 = normalizeFeature(route.download);
394
- const deleteFeature = normalizeFeature(route.delete);
395
- const multipart = normalizeFeature(multipartInput);
396
- if (!upload2.enabled && !download2.enabled && !deleteFeature.enabled) {
397
- throw new Error(
398
- `dimahS3 route "${name}": enable upload, download, or delete.`
399
- );
400
- }
401
- const resolvedUpload = upload2.enabled ? { ...upload2, multipart } : { enabled: false, multipart: { enabled: false } };
402
- if (resolvedUpload.enabled) {
403
- const maxFileSize = resolvedUpload.maxFileSize;
404
- if (maxFileSize != null && (!Number.isFinite(maxFileSize) || maxFileSize <= 0)) {
405
- throw new Error(
406
- `dimahS3 route "${name}": maxFileSize must be a positive number.`
407
- );
408
- }
409
- }
410
- return {
411
- name,
412
- client,
413
- bucket,
414
- keyPrefix: resolveKeyPrefix(name, route.keyPrefix),
415
- guard: route.guard,
416
- skippedPluginIds: skippedPluginIds(route.plugins),
417
- upload: resolvedUpload,
418
- download: download2,
419
- delete: deleteFeature
420
- };
421
- }
422
- function normalizeRoutes(config) {
423
- const entries = Object.entries(config.routes);
424
- if (entries.length === 0) {
425
- throw new Error("dimahS3: at least one route is required.");
426
- }
427
- const routes = {};
428
- for (const [name, route] of entries) {
429
- routes[name] = normalizeRoute(name, route, config);
430
- }
431
- assertDistinctKeyPrefixes(routes);
432
- return routes;
433
- }
434
- function prefixesOverlap(a, b) {
435
- return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
436
- }
437
- function assertDistinctKeyPrefixes(routes) {
438
- const named = Object.entries(routes).filter(
439
- (entry) => entry[1].keyPrefix !== false
440
- );
441
- for (let i = 0; i < named.length; i++) {
442
- for (let j = i + 1; j < named.length; j++) {
443
- const [nameA, routeA] = named[i];
444
- const [nameB, routeB] = named[j];
445
- if (prefixesOverlap(routeA.keyPrefix, routeB.keyPrefix)) {
446
- throw new Error(
447
- `dimahS3: routes "${nameA}" and "${nameB}" have overlapping keyPrefix values ("${routeA.keyPrefix}" and "${routeB.keyPrefix}").`
448
- );
164
+
165
+ // src/api/create-s3-middleware.ts
166
+ function contextMiddleware(options) {
167
+ return createMiddleware(async (ctx) => {
168
+ const resolved = resolvedConfig(ctx.context);
169
+ const injected = ctx.context;
170
+ const { config } = injected;
171
+ const request = ctx.request ?? syntheticRequest(resolved, { headers: ctx.headers });
172
+ if (injected.locals) return { config, request, locals: injected.locals };
173
+ const locals = createLocals();
174
+ if (options.runGuards) {
175
+ try {
176
+ await runGuards(resolved.guard, {
177
+ request,
178
+ operation: "plugin",
179
+ locals
180
+ });
181
+ } catch (error) {
182
+ throw toAPIError(error, resolved, request, "plugin");
449
183
  }
450
184
  }
451
- }
452
- }
453
-
454
- // src/helpers/request.ts
455
- var SYNTHETIC_ORIGIN = "http://dimah-s3.local";
456
- function requestFromHeaders(headers) {
457
- return new Request(SYNTHETIC_ORIGIN, { headers });
458
- }
459
- function assertWithinMaxFileSize(maxFileSize, size) {
460
- if (typeof maxFileSize === "number" && size > maxFileSize) {
461
- throw errors.payloadTooLarge();
462
- }
463
- }
464
- function assertDeclaredConstraints(constraints, input) {
465
- if (constraints?.fileTypes?.length && !matchesFileTypes(input.fileName, input.contentType, constraints.fileTypes)) {
466
- throw errors.fileTypeNotAllowed(input.fileName, input.contentType);
467
- }
468
- assertWithinMaxFileSize(constraints?.maxFileSize, input.fileSize);
469
- }
470
- function assertVerifiedConstraints(constraints, input) {
471
- assertWithinMaxFileSize(constraints?.maxFileSize, input.contentLength);
472
- const name = input.fileName ?? "";
473
- if (constraints?.fileTypes?.length && !matchesFileTypes(name, input.contentType, constraints.fileTypes)) {
474
- throw errors.fileTypeNotAllowed(name || "unknown", input.contentType);
475
- }
476
- }
477
-
478
- // src/helpers/resolve-route.ts
479
- function getResolvedRoute(config, name) {
480
- const route = config.routes[name];
481
- if (!route) {
482
- throw errors.unknownRoute(name);
483
- }
484
- return route;
485
- }
486
- function featureIsEnabled(route, feature) {
487
- if (feature === "multipart") return route.upload.multipart.enabled;
488
- return route[feature].enabled;
489
- }
490
- function assertFeatureEnabled(route, feature) {
491
- if (!featureIsEnabled(route, feature)) {
492
- throw errors.featureDisabled(feature);
493
- }
494
- }
495
- async function openRoute(config, name, request, feature) {
496
- const route = getResolvedRoute(config, name);
497
- assertFeatureEnabled(route, feature);
498
- await runHook(route.guard, { request, route: route.name });
499
- return route;
500
- }
501
- function storedObjectContext(request, route, key) {
502
- return { request, route: route.name, key, bucket: route.bucket };
503
- }
504
- async function openUploadTarget(config, input, request, feature) {
505
- const route = await openRoute(config, input.route, request, feature);
506
- const fileSize = Math.floor(input.fileSize);
507
- const fileName = input.fileName;
508
- assertDeclaredConstraints(route.upload, {
509
- fileName,
510
- fileSize,
511
- contentType: input.contentType
512
- });
513
- const target = await resolveUploadTarget(route, {
514
- request,
515
- route: route.name,
516
- file: {
517
- name: fileName,
518
- size: fileSize,
519
- type: input.contentType
520
- },
521
- clientMetadata: input.metadata
185
+ return { config, request, locals };
522
186
  });
523
- return {
524
- route,
525
- ...target,
526
- stored: storedObjectContext(request, route, target.key)
527
- };
528
- }
529
- async function openStoredTarget(config, input, request, feature) {
530
- const route = await openRoute(config, input.route, request, feature);
531
- const target = resolveStoredTarget(route, input.key);
532
- return {
533
- route,
534
- ...target,
535
- stored: storedObjectContext(request, route, target.key)
536
- };
537
- }
538
- async function objectExists(client, bucket, key) {
539
- try {
540
- await client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }));
541
- return true;
542
- } catch (err) {
543
- if (isAwsNotFound(err)) return false;
544
- throw err;
545
- }
546
- }
547
- async function headObjectOrNotFound(client, bucket, key) {
548
- return sendOrObjectNotFound(
549
- () => client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
550
- );
551
187
  }
552
- async function headObjectAfterMultipartComplete(client, bucket, key) {
553
- const send = () => sendOrObjectNotFound(
554
- () => client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
555
- );
556
- let head = await send();
557
- for (let attempt = 0; attempt < 4 && typeof head.ContentLength !== "number"; attempt++) {
558
- await new Promise((r) => setTimeout(r, 250 * 2 ** attempt));
559
- head = await send();
560
- }
561
- return head;
562
- }
563
- function requireContentLength(head) {
564
- if (typeof head.ContentLength !== "number") {
565
- throw errors.internalError();
566
- }
567
- return head.ContentLength;
568
- }
569
- async function listAllParts(client, input) {
570
- const parts = [];
571
- let partNumberMarker;
572
- let isTruncated = true;
573
- while (isTruncated) {
574
- const response = await sendOrObjectNotFound(
575
- () => client.send(
576
- new ListPartsCommand({
577
- Bucket: input.bucket,
578
- Key: input.key,
579
- UploadId: input.uploadId,
580
- ...partNumberMarker ? { PartNumberMarker: partNumberMarker } : {}
581
- })
582
- )
188
+ var s3ContextMiddleware = contextMiddleware({ runGuards: true });
189
+ var coreContextMiddleware = contextMiddleware({ runGuards: false });
190
+ var createS3Middleware = createMiddleware.create({
191
+ use: [s3ContextMiddleware]
192
+ });
193
+
194
+ // src/api/create-s3-endpoint.ts
195
+ var pluginEndpoint = createEndpoint.create({
196
+ use: [s3ContextMiddleware]
197
+ });
198
+ createEndpoint.create({
199
+ use: [coreContextMiddleware]
200
+ });
201
+ var BODY_MEDIA_TYPES = ["application/json"];
202
+ var CORE_PATHS = new Set(Object.values(S3_API_ROUTES));
203
+ function createS3Endpoint(path, options, handler) {
204
+ if (CORE_PATHS.has(path)) {
205
+ throw new Error(
206
+ `createS3Endpoint("${path}"): the path belongs to a core endpoint.`
583
207
  );
584
- parts.push(...response.Parts ?? []);
585
- isTruncated = response.IsTruncated === true;
586
- partNumberMarker = isTruncated ? response.NextPartNumberMarker : void 0;
587
- }
588
- return parts;
589
- }
590
- function listedPartsByteSize(parts, excludePartNumber) {
591
- let total = 0;
592
- for (const part of parts) {
593
- if (excludePartNumber !== void 0 && part.PartNumber === excludePartNumber) {
594
- continue;
595
- }
596
- total += part.Size ?? 0;
597
208
  }
598
- return total;
599
- }
600
- function applyInlineTypes(inlineTypes, input) {
601
- if (!inlineTypes) return { disposition: input.disposition };
602
- return resolveInlineDisposition({
603
- contentType: input.contentType,
604
- fileName: input.fileName ?? fileNameFromKey(input.key),
605
- allow: inlineTypes,
606
- requested: input.disposition
607
- });
209
+ return buildEndpoint(pluginEndpoint, path, options, handler, "plugin");
608
210
  }
609
- async function finalizeConfirmedObject(client, bucket, key, input) {
610
- const { config, route, stored, head, uploadId, acl } = input;
611
- const rawMetadata = head.Metadata ?? {};
612
- const fileName = resolveStoredFileName(head.ContentDisposition, key);
613
- let context;
614
- try {
615
- const contentLength = requireContentLength(head);
616
- assertVerifiedConstraints(route.upload, {
617
- fileName,
618
- contentType: head.ContentType,
619
- contentLength
620
- });
621
- const metadata = stripPreviousKeyMeta(rawMetadata);
622
- context = {
623
- ...stored,
624
- contentType: head.ContentType,
625
- contentLength,
626
- eTag: head.ETag?.replaceAll('"', ""),
627
- metadata,
628
- acl,
629
- fileName,
630
- versionId: head.VersionId,
631
- lastModified: head.LastModified?.toISOString(),
632
- uploadId
633
- };
634
- await runLifecycleHook(route.upload.onConfirmed, context, config);
635
- } catch (err) {
636
- await deleteObjectBestEffort(client, bucket, key);
637
- throw err;
638
- }
639
- const previousKey = previousKeyFromMetadata(rawMetadata);
640
- if (previousKey && previousKey !== key) {
211
+ function buildEndpoint(create, path, options, handler, operation) {
212
+ const endpoint = create(path, endpointOptions(path, options), async (ctx) => {
641
213
  try {
642
- const safe = assertStoredKey(previousKey, route.keyPrefix);
643
- await deleteObjectBestEffort(client, bucket, safe);
644
- } catch {
214
+ return await handler(ctx);
215
+ } catch (error) {
216
+ const apiError = toAPIError(
217
+ error,
218
+ resolvedConfig(ctx.context),
219
+ ctx.context.request,
220
+ operation
221
+ );
222
+ new Headers(apiError.headers).forEach((value, name) => {
223
+ ctx.setHeader(name, value);
224
+ });
225
+ throw apiError;
645
226
  }
646
- }
647
- return {
648
- key,
649
- bucket,
650
- contentType: context.contentType,
651
- contentLength: context.contentLength,
652
- eTag: context.eTag,
653
- metadata: context.metadata ?? {},
654
- acl,
655
- fileName,
656
- versionId: context.versionId,
657
- lastModified: context.lastModified
658
- };
227
+ });
228
+ return withCallContext(endpoint);
659
229
  }
660
- var s3ContextMiddleware = createMiddleware(async (ctx) => {
661
- const injected = ctx.context;
662
- if (!injected?.config) {
230
+ function endpointOptions(path, options) {
231
+ const { method } = options;
232
+ if (!["GET", "POST", "PATCH", "DELETE"].includes(method)) {
663
233
  throw new Error(
664
- "createS3Endpoint requires dimahS3 router context. Call endpoints through dimahS3().api or the HTTP handler."
234
+ `createS3Endpoint("${path}"): method must be GET, POST, PATCH or DELETE.`
665
235
  );
666
236
  }
667
- const request = ctx.request ?? injected.request ?? requestFromHeaders(ctx.headers);
668
- await runHook(injected.config.guard, { request });
669
- return {
670
- config: injected.config,
671
- request
672
- };
673
- });
674
- var createS3Middleware = createMiddleware.create({
675
- use: [s3ContextMiddleware]
676
- });
677
-
678
- // src/api/create-s3-endpoint.ts
679
- var createEndpointWithContext = createEndpoint.create({
680
- use: [s3ContextMiddleware]
681
- });
682
- function compileIfZod(schema) {
683
- if (schema !== null && typeof schema === "object" && "_zod" in schema) {
684
- return z.compile(schema);
237
+ const readsBody = method === "POST" || method === "PATCH";
238
+ if (!readsBody && options.body !== void 0) {
239
+ throw new Error(
240
+ `createS3Endpoint("${path}"): ${method} reads the query, so it cannot have a body schema.`
241
+ );
685
242
  }
686
- return schema;
687
- }
688
- function withS3Validation(options) {
689
243
  return {
690
244
  ...options,
691
245
  ...options.body !== void 0 ? { body: compileIfZod(options.body) } : {},
692
246
  ...options.query !== void 0 ? { query: compileIfZod(options.query) } : {},
693
- // better-call reads the body before hooks. Clone first so
694
- // `request.clone().json()` in guard / resolveScope still works.
695
- ...options.body !== void 0 && options.cloneRequest === void 0 ? { cloneRequest: true } : {},
247
+ metadata: readsBody ? { ...options.metadata, allowedMediaTypes: BODY_MEDIA_TYPES } : options.metadata,
248
+ // A DELETE is never parsed for a body, so a form post cannot reach it.
249
+ ...method === "DELETE" ? { disableBody: true } : {},
250
+ // The router reads the body before the hooks run. Reading a clone keeps
251
+ // the original request readable for guards.
252
+ ...readsBody && options.cloneRequest === void 0 ? { cloneRequest: true } : {},
696
253
  onValidationError: options.onValidationError ?? (({ message }) => {
697
- throw errors.validationError(message);
254
+ throw s3Error("VALIDATION_ERROR", { issue: message });
698
255
  })
699
256
  };
700
257
  }
701
- var createS3Endpoint = ((pathOrOptions, optionsOrHandler, maybeHandler) => {
702
- if (typeof pathOrOptions === "string") {
703
- return createEndpointWithContext(
704
- pathOrOptions,
705
- withS3Validation(optionsOrHandler),
706
- maybeHandler
707
- );
258
+ function compileIfZod(schema) {
259
+ if ("_zod" in schema) {
260
+ return z.compile(schema);
708
261
  }
709
- return createEndpointWithContext(
710
- withS3Validation(pathOrOptions),
711
- optionsOrHandler
712
- );
713
- });
714
-
715
- // src/api/routes/confirm.ts
716
- async function handleConfirm(config, input, request) {
717
- const { route, key, bucket, stored } = await openStoredTarget(
718
- config,
719
- input,
720
- request,
721
- "upload"
722
- );
723
- await runHook(route.upload.confirmGuard, {
724
- ...stored,
725
- replace: route.upload.replace
726
- });
727
- const head = await headObjectOrNotFound(route.client, bucket, key);
728
- return finalizeConfirmedObject(route.client, bucket, key, {
729
- config,
730
- route,
731
- stored,
732
- head,
733
- acl: route.upload.acl
262
+ return schema;
263
+ }
264
+ function withCallContext(endpoint) {
265
+ const call = (input = {}) => endpoint({ ...input, context: { ...input.context } });
266
+ return Object.assign(call, {
267
+ path: endpoint.path,
268
+ options: endpoint.options
734
269
  });
735
270
  }
736
- var confirm = createS3Endpoint(
737
- S3_API_ROUTES.uploadConfirm,
738
- { method: "POST", body: confirmBodySchema },
739
- async (ctx) => {
740
- return handleConfirm(ctx.context.config, ctx.body, ctx.context.request);
741
- }
742
- );
743
- async function deleteStoredObject(config, input, request) {
744
- const { route, key, bucket, stored } = await openStoredTarget(
745
- config,
746
- input,
747
- request,
748
- "delete"
749
- );
750
- await runHook(route.delete.guard, stored);
751
- const existed = await objectExists(route.client, bucket, key);
752
- if (existed) {
753
- await route.client.send(
754
- new DeleteObjectCommand({ Bucket: bucket, Key: key })
755
- );
271
+
272
+ // src/config/feature-toggle.ts
273
+ function isFeatureOn(value, defaultOn = false) {
274
+ if (value === void 0) return defaultOn;
275
+ if (typeof value === "boolean") return value;
276
+ if ("enabled" in value && typeof value.enabled === "boolean") {
277
+ return value.enabled;
756
278
  }
757
- await runLifecycleHook(
758
- route.delete.onDeleted,
759
- { ...stored, existed },
760
- config
761
- );
762
- return { success: true, bucket, key, existed };
279
+ return true;
763
280
  }
764
- var deleteObject = createS3Endpoint(
765
- S3_API_ROUTES.delete,
766
- { method: "DELETE", query: deleteQuerySchema },
767
- async (ctx) => {
768
- return deleteStoredObject(
769
- ctx.context.config,
770
- ctx.query,
771
- ctx.context.request
772
- );
773
- }
774
- );
775
- var deleteBatch = createS3Endpoint(
776
- S3_API_ROUTES.deleteBatch,
777
- { method: "POST", body: deleteBatchBodySchema },
778
- async (ctx) => {
779
- const config = ctx.context.config;
780
- const request = ctx.context.request;
781
- const results = [];
782
- for (const key of ctx.body.keys) {
783
- try {
784
- const { existed } = await deleteStoredObject(
785
- config,
786
- { route: ctx.body.route, key },
787
- request
788
- );
789
- results.push({ key, success: true, existed });
790
- } catch (err) {
791
- results.push({
792
- key,
793
- success: false,
794
- error: isAPIError(err) ? { code: err.code ?? "INTERNAL_ERROR", message: err.message } : { code: "INTERNAL_ERROR", message: "Internal server error" }
795
- });
796
- }
797
- }
798
- return { results };
799
- }
800
- );
801
- function fileUrl(request, basePath, query) {
802
- const url = new URL(request.url);
803
- const prefix = basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
804
- url.pathname = `${prefix}${S3_API_ROUTES.file}`;
805
- url.search = "";
806
- url.searchParams.set("route", query.route);
807
- url.searchParams.set("key", query.key);
808
- if (query.fileName) url.searchParams.set("fileName", query.fileName);
809
- if (query.disposition) url.searchParams.set("disposition", query.disposition);
810
- return url.toString();
281
+
282
+ // src/plugin/define-plugin.ts
283
+ function definePlugin(plugin) {
284
+ return plugin;
811
285
  }
812
- async function handleDownload(config, input, request) {
813
- const { route, key, bucket, stored } = await openStoredTarget(
814
- config,
815
- input,
816
- request,
817
- "download"
818
- );
819
- const resolved = await route.download.resolve?.({
820
- ...stored,
821
- fileName: input.fileName,
822
- disposition: input.disposition ?? route.download.disposition,
823
- expiresIn: input.expiresIn
824
- });
825
- const fileName = resolved?.fileName ?? input.fileName;
826
- const disposition = resolved?.disposition ?? input.disposition ?? route.download.disposition ?? "attachment";
827
- const mode = route.download.mode ?? "presign";
828
- const expiresIn = mode === "proxy" ? 0 : clampDownloadExpiresIn({
829
- requested: input.expiresIn,
830
- routeExpiresIn: route.download.expiresIn,
831
- resolvedExpiresIn: resolved?.expiresIn,
832
- maxExpiresIn: config.maxExpiresIn
833
- });
834
- await runHook(route.download.guard, {
835
- ...stored,
836
- fileName,
837
- disposition,
838
- expiresIn
839
- });
840
- const head = await headObjectOrNotFound(route.client, bucket, key);
841
- const signed = applyInlineTypes(route.download.inlineTypes, {
842
- key,
843
- fileName,
844
- disposition,
845
- contentType: head.ContentType
846
- });
847
- const contentDisposition = fileName ? buildContentDisposition(fileName, signed.disposition) : signed.disposition;
848
- const url = mode === "proxy" ? fileUrl(request, config.basePath ?? "/api/s3", {
849
- route: input.route,
850
- key,
851
- fileName,
852
- disposition: signed.disposition
853
- }) : await getSignedUrl(
854
- route.client,
855
- new GetObjectCommand({
856
- Bucket: bucket,
857
- Key: key,
858
- ResponseContentDisposition: contentDisposition,
859
- ResponseContentType: signed.contentType
860
- }),
861
- { expiresIn }
862
- );
863
- await runLifecycleHook(
864
- route.download.onPresigned,
865
- {
866
- ...stored,
867
- fileName,
868
- url,
869
- expiresIn
870
- },
871
- config
872
- );
873
- return {
874
- bucket,
875
- key,
876
- url,
877
- expiresIn,
878
- mode,
879
- disposition: signed.disposition
880
- };
286
+ function fields(error) {
287
+ return typeof error === "object" && error !== null ? error : {};
881
288
  }
882
- var download = createS3Endpoint(
883
- S3_API_ROUTES.download,
884
- { method: "GET", query: downloadQuerySchema },
885
- async (ctx) => {
886
- return handleDownload(ctx.context.config, ctx.query, ctx.context.request);
887
- }
888
- );
889
- function catalogUpload(upload2) {
890
- if (!isEnabled(upload2)) return { enabled: false };
891
- return {
892
- enabled: true,
893
- fileTypes: upload2.fileTypes,
894
- maxFileSize: upload2.maxFileSize,
895
- multipart: isEnabled(upload2.multipart),
896
- ...upload2.checksum ? { checksum: true } : {},
897
- ...upload2.replace ? { replace: upload2.replace } : {}
898
- };
289
+ function named(error, names) {
290
+ const { name, Code } = fields(error);
291
+ return typeof name === "string" && names.includes(name) || typeof Code === "string" && names.includes(Code);
899
292
  }
900
- function catalogDownload(download2, maxExpiresIn) {
901
- if (!isEnabled(download2)) return { enabled: false };
902
- return {
903
- enabled: true,
904
- expiresIn: normalizeExpiresIn(download2.expiresIn, maxExpiresIn),
905
- ...download2.disposition ? { disposition: download2.disposition } : {},
906
- ...download2.inlineTypes ? { inlineTypes: [...download2.inlineTypes] } : {},
907
- ...download2.mode ? { mode: download2.mode } : {}
908
- };
293
+ function matches(error, names, status) {
294
+ return named(error, names) || awsStatus(error) === status;
909
295
  }
910
- function buildRouteCatalog(config) {
911
- const routes = {};
912
- for (const [name, route] of Object.entries(config.routes)) {
913
- routes[name] = {
914
- upload: catalogUpload(route.upload),
915
- download: catalogDownload(route.download, config.maxExpiresIn),
916
- delete: isEnabled(route.delete) ? { enabled: true } : { enabled: false }
917
- };
918
- }
919
- return { routes };
296
+ function awsStatus(error) {
297
+ const status = fields(error).$metadata?.httpStatusCode;
298
+ return typeof status === "number" ? status : void 0;
920
299
  }
921
- var catalog = createS3Endpoint(
922
- S3_API_ROUTES.catalog,
923
- { method: "GET" },
924
- async (ctx) => {
925
- return buildRouteCatalog(ctx.context.config);
926
- }
927
- );
928
- async function handleFile(config, input, request) {
929
- const { route, key, bucket, stored } = await openStoredTarget(
930
- config,
931
- input,
932
- request,
933
- "download"
934
- );
935
- const resolved = await route.download.resolve?.({
936
- ...stored,
937
- fileName: input.fileName,
938
- disposition: input.disposition ?? route.download.disposition
939
- });
940
- const fileName = resolved?.fileName ?? input.fileName;
941
- const disposition = resolved?.disposition ?? input.disposition ?? route.download.disposition ?? "attachment";
942
- await runHook(route.download.guard, {
943
- ...stored,
944
- fileName,
945
- disposition
946
- });
947
- const head = await headObjectOrNotFound(route.client, bucket, key);
948
- const signed = applyInlineTypes(route.download.inlineTypes, {
949
- key,
950
- fileName,
951
- disposition,
952
- contentType: head.ContentType
953
- });
954
- const contentDisposition = fileName ? buildContentDisposition(fileName, signed.disposition) : signed.disposition;
955
- const result = await sendOrObjectNotFound(
956
- () => route.client.send(
957
- new GetObjectCommand({
958
- Bucket: bucket,
959
- Key: key,
960
- ResponseContentDisposition: contentDisposition
961
- })
962
- )
963
- );
964
- const body = result.Body;
965
- if (!body) throw errors.objectNotFound();
966
- const stream = "transformToWebStream" in body && typeof body.transformToWebStream === "function" ? body.transformToWebStream() : body;
967
- const headers = new Headers();
968
- headers.set(
969
- "Content-Type",
970
- signed.contentType ?? result.ContentType ?? "application/octet-stream"
971
- );
972
- headers.set("Content-Disposition", contentDisposition);
973
- headers.set("X-Content-Type-Options", "nosniff");
974
- if (typeof result.ContentLength === "number") {
975
- headers.set("Content-Length", String(result.ContentLength));
976
- }
977
- return new Response(stream, { headers });
300
+ function isAwsNotFound(error) {
301
+ if (named(error, ["NoSuchBucket"])) return false;
302
+ return matches(error, ["NoSuchKey", "NotFound", "NoSuchUpload"], 404);
978
303
  }
979
- var file = createS3Endpoint(
980
- S3_API_ROUTES.file,
981
- { method: "GET", query: fileQuerySchema },
982
- async (ctx) => {
983
- return handleFile(ctx.context.config, ctx.query, ctx.context.request);
984
- }
985
- );
986
- async function handleAbort(config, input, request) {
987
- const { route, key, bucket, stored } = await openStoredTarget(
988
- config,
989
- input,
990
- request,
991
- "multipart"
992
- );
993
- const uploadId = input.uploadId;
994
- await runHook(route.upload.multipart.guard, {
995
- ...stored,
996
- uploadId,
997
- action: "abort"
998
- });
999
- await sendOrObjectNotFound(
1000
- () => route.client.send(
1001
- new AbortMultipartUploadCommand({
1002
- Bucket: bucket,
1003
- Key: key,
1004
- UploadId: uploadId
1005
- })
1006
- )
1007
- );
1008
- await runLifecycleHook(
1009
- route.upload.multipart.onAbort,
1010
- {
1011
- ...stored,
1012
- uploadId
1013
- },
1014
- config
1015
- );
1016
- return { bucket, key, uploadId, aborted: true };
304
+ function isAwsPreconditionFailed(error) {
305
+ return matches(error, ["PreconditionFailed"], 412);
1017
306
  }
1018
- var multipartAbort = createS3Endpoint(
1019
- S3_API_ROUTES.multipartAbort,
1020
- { method: "POST", body: multipartAbortBodySchema },
1021
- async (ctx) => {
1022
- return handleAbort(ctx.context.config, ctx.body, ctx.context.request);
1023
- }
1024
- );
1025
- async function handleComplete(config, input, request) {
1026
- const { route, key, bucket, stored } = await openStoredTarget(
1027
- config,
1028
- input,
1029
- request,
1030
- "multipart"
1031
- );
1032
- const uploadId = input.uploadId;
1033
- const parts = [
1034
- ...new Set(input.parts.map(({ partNumber }) => partNumber))
1035
- ].toSorted((a, b) => a - b);
1036
- const partRefs = parts.map((partNumber) => ({ partNumber }));
1037
- await runHook(route.upload.multipart.guard, {
1038
- ...stored,
1039
- uploadId,
1040
- action: "complete"
1041
- });
1042
- await runHook(route.upload.confirmGuard, {
1043
- ...stored,
1044
- uploadId,
1045
- parts: partRefs,
1046
- replace: route.upload.replace
1047
- });
1048
- const listedParts = await listAllParts(route.client, {
1049
- bucket,
1050
- key,
1051
- uploadId
1052
- });
1053
- let assembledBytes = 0;
1054
- const completeParts = parts.map((partNumber) => {
1055
- const found = listedParts.find((p) => p.PartNumber === partNumber);
1056
- if (!found?.ETag) {
1057
- throw errors.multipartPartMissing(partNumber);
1058
- }
1059
- assembledBytes += found.Size ?? 0;
1060
- return { PartNumber: partNumber, ETag: found.ETag };
1061
- });
1062
- try {
1063
- assertWithinMaxFileSize(route.upload.maxFileSize, assembledBytes);
1064
- } catch (err) {
1065
- await abortMultipartBestEffort(route.client, bucket, key, uploadId);
1066
- throw err;
1067
- }
1068
- const completeResult = await sendOrObjectNotFound(
1069
- () => route.client.send(
1070
- new CompleteMultipartUploadCommand({
1071
- Bucket: bucket,
1072
- Key: key,
1073
- UploadId: uploadId,
1074
- MultipartUpload: { Parts: completeParts }
1075
- })
1076
- )
1077
- );
1078
- const head = await headObjectAfterMultipartComplete(
1079
- route.client,
1080
- bucket,
1081
- key
1082
- );
1083
- const confirmed = await finalizeConfirmedObject(route.client, bucket, key, {
1084
- config,
1085
- route,
1086
- stored,
1087
- head: {
1088
- ...head,
1089
- ETag: head.ETag ?? completeResult.ETag
1090
- },
1091
- uploadId,
1092
- acl: route.upload.acl
1093
- });
1094
- return { ...confirmed, uploadId };
307
+ function isAwsNotImplemented(error) {
308
+ return matches(error, ["NotImplemented"], 501);
1095
309
  }
1096
- var multipartComplete = createS3Endpoint(
1097
- S3_API_ROUTES.multipartComplete,
1098
- { method: "POST", body: multipartCompleteBodySchema },
1099
- async (ctx) => {
1100
- return handleComplete(ctx.context.config, ctx.body, ctx.context.request);
1101
- }
1102
- );
1103
- async function handleMultipartInit(config, input, request) {
1104
- const fileSize = Math.floor(input.fileSize);
1105
- const fileName = input.fileName;
1106
- const {
1107
- route,
1108
- key,
1109
- bucket,
1110
- metadata,
1111
- acl,
1112
- storageClass,
1113
- cacheControl,
1114
- tagging,
1115
- stored
1116
- } = await openUploadTarget(
1117
- config,
1118
- {
1119
- route: input.route,
1120
- fileName,
1121
- fileSize,
1122
- contentType: input.contentType,
1123
- metadata: input.metadata
1124
- },
1125
- request,
1126
- "multipart"
1127
- );
1128
- const objectS3 = normalizeObjectS3({ storageClass, cacheControl, tagging });
1129
- await runHook(route.upload.guard, {
1130
- ...stored,
1131
- file: {
1132
- name: fileName,
1133
- size: fileSize,
1134
- type: input.contentType
1135
- },
1136
- metadata,
1137
- clientMetadata: input.metadata,
1138
- acl,
1139
- ...objectS3,
1140
- replace: route.upload.replace
1141
- });
1142
- const { UploadId } = await route.client.send(
1143
- new CreateMultipartUploadCommand({
1144
- Bucket: bucket,
1145
- Key: key,
1146
- ContentType: input.contentType,
1147
- ContentDisposition: buildContentDisposition(fileName),
1148
- Metadata: metadata,
1149
- ACL: acl,
1150
- ...objectCommandExtras(objectS3)
1151
- })
1152
- );
1153
- if (!UploadId) {
1154
- throw errors.internalError();
310
+ async function deleteObjectIfMatch(client, input) {
311
+ const target = { Bucket: input.bucket, Key: input.key };
312
+ if (input.eTag === void 0) {
313
+ await client.send(new DeleteObjectCommand(target));
314
+ return true;
1155
315
  }
1156
316
  try {
1157
- await runLifecycleHook(
1158
- route.upload.multipart.onInit,
1159
- {
1160
- ...stored,
1161
- uploadId: UploadId,
1162
- file: {
1163
- name: fileName,
1164
- size: fileSize,
1165
- type: input.contentType
1166
- },
1167
- metadata,
1168
- clientMetadata: input.metadata,
1169
- acl,
1170
- ...objectS3,
1171
- replace: route.upload.replace
1172
- },
1173
- config
1174
- );
1175
- } catch (err) {
1176
- await abortMultipartBestEffort(route.client, bucket, key, UploadId);
1177
- try {
1178
- await runLifecycleHook(
1179
- route.upload.multipart.onAbort,
1180
- {
1181
- ...stored,
1182
- uploadId: UploadId
1183
- },
1184
- config
1185
- );
1186
- } catch {
1187
- }
1188
- throw err;
1189
- }
1190
- return { bucket, key, uploadId: UploadId };
1191
- }
1192
- var multipartInit = createS3Endpoint(
1193
- S3_API_ROUTES.multipartInit,
1194
- { method: "POST", body: multipartInitBodySchema },
1195
- async (ctx) => {
1196
- const result = await handleMultipartInit(
1197
- ctx.context.config,
1198
- ctx.body,
1199
- ctx.context.request
1200
- );
1201
- ctx.setStatus(201);
1202
- return result;
1203
- }
1204
- );
1205
- async function handleListParts(config, input, request) {
1206
- const { route, key, bucket, stored } = await openStoredTarget(
1207
- config,
1208
- input,
1209
- request,
1210
- "multipart"
1211
- );
1212
- const uploadId = input.uploadId;
1213
- await runHook(route.upload.multipart.guard, {
1214
- ...stored,
1215
- uploadId,
1216
- action: "list"
1217
- });
1218
- const listed = await listAllParts(route.client, { bucket, key, uploadId });
1219
- const parts = listed.flatMap((p) => {
1220
- if (p.PartNumber == null || p.PartNumber < 1) return [];
1221
- return [
1222
- {
1223
- partNumber: p.PartNumber,
1224
- size: p.Size ?? 0,
1225
- eTag: (p.ETag ?? "").replaceAll('"', "")
1226
- }
1227
- ];
1228
- });
1229
- await runLifecycleHook(
1230
- route.upload.multipart.onList,
1231
- {
1232
- ...stored,
1233
- uploadId,
1234
- parts
1235
- },
1236
- config
1237
- );
1238
- return { parts };
1239
- }
1240
- var multipartListParts = createS3Endpoint(
1241
- S3_API_ROUTES.multipartListParts,
1242
- { method: "GET", query: multipartListPartsQuerySchema },
1243
- async (ctx) => {
1244
- return handleListParts(ctx.context.config, ctx.query, ctx.context.request);
1245
- }
1246
- );
1247
- async function handleSignPart(config, input, request) {
1248
- const { route, key, bucket, stored } = await openStoredTarget(
1249
- config,
1250
- input,
1251
- request,
1252
- "multipart"
1253
- );
1254
- const uploadId = input.uploadId;
1255
- const partNumber = input.partNumber;
1256
- const expiresIn = normalizeExpiresIn(
1257
- route.upload.expiresIn,
1258
- config.maxExpiresIn
1259
- );
1260
- const partSize = Math.floor(input.partSize);
1261
- await runHook(route.upload.multipart.guard, {
1262
- ...stored,
1263
- uploadId,
1264
- action: "part",
1265
- partNumber,
1266
- partSize
1267
- });
1268
- const maxFileSize = route.upload.maxFileSize;
1269
- assertWithinMaxFileSize(maxFileSize, partSize);
1270
- if (typeof maxFileSize === "number") {
1271
- const listed = await listAllParts(route.client, { bucket, key, uploadId });
1272
- assertWithinMaxFileSize(
1273
- maxFileSize,
1274
- listedPartsByteSize(listed, partNumber) + partSize
317
+ await client.send(
318
+ new DeleteObjectCommand({ ...target, IfMatch: input.eTag })
1275
319
  );
320
+ } catch (error) {
321
+ if (isAwsPreconditionFailed(error)) return false;
322
+ if (!isAwsNotImplemented(error)) throw error;
323
+ await client.send(new DeleteObjectCommand(target));
1276
324
  }
1277
- const url = await getSignedUrl(
1278
- route.client,
1279
- new UploadPartCommand({
1280
- Bucket: bucket,
1281
- Key: key,
1282
- UploadId: uploadId,
1283
- PartNumber: partNumber,
1284
- ContentLength: partSize
1285
- }),
1286
- {
1287
- expiresIn,
1288
- signableHeaders: /* @__PURE__ */ new Set(["content-length"])
1289
- }
1290
- );
1291
- return {
1292
- url,
1293
- partNumber,
1294
- uploadId,
1295
- bucket,
1296
- expiresIn,
1297
- partSize
1298
- };
325
+ return true;
1299
326
  }
1300
- var multipartPart = createS3Endpoint(
1301
- S3_API_ROUTES.multipartPart,
1302
- { method: "POST", body: multipartSignPartBodySchema },
1303
- async (ctx) => {
1304
- return handleSignPart(ctx.context.config, ctx.body, ctx.context.request);
327
+ var ENCODED_WORD = /^=\?([^?*]+)(?:\*[^?]*)?\?([bq])\?([^?]*)\?=$/i;
328
+ var UTF8_CHARSETS = /* @__PURE__ */ new Set(["utf-8", "utf8", "us-ascii"]);
329
+ function decodeMetadataValue(value) {
330
+ const words = value.trim().split(/\s+/);
331
+ const chunks = [];
332
+ for (const word of words) {
333
+ const match = ENCODED_WORD.exec(word);
334
+ if (!match || !UTF8_CHARSETS.has(match[1].toLowerCase())) return value;
335
+ const bytes = match[2].toLowerCase() === "b" ? fromBase64(match[3]) : fromQuotedPrintable(match[3]);
336
+ if (!bytes) return value;
337
+ chunks.push(bytes);
1305
338
  }
1306
- );
1307
- function objectUserMetadata(metadata) {
1308
- if (!metadata) return {};
1309
- const fields = {};
1310
- for (const [k, v] of Object.entries(metadata)) {
1311
- fields[`x-amz-meta-${k}`] = v;
339
+ try {
340
+ return new TextDecoder("utf-8", { fatal: true }).decode(concat(chunks));
341
+ } catch {
342
+ return value;
1312
343
  }
1313
- return fields;
1314
344
  }
1315
- async function handleUpload(config, input, request) {
1316
- const fileSize = Math.floor(input.fileSize);
1317
- const fileName = input.fileName;
1318
- const {
1319
- route,
1320
- key,
1321
- bucket,
1322
- metadata,
1323
- acl,
1324
- storageClass,
1325
- cacheControl,
1326
- tagging,
1327
- stored
1328
- } = await openUploadTarget(
1329
- config,
1330
- {
1331
- route: input.route,
1332
- fileName,
1333
- fileSize,
1334
- contentType: input.contentType,
1335
- metadata: input.metadata
1336
- },
1337
- request,
1338
- "upload"
1339
- );
1340
- const objectS3 = normalizeObjectS3({ storageClass, cacheControl, tagging });
1341
- const method = route.upload.method ?? "POST";
1342
- if (route.upload.checksum && !input.checksum) {
1343
- throw errors.validationError("Checksum is required for this route");
345
+ function fromBase64(text) {
346
+ if (!/^[a-z0-9+/]*={0,2}$/i.test(text) || text.length % 4 !== 0) {
347
+ return void 0;
1344
348
  }
1345
- if (method === "POST" && fileSize > S3_MAX_POST_OBJECT_BYTES) {
1346
- throw errors.payloadTooLarge(
1347
- `POST uploads cannot exceed ${S3_MAX_POST_OBJECT_BYTES} bytes. Enable upload.multipart or set upload.method to "PUT".`
1348
- );
1349
- }
1350
- const expiresIn = normalizeExpiresIn(
1351
- route.upload.expiresIn,
1352
- config.maxExpiresIn
1353
- );
1354
- const contentType = input.contentType ?? "application/octet-stream";
1355
- const hookCtx = {
1356
- ...stored,
1357
- file: {
1358
- name: fileName,
1359
- size: fileSize,
1360
- type: input.contentType
1361
- },
1362
- metadata,
1363
- clientMetadata: input.metadata,
1364
- acl,
1365
- ...objectS3,
1366
- replace: route.upload.replace
1367
- };
1368
- await runHook(route.upload.guard, hookCtx);
1369
- if (method === "PUT") {
1370
- const putHeaders = {
1371
- "Content-Type": contentType,
1372
- ...objectUserMetadata(metadata),
1373
- "Content-Disposition": buildContentDisposition(fileName),
1374
- ...objectPutHeaders(objectS3),
1375
- ...input.checksum ? { "x-amz-checksum-sha256": input.checksum } : {}
1376
- };
1377
- const url2 = await getSignedUrl(
1378
- route.client,
1379
- new PutObjectCommand({
1380
- Bucket: bucket,
1381
- Key: key,
1382
- ContentType: contentType,
1383
- ACL: acl,
1384
- Metadata: metadata,
1385
- ContentDisposition: buildContentDisposition(fileName),
1386
- ContentLength: fileSize,
1387
- ...objectCommandExtras(objectS3),
1388
- ...input.checksum ? { ChecksumSHA256: input.checksum, ChecksumAlgorithm: "SHA256" } : {}
1389
- }),
1390
- {
1391
- expiresIn,
1392
- signableHeaders: /* @__PURE__ */ new Set([
1393
- "content-length",
1394
- ...input.checksum ? ["x-amz-checksum-sha256"] : []
1395
- ])
1396
- }
1397
- );
1398
- await runLifecycleHook(
1399
- route.upload.onPresigned,
1400
- {
1401
- ...hookCtx,
1402
- url: url2,
1403
- expiresIn
1404
- },
1405
- config
349
+ try {
350
+ return base64UrlDecode(
351
+ text.replace(/=+$/, "").replaceAll("+", "-").replaceAll("/", "_")
1406
352
  );
1407
- return {
1408
- bucket,
1409
- key,
1410
- url: url2,
1411
- headers: putHeaders,
1412
- expiresIn,
1413
- method: "PUT"
1414
- };
1415
- }
1416
- const fields = {
1417
- acl,
1418
- "Content-Type": contentType,
1419
- "Content-Disposition": buildContentDisposition(fileName),
1420
- ...objectUserMetadata(metadata),
1421
- ...objectPutHeaders(objectS3),
1422
- ...input.checksum ? { "x-amz-checksum-sha256": input.checksum } : {}
1423
- };
1424
- const { url, fields: signedFields } = await createPresignedPost(
1425
- route.client,
1426
- {
1427
- Bucket: bucket,
1428
- Key: key,
1429
- Conditions: [["content-length-range", fileSize, fileSize]],
1430
- Fields: fields,
1431
- Expires: expiresIn
1432
- }
1433
- );
1434
- await runLifecycleHook(
1435
- route.upload.onPresigned,
1436
- {
1437
- ...hookCtx,
1438
- url,
1439
- expiresIn
1440
- },
1441
- config
1442
- );
1443
- return {
1444
- bucket,
1445
- key,
1446
- url,
1447
- fields: signedFields,
1448
- expiresIn,
1449
- method: "POST"
1450
- };
1451
- }
1452
- var upload = createS3Endpoint(
1453
- S3_API_ROUTES.upload,
1454
- { method: "POST", body: uploadBodySchema },
1455
- async (ctx) => {
1456
- return handleUpload(ctx.context.config, ctx.body, ctx.context.request);
1457
- }
1458
- );
1459
-
1460
- // src/api/routes/index.ts
1461
- var coreEndpoints = {
1462
- upload,
1463
- confirm,
1464
- download,
1465
- catalog,
1466
- file,
1467
- delete: deleteObject,
1468
- deleteBatch,
1469
- multipartInit,
1470
- multipartPart,
1471
- multipartListParts,
1472
- multipartComplete,
1473
- multipartAbort
1474
- };
1475
- var CORE_ENDPOINT_NAMES = Object.keys(
1476
- coreEndpoints
1477
- );
1478
-
1479
- // src/plugin/chain-hooks.ts
1480
- function chainHooks(...hooks) {
1481
- return async (context) => {
1482
- for (const hook of hooks) {
1483
- if (hook) await hook(context);
353
+ } catch {
354
+ return void 0;
355
+ }
356
+ }
357
+ function fromQuotedPrintable(text) {
358
+ const bytes = [];
359
+ for (let i = 0; i < text.length; i++) {
360
+ const char = text[i];
361
+ if (char === "_") {
362
+ bytes.push(32);
363
+ } else if (char === "=") {
364
+ const hex = text.slice(i + 1, i + 3);
365
+ if (!/^[0-9a-f]{2}$/i.test(hex)) return void 0;
366
+ bytes.push(Number.parseInt(hex, 16));
367
+ i += 2;
368
+ } else {
369
+ const code = char.charCodeAt(0);
370
+ if (code < 33 || code > 126) return void 0;
371
+ bytes.push(code);
1484
372
  }
1485
- };
1486
- }
1487
-
1488
- // src/plugin/hook-registry.ts
1489
- var FEATURE_HOOK_KEYS = {
1490
- upload: ["guard", "onPresigned", "confirmGuard", "onConfirmed"],
1491
- download: ["guard", "onPresigned"],
1492
- delete: ["guard", "onDeleted"]
1493
- };
1494
- var MULTIPART_HOOK_KEYS = [
1495
- "onInit",
1496
- "guard",
1497
- "onAbort",
1498
- "onList"
1499
- ];
1500
- var LIFECYCLE_FEATURE_HOOK_KEYS = {
1501
- upload: ["onPresigned", "onConfirmed"],
1502
- download: ["onPresigned"],
1503
- delete: ["onDeleted"]
1504
- };
1505
- var LIFECYCLE_MULTIPART_HOOK_KEYS = [
1506
- "onInit",
1507
- "onAbort",
1508
- "onList"
1509
- ];
1510
-
1511
- // src/plugin/types.ts
1512
- var RESERVED_PLUGIN_IDS = [
1513
- "handler",
1514
- "api",
1515
- "context",
1516
- "getPlugin",
1517
- "$ERROR_CODES",
1518
- "$Infer",
1519
- "upload",
1520
- "confirm",
1521
- "download",
1522
- "catalog",
1523
- "file",
1524
- "delete",
1525
- "deleteBatch",
1526
- "put",
1527
- "multipart"
1528
- ];
1529
-
1530
- // src/plugin/apply-plugins.ts
1531
- function mergeHookField(pluginHooks, userHook, order = "plugins-first") {
1532
- const present2 = (order === "user-first" ? [userHook, ...pluginHooks] : [...pluginHooks, userHook]).filter((h) => h != null);
1533
- if (present2.length === 0) return void 0;
1534
- if (present2.length === 1) return present2[0];
1535
- return chainHooks(...present2);
1536
- }
1537
- function mergeHooks(keys, plugins, userFeature, pick, lifecycleKeys = /* @__PURE__ */ new Set()) {
1538
- const merged = { ...userFeature };
1539
- for (const key of keys) {
1540
- const next = mergeHookField(
1541
- plugins.map((plugin) => pick(plugin)?.[key]),
1542
- userFeature[key],
1543
- lifecycleKeys.has(key) ? "user-first" : "plugins-first"
1544
- );
1545
- if (next !== void 0) merged[key] = next;
1546
373
  }
1547
- return merged;
1548
- }
1549
- function applyHooksToRoute(route, plugins) {
1550
- const active = plugins.filter((p) => !route.skippedPluginIds.has(p.id));
1551
- const upload2 = isEnabled(route.upload) ? {
1552
- ...mergeHooks(
1553
- FEATURE_HOOK_KEYS.upload,
1554
- active,
1555
- route.upload,
1556
- (p) => p.hooks?.upload,
1557
- new Set(LIFECYCLE_FEATURE_HOOK_KEYS.upload)
1558
- ),
1559
- multipart: isEnabled(route.upload.multipart) ? mergeHooks(
1560
- MULTIPART_HOOK_KEYS,
1561
- active,
1562
- route.upload.multipart,
1563
- (p) => p.hooks?.upload?.multipart,
1564
- new Set(LIFECYCLE_MULTIPART_HOOK_KEYS)
1565
- ) : route.upload.multipart
1566
- } : route.upload;
1567
- return {
1568
- ...route,
1569
- upload: upload2,
1570
- download: isEnabled(route.download) ? mergeHooks(
1571
- FEATURE_HOOK_KEYS.download,
1572
- active,
1573
- route.download,
1574
- (p) => p.hooks?.download,
1575
- new Set(LIFECYCLE_FEATURE_HOOK_KEYS.download)
1576
- ) : route.download,
1577
- delete: isEnabled(route.delete) ? mergeHooks(
1578
- FEATURE_HOOK_KEYS.delete,
1579
- active,
1580
- route.delete,
1581
- (p) => p.hooks?.delete,
1582
- new Set(LIFECYCLE_FEATURE_HOOK_KEYS.delete)
1583
- ) : route.delete
1584
- };
374
+ return Uint8Array.from(bytes);
1585
375
  }
1586
- function applyPlugins(config) {
1587
- const plugins = config.plugins ?? [];
1588
- const seen = /* @__PURE__ */ new Set();
1589
- const byId = /* @__PURE__ */ new Map();
1590
- const context = {};
1591
- const getPlugin = (id) => byId.get(id);
1592
- for (const plugin of plugins) {
1593
- if (RESERVED_PLUGIN_IDS.includes(plugin.id)) {
1594
- throw new Error(
1595
- `Plugin id "${plugin.id}" is reserved on the dimahS3 instance. Choose a different id.`
1596
- );
1597
- }
1598
- if (seen.has(plugin.id)) {
1599
- throw new Error(
1600
- `Duplicate dimah-s3 plugin id "${plugin.id}". Each plugin id must be unique.`
1601
- );
1602
- }
1603
- seen.add(plugin.id);
1604
- byId.set(plugin.id, plugin);
1605
- }
1606
- for (const plugin of plugins) {
1607
- for (const dep of plugin.dependsOn ?? []) {
1608
- if (!seen.has(dep)) {
1609
- throw new Error(
1610
- `Plugin "${plugin.id}" depends on "${dep}", which is not registered.`
1611
- );
1612
- }
1613
- }
376
+ function concat(chunks) {
377
+ const out = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));
378
+ let offset = 0;
379
+ for (const chunk of chunks) {
380
+ out.set(chunk, offset);
381
+ offset += chunk.length;
1614
382
  }
1615
- const visiting = /* @__PURE__ */ new Set();
1616
- const visited = /* @__PURE__ */ new Set();
1617
- function visit(id, stack) {
1618
- if (visited.has(id)) return;
1619
- if (visiting.has(id)) {
1620
- throw new Error(
1621
- `Circular plugin dependency detected: ${[...stack, id].join(" -> ")}.`
1622
- );
1623
- }
1624
- visiting.add(id);
1625
- const plugin = byId.get(id);
1626
- for (const dep of plugin?.dependsOn ?? []) {
1627
- visit(dep, [...stack, id]);
1628
- }
1629
- visiting.delete(id);
1630
- visited.add(id);
1631
- }
1632
- for (const plugin of plugins) {
1633
- visit(plugin.id, []);
1634
- }
1635
- for (const plugin of plugins) {
1636
- if (plugin.context !== void 0) {
1637
- context[plugin.id] = plugin.context;
1638
- }
1639
- }
1640
- const reservedRoutePaths = new Set(Object.values(S3_API_ROUTES));
1641
- const reservedNames = /* @__PURE__ */ new Set([...CORE_ENDPOINT_NAMES, "multipart"]);
1642
- const seenEndpointKeys = /* @__PURE__ */ new Set();
1643
- const endpoints = {};
1644
- for (const plugin of plugins) {
1645
- for (const [name, endpoint] of Object.entries(plugin.endpoints ?? {})) {
1646
- if (reservedNames.has(name) || Object.hasOwn(endpoints, name)) {
1647
- throw new Error(
1648
- `Plugin "${plugin.id}" endpoint "${name}" collides with an existing endpoint.`
1649
- );
1650
- }
1651
- const path = endpoint.path;
1652
- if (typeof path !== "string" || !path.startsWith("/")) {
1653
- throw new Error(
1654
- `Plugin "${plugin.id}" endpoint "${name}" path must start with "/".`
1655
- );
1656
- }
1657
- if (reservedRoutePaths.has(path)) {
1658
- throw new Error(
1659
- `Plugin "${plugin.id}" endpoint "${name}" collides with a core route.`
1660
- );
1661
- }
1662
- const methods = Array.isArray(endpoint.options.method) ? endpoint.options.method : [endpoint.options.method];
1663
- for (const method of methods) {
1664
- const routeKey = `${method} ${path}`;
1665
- if (seenEndpointKeys.has(routeKey)) {
1666
- throw new Error(`Duplicate plugin endpoint ${routeKey}.`);
1667
- }
1668
- seenEndpointKeys.add(routeKey);
1669
- }
1670
- endpoints[name] = endpoint;
1671
- }
1672
- }
1673
- const { plugins: _omit, ...rest } = config;
1674
- const normalized = normalizeRoutes(rest);
1675
- for (const plugin of plugins) {
1676
- plugin.init?.({ config: rest, getPlugin });
1677
- }
1678
- const routes = {};
1679
- for (const [name, route] of Object.entries(normalized)) {
1680
- routes[name] = applyHooksToRoute(route, plugins);
1681
- }
1682
- const guard = mergeHookField(
1683
- plugins.map((p) => p.hooks?.guard),
1684
- rest.guard
1685
- );
1686
- const merged = {
1687
- ...rest,
1688
- routes,
1689
- ...guard !== void 0 ? { guard } : {}
1690
- };
1691
- return {
1692
- config: merged,
1693
- context,
1694
- getPlugin,
1695
- endpoints
1696
- };
383
+ return out;
1697
384
  }
1698
385
 
1699
- // src/plugin/define-plugin.ts
1700
- function definePlugin(plugin) {
1701
- return plugin;
386
+ // src/helpers/object-meta.ts
387
+ var UPLOAD_MARKER_META = "dimah-upload";
388
+ var PREVIOUS_KEY_META = "dimah-previous-key";
389
+ function readObjectMetadata(raw) {
390
+ const metadata = {};
391
+ let uploadToken;
392
+ let previousKey;
393
+ for (const [name, value] of Object.entries(raw ?? {})) {
394
+ const key = name.toLowerCase();
395
+ const decoded = decodeMetadataValue(value);
396
+ if (key === UPLOAD_MARKER_META) uploadToken = decoded;
397
+ else if (key === PREVIOUS_KEY_META) previousKey = decoded || void 0;
398
+ else metadata[key] = decoded;
399
+ }
400
+ return { metadata, uploadToken, previousKey };
401
+ }
402
+ function readUploadMarker(metadata) {
403
+ return readObjectMetadata(metadata).uploadToken;
1702
404
  }
1703
405
 
1704
- // src/types/config.ts
1705
- var ROUTE_FEATURES = ["upload", "download", "delete"];
1706
- var ROUTE_OPERATIONS = [...ROUTE_FEATURES, "multipart"];
1707
-
1708
- export { CORE_ENDPOINT_NAMES, FEATURE_HOOK_KEYS, LIFECYCLE_FEATURE_HOOK_KEYS, LIFECYCLE_MULTIPART_HOOK_KEYS, MULTIPART_HOOK_KEYS, RESERVED_PLUGIN_IDS, ROUTE_FEATURES, ROUTE_OPERATIONS, applyPlugins, chainHooks, createS3Endpoint, createS3Middleware, definePlugin, isFeatureOn };
406
+ export { createS3Endpoint, createS3Middleware, definePlugin, deleteObjectIfMatch, isAwsNotFound, isFeatureOn, readUploadMarker };
1709
407
  //# sourceMappingURL=plugins.js.map
1710
408
  //# sourceMappingURL=plugins.js.map