@dimah-s3/core 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 (74) hide show
  1. package/README.md +32 -13
  2. package/dist/create-s3-client.d.ts +3 -0
  3. package/dist/create-s3-client.d.ts.map +1 -1
  4. package/dist/error-codes.d.ts +297 -29
  5. package/dist/error-codes.d.ts.map +1 -1
  6. package/dist/error.d.ts +46 -14
  7. package/dist/error.d.ts.map +1 -1
  8. package/dist/helpers/base64url.d.ts +19 -0
  9. package/dist/helpers/base64url.d.ts.map +1 -0
  10. package/dist/helpers/build-content-disposition.d.ts +4 -4
  11. package/dist/helpers/build-content-disposition.d.ts.map +1 -1
  12. package/dist/helpers/checksum.d.ts +8 -2
  13. package/dist/helpers/checksum.d.ts.map +1 -1
  14. package/dist/helpers/content-type.d.ts +17 -0
  15. package/dist/helpers/content-type.d.ts.map +1 -0
  16. package/dist/helpers/fit-file-name.d.ts +15 -0
  17. package/dist/helpers/fit-file-name.d.ts.map +1 -0
  18. package/dist/helpers/index.d.ts +7 -9
  19. package/dist/helpers/index.d.ts.map +1 -1
  20. package/dist/helpers/magic-bytes.d.ts +9 -2
  21. package/dist/helpers/magic-bytes.d.ts.map +1 -1
  22. package/dist/helpers/normalize-object-key.d.ts +8 -3
  23. package/dist/helpers/normalize-object-key.d.ts.map +1 -1
  24. package/dist/helpers/parse-file-name.d.ts +5 -0
  25. package/dist/helpers/parse-file-name.d.ts.map +1 -1
  26. package/dist/helpers/resolve-inline-disposition.d.ts +16 -6
  27. package/dist/helpers/resolve-inline-disposition.d.ts.map +1 -1
  28. package/dist/helpers/validate-file.d.ts +13 -16
  29. package/dist/helpers/validate-file.d.ts.map +1 -1
  30. package/dist/index.d.ts +2 -2
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +720 -478
  33. package/dist/index.js.map +1 -1
  34. package/dist/limits.d.ts +30 -0
  35. package/dist/limits.d.ts.map +1 -0
  36. package/dist/plugin/create-s3-fetch.d.ts +5 -3
  37. package/dist/plugin/create-s3-fetch.d.ts.map +1 -1
  38. package/dist/plugin/types.d.ts +13 -4
  39. package/dist/plugin/types.d.ts.map +1 -1
  40. package/dist/routes.d.ts +10 -4
  41. package/dist/routes.d.ts.map +1 -1
  42. package/dist/schema/catalog.d.ts +30 -39
  43. package/dist/schema/catalog.d.ts.map +1 -1
  44. package/dist/schema/delete.d.ts +1 -2
  45. package/dist/schema/delete.d.ts.map +1 -1
  46. package/dist/schema/download.d.ts +16 -3
  47. package/dist/schema/download.d.ts.map +1 -1
  48. package/dist/schema/index.d.ts +5 -9
  49. package/dist/schema/index.d.ts.map +1 -1
  50. package/dist/schema/index.js +221 -0
  51. package/dist/schema/index.js.map +1 -0
  52. package/dist/schema/multipart.d.ts +6 -29
  53. package/dist/schema/multipart.d.ts.map +1 -1
  54. package/dist/schema/shared.d.ts +25 -17
  55. package/dist/schema/shared.d.ts.map +1 -1
  56. package/dist/schema/upload.d.ts +10 -7
  57. package/dist/schema/upload.d.ts.map +1 -1
  58. package/dist/types/index.d.ts +2 -2
  59. package/dist/types/index.d.ts.map +1 -1
  60. package/dist/types/requests.d.ts +25 -31
  61. package/dist/types/requests.d.ts.map +1 -1
  62. package/dist/types/responses.d.ts +96 -83
  63. package/dist/types/responses.d.ts.map +1 -1
  64. package/package.json +9 -4
  65. package/dist/helpers/format-file-size.d.ts +0 -18
  66. package/dist/helpers/format-file-size.d.ts.map +0 -1
  67. package/dist/helpers/sanitize-file-name.d.ts +0 -3
  68. package/dist/helpers/sanitize-file-name.d.ts.map +0 -1
  69. package/dist/helpers/truncate-file-name.d.ts +0 -5
  70. package/dist/helpers/truncate-file-name.d.ts.map +0 -1
  71. package/dist/schema/error.d.ts +0 -14
  72. package/dist/schema/error.d.ts.map +0 -1
  73. package/dist/schema/file.d.ts +0 -12
  74. package/dist/schema/file.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,135 +1,201 @@
1
- import * as z3 from 'zod';
2
- import { APIError as APIError$1 } from 'better-call/error';
1
+ import { statusCodes, APIError as APIError$1 } from 'better-call/error';
2
+ import { sha256 } from '@noble/hashes/sha2.js';
3
3
  import { createFetch } from '@better-fetch/fetch';
4
4
 
5
- // src/helpers/validate-file.ts
6
- function matchesFileTypes(fileName, contentType, fileTypes) {
7
- if (!fileTypes.length) return true;
8
- const type = contentType ?? "";
9
- return fileTypes.some((token) => {
10
- if (token.startsWith(".")) {
11
- return fileName.toLowerCase().endsWith(token.toLowerCase());
12
- }
13
- if (token.endsWith("/*")) {
14
- return type.startsWith(token.slice(0, -1));
15
- }
16
- return type === token;
17
- });
18
- }
19
- function validateFile(file, options) {
20
- if (options.accept?.length) {
21
- if (!matchesFileTypes(file.name, file.type, options.accept)) {
22
- const ext = file.name.includes(".") ? file.name.split(".").pop() : null;
23
- const type = ext ? `.${ext}` : file.type || "unknown";
24
- return {
25
- code: "FILE_TYPE_NOT_ALLOWED",
26
- message: `File type "${type}" is not allowed`,
27
- params: { type }
28
- };
29
- }
30
- }
31
- if (file.size === 0) {
32
- return {
33
- code: "FILE_EMPTY",
34
- message: "File is empty"
35
- };
36
- }
37
- if (typeof options.maxFileSize === "number" && file.size > options.maxFileSize) {
38
- const maxMB = (options.maxFileSize / (1024 * 1024)).toFixed(1);
39
- return {
40
- code: "FILE_TOO_LARGE",
41
- message: `File size exceeds ${maxMB} MB limit`,
42
- params: { size: `${maxMB} MB` }
43
- };
44
- }
45
- return null;
46
- }
5
+ // src/error.ts
47
6
 
48
- // src/helpers/strip-slashes.ts
49
- var SLASH = "/";
50
- function stripTrailingSlashes(value) {
51
- let end = value.length;
52
- while (end > 0 && value.charAt(end - 1) === SLASH) end -= 1;
53
- return end === value.length ? value : value.slice(0, end);
7
+ // src/error-codes.ts
8
+ function defineErrorCodes(codes) {
9
+ const entries = {};
10
+ for (const code of Object.keys(codes)) {
11
+ entries[code] = { code, ...codes[code] };
12
+ }
13
+ return entries;
54
14
  }
55
- function stripSurroundingSlashes(value) {
56
- let start = 0;
57
- let end = value.length;
58
- while (start < end && value.charAt(start) === SLASH) start += 1;
59
- while (end > start && value.charAt(end - 1) === SLASH) end -= 1;
60
- return start === 0 && end === value.length ? value : value.slice(start, end);
15
+ var S3_ERROR_CODES = defineErrorCodes({
16
+ // protocol
17
+ VALIDATION_ERROR: { status: 400, message: "Invalid request: {issue}" },
18
+ REQUEST_TOO_LARGE: {
19
+ status: 413,
20
+ message: "Request body exceeds {maxSize} bytes"
21
+ },
22
+ UNSUPPORTED_MEDIA_TYPE: {
23
+ status: 415,
24
+ message: "Request body must be application/json"
25
+ },
26
+ NOT_FOUND: { status: 404, message: "Not found" },
27
+ UNAUTHORIZED: { status: 401, message: "Unauthorized" },
28
+ FORBIDDEN: { status: 403, message: "Forbidden" },
29
+ /** A concurrent change won; retrying may succeed. */
30
+ CONFLICT: { status: 409, message: "Conflict" },
31
+ INTERNAL_ERROR: { status: 500, message: "Internal server error" },
32
+ S3_NETWORK_ERROR: {
33
+ status: 502,
34
+ message: "S3 endpoint unreachable ({code})"
35
+ },
36
+ UNKNOWN_ROUTE: { status: 404, message: 'Unknown file route "{route}"' },
37
+ FEATURE_DISABLED: { status: 404, message: "{feature} is disabled" },
38
+ KEY_INVALID: { status: 400, message: "Object key is invalid" },
39
+ OBJECT_NOT_FOUND: { status: 404, message: "Object not found" },
40
+ RANGE_NOT_SATISFIABLE: {
41
+ status: 416,
42
+ message: "Requested range not satisfiable"
43
+ },
44
+ PRECONDITION_FAILED: { status: 412, message: "Precondition failed" },
45
+ // files
46
+ FILE_EMPTY: { status: 400, message: "File is empty" },
47
+ FILE_TOO_LARGE: {
48
+ status: 413,
49
+ message: "File is {size} bytes; the limit is {maxFileSize} bytes"
50
+ },
51
+ FILE_TYPE_NOT_ALLOWED: {
52
+ status: 400,
53
+ message: 'File type "{type}" is not allowed'
54
+ },
55
+ FILE_CONTENT_MISMATCH: {
56
+ status: 400,
57
+ message: 'File content does not match type "{type}"'
58
+ },
59
+ CHECKSUM_REQUIRED: {
60
+ status: 400,
61
+ message: "A SHA-256 checksum is required"
62
+ },
63
+ QUOTA_EXCEEDED: { status: 403, message: "Storage quota exceeded" },
64
+ // upload sessions
65
+ UPLOAD_TICKET_INVALID: { status: 403, message: "Upload ticket is invalid" },
66
+ UPLOAD_TICKET_EXPIRED: { status: 410, message: "Upload ticket has expired" },
67
+ UPLOAD_SIZE_MISMATCH: {
68
+ status: 400,
69
+ message: "Uploaded {actual} bytes; expected {expected}"
70
+ },
71
+ MULTIPART_PART_MISSING: {
72
+ status: 400,
73
+ message: "Uploaded part {partNumber} was not found"
74
+ },
75
+ MULTIPART_PART_INVALID: {
76
+ status: 400,
77
+ message: "Part {partNumber} is outside 1..{partCount}"
78
+ },
79
+ // db plugin
80
+ OBJECT_EXISTS: {
81
+ status: 409,
82
+ message: "An object already exists at this key"
83
+ },
84
+ FOLDER_INVALID: { status: 400, message: "Folder path is invalid" },
85
+ FOLDER_EXISTS: { status: 409, message: "Folder already exists" },
86
+ FOLDER_NOT_EMPTY: { status: 409, message: "Folder is not empty" },
87
+ // client-only (never sent by the server)
88
+ TOO_MANY_FILES: {
89
+ status: 400,
90
+ client: true,
91
+ message: "At most {maxFiles} files can be added"
92
+ },
93
+ HOOK_FAILED: {
94
+ status: 500,
95
+ client: true,
96
+ message: "The {hook} callback failed"
97
+ },
98
+ NETWORK_ERROR: { status: 502, client: true, message: "Network error" },
99
+ UPLOAD_FAILED: {
100
+ status: 502,
101
+ client: true,
102
+ message: "Upload failed with HTTP {status}"
103
+ },
104
+ DOWNLOAD_FAILED: {
105
+ status: 502,
106
+ client: true,
107
+ message: "Download failed with HTTP {status}"
108
+ },
109
+ CHECKSUM_MISMATCH: {
110
+ status: 400,
111
+ client: true,
112
+ message: "Uploaded bytes do not match the checksum"
113
+ },
114
+ PARTIAL_FAILURE: {
115
+ status: 207,
116
+ client: true,
117
+ message: "{failed} of {total} operations failed"
118
+ },
119
+ UNKNOWN_ERROR: {
120
+ status: 500,
121
+ client: true,
122
+ message: "Something went wrong"
123
+ }
124
+ });
125
+ function formatErrorMessage(template, params) {
126
+ if (!params) return template;
127
+ return template.replaceAll(
128
+ /\{(\w+)\}/g,
129
+ (placeholder, name) => Object.hasOwn(params, name) ? String(params[name]) : placeholder
130
+ );
61
131
  }
62
132
 
63
- // src/helpers/build-object-key.ts
64
- function buildObjectKey(...parts) {
65
- return parts.map((part) => stripSurroundingSlashes(part)).filter(Boolean).join("/");
133
+ // src/error.ts
134
+ var statusNames = new Map(
135
+ Object.keys(statusCodes).map((name) => [
136
+ statusCodes[name],
137
+ name
138
+ ])
139
+ );
140
+ function toNamedStatus(status) {
141
+ if (typeof status !== "number") return status;
142
+ return statusNames.get(status) ?? status;
66
143
  }
67
-
68
- // src/helpers/parse-file-name.ts
69
- function parseFileName(contentDisposition) {
70
- if (!contentDisposition) return void 0;
71
- const utf8Match = contentDisposition.match(/filename\*=UTF-8''([^;,\s]+)/i);
72
- if (utf8Match) {
73
- try {
74
- return decodeURIComponent(utf8Match[1]);
75
- } catch {
144
+ var APIError = class _APIError extends APIError$1 {
145
+ constructor(status, body, headers) {
146
+ const { cause, ...rest } = body;
147
+ super(toNamedStatus(status), rest, headers);
148
+ this.name = "APIError";
149
+ if (cause !== void 0) {
150
+ this.cause = cause;
76
151
  }
77
152
  }
78
- const asciiMatch = contentDisposition.match(/filename="([^"]*)"/i);
79
- return asciiMatch?.[1];
80
- }
81
- function fileNameFromKey(key) {
82
- return key.split("/").findLast((part) => part.length > 0);
83
- }
84
- function resolveStoredFileName(contentDisposition, key) {
85
- return parseFileName(contentDisposition) ?? fileNameFromKey(key);
86
- }
87
-
88
- // src/helpers/format-file-size.ts
89
- var UNITS = [
90
- "B",
91
- "KB",
92
- "MB",
93
- "GB",
94
- "TB",
95
- "PB",
96
- "EB"
97
- ];
98
- var numberFormats = /* @__PURE__ */ new Map();
99
- function numberFormat(locale, fractionDigits) {
100
- const id = `${String(locale)}|${fractionDigits}`;
101
- let format = numberFormats.get(id);
102
- if (!format) {
103
- format = new Intl.NumberFormat(
104
- typeof locale === "string" ? locale : [...locale],
105
- {
106
- minimumFractionDigits: fractionDigits,
107
- maximumFractionDigits: fractionDigits,
108
- useGrouping: false
109
- }
110
- );
111
- numberFormats.set(id, format);
153
+ /** Stable machine-readable code; always set. */
154
+ get code() {
155
+ return this.body.code;
112
156
  }
113
- return format;
114
- }
115
- function formatFileSize(bytes, options = {}) {
116
- const size = Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
117
- const i = size === 0 ? 0 : Math.min(Math.floor(Math.log(size) / Math.log(1024)), UNITS.length - 1);
118
- const unit = UNITS[i] ?? "B";
119
- const value = numberFormat(options.locale ?? "en-US", i === 0 ? 0 : 1).format(
120
- size / 1024 ** i
121
- );
122
- return `${value} ${options.units?.[unit] ?? unit}`;
157
+ get params() {
158
+ return this.body.params;
159
+ }
160
+ /** Plugin-defined or catalog codes with an explicit status. */
161
+ static from(status, body) {
162
+ return new _APIError(status, {
163
+ code: body.code,
164
+ message: body.message,
165
+ ...body.params !== void 0 ? { params: body.params } : {}
166
+ });
167
+ }
168
+ /**
169
+ * Rebuild from a wire body (e.g. `deleteMany` `failed[].error`).
170
+ * Status: explicit, else the catalog status, else 500.
171
+ */
172
+ static fromShape(shape, status) {
173
+ return _APIError.from(status ?? catalogStatus(shape.code) ?? 500, shape);
174
+ }
175
+ };
176
+ function catalogStatus(code) {
177
+ return Object.hasOwn(S3_ERROR_CODES, code) ? S3_ERROR_CODES[code].status : void 0;
178
+ }
179
+ function s3Error(code, ...args) {
180
+ const [params, options] = args;
181
+ const entry = S3_ERROR_CODES[code];
182
+ return new APIError(options?.status ?? entry.status, {
183
+ code,
184
+ message: formatErrorMessage(entry.message, params),
185
+ ...params !== void 0 ? { params } : {},
186
+ ...options?.cause !== void 0 ? { cause: options.cause } : {}
187
+ });
123
188
  }
124
-
125
- // src/helpers/build-content-disposition.ts
126
- function buildContentDisposition(fileName, type = "attachment") {
127
- const ascii = fileName.replaceAll(/[^\x20-\x7E]/g, "_").replaceAll(/["\\]/g, "_");
128
- const encoded = encodeURIComponent(fileName);
129
- return `${type}; filename="${ascii}"; filename*=UTF-8''${encoded}`;
189
+ function isAPIError(error) {
190
+ if (error instanceof APIError) return true;
191
+ const candidate = error;
192
+ return candidate?.name === "APIError" && typeof candidate.code === "string" && typeof candidate.statusCode === "number";
193
+ }
194
+ function isS3ErrorCode(error, code) {
195
+ return isAPIError(error) && error.code === code;
130
196
  }
131
197
 
132
- // src/helpers/resolve-inline-disposition.ts
198
+ // src/helpers/content-type.ts
133
199
  var TYPE_BY_EXTENSION = {
134
200
  avif: "image/avif",
135
201
  bmp: "image/bmp",
@@ -174,8 +240,117 @@ function typeFromFileName(fileName) {
174
240
  if (!fileName || dot < 0) return void 0;
175
241
  return TYPE_BY_EXTENSION[fileName.slice(dot + 1).toLowerCase()];
176
242
  }
243
+ function effectiveContentType(contentType, fileName) {
244
+ const stored = baseType(contentType);
245
+ return UNTYPED.has(stored) ? typeFromFileName(fileName) : stored;
246
+ }
247
+ function describeFileType(fileName, contentType) {
248
+ const dot = fileName.lastIndexOf(".");
249
+ if (dot >= 0 && dot < fileName.length - 1) return fileName.slice(dot);
250
+ return contentType || "unknown";
251
+ }
252
+
253
+ // src/helpers/validate-file.ts
254
+ function matchesFileTypes(fileName, contentType, fileTypes) {
255
+ if (!fileTypes.length) return true;
256
+ const type = baseType(contentType);
257
+ const name = fileName.toLowerCase();
258
+ return fileTypes.some((entry) => {
259
+ const token = entry.trim().toLowerCase();
260
+ if (token === "*" || token === "*/*") return true;
261
+ if (token.startsWith(".")) return name.endsWith(token);
262
+ if (token.endsWith("/*")) return type.startsWith(token.slice(0, -1));
263
+ return type === token;
264
+ });
265
+ }
266
+ function validateFile(file, options) {
267
+ const { accept, maxFileSize } = options;
268
+ if (accept?.length && !matchesFileTypes(file.name, file.type, accept)) {
269
+ return s3Error("FILE_TYPE_NOT_ALLOWED", {
270
+ type: describeFileType(file.name, file.type),
271
+ allowed: accept.join(", ")
272
+ });
273
+ }
274
+ if (file.size === 0) {
275
+ return s3Error("FILE_EMPTY");
276
+ }
277
+ if (typeof maxFileSize === "number" && file.size > maxFileSize) {
278
+ return s3Error("FILE_TOO_LARGE", { size: file.size, maxFileSize });
279
+ }
280
+ return null;
281
+ }
282
+
283
+ // src/helpers/strip-slashes.ts
284
+ var SLASH = "/";
285
+ function stripTrailingSlashes(value) {
286
+ let end = value.length;
287
+ while (end > 0 && value.charAt(end - 1) === SLASH) end -= 1;
288
+ return end === value.length ? value : value.slice(0, end);
289
+ }
290
+ function stripSurroundingSlashes(value) {
291
+ let start = 0;
292
+ let end = value.length;
293
+ while (start < end && value.charAt(start) === SLASH) start += 1;
294
+ while (end > start && value.charAt(end - 1) === SLASH) end -= 1;
295
+ return start === 0 && end === value.length ? value : value.slice(start, end);
296
+ }
297
+
298
+ // src/helpers/build-object-key.ts
299
+ function buildObjectKey(...parts) {
300
+ return parts.map((part) => stripSurroundingSlashes(part)).filter(Boolean).join("/");
301
+ }
302
+
303
+ // src/helpers/parse-file-name.ts
304
+ var EXT_VALUE = /filename\*\s*=\s*([\w!#$&+.^`|~-]+)'[^']*'([^;\s]+)/i;
305
+ var QUOTED = /filename\s*=\s*"((?:[^"\\]|\\.)*)"/i;
306
+ var TOKEN = /filename\s*=\s*([^";\s]+)/i;
307
+ function parseFileName(contentDisposition) {
308
+ if (!contentDisposition) return void 0;
309
+ const ext = EXT_VALUE.exec(contentDisposition);
310
+ if (ext && /^utf-8$/i.test(ext[1])) {
311
+ try {
312
+ return decodeURIComponent(ext[2]);
313
+ } catch {
314
+ }
315
+ }
316
+ const quoted = QUOTED.exec(contentDisposition);
317
+ if (quoted) return quoted[1].replaceAll(/\\(.)/g, "$1");
318
+ return TOKEN.exec(contentDisposition)?.[1];
319
+ }
320
+ function fileNameFromKey(key) {
321
+ return key.split("/").findLast((part) => part.length > 0);
322
+ }
323
+ function resolveStoredFileName(contentDisposition, key) {
324
+ return parseFileName(contentDisposition) ?? fileNameFromKey(key);
325
+ }
326
+
327
+ // src/helpers/build-content-disposition.ts
328
+ function encodeExtValue(value) {
329
+ return encodeURIComponent(value).replaceAll(
330
+ /['()*]/g,
331
+ (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`
332
+ );
333
+ }
334
+ function buildContentDisposition(fileName, type = "attachment") {
335
+ const ascii2 = fileName.replaceAll(/[^\x20-\x7E]|["\\%]/g, "_");
336
+ return `${type}; filename="${ascii2}"; filename*=UTF-8''${encodeExtValue(fileName)}`;
337
+ }
338
+
339
+ // src/helpers/resolve-inline-disposition.ts
340
+ var DEFAULT_INLINE_TYPES = [
341
+ "image/png",
342
+ "image/jpeg",
343
+ "image/gif",
344
+ "image/webp",
345
+ "image/avif",
346
+ "image/bmp",
347
+ "application/pdf",
348
+ "audio/*",
349
+ "video/*",
350
+ "text/plain"
351
+ ];
177
352
  function isActiveContentType(type) {
178
- return type === "text/html" || type.endsWith("/xml") || type.endsWith("+xml") || type.includes("javascript") || type.includes("ecmascript");
353
+ return type === "text/html" || type === "text/xsl" || type.endsWith("/xml") || type.endsWith("+xml") || type.includes("javascript") || type.includes("ecmascript");
179
354
  }
180
355
  function isAllowed(type, allow) {
181
356
  const active = isActiveContentType(type);
@@ -187,43 +362,92 @@ function isAllowed(type, allow) {
187
362
  });
188
363
  }
189
364
  function resolveInlineDisposition(input) {
190
- if (input.requested !== "inline") return { disposition: "attachment" };
191
- const stored = baseType(input.contentType);
192
- const untyped = UNTYPED.has(stored);
193
- const type = untyped ? typeFromFileName(input.fileName) : stored;
194
- if (!type || !isAllowed(type, input.allow)) {
365
+ const allow = input.allow ?? DEFAULT_INLINE_TYPES;
366
+ if (input.requested !== "inline" || allow === false) {
367
+ return { disposition: "attachment" };
368
+ }
369
+ const type = effectiveContentType(input.contentType, input.fileName);
370
+ if (!type || !isAllowed(type, allow)) {
195
371
  return { disposition: "attachment" };
196
372
  }
197
- return untyped ? { disposition: "inline", contentType: type } : { disposition: "inline" };
373
+ return type === baseType(input.contentType) ? { disposition: "inline" } : { disposition: "inline", contentType: type };
198
374
  }
199
375
 
200
- // src/helpers/sanitize-file-name.ts
201
- function sanitizeFileName(fileName) {
202
- return fileName.replaceAll(/["\\\r\n\0]/g, "_");
203
- }
376
+ // src/limits.ts
377
+ var S3_DEFAULT_EXPIRES_IN = 600;
378
+ var S3_MAX_EXPIRES_IN = 604800;
379
+ var S3_MAX_POST_OBJECT_BYTES = 5 * 1024 * 1024 * 1024;
380
+ var S3_MAX_PART_NUMBER = 1e4;
381
+ var S3_MIN_PART_SIZE = 5 * 1024 * 1024;
382
+ var S3_MAX_PART_SIZE = 5 * 1024 * 1024 * 1024;
383
+ var S3_DEFAULT_PART_SIZE = 8 * 1024 * 1024;
384
+ var S3_MAX_OBJECT_SIZE = 5 * 1024 ** 4;
385
+ var S3_MAX_FILE_FIELD_BYTES = 255;
386
+ var UPLOAD_TICKET_MAX_LENGTH = 8192;
387
+ var S3_MAX_METADATA_ENTRIES = 32;
388
+ var DELETE_MANY_MAX_KEYS = 100;
389
+ var ROUTE_NAME_PATTERN = /^[a-z][\w-]{0,63}$/i;
204
390
 
205
- // src/helpers/truncate-file-name.ts
206
- function truncateFileName(name, maxChars = 48) {
207
- if (name.length <= maxChars) return name;
208
- const dotIndex = name.lastIndexOf(".");
209
- if (dotIndex <= 0) {
210
- return name.slice(0, maxChars - 1) + "\u2026";
391
+ // src/helpers/fit-file-name.ts
392
+ var MAX_EXTENSION_BYTES = 32;
393
+ var FALLBACK_FILE_NAME = "file";
394
+ var CONTROL_CHARACTERS = /\p{Cc}/gu;
395
+ var BIDI_CONTROL = /[\u202A-\u202E\u2066-\u2069]/u;
396
+ var BIDI_CONTROLS = new RegExp(BIDI_CONTROL.source, "gu");
397
+ var utf8 = new TextEncoder();
398
+ function byteLength(text) {
399
+ return utf8.encode(text).byteLength;
400
+ }
401
+ var graphemeSegmenter;
402
+ function graphemes(text) {
403
+ if (graphemeSegmenter === void 0) {
404
+ graphemeSegmenter = typeof Intl.Segmenter === "function" ? new Intl.Segmenter(void 0, { granularity: "grapheme" }) : null;
211
405
  }
212
- const ext = name.slice(dotIndex);
213
- const available = maxChars - ext.length - 1;
214
- if (available <= 0) {
215
- return name.slice(0, maxChars - 1) + "\u2026";
406
+ if (!graphemeSegmenter) return text;
407
+ return Array.from(graphemeSegmenter.segment(text), (part) => part.segment);
408
+ }
409
+ function takeWithin(parts, maxBytes) {
410
+ let taken = "";
411
+ let used = 0;
412
+ for (const part of parts) {
413
+ used += byteLength(part);
414
+ if (used > maxBytes) break;
415
+ taken += part;
216
416
  }
217
- return name.slice(0, available) + "\u2026 " + ext;
417
+ return taken;
418
+ }
419
+ function cutToBytes(text, maxBytes) {
420
+ return takeWithin(graphemes(text), maxBytes) || takeWithin(text, maxBytes);
421
+ }
422
+ function fitFileName(name) {
423
+ const cleaned = name.toWellFormed().replaceAll(CONTROL_CHARACTERS, "").replaceAll(BIDI_CONTROLS, "").trim();
424
+ if (byteLength(cleaned) <= S3_MAX_FILE_FIELD_BYTES) {
425
+ return cleaned || FALLBACK_FILE_NAME;
426
+ }
427
+ const dot = cleaned.lastIndexOf(".");
428
+ const extension = dot > 0 ? cleaned.slice(dot) : "";
429
+ const keepExtension = extension.length > 1 && byteLength(extension) <= MAX_EXTENSION_BYTES;
430
+ const suffix = keepExtension ? extension : "";
431
+ const stem = keepExtension ? cleaned.slice(0, dot) : cleaned;
432
+ const budget = S3_MAX_FILE_FIELD_BYTES - byteLength(suffix);
433
+ const base = cutToBytes(stem, budget).trimEnd() || FALLBACK_FILE_NAME;
434
+ return `${base}${suffix}`;
218
435
  }
219
436
 
220
437
  // src/helpers/normalize-object-key.ts
221
- var S3_MAX_OBJECT_KEY_LENGTH = 1024;
438
+ var S3_MAX_OBJECT_KEY_BYTES = 1024;
439
+ var utf82 = new TextEncoder();
440
+ function objectKeyByteLength(key) {
441
+ return utf82.encode(key).byteLength;
442
+ }
443
+ var CONTROL_CHARACTER = /\p{Cc}/u;
222
444
  function normalizeObjectKey(key) {
223
445
  const trimmed = stripSurroundingSlashes(key);
224
- if (!trimmed) return null;
225
- if (trimmed.length > S3_MAX_OBJECT_KEY_LENGTH) return null;
226
- if (trimmed.includes("\\") || trimmed.includes("\0")) return null;
446
+ if (!trimmed || trimmed !== trimmed.trim()) return null;
447
+ if (trimmed.length > S3_MAX_OBJECT_KEY_BYTES) return null;
448
+ if (!trimmed.isWellFormed()) return null;
449
+ if (objectKeyByteLength(trimmed) > S3_MAX_OBJECT_KEY_BYTES) return null;
450
+ if (trimmed.includes("\\") || CONTROL_CHARACTER.test(trimmed)) return null;
227
451
  const parts = trimmed.split("/");
228
452
  if (parts.some((part) => part === "" || part === "." || part === "..")) {
229
453
  return null;
@@ -231,48 +455,255 @@ function normalizeObjectKey(key) {
231
455
  return parts.join("/");
232
456
  }
233
457
 
458
+ // src/helpers/base64url.ts
459
+ var BASE64URL_PATTERN = /^[\w-]*$/;
460
+ var BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
461
+ var encoder = new TextEncoder();
462
+ function bytesToBase64(bytes) {
463
+ const extra = bytes.length % 3;
464
+ const parts = new Array(Math.ceil(bytes.length / 3));
465
+ let part = 0;
466
+ const length = bytes.length - extra;
467
+ for (let index = 0; index < length; index += 3) {
468
+ const value = (bytes[index] ?? 0) << 16 | (bytes[index + 1] ?? 0) << 8 | (bytes[index + 2] ?? 0);
469
+ parts[part++] = (BASE64_ALPHABET[value >>> 18] ?? "") + (BASE64_ALPHABET[value >>> 12 & 63] ?? "") + (BASE64_ALPHABET[value >>> 6 & 63] ?? "") + (BASE64_ALPHABET[value & 63] ?? "");
470
+ }
471
+ if (extra === 1) {
472
+ const value = (bytes[length] ?? 0) << 16;
473
+ parts[part] = (BASE64_ALPHABET[value >>> 18] ?? "") + (BASE64_ALPHABET[value >>> 12 & 63] ?? "") + "==";
474
+ } else if (extra === 2) {
475
+ const value = (bytes[length] ?? 0) << 16 | (bytes[length + 1] ?? 0) << 8;
476
+ parts[part] = (BASE64_ALPHABET[value >>> 18] ?? "") + (BASE64_ALPHABET[value >>> 12 & 63] ?? "") + (BASE64_ALPHABET[value >>> 6 & 63] ?? "") + "=";
477
+ }
478
+ return parts.join("");
479
+ }
480
+ function base64UrlEncode(bytes) {
481
+ const data = typeof bytes === "string" ? encoder.encode(bytes) : bytes;
482
+ return bytesToBase64(data).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
483
+ }
484
+ function base64UrlDecode(value) {
485
+ if (!BASE64URL_PATTERN.test(value) || value.length % 4 === 1) {
486
+ throw new TypeError("Invalid base64url string");
487
+ }
488
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/");
489
+ const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
490
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
491
+ if (base64UrlEncode(bytes) !== value) {
492
+ throw new TypeError("Invalid base64url string");
493
+ }
494
+ return bytes;
495
+ }
496
+
234
497
  // src/helpers/checksum.ts
498
+ var CHUNK_SIZE = 1024 * 1024;
499
+ function toUnpaddedBase64(bytes) {
500
+ return bytesToBase64(bytes).replace(/=+$/, "");
501
+ }
235
502
  async function sha256Base64(data) {
236
503
  const digest = await crypto.subtle.digest("SHA-256", data);
237
- const bytes = new Uint8Array(digest);
238
- return btoa(String.fromCharCode(...bytes)).replaceAll(/=+$/g, "");
239
- }
240
- async function sha256File(file) {
241
- return sha256Base64(await file.arrayBuffer());
504
+ return toUnpaddedBase64(new Uint8Array(digest));
505
+ }
506
+ async function sha256Blob(blob, options = {}) {
507
+ const { signal } = options;
508
+ signal?.throwIfAborted();
509
+ const hash = sha256.create();
510
+ for (let offset = 0; offset < blob.size; offset += CHUNK_SIZE) {
511
+ const chunk = await blob.slice(offset, offset + CHUNK_SIZE).arrayBuffer();
512
+ signal?.throwIfAborted();
513
+ hash.update(new Uint8Array(chunk));
514
+ }
515
+ return toUnpaddedBase64(hash.digest());
242
516
  }
243
517
 
244
518
  // src/helpers/magic-bytes.ts
245
- var MAGIC = [
246
- { mime: "image/png", bytes: [137, 80, 78, 71] },
247
- { mime: "image/jpeg", bytes: [255, 216, 255] },
248
- { mime: "image/gif", bytes: [71, 73, 70, 56] },
249
- { mime: "image/webp", bytes: [82, 73, 70, 70], offset: 0 },
250
- { mime: "application/pdf", bytes: [37, 80, 68, 70] },
251
- { mime: "application/zip", bytes: [80, 75, 3, 4] },
252
- { mime: "video/webm", bytes: [26, 69, 223, 163] }
519
+ var SNIFF_BYTE_LENGTH = 4096;
520
+ var FTYP_BRANDS = [
521
+ { brands: ["avif", "avis"], type: "image/avif" },
522
+ {
523
+ brands: ["heic", "heix", "heim", "heis", "hevc", "hevx"],
524
+ type: "image/heic"
525
+ },
526
+ { brands: ["qt "], type: "video/quicktime" },
527
+ { brands: ["M4A ", "M4B ", "M4P "], type: "audio/mp4" },
528
+ {
529
+ brands: [
530
+ "isom",
531
+ "iso2",
532
+ "iso4",
533
+ "iso5",
534
+ "iso6",
535
+ "mp41",
536
+ "mp42",
537
+ "mp71",
538
+ "avc1",
539
+ "dash",
540
+ "M4V ",
541
+ "MSNV",
542
+ "f4v "
543
+ ],
544
+ type: "video/mp4"
545
+ }
253
546
  ];
254
- function prefixEquals(bytes, expected, offset = 0) {
547
+ function startsWith(bytes, expected, offset = 0) {
255
548
  if (bytes.length < offset + expected.length) return false;
256
549
  return expected.every((value, i) => bytes[offset + i] === value);
257
550
  }
258
- function sniffContentType(bytes) {
259
- if (prefixEquals(bytes, [82, 73, 70, 70]) && bytes.length >= 12) {
260
- const tag = String.fromCharCode(...bytes.subarray(8, 12));
261
- if (tag === "WEBP") return "image/webp";
551
+ function ascii(bytes, start, end) {
552
+ return String.fromCharCode(...bytes.subarray(start, end));
553
+ }
554
+ function hasAscii(bytes, text, offset = 0) {
555
+ return ascii(bytes, offset, offset + text.length) === text;
556
+ }
557
+ function isRiff(bytes, form) {
558
+ return hasAscii(bytes, "RIFF") && hasAscii(bytes, form, 8);
559
+ }
560
+ function ftypTypeOf(brand) {
561
+ return FTYP_BRANDS.find((entry) => entry.brands.includes(brand))?.type;
562
+ }
563
+ function ftypType(bytes) {
564
+ if (!hasAscii(bytes, "ftyp", 4) || bytes.length < 12) return void 0;
565
+ const major = ftypTypeOf(ascii(bytes, 8, 12));
566
+ if (major) return major;
567
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
568
+ const boxEnd = Math.min(view.getUint32(0), bytes.length);
569
+ const brands = [];
570
+ for (let offset = 16; offset + 4 <= boxEnd; offset += 4) {
571
+ brands.push(ascii(bytes, offset, offset + 4));
262
572
  }
263
- for (const entry of MAGIC) {
264
- if (entry.mime === "image/webp") continue;
265
- if (prefixEquals(bytes, entry.bytes, entry.offset)) return entry.mime;
573
+ return FTYP_BRANDS.find(
574
+ (entry) => entry.brands.some((brand) => brands.includes(brand))
575
+ )?.type;
576
+ }
577
+ function isMp3Frame(bytes) {
578
+ if (bytes.length < 3 || bytes[0] !== 255) return false;
579
+ const version = bytes[1] >> 3 & 3;
580
+ const layer = bytes[1] >> 1 & 3;
581
+ const bitrate = bytes[2] >> 4;
582
+ const sampleRate = bytes[2] >> 2 & 3;
583
+ return (bytes[1] & 224) === 224 && version !== 1 && layer === 1 && bitrate !== 15 && sampleRate !== 3;
584
+ }
585
+ function id3v2End(bytes) {
586
+ if (bytes.length < 10 || !hasAscii(bytes, "ID3")) return void 0;
587
+ if (bytes[3] < 2 || bytes[3] > 4) return void 0;
588
+ const size = bytes.subarray(6, 10);
589
+ if (size.some((byte) => byte & 128)) return void 0;
590
+ const footer = bytes[5] & 16 ? 10 : 0;
591
+ return 10 + (size[0] << 21 | size[1] << 14 | size[2] << 7 | size[3]) + footer;
592
+ }
593
+ function afterId3v2(bytes) {
594
+ const end = id3v2End(bytes);
595
+ return end === void 0 ? new Uint8Array() : bytes.subarray(end);
596
+ }
597
+ function hasTruncatedId3v2(bytes) {
598
+ const end = id3v2End(bytes);
599
+ return end !== void 0 && end >= bytes.length;
600
+ }
601
+ function isBmp(bytes) {
602
+ if (!hasAscii(bytes, "BM") || bytes.length < 18) return false;
603
+ const dibSize = bytes[14] | bytes[15] << 8 | bytes[16] << 16 | bytes[17] << 24;
604
+ return [12, 40, 52, 56, 64, 108, 124].includes(dibSize);
605
+ }
606
+ function ftypSignature(type, aliases) {
607
+ return { type, aliases, test: (bytes) => ftypType(bytes) === type };
608
+ }
609
+ var SIGNATURES = [
610
+ {
611
+ type: "image/png",
612
+ test: (bytes) => startsWith(bytes, [137, 80, 78, 71])
613
+ },
614
+ {
615
+ type: "image/jpeg",
616
+ test: (bytes) => startsWith(bytes, [255, 216, 255])
617
+ },
618
+ { type: "image/gif", test: (bytes) => hasAscii(bytes, "GIF8") },
619
+ { type: "image/bmp", test: isBmp },
620
+ {
621
+ type: "image/tiff",
622
+ test: (bytes) => startsWith(bytes, [73, 73, 42, 0]) || startsWith(bytes, [77, 77, 0, 42])
623
+ },
624
+ {
625
+ type: "image/x-icon",
626
+ aliases: ["image/vnd.microsoft.icon"],
627
+ test: (bytes) => startsWith(bytes, [0, 0, 1, 0])
628
+ },
629
+ { type: "image/webp", test: (bytes) => isRiff(bytes, "WEBP") },
630
+ ftypSignature("image/avif"),
631
+ ftypSignature("image/heic", ["image/heif"]),
632
+ ftypSignature("video/quicktime"),
633
+ ftypSignature("audio/mp4", ["audio/x-m4a", "video/mp4"]),
634
+ ftypSignature("video/mp4", ["audio/mp4", "audio/x-m4a", "video/x-m4v"]),
635
+ { type: "application/pdf", test: (bytes) => hasAscii(bytes, "%PDF") },
636
+ {
637
+ type: "application/zip",
638
+ aliases: ["application/x-zip-compressed"],
639
+ test: (bytes) => startsWith(bytes, [80, 75, 3, 4])
640
+ },
641
+ {
642
+ type: "application/gzip",
643
+ aliases: ["application/x-gzip"],
644
+ test: (bytes) => startsWith(bytes, [31, 139])
645
+ },
646
+ {
647
+ // EBML: WebM and Matroska share it.
648
+ type: "video/webm",
649
+ aliases: ["audio/webm", "video/x-matroska", "audio/x-matroska"],
650
+ test: (bytes) => startsWith(bytes, [26, 69, 223, 163])
651
+ },
652
+ {
653
+ type: "audio/flac",
654
+ aliases: ["audio/x-flac"],
655
+ test: (bytes) => hasAscii(afterId3v2(bytes), "fLaC")
656
+ },
657
+ {
658
+ // The tag hides what follows: MP3 is likelier, but FLAC is not ruled out.
659
+ type: "audio/mpeg",
660
+ aliases: ["audio/mp3", "audio/flac", "audio/x-flac"],
661
+ test: hasTruncatedId3v2
662
+ },
663
+ {
664
+ type: "audio/mpeg",
665
+ aliases: ["audio/mp3"],
666
+ test: (bytes) => hasAscii(bytes, "ID3") || isMp3Frame(bytes)
667
+ },
668
+ {
669
+ type: "audio/ogg",
670
+ aliases: ["video/ogg", "application/ogg"],
671
+ test: (bytes) => hasAscii(bytes, "OggS")
672
+ },
673
+ {
674
+ type: "audio/wav",
675
+ aliases: ["audio/wave", "audio/x-wav", "audio/vnd.wave"],
676
+ test: (bytes) => isRiff(bytes, "WAVE")
677
+ },
678
+ {
679
+ type: "audio/flac",
680
+ aliases: ["audio/x-flac"],
681
+ test: (bytes) => hasAscii(bytes, "fLaC")
266
682
  }
267
- return void 0;
683
+ ];
684
+ function typesOf(signature) {
685
+ return [signature.type, ...signature.aliases ?? []];
686
+ }
687
+ function sniffSignature(bytes) {
688
+ return SIGNATURES.find((signature) => signature.test(bytes));
689
+ }
690
+ function sniffContentType(bytes) {
691
+ return sniffSignature(bytes)?.type;
692
+ }
693
+ function isSniffableType(type) {
694
+ const base = baseType(type);
695
+ return SIGNATURES.some((signature) => typesOf(signature).includes(base));
268
696
  }
269
697
  function matchesMagicBytes(bytes, expected) {
270
- const sniffed = sniffContentType(bytes);
271
- if (!sniffed) return false;
272
- if (expected.endsWith("/*")) {
273
- return sniffed.startsWith(expected.slice(0, -1));
698
+ const signature = sniffSignature(bytes);
699
+ if (!signature) return false;
700
+ const base = baseType(expected);
701
+ const types = typesOf(signature);
702
+ if (base.endsWith("/*")) {
703
+ const prefix = base.slice(0, -1);
704
+ return types.some((type) => type.startsWith(prefix));
274
705
  }
275
- return sniffed === expected;
706
+ return types.includes(base);
276
707
  }
277
708
 
278
709
  // src/helpers/public-object-url.ts
@@ -281,297 +712,87 @@ function buildPublicObjectUrl(options) {
281
712
  const path = options.key.split("/").filter((part) => part.length > 0).map((part) => encodeURIComponent(part)).join("/");
282
713
  return `${base}/${path}`;
283
714
  }
284
- var S3_DEFAULT_EXPIRES_IN = 600;
285
- var S3_MAX_EXPIRES_IN = 604800;
286
- var S3_MAX_POST_OBJECT_BYTES = 5 * 1024 * 1024 * 1024;
287
- var S3_MAX_PART_NUMBER = 1e4;
288
- var S3_MAX_METADATA_ENTRIES = 32;
289
- var ROUTE_NAME_PATTERN = /^[a-z][\w-]{0,63}$/i;
290
- var trimmedString = z3.string().trim().min(1);
291
- var optionalTrimmedString = z3.preprocess((value) => {
292
- if (typeof value !== "string") return value;
293
- const trimmed = value.trim();
294
- return trimmed === "" ? void 0 : trimmed;
295
- }, z3.string().optional());
296
- var routeNameSchema = trimmedString.regex(
297
- ROUTE_NAME_PATTERN,
298
- "Invalid route name"
299
- );
300
- var objectKeySchema = trimmedString.max(S3_MAX_OBJECT_KEY_LENGTH).transform((value, ctx) => {
301
- const normalized = normalizeObjectKey(value);
302
- if (normalized == null) {
303
- ctx.issues.push({
304
- code: "custom",
305
- message: "Invalid object key",
306
- input: value
307
- });
308
- return z3.NEVER;
309
- }
310
- return normalized;
311
- });
312
- var partNumberSchema = z3.int().min(1).max(S3_MAX_PART_NUMBER);
313
- var s3ObjectAclSchema = z3.enum(["private", "public-read"]);
314
- var sha256ChecksumSchema = z3.stringFormat(
315
- "sha256-base64",
316
- /^[A-Z0-9+/]{43}=?$/i
317
- );
318
- var optionalChecksumSchema = optionalTrimmedString.pipe(
319
- sha256ChecksumSchema.optional()
320
- );
321
- var metadataKeySchema = z3.string().regex(/^[a-z0-9][a-z0-9-]*$/i, "Invalid metadata key").max(128);
322
- var metadataSchema = z3.record(metadataKeySchema, z3.string().max(2048)).refine((value) => Object.keys(value).length <= S3_MAX_METADATA_ENTRIES, {
323
- message: "Too many metadata entries"
324
- });
325
- var uploadBodySchema = z3.strictObject({
326
- route: routeNameSchema,
327
- fileName: trimmedString,
328
- fileSize: z3.int().positive(),
329
- contentType: optionalTrimmedString,
330
- metadata: metadataSchema.optional(),
331
- /** Unpadded base64 SHA-256. Required when the route sets `upload.checksum`. */
332
- checksum: optionalChecksumSchema
333
- });
334
- var confirmBodySchema = z3.strictObject({
335
- route: routeNameSchema,
336
- key: objectKeySchema
337
- });
338
- var downloadDispositionSchema = z3.enum(["inline", "attachment"]);
339
- var downloadModeSchema = z3.enum(["presign", "proxy"]);
340
- var routeCatalogUploadSchema = z3.discriminatedUnion("enabled", [
341
- z3.strictObject({
342
- enabled: z3.literal(true),
343
- fileTypes: z3.array(z3.string()).optional(),
344
- maxFileSize: z3.int().positive().optional(),
345
- multipart: z3.boolean(),
346
- checksum: z3.boolean().optional(),
347
- replace: z3.literal("overwrite").optional()
348
- }),
349
- z3.strictObject({ enabled: z3.literal(false) })
350
- ]);
351
- var routeCatalogDownloadSchema = z3.discriminatedUnion("enabled", [
352
- z3.strictObject({
353
- enabled: z3.literal(true),
354
- /**
355
- * Maximum presign TTL in seconds. Clients may request a shorter
356
- * `expiresIn`. Omitted means the protocol default (600).
357
- */
358
- expiresIn: z3.int().positive().max(S3_MAX_EXPIRES_IN).optional(),
359
- disposition: downloadDispositionSchema.optional(),
360
- /** Types that may open inline. Pass to `resolveInlineDisposition`. */
361
- inlineTypes: z3.array(z3.string()).optional(),
362
- mode: downloadModeSchema.optional()
363
- }),
364
- z3.strictObject({ enabled: z3.literal(false) })
365
- ]);
366
- var routeCatalogDeleteSchema = z3.discriminatedUnion("enabled", [
367
- z3.strictObject({ enabled: z3.literal(true) }),
368
- z3.strictObject({ enabled: z3.literal(false) })
369
- ]);
370
- var routeCatalogEntrySchema = z3.strictObject({
371
- upload: routeCatalogUploadSchema,
372
- download: routeCatalogDownloadSchema,
373
- delete: routeCatalogDeleteSchema
374
- });
375
- var routeCatalogResponseSchema = z3.strictObject({
376
- routes: z3.record(routeNameSchema, routeCatalogEntrySchema)
377
- });
378
-
379
- // src/schema/download.ts
380
- var optionalExpiresInSchema = z3.preprocess((value) => {
381
- if (value == null || value === "") return void 0;
382
- if (typeof value === "number") return value;
383
- if (typeof value === "string") {
384
- const trimmed = value.trim();
385
- if (trimmed === "") return void 0;
386
- if (/^\d+$/.test(trimmed)) return Number(trimmed);
387
- }
388
- return value;
389
- }, z3.int().positive().max(S3_MAX_EXPIRES_IN).optional());
390
- var downloadQuerySchema = z3.strictObject({
391
- route: routeNameSchema,
392
- key: objectKeySchema,
393
- fileName: optionalTrimmedString,
394
- disposition: downloadDispositionSchema.optional(),
395
- /**
396
- * Requested TTL in seconds. Signed only when it is shorter than the
397
- * route `download.expiresIn`. `download.resolve` can still replace it.
398
- */
399
- expiresIn: optionalExpiresInSchema
400
- });
401
- var DELETE_BATCH_MAX_KEYS = 100;
402
- var deleteQuerySchema = z3.strictObject({
403
- route: routeNameSchema,
404
- key: objectKeySchema
405
- });
406
- var deleteBatchBodySchema = z3.strictObject({
407
- route: routeNameSchema,
408
- keys: z3.array(objectKeySchema).min(1).max(DELETE_BATCH_MAX_KEYS)
409
- });
410
- var fileQuerySchema = z3.strictObject({
411
- route: routeNameSchema,
412
- key: objectKeySchema,
413
- fileName: optionalTrimmedString,
414
- disposition: downloadDispositionSchema.optional()
415
- });
416
- var multipartInitBodySchema = uploadBodySchema;
417
- var multipartSessionFields = {
418
- route: routeNameSchema,
419
- key: objectKeySchema,
420
- uploadId: trimmedString
421
- };
422
- var multipartSignPartBodySchema = z3.strictObject({
423
- ...multipartSessionFields,
424
- partNumber: partNumberSchema,
425
- partSize: z3.int().positive()
426
- });
427
- var multipartListPartsQuerySchema = z3.strictObject({
428
- ...multipartSessionFields
429
- });
430
- var multipartCompletedPartSchema = z3.strictObject({
431
- partNumber: partNumberSchema
432
- });
433
- var multipartCompleteBodySchema = z3.strictObject({
434
- ...multipartSessionFields,
435
- parts: z3.array(multipartCompletedPartSchema).min(1)
436
- });
437
- var multipartAbortBodySchema = z3.strictObject({
438
- ...multipartSessionFields
439
- });
440
- var s3ErrorParamsSchema = z3.record(
441
- z3.string(),
442
- z3.union([z3.string(), z3.number()])
443
- );
444
- var s3FetchErrorSchema = z3.object({
445
- message: z3.string(),
446
- code: z3.string().optional(),
447
- params: s3ErrorParamsSchema.optional()
448
- });
449
-
450
- // src/error-codes.ts
451
- function defineErrorCodes(messages) {
452
- const codes = {};
453
- for (const code of Object.keys(messages)) {
454
- codes[code] = { code, message: messages[code] };
455
- }
456
- return codes;
457
- }
458
- var S3_ERROR_CODES = defineErrorCodes({
459
- NOT_FOUND: "Not Found",
460
- UNAUTHORIZED: "Unauthorized",
461
- FORBIDDEN: "Forbidden",
462
- CONFLICT: "Conflict",
463
- INTERNAL_ERROR: "Internal server error",
464
- OBJECT_NOT_FOUND: "Object not found",
465
- FEATURE_DISABLED: "{feature} is disabled",
466
- INVALID_KEY: "Object key is invalid",
467
- UNKNOWN_ROUTE: "Unknown file route",
468
- FILE_TYPE_NOT_ALLOWED: "File type is not allowed",
469
- S3_NETWORK_ERROR: "S3 endpoint unreachable ({code}): check your endpoint URL and network connectivity",
470
- MULTIPART_PART_MISSING: "Uploaded part {partNumber} was not found",
471
- PAYLOAD_TOO_LARGE: "Payload too large",
472
- QUOTA_EXCEEDED: "Storage quota exceeded",
473
- VALIDATION_ERROR: "Validation Error"
474
- });
475
-
476
- // src/error.ts
477
- var APIError = class _APIError extends APIError$1 {
478
- constructor(status = "BAD_REQUEST", body, headers) {
479
- const { cause, ...rest } = body ?? {};
480
- super(
481
- status,
482
- Object.keys(rest).length > 0 ? rest : void 0,
483
- headers
484
- );
485
- this.name = "APIError";
486
- if (cause !== void 0) {
487
- this.cause = cause;
488
- }
489
- }
490
- get code() {
491
- return this.body?.code;
492
- }
493
- get params() {
494
- return this.body?.params;
495
- }
496
- /** Throw a catalog (or custom) `{ code, message }` with an HTTP status. */
497
- static from(status, error) {
498
- return new _APIError(status, {
499
- message: error.message,
500
- code: error.code,
501
- ...error.params !== void 0 ? { params: error.params } : {}
502
- });
503
- }
504
- static fromStatus(status, body) {
505
- return new _APIError(status, body);
506
- }
507
- };
508
- function isAPIError(error) {
509
- return error instanceof APIError$1 || error instanceof APIError || error?.name === "APIError";
510
- }
511
- function isS3ErrorCode(error, code) {
512
- return isAPIError(error) && error.code === code;
513
- }
514
715
 
515
716
  // src/routes.ts
516
717
  var S3_API_BASE_PATH = "/api/s3";
517
718
  function normalizeS3ApiBasePath(basePath) {
518
- return stripTrailingSlashes(basePath);
719
+ const path = stripSurroundingSlashes(basePath.trim());
720
+ return path ? `/${path}` : "";
519
721
  }
520
722
  var S3_API_ROUTES = {
521
723
  upload: "/presign/upload",
522
- uploadConfirm: "/presign/upload/confirm",
724
+ confirm: "/presign/upload/confirm",
523
725
  download: "/presign/download",
524
726
  file: "/file",
525
727
  catalog: "/routes",
526
728
  delete: "/delete",
527
- deleteBatch: "/delete/batch",
729
+ deleteMany: "/delete/batch",
528
730
  multipartInit: "/presign/multipart/init",
529
- multipartPart: "/presign/multipart/part",
731
+ multipartSignPart: "/presign/multipart/part",
732
+ /** `POST`, because the body carries the upload ticket. */
733
+ multipartListParts: "/presign/multipart/parts",
530
734
  multipartComplete: "/presign/multipart/complete",
531
- multipartAbort: "/presign/multipart/abort",
532
- multipartListParts: "/presign/multipart/parts"
735
+ multipartAbort: "/presign/multipart/abort"
533
736
  };
737
+ function readErrorBody(value) {
738
+ if (typeof value !== "object" || value === null) return void 0;
739
+ const { code, message, params } = value;
740
+ if (typeof code !== "string" || typeof message !== "string") return void 0;
741
+ const kept = typeof params === "object" && params !== null && !Array.isArray(params) ? Object.entries(params).filter(
742
+ (entry) => typeof entry[1] === "string" || typeof entry[1] === "number"
743
+ ) : [];
744
+ return kept.length > 0 ? { code, message, params: Object.fromEntries(kept) } : { code, message };
745
+ }
534
746
  async function resolveHeaders(headers) {
535
747
  if (headers == null) return void 0;
536
748
  if (typeof headers === "function") return headers();
537
749
  return headers;
538
750
  }
539
- function fallbackMessage(error) {
540
- if (typeof error.error === "string" && error.error.trim()) {
541
- return error.error;
542
- }
543
- return error.statusText || "Request failed";
544
- }
545
- function apiErrorFromFetch(error) {
546
- const { status } = error;
547
- if (s3FetchErrorSchema.validate(error)) {
548
- const { message, code, params } = error;
549
- return new APIError(status, {
550
- message,
551
- ...code !== void 0 ? { code } : {},
552
- ...params !== void 0 ? { params } : {}
553
- });
554
- }
555
- return new APIError(status, { message: fallbackMessage(error) });
751
+ function apiErrorFromResponse(status, body) {
752
+ const shape = readErrorBody(body);
753
+ if (shape) return APIError.fromShape(shape, status);
754
+ const code = status >= 500 ? "INTERNAL_ERROR" : "UNKNOWN_ERROR";
755
+ return s3Error(code, void 0, { status });
756
+ }
757
+ function isJsonBody(data) {
758
+ if (Array.isArray(data)) return true;
759
+ if (data === null || typeof data !== "object") return false;
760
+ const prototype = Object.getPrototypeOf(data);
761
+ return prototype === Object.prototype || prototype === null;
762
+ }
763
+ function withNetworkErrors(fetchImpl) {
764
+ return async (input, init) => {
765
+ try {
766
+ return await (fetchImpl ?? fetch)(input, init);
767
+ } catch (error) {
768
+ if (init?.signal?.aborted) throw init.signal.reason;
769
+ throw s3Error("NETWORK_ERROR", void 0, { cause: error });
770
+ }
771
+ };
556
772
  }
557
773
  function createS3Fetch(base, options) {
558
774
  return createFetch({
559
775
  baseURL: base,
560
776
  throw: true,
561
- errorSchema: s3FetchErrorSchema,
562
- customFetchImpl: options?.fetch,
777
+ customFetchImpl: withNetworkErrors(options?.fetch),
563
778
  credentials: options?.credentials,
564
779
  onRequest: async (ctx) => {
565
- const extra = await resolveHeaders(options?.headers);
566
- if (!extra) return ctx;
567
- const headers = new Headers(ctx.headers);
568
- for (const [key, value] of new Headers(extra)) {
780
+ const clientHeaders = await resolveHeaders(options?.headers);
781
+ if (!clientHeaders) return ctx;
782
+ const headers = new Headers(clientHeaders);
783
+ for (const [key, value] of ctx.headers) {
569
784
  headers.set(key, value);
570
785
  }
571
786
  return { ...ctx, headers };
572
787
  },
788
+ onSuccess: (ctx) => {
789
+ if (isJsonBody(ctx.data)) return;
790
+ throw s3Error("UNKNOWN_ERROR", void 0, {
791
+ status: ctx.response.status
792
+ });
793
+ },
573
794
  onError: (ctx) => {
574
- throw apiErrorFromFetch(ctx.error);
795
+ throw apiErrorFromResponse(ctx.response.status, ctx.error);
575
796
  }
576
797
  });
577
798
  }
@@ -606,88 +827,106 @@ var RESERVED_CLIENT_KEYS = [
606
827
  ];
607
828
 
608
829
  // src/create-s3-client.ts
609
- function withoutHeaders(value) {
610
- const { headers: _headers, ...rest } = value;
611
- return rest;
830
+ var ABSOLUTE_URL = /^[a-z][a-z\d+.-]*:\/\//i;
831
+ function callOptions(options) {
832
+ return {
833
+ signal: options?.signal,
834
+ headers: options?.headers ? new Headers(options.headers) : void 0
835
+ };
612
836
  }
613
- function createCoreApi($fetch) {
837
+ function resolveProxyUrl(url, base) {
838
+ if (!url.startsWith("/") || url.startsWith("//")) return url;
839
+ if (!ABSOLUTE_URL.test(base)) return url;
840
+ return new URL(url, base).href;
841
+ }
842
+ function createCoreApi($fetch, base) {
614
843
  return {
615
- upload(payload) {
844
+ upload(payload, options) {
616
845
  return $fetch(S3_API_ROUTES.upload, {
617
846
  method: "POST",
618
- body: withoutHeaders(payload)
847
+ body: payload,
848
+ ...callOptions(options)
619
849
  });
620
850
  },
621
- confirm(payload) {
622
- return $fetch(S3_API_ROUTES.uploadConfirm, {
851
+ confirm(payload, options) {
852
+ return $fetch(S3_API_ROUTES.confirm, {
623
853
  method: "POST",
624
- body: withoutHeaders(payload)
854
+ body: payload,
855
+ ...callOptions(options)
625
856
  });
626
857
  },
627
- download(payload) {
628
- const { route, key, fileName, disposition, expiresIn } = withoutHeaders(payload);
629
- return $fetch(S3_API_ROUTES.download, {
630
- method: "GET",
631
- query: {
632
- route,
633
- key,
634
- fileName: fileName ? sanitizeFileName(fileName) : void 0,
635
- disposition,
636
- expiresIn
858
+ async download(payload, options) {
859
+ const { route, key, name, disposition, expiresIn } = payload;
860
+ const response = await $fetch(
861
+ S3_API_ROUTES.download,
862
+ {
863
+ method: "GET",
864
+ query: {
865
+ route,
866
+ key,
867
+ // The same rule as an upload name, so any name downloads.
868
+ name: name ? fitFileName(name) : void 0,
869
+ disposition,
870
+ expiresIn
871
+ },
872
+ ...callOptions(options)
637
873
  }
638
- });
874
+ );
875
+ return { ...response, url: resolveProxyUrl(response.url, base) };
639
876
  },
640
- catalog() {
877
+ catalog(options) {
641
878
  return $fetch(S3_API_ROUTES.catalog, {
642
- method: "GET"
879
+ method: "GET",
880
+ ...callOptions(options)
643
881
  });
644
882
  },
645
- delete(payload) {
646
- const { route, key } = withoutHeaders(payload);
883
+ delete(payload, options) {
884
+ const { route, key } = payload;
647
885
  return $fetch(S3_API_ROUTES.delete, {
648
886
  method: "DELETE",
649
- query: { route, key }
887
+ query: { route, key },
888
+ ...callOptions(options)
650
889
  });
651
890
  },
652
- deleteMany(payload) {
653
- return $fetch(S3_API_ROUTES.deleteBatch, {
891
+ deleteMany(payload, options) {
892
+ return $fetch(S3_API_ROUTES.deleteMany, {
654
893
  method: "POST",
655
- body: withoutHeaders(payload)
894
+ body: payload,
895
+ ...callOptions(options)
656
896
  });
657
897
  },
658
898
  multipart: {
659
- init(payload) {
899
+ init(payload, options) {
660
900
  return $fetch(S3_API_ROUTES.multipartInit, {
661
901
  method: "POST",
662
- body: withoutHeaders(payload)
902
+ body: payload,
903
+ ...callOptions(options)
663
904
  });
664
905
  },
665
- signPart(payload) {
666
- return $fetch(S3_API_ROUTES.multipartPart, {
906
+ signPart(payload, options) {
907
+ return $fetch(S3_API_ROUTES.multipartSignPart, {
667
908
  method: "POST",
668
- body: withoutHeaders(payload)
909
+ body: payload,
910
+ ...callOptions(options)
669
911
  });
670
912
  },
671
- listParts(payload) {
672
- const { route, key, uploadId } = withoutHeaders(payload);
913
+ listParts(payload, options) {
673
914
  return $fetch(
674
915
  S3_API_ROUTES.multipartListParts,
675
- { method: "GET", query: { route, key, uploadId } }
916
+ { method: "POST", body: payload, ...callOptions(options) }
676
917
  );
677
918
  },
678
- complete(payload) {
919
+ complete(payload, options) {
679
920
  return $fetch(
680
921
  S3_API_ROUTES.multipartComplete,
681
- {
682
- method: "POST",
683
- body: withoutHeaders(payload)
684
- }
922
+ { method: "POST", body: payload, ...callOptions(options) }
685
923
  );
686
924
  },
687
- abort(payload) {
925
+ abort(payload, options) {
688
926
  return $fetch(S3_API_ROUTES.multipartAbort, {
689
927
  method: "POST",
690
- body: withoutHeaders(payload)
928
+ body: payload,
929
+ ...callOptions(options)
691
930
  });
692
931
  }
693
932
  }
@@ -695,11 +934,14 @@ function createCoreApi($fetch) {
695
934
  }
696
935
  function createS3Client(options) {
697
936
  const { basePath, baseURL, plugins, ...fetchOptions } = options ?? {};
698
- const base = normalizeS3ApiBasePath(baseURL ?? basePath ?? S3_API_BASE_PATH);
937
+ const base = baseURL !== void 0 ? stripTrailingSlashes(baseURL) : normalizeS3ApiBasePath(basePath ?? S3_API_BASE_PATH);
699
938
  const $fetch = createS3Fetch(base, fetchOptions);
700
- const api = createCoreApi($fetch);
939
+ const api = createCoreApi($fetch, base);
701
940
  const pluginMethods = {};
702
941
  for (const plugin of plugins ?? []) {
942
+ if (!ROUTE_NAME_PATTERN.test(plugin.id)) {
943
+ throw new Error(`Client plugin id "${plugin.id}" is invalid.`);
944
+ }
703
945
  if (RESERVED_CLIENT_KEYS.includes(plugin.id)) {
704
946
  throw new Error(
705
947
  `Client plugin id "${plugin.id}" is reserved on the S3 client.`
@@ -719,6 +961,6 @@ function createS3Client(options) {
719
961
  };
720
962
  }
721
963
 
722
- export { APIError, DELETE_BATCH_MAX_KEYS, RESERVED_CLIENT_KEYS, ROUTE_NAME_PATTERN, S3_API_BASE_PATH, S3_API_ROUTES, S3_DEFAULT_EXPIRES_IN, S3_ERROR_CODES, S3_MAX_EXPIRES_IN, S3_MAX_METADATA_ENTRIES, S3_MAX_OBJECT_KEY_LENGTH, S3_MAX_PART_NUMBER, S3_MAX_POST_OBJECT_BYTES, buildContentDisposition, buildObjectKey, buildPublicObjectUrl, confirmBodySchema, createS3Client, createS3Fetch, defineClientPlugin, defineErrorCodes, deleteBatchBodySchema, deleteQuerySchema, downloadDispositionSchema, downloadModeSchema, downloadQuerySchema, fileNameFromKey, fileQuerySchema, formatFileSize, isAPIError, isS3ErrorCode, matchesFileTypes, matchesMagicBytes, metadataSchema, multipartAbortBodySchema, multipartCompleteBodySchema, multipartCompletedPartSchema, multipartInitBodySchema, multipartListPartsQuerySchema, multipartSignPartBodySchema, normalizeObjectKey, normalizeS3ApiBasePath, objectKeySchema, optionalChecksumSchema, optionalTrimmedString, parseFileName, partNumberSchema, pluginPath, resolveInlineDisposition, resolveStoredFileName, routeCatalogEntrySchema, routeCatalogResponseSchema, routeNameSchema, s3ErrorParamsSchema, s3FetchErrorSchema, s3ObjectAclSchema, sanitizeFileName, sha256Base64, sha256ChecksumSchema, sha256File, sniffContentType, trimmedString, truncateFileName, uploadBodySchema, validateFile };
964
+ export { APIError, DEFAULT_INLINE_TYPES, DELETE_MANY_MAX_KEYS, RESERVED_CLIENT_KEYS, ROUTE_NAME_PATTERN, S3_API_BASE_PATH, S3_API_ROUTES, S3_DEFAULT_EXPIRES_IN, S3_DEFAULT_PART_SIZE, S3_ERROR_CODES, S3_MAX_EXPIRES_IN, S3_MAX_FILE_FIELD_BYTES, S3_MAX_METADATA_ENTRIES, S3_MAX_OBJECT_KEY_BYTES, S3_MAX_OBJECT_SIZE, S3_MAX_PART_NUMBER, S3_MAX_PART_SIZE, S3_MAX_POST_OBJECT_BYTES, S3_MIN_PART_SIZE, SNIFF_BYTE_LENGTH, UPLOAD_TICKET_MAX_LENGTH, base64UrlDecode, base64UrlEncode, buildContentDisposition, buildObjectKey, buildPublicObjectUrl, createS3Client, createS3Fetch, defineClientPlugin, defineErrorCodes, describeFileType, effectiveContentType, fileNameFromKey, fitFileName, formatErrorMessage, isAPIError, isS3ErrorCode, isSniffableType, matchesFileTypes, matchesMagicBytes, normalizeObjectKey, normalizeS3ApiBasePath, objectKeyByteLength, parseFileName, pluginPath, resolveInlineDisposition, resolveStoredFileName, s3Error, sha256Base64, sha256Blob, sniffContentType, validateFile };
723
965
  //# sourceMappingURL=index.js.map
724
966
  //# sourceMappingURL=index.js.map