@nextlyhq/storage-s3 0.0.2-alpha.7 → 0.0.2-alpha.70

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.
package/dist/index.mjs CHANGED
@@ -1,470 +1,1356 @@
1
- import { S3Client, DeleteObjectCommand, DeleteObjectsCommand, HeadObjectCommand, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
2
- import { Upload } from '@aws-sdk/lib-storage';
3
- import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
4
-
1
+ import { DeleteObjectCommand, DeleteObjectsCommand, GetObjectCommand, HeadObjectCommand, ListObjectsV2Command, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
2
+ import { Upload } from "@aws-sdk/lib-storage";
3
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
4
+ // ../nextly/dist/nextly-error-D21_8kpX.mjs
5
+ function isDbError(err) {
6
+ if (!err || typeof err !== "object") return false;
7
+ const obj = err;
8
+ return obj.name === "DbError" && typeof obj.kind === "string";
9
+ }
10
+ /**
11
+ * The driver's own code for an error, wherever that driver puts it.
12
+ *
13
+ * Exported so callers that must distinguish one failure from another classify
14
+ * by the SAME extraction this module's mapping uses. A second reader would go
15
+ * looking in a different set of properties and disagree on exactly the drivers
16
+ * whose codes are hardest to find.
17
+ */
18
+ /**
19
+ * Whether an error is a duplicate-key rejection.
20
+ *
21
+ * Exposed because a plugin inserting into a table with a unique index has to
22
+ * tell "this row already exists" from "the database is broken", and the two
23
+ * arrive as the same thrown object. Derived from the existing SQLSTATE
24
+ * classification rather than by matching driver messages: those differ per
25
+ * driver and per version, and a plugin re-deriving it would be a second
26
+ * implementation of a question this module already answers.
27
+ */
28
+ /**
29
+ * Whether a driver code says the database was busy: the adapters' own code
30
+ * for a request that waited out `pool.connectionTimeoutMs`, the same on
31
+ * every dialect, or SQLITE_BUSY and its extended codes, another process
32
+ * holding the SQLite file past `busyTimeout`. Neither depends on the dialect,
33
+ * which is what lets {@link isDatabaseBusy} answer without one.
34
+ */
35
+ function isBusyCode(code) {
36
+ if (code === void 0) return false;
37
+ return code === "NEXTLY_POOL_WAIT_TIMEOUT" || code.toUpperCase().startsWith("SQLITE_BUSY");
38
+ }
39
+ /**
40
+ * Whether an error is the database being busy, however it arrives: a DbError
41
+ * of kind "busy", or the raw error an adapter or driver threw.
42
+ *
43
+ * For the boundaries that answer a request with whatever its work threw.
44
+ * `withDbErrors` converts only DbErrors, so a raw driver error reaches them
45
+ * unconverted, and without this it would read as an internal fault rather
46
+ * than a request worth retrying.
47
+ */
48
+ function isDatabaseBusy(error) {
49
+ if (isDbError(error)) return error.kind === "busy";
50
+ return isBusyCode(safeCode(error));
51
+ }
52
+ function safeCode(error) {
53
+ if (!error || typeof error !== "object") return void 0;
54
+ const e = error;
55
+ let c = e.code ?? e.sqlState ?? e.state ?? e.errno ?? void 0;
56
+ if (!c && typeof e.originalError?.code === "string") c = e.originalError.code;
57
+ if (!c && typeof e.cause?.code === "string") c = e.cause.code;
58
+ if (!c && typeof e.severity === "string" && typeof e.code === "string") c = e.code;
59
+ if (typeof c === "number") return String(c);
60
+ if (typeof c === "string" && c.length > 0) return c;
61
+ }
62
+ /**
63
+ * Canonical NextlyError codes and their HTTP status mappings.
64
+ *
65
+ * Plugin codes outside this enum must always pass an explicit `statusCode`
66
+ * to the NextlyError constructor (no enum lookup happens for unknown codes).
67
+ */
68
+ const NEXTLY_ERROR_STATUS = {
69
+ VALIDATION_ERROR: 400,
70
+ INVALID_INPUT: 400,
71
+ AUTH_REQUIRED: 401,
72
+ AUTH_INVALID_CREDENTIALS: 401,
73
+ TOKEN_EXPIRED: 401,
74
+ FORBIDDEN: 403,
75
+ EMAIL_NOT_VERIFIED: 403,
76
+ BUILDER_DISABLED: 403,
77
+ CSRF_FAILED: 403,
78
+ SETUP_TOKEN_REQUIRED: 403,
79
+ API_KEY_ROLE_ABOVE_CREATOR: 403,
80
+ NOT_FOUND: 404,
81
+ METHOD_NOT_ALLOWED: 405,
82
+ CONFLICT: 409,
83
+ DUPLICATE: 409,
84
+ RATE_LIMITED: 429,
85
+ PAYLOAD_TOO_LARGE: 413,
86
+ UNSUPPORTED_MEDIA_TYPE: 415,
87
+ BUSINESS_RULE_VIOLATION: 422,
88
+ INTERNAL_ERROR: 500,
89
+ DATABASE_ERROR: 500,
90
+ DATABASE_BUSY: 503,
91
+ EXTERNAL_SERVICE_ERROR: 502,
92
+ SERVICE_UNAVAILABLE: 503,
93
+ EXTERNAL_URL_BLOCKED: 400,
94
+ EXTERNAL_REQUEST_FAILED: 502,
95
+ FILENAME_INVALID: 400,
96
+ EXTENSION_BLOCKED: 400,
97
+ MIME_BLOCKED: 415,
98
+ MIME_NOT_ALLOWED: 415,
99
+ SIZE_EXCEEDED: 413,
100
+ STORAGE_READ_TOO_LARGE: 413,
101
+ STORAGE_READ_TIMEOUT: 504,
102
+ STORAGE_READ_UNREACHABLE: 502,
103
+ MAGIC_BYTE_MISMATCH: 400,
104
+ SVG_SANITIZATION_FAILED: 400,
105
+ UNSUPPORTED_FOR_BACKEND: 415,
106
+ NEXTLY_LEGACY_BOOKKEEPING_DETECTED: 409,
107
+ NEXTLY_UPGRADE_TABLE_NAME_COLLISION: 409,
108
+ NEXTLY_UPGRADE_IN_PROGRESS: 409,
109
+ NEXTLY_MIGRATE_LOCK_BUSY: 409,
110
+ NEXTLY_BASELINE_LOCK_NOT_HELD: 409,
111
+ NEXTLY_RESOLVE_LOCK_NOT_HELD: 409,
112
+ NEXTLY_BOOT_MIGRATIONS_NOT_RUN: 503,
113
+ NEXTLY_BOOT_MIGRATIONS_PENDING: 503,
114
+ NEXTLY_CORE_DESTRUCTIVE_REFUSED: 409,
115
+ NEXTLY_MIGRATION_DRIFT: 409,
116
+ NEXTLY_MIGRATION_APPLY_FAILED: 500,
117
+ NEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION: 409,
118
+ NEXTLY_MIGRATION_PARTIALLY_APPLIED: 500,
119
+ NEXTLY_MIGRATION_CONCURRENT_RUN: 409,
120
+ NEXTLY_MIGRATION_FILE_MISSING: 404,
121
+ NEXTLY_MIGRATION_SNAPSHOT_MISSING: 404,
122
+ NEXTLY_MIGRATION_RESOLVE_DRIFT: 409,
123
+ NEXTLY_MIGRATION_RESOLVE_PRECONDITION: 409,
124
+ NEXTLY_UI_SCHEMA_INVALID: 400,
125
+ NEXTLY_SCHEMA_SLUG_COLLISION: 409,
126
+ NEXTLY_SCHEMA_RELATION_TARGET_MISSING: 400,
127
+ NEXTLY_SCHEMA_RELATION_UNRESOLVED: 400,
128
+ NEXTLY_SCHEMA_EXTEND_TARGET_UNKNOWN: 400,
129
+ NEXTLY_SCHEMA_EXTEND_FIELD_DUPLICATE: 409,
130
+ NEXTLY_SCHEMA_CROSS_PLUGIN_RELATION: 409,
131
+ NEXTLY_SCHEMA_RENAME_UNKNOWN_TARGET: 400,
132
+ NEXTLY_PLUGIN_CLIENT_CONFIG_INVALID: 500,
133
+ NEXTLY_PLUGIN_ADMIN_WIDGET_INVALID: 500,
134
+ NEXTLY_ADMIN_COMPONENT_MAP_STALE: 500,
135
+ NEXTLY_PLUGIN_DOCUMENT_VIEW_INVALID: 500,
136
+ PLUGIN_RESOLUTION_ERROR: 500,
137
+ PLUGIN_DEPENDENCY_NOT_INSTALLED: 409,
138
+ PLUGIN_HAS_DEPENDENTS: 409,
139
+ PLUGIN_UNINSTALL_IRREVERSIBLE: 409,
140
+ PLUGIN_UNINSTALL_UNCONFIRMED: 409,
141
+ PLUGIN_SCHEMA_BEHIND: 409,
142
+ PLUGIN_SCHEMA_UNINSTALLED: 409,
143
+ PLUGIN_NOT_INSTALLED: 409,
144
+ PLUGIN_DISABLED: 409,
145
+ PLUGIN_UNINSTALL_UNFINISHED: 409,
146
+ PLUGIN_SCHEMA_VERSION_NOT_ADVANCED: 409,
147
+ PLUGIN_MIGRATION_DROPS_CREATED_SCHEMA: 409,
148
+ PLUGIN_MIGRATION_ADDS_UNFILLABLE_COLUMN: 409,
149
+ PLUGIN_MIGRATION_SQL_MISSING: 409,
150
+ PLUGIN_MIGRATIONS_UNAVAILABLE: 409,
151
+ DROP_OF_FOREIGN_TABLE: 409,
152
+ MIGRATION_CHECKSUM_MISMATCH: 409,
153
+ PLUGIN_MIGRATIONS_OUT_OF_ORDER: 409,
154
+ PLUGIN_MIGRATION_HISTORY_CHANGED: 409,
155
+ NEXTLY_ROUTE_COLLISION: 409,
156
+ NEXTLY_ROUTE_INVALID_PATH: 400,
157
+ NEXTLY_ROUTE_UNREACHABLE_ROOT: 400,
158
+ NEXTLY_ROUTE_INVALID_MOUNT: 400,
159
+ NEXTLY_EMAIL_TRANSPORT_UNAVAILABLE: 503,
160
+ NEXTLY_CONFIG_TOOLING_UNAVAILABLE: 503,
161
+ NEXTLY_POSTGRES_SCHEMA_MISMATCH: 500,
162
+ NEXTLY_POSTGRES_SCHEMA_UNSUPPORTED: 500
163
+ };
164
+ ({ ...Object.fromEntries([
165
+ "VALIDATION_ERROR",
166
+ "AUTH_REQUIRED",
167
+ "FORBIDDEN",
168
+ "NOT_FOUND",
169
+ "CONFLICT",
170
+ "PAYLOAD_TOO_LARGE",
171
+ "UNSUPPORTED_MEDIA_TYPE",
172
+ "RATE_LIMITED",
173
+ "EXTERNAL_SERVICE_ERROR",
174
+ "SERVICE_UNAVAILABLE"
175
+ ].map((code) => [NEXTLY_ERROR_STATUS[code], code])) });
176
+ /**
177
+ * The sentence a caller reads for a code, when the failure supplied none.
178
+ *
179
+ * Kept beside the status table because they answer the same question together:
180
+ * a code-less envelope's own `message` is NOT usable here. Those envelopes come
181
+ * from legacy converters that store a raw exception's text, so promoting it
182
+ * would put driver output, table names and internal paths on the wire -- the
183
+ * disclosure the public error shape exists to prevent (spec 13.8).
184
+ *
185
+ * Every entry is generic by design. The specific detail stays in `logContext`
186
+ * for the operator, against the same request id.
187
+ */
188
+ const GENERIC_PUBLIC_MESSAGE = {
189
+ VALIDATION_ERROR: "Validation failed.",
190
+ INVALID_INPUT: "The request could not be processed.",
191
+ AUTH_REQUIRED: "Authentication required.",
192
+ FORBIDDEN: "You don't have permission to perform this action.",
193
+ NOT_FOUND: "Not found.",
194
+ METHOD_NOT_ALLOWED: "That method is not allowed on this address.",
195
+ CONFLICT: "The resource has changed since you last loaded it. Please refresh and try again.",
196
+ DUPLICATE: "Resource already exists.",
197
+ PAYLOAD_TOO_LARGE: "The request is too large.",
198
+ UNSUPPORTED_MEDIA_TYPE: "That file type is not supported.",
199
+ RATE_LIMITED: "Too many requests. Please try again later.",
200
+ EXTERNAL_SERVICE_ERROR: "An upstream service failed.",
201
+ SERVICE_UNAVAILABLE: "The service is temporarily unavailable.",
202
+ DATABASE_BUSY: "The database is busy. Please try again shortly.",
203
+ INTERNAL_ERROR: "An unexpected error occurred."
204
+ };
205
+ /** The generic sentence for a code; the internal one for anything unlisted. */
206
+ function genericPublicMessage(code) {
207
+ return GENERIC_PUBLIC_MESSAGE[code] ?? GENERIC_PUBLIC_MESSAGE.INTERNAL_ERROR;
208
+ }
209
+ /**
210
+ * Default mapping from DbErrorKind to NextlyError contract. Used by
211
+ * `NextlyError.fromDatabaseError`. Public messages are intentionally generic
212
+ * per spec §13.8 — no DB driver text, no constraint names, no field hints.
213
+ *
214
+ * `satisfies Record<DbErrorKind, ...>` makes the mapping exhaustive at
215
+ * compile time: adding a new DbErrorKind without updating this table is a
216
+ * type error.
217
+ */
218
+ const DB_ERROR_MAPPING = {
219
+ "unique-violation": {
220
+ code: "DUPLICATE",
221
+ statusCode: 409,
222
+ publicMessage: "Resource already exists."
223
+ },
224
+ "fk-violation": {
225
+ code: "VALIDATION_ERROR",
226
+ statusCode: 400,
227
+ publicMessage: "Referenced record does not exist."
228
+ },
229
+ "not-null-violation": {
230
+ code: "VALIDATION_ERROR",
231
+ statusCode: 400,
232
+ publicMessage: "A required field is missing."
233
+ },
234
+ constraint: {
235
+ code: "VALIDATION_ERROR",
236
+ statusCode: 400,
237
+ publicMessage: "The provided data violates a constraint."
238
+ },
239
+ deadlock: {
240
+ code: "CONFLICT",
241
+ statusCode: 409,
242
+ publicMessage: "The operation could not be completed. Please retry."
243
+ },
244
+ "serialization-failure": {
245
+ code: "CONFLICT",
246
+ statusCode: 409,
247
+ publicMessage: "The operation could not be completed. Please retry."
248
+ },
249
+ busy: {
250
+ code: "DATABASE_BUSY",
251
+ statusCode: NEXTLY_ERROR_STATUS.DATABASE_BUSY,
252
+ publicMessage: genericPublicMessage("DATABASE_BUSY"),
253
+ publicData: { retryAfterSeconds: 5 }
254
+ },
255
+ timeout: {
256
+ code: "DATABASE_ERROR",
257
+ statusCode: 500,
258
+ publicMessage: "The operation timed out. Please try again."
259
+ },
260
+ "connection-lost": {
261
+ code: "DATABASE_ERROR",
262
+ statusCode: 500,
263
+ publicMessage: "A temporary database error occurred. Please try again."
264
+ },
265
+ syntax: {
266
+ code: "INTERNAL_ERROR",
267
+ statusCode: 500,
268
+ publicMessage: "An unexpected error occurred."
269
+ },
270
+ internal: {
271
+ code: "INTERNAL_ERROR",
272
+ statusCode: 500,
273
+ publicMessage: "An unexpected error occurred."
274
+ }
275
+ };
276
+ const NEXTLY_ERROR_BRAND = Symbol.for("nextly/NextlyError");
277
+ function hasBrand(value) {
278
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
279
+ return value[NEXTLY_ERROR_BRAND] === true;
280
+ }
281
+ /**
282
+ * Unified error class for Nextly. Used at every throw site across services,
283
+ * direct API, auth, and plugins. Carries two distinct payloads:
284
+ *
285
+ * - Public (`code`, `publicMessage`, `publicData`, `statusCode`, `messageKey`)
286
+ * sent in HTTP responses and Server Action results.
287
+ * - Log (`logMessage`, `logContext`, `cause`, stack trace)
288
+ * written to the server logger; never serialised to the wire.
289
+ *
290
+ * Use the static factories (notFound, forbidden, validation, ...) for the
291
+ * common cases. Use the free-form constructor for plugin codes or one-off
292
+ * shapes.
293
+ */
294
+ var NextlyError = class NextlyError extends Error {
295
+ code;
296
+ statusCode;
297
+ publicMessage;
298
+ publicData;
299
+ messageKey;
300
+ logMessage;
301
+ logContext;
302
+ cause;
303
+ timestamp;
304
+ constructor(opts) {
305
+ super(opts.publicMessage);
306
+ this.name = "NextlyError";
307
+ this.code = opts.code;
308
+ this.publicMessage = opts.publicMessage;
309
+ this.publicData = opts.publicData;
310
+ this.messageKey = opts.messageKey;
311
+ this.logMessage = opts.logMessage;
312
+ this.logContext = opts.logContext;
313
+ this.cause = opts.cause;
314
+ this.timestamp = /* @__PURE__ */ new Date();
315
+ this.statusCode = NextlyError.resolveStatusCode(opts);
316
+ Error.captureStackTrace?.(this, NextlyError);
317
+ }
318
+ static {
319
+ NextlyError.prototype[NEXTLY_ERROR_BRAND] = true;
320
+ }
321
+ static resolveStatusCode(opts) {
322
+ if (typeof opts.statusCode === "number") return opts.statusCode;
323
+ if (opts.code in NEXTLY_ERROR_STATUS) return NEXTLY_ERROR_STATUS[opts.code];
324
+ return 500;
325
+ }
326
+ /** HTTP-safe JSON. Strips logMessage / logContext / cause / stack. */
327
+ toResponseJSON(requestId) {
328
+ const json = {
329
+ code: String(this.code),
330
+ message: this.publicMessage,
331
+ requestId
332
+ };
333
+ if (this.messageKey) json.messageKey = this.messageKey;
334
+ if (this.publicData !== void 0) json.data = this.publicData;
335
+ return json;
336
+ }
337
+ /** Operator-facing JSON for log lines. Includes everything. */
338
+ toLogJSON(requestId) {
339
+ return {
340
+ code: this.code,
341
+ statusCode: this.statusCode,
342
+ publicMessage: this.publicMessage,
343
+ messageKey: this.messageKey,
344
+ logMessage: this.logMessage,
345
+ logContext: this.logContext,
346
+ cause: this.cause ? {
347
+ name: this.cause.name,
348
+ message: this.cause.message,
349
+ stack: this.cause.stack
350
+ } : void 0,
351
+ timestamp: this.timestamp.toISOString(),
352
+ requestId
353
+ };
354
+ }
355
+ static invalidCredentials(opts) {
356
+ return new NextlyError({
357
+ code: "AUTH_INVALID_CREDENTIALS",
358
+ publicMessage: "Invalid email or password.",
359
+ logMessage: "Login failed",
360
+ logContext: opts?.logContext
361
+ });
362
+ }
363
+ /**
364
+ * The password was correct and the address is unverified. Thrown only once
365
+ * the password is proven, so only someone who holds it learns the address
366
+ * is unverified; every other refusal stays
367
+ * {@link NextlyError.invalidCredentials}.
368
+ */
369
+ static emailNotVerified(opts) {
370
+ return new NextlyError({
371
+ code: "EMAIL_NOT_VERIFIED",
372
+ publicMessage: "Verify your email address to sign in. Check your inbox for the link.",
373
+ logMessage: "Login refused: email not verified",
374
+ logContext: opts?.logContext
375
+ });
376
+ }
377
+ static authRequired(opts) {
378
+ return new NextlyError({
379
+ code: "AUTH_REQUIRED",
380
+ publicMessage: "Authentication required.",
381
+ logContext: opts?.logContext
382
+ });
383
+ }
384
+ /**
385
+ * Distinct from `authRequired`: the caller was authenticated but the
386
+ * session token expired. Clients key on the TOKEN_EXPIRED *code* to
387
+ * silently refresh and retry rather than redirecting to login; the public
388
+ * message stays the generic spec §13.6 string ("Authentication required.")
389
+ * so the wire never reveals the session state — same as `authRequired`.
390
+ */
391
+ static tokenExpired(opts) {
392
+ return new NextlyError({
393
+ code: "TOKEN_EXPIRED",
394
+ publicMessage: "Authentication required.",
395
+ logContext: opts?.logContext
396
+ });
397
+ }
398
+ static notFound(opts) {
399
+ return new NextlyError({
400
+ code: "NOT_FOUND",
401
+ publicMessage: opts?.message ?? "Not found.",
402
+ cause: opts?.cause,
403
+ logContext: opts?.logContext
404
+ });
405
+ }
406
+ static forbidden(opts) {
407
+ return new NextlyError({
408
+ code: "FORBIDDEN",
409
+ publicMessage: "You don't have permission to perform this action.",
410
+ cause: opts?.cause,
411
+ logContext: opts?.logContext
412
+ });
413
+ }
414
+ /**
415
+ * A collection, Single or component defined in code, which is changed by
416
+ * changing its code and not from here. Forbidden, and the message says so:
417
+ * it is a fact about the thing, not about the caller's permissions, so it
418
+ * names no permission and no policy. The lock's detail goes to the log
419
+ * through `logContext`.
420
+ */
421
+ static definedInCode(opts) {
422
+ return new NextlyError({
423
+ code: "FORBIDDEN",
424
+ publicMessage: `This ${opts.thing} is defined in code, so it can't be ${opts.change === "change" ? "changed" : "deleted"} here.`,
425
+ logContext: opts.logContext
426
+ });
427
+ }
428
+ /**
429
+ * An autosave where the collection or Single does not autosave: its owner
430
+ * switched autosave off, or it keeps no drafts to autosave into. Forbidden,
431
+ * and the message says so, since it is a setting and not a permission.
432
+ */
433
+ static autosaveOff(opts) {
434
+ return new NextlyError({
435
+ code: "FORBIDDEN",
436
+ publicMessage: `Autosave is turned off for this ${opts.scopeKind === "single" ? "Single" : "collection"}.`,
437
+ logContext: opts.logContext
438
+ });
439
+ }
440
+ /**
441
+ * An API key refused because its role allows more than the person creating
442
+ * it may do. The sentence is FORBIDDEN's and names no permission; which one
443
+ * exceeded goes to the log through `logContext`. The code is its own, so a
444
+ * client can tell "choose a smaller role" from plain FORBIDDEN.
445
+ */
446
+ static apiKeyRoleAboveCreator(opts) {
447
+ return new NextlyError({
448
+ code: "API_KEY_ROLE_ABOVE_CREATOR",
449
+ publicMessage: genericPublicMessage("FORBIDDEN"),
450
+ logContext: opts?.logContext
451
+ });
452
+ }
453
+ /**
454
+ * A cookie-authenticated write refused because its origin or CSRF token did
455
+ * not check out. The public message names no detail of which check failed;
456
+ * that goes to the log through `logMessage`.
457
+ */
458
+ static csrfFailed(opts) {
459
+ return new NextlyError({
460
+ code: "CSRF_FAILED",
461
+ publicMessage: "This request could not be verified. Reload the page and try again.",
462
+ logMessage: opts?.logMessage,
463
+ logContext: opts?.logContext
464
+ });
465
+ }
466
+ /**
467
+ * A call the caller got wrong, where naming the mistake IS the value of the
468
+ * error.
469
+ *
470
+ * The only factory that takes its public message from the caller. The
471
+ * generic messages elsewhere exist so an HTTP response cannot leak internal
472
+ * detail; this one is for arguments and configuration a developer controls
473
+ * and must be told about — a missing option, an unusable combination — where
474
+ * `internal()` would reduce the one useful sentence to "An unexpected error
475
+ * occurred." Do not pass user-supplied data through it.
476
+ */
477
+ static invalidInput(opts) {
478
+ return new NextlyError({
479
+ code: "INVALID_INPUT",
480
+ publicMessage: opts.message,
481
+ logContext: opts.logContext
482
+ });
483
+ }
484
+ static validation(opts) {
485
+ return new NextlyError({
486
+ code: "VALIDATION_ERROR",
487
+ publicMessage: "Validation failed.",
488
+ publicData: { errors: opts.errors },
489
+ cause: opts.cause,
490
+ logContext: opts.logContext
491
+ });
492
+ }
493
+ static conflict(opts) {
494
+ return new NextlyError({
495
+ code: "CONFLICT",
496
+ publicMessage: opts?.message ?? "The resource has changed since you last loaded it. Please refresh and try again.",
497
+ publicData: opts?.data,
498
+ cause: opts?.cause,
499
+ logContext: {
500
+ reason: opts?.reason,
501
+ ...opts?.logContext
502
+ }
503
+ });
504
+ }
505
+ static duplicate(opts) {
506
+ return new NextlyError({
507
+ code: "DUPLICATE",
508
+ publicMessage: "Resource already exists.",
509
+ logContext: opts?.logContext
510
+ });
511
+ }
512
+ static rateLimited(opts) {
513
+ return new NextlyError({
514
+ code: "RATE_LIMITED",
515
+ publicMessage: "Too many requests. Please try again later.",
516
+ publicData: opts?.retryAfterSeconds !== void 0 ? { retryAfterSeconds: opts.retryAfterSeconds } : void 0,
517
+ logContext: opts?.logContext
518
+ });
519
+ }
520
+ /**
521
+ * A request that waited `pool.connectionTimeoutMs` for a database
522
+ * connection and was given none. The statement or transaction that waited
523
+ * never ran; work committed before it stays committed. The same error
524
+ * `fromDatabaseError` gives a busy DbError, from the same table row.
525
+ */
526
+ static databaseBusy(opts) {
527
+ const busy = DB_ERROR_MAPPING.busy;
528
+ return new NextlyError({
529
+ code: busy.code,
530
+ statusCode: busy.statusCode,
531
+ publicMessage: busy.publicMessage,
532
+ publicData: busy.publicData,
533
+ cause: opts?.cause,
534
+ logContext: opts?.logContext
535
+ });
536
+ }
537
+ /**
538
+ * What a request boundary answers with for a thrown value that is not a
539
+ * NextlyError: "database busy" when the request waited out its bound for a
540
+ * connection, which is retryable and no fault of the server's code, and an
541
+ * internal error for anything else.
542
+ *
543
+ * The busy case has to be read here because it usually arrives raw:
544
+ * `withDbErrors` converts only DbErrors, so a driver's error passes through
545
+ * services unconverted to the boundary that answers the request.
546
+ */
547
+ static fromUnexpected(error) {
548
+ return NextlyError.busyOr(error, () => NextlyError.internal({ cause: error instanceof Error ? error : void 0 }));
549
+ }
550
+ /**
551
+ * "Database busy" when `error` is a request that waited out its bound for
552
+ * a connection, and `otherwise()` for anything else.
553
+ *
554
+ * For a boundary that answers an unexpected failure with an error of its
555
+ * own choosing rather than an internal one (a 503 for a flow that must not
556
+ * answer on incomplete data), so that a busy database still answers there
557
+ * as it does everywhere else. `fromUnexpected` is this rule with the
558
+ * internal error as its fallback.
559
+ */
560
+ static busyOr(error, otherwise) {
561
+ if (!isDatabaseBusy(error)) return otherwise();
562
+ return NextlyError.databaseBusy({ cause: error instanceof Error ? error : void 0 });
563
+ }
564
+ static internal(opts) {
565
+ return new NextlyError({
566
+ code: "INTERNAL_ERROR",
567
+ publicMessage: "An unexpected error occurred.",
568
+ cause: opts?.cause,
569
+ logContext: opts?.logContext
570
+ });
571
+ }
572
+ static serviceUnavailable(opts) {
573
+ return new NextlyError({
574
+ code: "SERVICE_UNAVAILABLE",
575
+ publicMessage: opts?.publicMessage ?? "Service unavailable. Please try again later.",
576
+ logMessage: opts?.logMessage,
577
+ cause: opts?.cause,
578
+ logContext: opts?.logContext
579
+ });
580
+ }
581
+ /**
582
+ * Convert a DbError (or arbitrary unknown thrown by the DB layer) to a
583
+ * NextlyError with a generic public message and rich logContext. Used by
584
+ * `withDbErrors` for auto-conversion (Pattern A) and by services that
585
+ * catch DB errors at boundaries (Pattern B). Spec §8.2 mapping table.
586
+ *
587
+ * Never leaks DB driver text, constraint names, or table names into
588
+ * `publicMessage`. All DB context goes into `logContext`. The original
589
+ * DbError is preserved as `cause`.
590
+ */
591
+ static fromDatabaseError(error) {
592
+ if (isDbError(error)) {
593
+ const mapping = DB_ERROR_MAPPING[error.kind];
594
+ const logContext = {
595
+ dbKind: error.kind,
596
+ dialect: error.dialect
597
+ };
598
+ if (error.code !== void 0) logContext.dbCode = error.code;
599
+ if (error.meta !== void 0) logContext.meta = error.meta;
600
+ return new NextlyError({
601
+ code: mapping.code,
602
+ statusCode: mapping.statusCode,
603
+ publicMessage: mapping.publicMessage,
604
+ publicData: "publicData" in mapping ? mapping.publicData : void 0,
605
+ logMessage: "Database error",
606
+ logContext,
607
+ cause: error
608
+ });
609
+ }
610
+ return new NextlyError({
611
+ code: "INTERNAL_ERROR",
612
+ statusCode: 500,
613
+ publicMessage: "An unexpected error occurred.",
614
+ logMessage: "Non-DbError passed to fromDatabaseError",
615
+ cause: error instanceof Error ? error : void 0,
616
+ logContext: error instanceof Error ? void 0 : { value: String(error) }
617
+ });
618
+ }
619
+ static is(err) {
620
+ return hasBrand(err);
621
+ }
622
+ static isCode(err, code) {
623
+ return hasBrand(err) && err.code === code;
624
+ }
625
+ static isNotFound(err) {
626
+ return NextlyError.isCode(err, "NOT_FOUND");
627
+ }
628
+ static isValidation(err) {
629
+ return NextlyError.isCode(err, "VALIDATION_ERROR");
630
+ }
631
+ static isAuthRequired(err) {
632
+ return NextlyError.isCode(err, "AUTH_REQUIRED");
633
+ }
634
+ static isForbidden(err) {
635
+ return NextlyError.isCode(err, "FORBIDDEN");
636
+ }
637
+ static isConflict(err) {
638
+ return NextlyError.isCode(err, "CONFLICT");
639
+ }
640
+ static isRateLimited(err) {
641
+ return NextlyError.isCode(err, "RATE_LIMITED");
642
+ }
643
+ };
644
+ // ../nextly/dist/validate-external-url-uHUKFZGh.mjs
645
+ /** Default response body cap: reject anything larger before buffering it all. */
646
+ /**
647
+ * How many bytes a bounded external read may buffer, absent a caller's own cap.
648
+ *
649
+ * Exported for the same reason as the deadline below: an adapter that never
650
+ * touches `safeFetch` still owes callers this default, and restating the number
651
+ * gives the tree two that drift.
652
+ */
653
+ const DEFAULT_MAX_RESPONSE_BYTES = 10485760;
654
+ /** Default overall deadline covering DNS + connect + TLS + response. */
655
+ /**
656
+ * How long a bounded external read may take, absent a caller's own limit.
657
+ *
658
+ * Exported so a caller that must begin the clock EARLIER — a storage adapter
659
+ * bounding a metadata lookup as well as the fetch that follows — uses this
660
+ * number rather than restating it. Two spellings of one default agree today and
661
+ * drift the first time either is tuned.
662
+ */
663
+ const DEFAULT_TIMEOUT_MS = 3e4;
664
+ // ../nextly/dist/storage/read-errors.mjs
665
+ /**
666
+ * The one way the storage layer says a read exceeded the caller's cap.
667
+ *
668
+ * `StorageReadOptions.maxBytes` is part of the adapter contract, so what happens
669
+ * when it is exceeded belongs to the contract too. Without this each backend
670
+ * refuses in its own vocabulary — the URL-addressed ones through a fetch error
671
+ * carrying a `reason`, S3 through whatever its own code threw — and a caller
672
+ * wanting to tell "too large" from "could not read" has to know which adapter it
673
+ * is talking to. That is the thing an adapter contract exists to stop.
674
+ *
675
+ * Distinct from a generic internal failure because callers ACT on the
676
+ * difference. The email attachment path answers an over-cap read with
677
+ * `ATTACHMENT_SIZE_EXCEEDED`, which tells an author to attach something smaller;
678
+ * a storage failure tells them nothing they can act on. Collapsing the two turns
679
+ * a fixable refusal into an opaque error, which is the same conflation this
680
+ * contract already draws between a missing key and an unreachable store.
681
+ *
682
+ * @module storage/read-errors
683
+ */
684
+ /**
685
+ * A read refused because the object is larger than the caller allowed.
686
+ *
687
+ * Carries the numbers rather than only a message, so a caller can say what the
688
+ * limit was without parsing prose — and so the message itself stays free of the
689
+ * key, which should not travel to whoever asked for the file.
690
+ */
691
+ var StorageReadTooLargeError = class extends NextlyError {
692
+ path;
693
+ maxBytes;
694
+ size;
695
+ constructor(path, maxBytes, size) {
696
+ super({
697
+ code: "STORAGE_READ_TOO_LARGE",
698
+ publicMessage: "The stored file is larger than the limit for this read.",
699
+ logContext: {
700
+ path,
701
+ maxBytes,
702
+ ...size === void 0 ? {} : { size }
703
+ }
704
+ });
705
+ this.path = path;
706
+ this.maxBytes = maxBytes;
707
+ this.size = size;
708
+ }
709
+ };
710
+ // ../nextly/dist/storage/fetch-stored-bytes.mjs
711
+ /** The deadline a stored read runs under when the caller names none. */
712
+ const DEFAULT_READ_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
713
+ /** The byte cap a stored read runs under when the caller names none. */
714
+ const DEFAULT_READ_MAX_BYTES = DEFAULT_MAX_RESPONSE_BYTES;
715
+ /**
716
+ * The bounds a read actually runs under, defaults filled in.
717
+ *
718
+ * ONE place, because every adapter needs the same answer and the ones that
719
+ * derived it themselves diverged: the URL-backed pair inherited `safeFetch`'s
720
+ * cap and deadline for free, while the local and S3 adapters — which never
721
+ * touch `safeFetch` — applied NO bound at all when the caller named none.
722
+ * `StorageReadOptions` promises the default either way, and a production caller
723
+ * reading media without options got it from two of four backends.
724
+ *
725
+ * Filling the defaults here rather than per adapter is what makes the promise
726
+ * true by construction rather than by four implementations agreeing.
727
+ */
728
+ function resolveReadBounds(options) {
729
+ return {
730
+ maxBytes: options?.maxBytes ?? DEFAULT_READ_MAX_BYTES,
731
+ timeoutMs: options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS
732
+ };
733
+ }
5
734
  // src/adapter.ts
735
+ /**
736
+ * S3 Storage Adapter
737
+ *
738
+ * Stores files on AWS S3 or S3-compatible services (Cloudflare R2, MinIO, DigitalOcean Spaces).
739
+ * Uses AWS SDK v3 with automatic multipart upload for large files (>5MB).
740
+ *
741
+ * Features:
742
+ * - Automatic multipart upload via @aws-sdk/lib-storage
743
+ * - Pre-signed URL generation for client-side uploads
744
+ * - Signed URL generation for private file access
745
+ * - Cloudflare R2 support (S3-compatible API)
746
+ * - Custom endpoint support (MinIO, DigitalOcean Spaces)
747
+ * - CDN URL override support
748
+ * - File metadata retrieval
749
+ *
750
+ * @example AWS S3
751
+ * ```typescript
752
+ * const adapter = new S3StorageAdapter({
753
+ * bucket: 'my-media-bucket',
754
+ * region: 'us-east-1',
755
+ * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
756
+ * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
757
+ * collections: { media: true }
758
+ * });
759
+ * ```
760
+ *
761
+ * @example Cloudflare R2
762
+ * ```typescript
763
+ * const adapter = new S3StorageAdapter({
764
+ * bucket: 'my-media',
765
+ * region: 'auto',
766
+ * accessKeyId: process.env.R2_ACCESS_KEY_ID!,
767
+ * secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
768
+ * endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
769
+ * publicUrl: 'https://pub-abc.r2.dev',
770
+ * collections: { media: true }
771
+ * });
772
+ * ```
773
+ *
774
+ * @example MinIO (self-hosted)
775
+ * ```typescript
776
+ * const adapter = new S3StorageAdapter({
777
+ * bucket: 'my-bucket',
778
+ * region: 'us-east-1',
779
+ * accessKeyId: process.env.MINIO_ACCESS_KEY!,
780
+ * secretAccessKey: process.env.MINIO_SECRET_KEY!,
781
+ * endpoint: 'http://localhost:9000',
782
+ * forcePathStyle: true,
783
+ * collections: { media: true }
784
+ * });
785
+ * ```
786
+ */
787
+ /**
788
+ * S3 Storage Adapter
789
+ *
790
+ * Implements the IStorageAdapter interface for AWS S3 and S3-compatible services.
791
+ * Provides full support for uploads, downloads, signed URLs, and client-side uploads.
792
+ */
793
+ /**
794
+ * The SDK request options carrying the caller's deadline, or none.
795
+ *
796
+ * A free function rather than a branch inside `read`, because it is the only
797
+ * part of that method with nothing to do with telling an absent key apart from
798
+ * an unreachable bucket — which is the distinction a reader has to hold in
799
+ * their head there.
800
+ *
801
+ * `AbortSignal.timeout` rather than a controller and a `setTimeout`: it needs no
802
+ * clearing, so it cannot leak a timer when the read resolves first. The signal
803
+ * covers the BODY as well as the request, because the SDK threads it through
804
+ * the response stream — and a backend that answers headers promptly and then
805
+ * stalls mid-transfer is exactly the case a request-only deadline misses.
806
+ */
807
+ function abortAfter(options) {
808
+ return { abortSignal: AbortSignal.timeout(resolveReadBounds(options).timeoutMs) };
809
+ }
6
810
  var S3StorageAdapter = class {
7
- /**
8
- * Create a new S3 storage adapter.
9
- *
10
- * @param config - S3 storage configuration
11
- * @throws Error if bucket or region is not provided
12
- */
13
- constructor(config) {
14
- this.config = config;
15
- if (!config.bucket) {
16
- throw new Error("@nextly/storage-s3: bucket is required");
17
- }
18
- if (!config.region) {
19
- throw new Error("@nextly/storage-s3: region is required");
20
- }
21
- this.isR2 = config.endpoint?.includes("r2.cloudflarestorage.com") ?? false;
22
- this.resolvedConfig = {
23
- bucket: config.bucket,
24
- region: config.region,
25
- endpoint: config.endpoint,
26
- forcePathStyle: config.forcePathStyle ?? false,
27
- acl: config.acl ?? "private",
28
- publicUrl: config.publicUrl,
29
- cacheControl: config.cacheControl ?? "public, max-age=31536000",
30
- contentDisposition: config.contentDisposition,
31
- signedUrlExpiresIn: config.signedUrlExpiresIn ?? 3600
32
- };
33
- const credentials = this.buildCredentials();
34
- this.client = new S3Client({
35
- region: config.region,
36
- endpoint: config.endpoint,
37
- credentials,
38
- forcePathStyle: this.resolvedConfig.forcePathStyle,
39
- ...config.config
40
- });
41
- }
42
- client;
43
- resolvedConfig;
44
- isR2;
45
- /**
46
- * Build AWS credentials from config.
47
- * Supports explicit credentials or falls back to SDK default chain.
48
- */
49
- buildCredentials() {
50
- if (this.config.accessKeyId && this.config.secretAccessKey) {
51
- return {
52
- accessKeyId: this.config.accessKeyId,
53
- secretAccessKey: this.config.secretAccessKey
54
- };
55
- }
56
- if (this.config.config?.credentials) {
57
- return void 0;
58
- }
59
- return void 0;
60
- }
61
- // ============================================================
62
- // Core IStorageAdapter Methods
63
- // ============================================================
64
- /**
65
- * Upload file to S3.
66
- *
67
- * Uses AWS SDK v3's Upload class from @aws-sdk/lib-storage which:
68
- * - Automatically handles multipart upload for large files (>5MB)
69
- * - Provides progress tracking capability
70
- * - Includes retry logic
71
- * - Optimizes upload performance
72
- *
73
- * @param buffer - File content as Buffer
74
- * @param options - Upload options (filename, mimeType, folder, collection)
75
- * @returns Upload result with URL and storage path
76
- */
77
- async upload(buffer, options) {
78
- const key = this.generateKey(options.filename, options.folder);
79
- const uploadParams = {
80
- Bucket: this.resolvedConfig.bucket,
81
- Key: key,
82
- Body: buffer,
83
- ContentType: options.contentType || options.mimeType,
84
- CacheControl: this.resolvedConfig.cacheControl
85
- };
86
- if (!this.isR2) {
87
- uploadParams.ACL = this.resolvedConfig.acl;
88
- }
89
- const disposition = options.contentDisposition ?? this.resolvedConfig.contentDisposition;
90
- if (disposition) {
91
- const filename = this.sanitizeFilename(options.filename);
92
- uploadParams.ContentDisposition = disposition === "attachment" ? `attachment; filename="${filename}"` : "inline";
93
- }
94
- uploadParams.Metadata = {
95
- "original-filename": options.filename
96
- };
97
- const upload = new Upload({
98
- client: this.client,
99
- params: uploadParams
100
- });
101
- await upload.done();
102
- return {
103
- url: this.getPublicUrl(key),
104
- path: key
105
- };
106
- }
107
- /**
108
- * Delete file from S3.
109
- *
110
- * @param filePath - Storage path/key to delete
111
- */
112
- async delete(filePath) {
113
- const command = new DeleteObjectCommand({
114
- Bucket: this.resolvedConfig.bucket,
115
- Key: filePath
116
- });
117
- await this.client.send(command);
118
- }
119
- /**
120
- * Bulk delete files from S3 using a single API call per 1000 keys.
121
- *
122
- * Uses AWS SDK v3's DeleteObjectsCommand which supports up to 1000 keys per
123
- * request. Automatically batches larger arrays and collects per-key results.
124
- *
125
- * @param filePaths - Storage paths/keys to delete
126
- * @returns Object with arrays of successful and failed deletions
127
- */
128
- async bulkDelete(filePaths) {
129
- const successful = [];
130
- const failed = [];
131
- const maxBatchSize = 1e3;
132
- for (let i = 0; i < filePaths.length; i += maxBatchSize) {
133
- const batch = filePaths.slice(i, i + maxBatchSize);
134
- const command = new DeleteObjectsCommand({
135
- Bucket: this.resolvedConfig.bucket,
136
- Delete: {
137
- Objects: batch.map((key) => ({ Key: key })),
138
- Quiet: false
139
- }
140
- });
141
- const response = await this.client.send(command);
142
- if (response.Errors && response.Errors.length > 0) {
143
- for (const err of response.Errors) {
144
- if (err.Key) {
145
- failed.push({
146
- filePath: err.Key,
147
- error: err.Message ?? "Unknown S3 delete error"
148
- });
149
- }
150
- }
151
- }
152
- if (response.Deleted) {
153
- for (const del of response.Deleted) {
154
- if (del.Key) {
155
- successful.push(del.Key);
156
- }
157
- }
158
- }
159
- }
160
- return { successful, failed };
161
- }
162
- /**
163
- * Check if file exists in S3.
164
- *
165
- * Uses HeadObject command which is more efficient than GetObject
166
- * for existence checks (doesn't download the file).
167
- *
168
- * @param filePath - Storage path/key to check
169
- * @returns true if file exists, false otherwise
170
- */
171
- async exists(filePath) {
172
- try {
173
- const command = new HeadObjectCommand({
174
- Bucket: this.resolvedConfig.bucket,
175
- Key: filePath
176
- });
177
- await this.client.send(command);
178
- return true;
179
- } catch (error) {
180
- if (this.isNotFoundError(error)) {
181
- return false;
182
- }
183
- throw error;
184
- }
185
- }
186
- /**
187
- * Get public URL for S3 file.
188
- *
189
- * Priority order:
190
- * 1. Custom publicUrl (CDN or custom domain) if configured
191
- * 2. Standard S3 URL based on region and bucket
192
- *
193
- * For R2: Requires publicUrl configuration (R2 has no default public URLs).
194
- *
195
- * @param filePath - Storage path/key
196
- * @returns Public URL to access the file
197
- * @throws Error if R2 is used without publicUrl configuration
198
- */
199
- getPublicUrl(filePath) {
200
- if (this.resolvedConfig.publicUrl) {
201
- const baseUrl = this.resolvedConfig.publicUrl.replace(/\/$/, "");
202
- return `${baseUrl}/${filePath}`;
203
- }
204
- if (this.isR2) {
205
- throw new Error(
206
- "@nextly/storage-s3: Cloudflare R2 requires publicUrl configuration.\n\nR2 does not have default public URLs like AWS S3. Configure one of:\n1. Public bucket URL: publicUrl: 'https://pub-xxx.r2.dev'\n2. Custom domain: publicUrl: 'https://cdn.example.com'\n\nSet up public access in the Cloudflare R2 dashboard."
207
- );
208
- }
209
- return `https://${this.resolvedConfig.bucket}.s3.${this.resolvedConfig.region}.amazonaws.com/${filePath}`;
210
- }
211
- /**
212
- * Get storage type identifier.
213
- *
214
- * Returns "s3" for all S3-compatible services (AWS S3, R2, MinIO, etc.)
215
- * as they all use the S3 API.
216
- */
217
- getType() {
218
- return "s3";
219
- }
220
- // ============================================================
221
- // Optional IStorageAdapter Methods
222
- // ============================================================
223
- /**
224
- * Get adapter info including capabilities.
225
- *
226
- * @returns Adapter info with type, name, and capability flags
227
- */
228
- getInfo() {
229
- return {
230
- type: "s3",
231
- name: "S3StorageAdapter",
232
- supportsSignedUrls: true,
233
- supportsClientUploads: true
234
- };
235
- }
236
- /**
237
- * Get file metadata from S3.
238
- *
239
- * Retrieves file information including size, content type, and timestamps
240
- * using the HeadObject command.
241
- *
242
- * @param filePath - Storage path/key
243
- * @returns File metadata or null if file not found
244
- */
245
- async getMetadata(filePath) {
246
- try {
247
- const command = new HeadObjectCommand({
248
- Bucket: this.resolvedConfig.bucket,
249
- Key: filePath
250
- });
251
- const response = await this.client.send(command);
252
- const filename = filePath.split("/").pop() || filePath;
253
- return {
254
- id: filePath,
255
- filename,
256
- originalFilename: response.Metadata?.["original-filename"] || filename,
257
- mimeType: response.ContentType || "application/octet-stream",
258
- size: response.ContentLength || 0,
259
- url: this.getPublicUrl(filePath),
260
- createdAt: response.LastModified?.toISOString() || (/* @__PURE__ */ new Date()).toISOString()
261
- };
262
- } catch (error) {
263
- if (this.isNotFoundError(error)) {
264
- return null;
265
- }
266
- throw error;
267
- }
268
- }
269
- /**
270
- * Generate signed URL for temporary private file access.
271
- *
272
- * Creates a pre-signed GetObject URL that grants temporary read access
273
- * to private files. Useful for serving files from private buckets.
274
- *
275
- * @param filePath - Storage path/key
276
- * @param expiresIn - URL validity duration in seconds (default: 3600)
277
- * @returns Pre-signed URL for downloading the file
278
- */
279
- async getSignedUrl(filePath, expiresIn) {
280
- const command = new GetObjectCommand({
281
- Bucket: this.resolvedConfig.bucket,
282
- Key: filePath
283
- });
284
- return getSignedUrl(this.client, command, {
285
- expiresIn: expiresIn ?? this.resolvedConfig.signedUrlExpiresIn
286
- });
287
- }
288
- /**
289
- * Generate pre-signed URL for client-side uploads.
290
- *
291
- * Creates a pre-signed PutObject URL that allows direct uploads from
292
- * the browser to S3, bypassing server-side upload limits (e.g., Vercel's 4.5MB).
293
- *
294
- * @param key - Storage path/key for the upload
295
- * @param mimeType - MIME type of the file being uploaded
296
- * @param expiresIn - URL validity duration in seconds (default: 3600)
297
- * @returns Client upload data with URL, method, and headers
298
- */
299
- async getPresignedUploadUrl(key, mimeType, expiresIn) {
300
- const expiration = expiresIn ?? this.resolvedConfig.signedUrlExpiresIn;
301
- const commandParams = {
302
- Bucket: this.resolvedConfig.bucket,
303
- Key: key,
304
- ContentType: mimeType,
305
- CacheControl: this.resolvedConfig.cacheControl
306
- };
307
- if (!this.isR2) {
308
- commandParams.ACL = this.resolvedConfig.acl;
309
- }
310
- const command = new PutObjectCommand(commandParams);
311
- const uploadUrl = await getSignedUrl(this.client, command, {
312
- expiresIn: expiration
313
- });
314
- return {
315
- uploadUrl,
316
- path: key,
317
- method: "PUT",
318
- headers: {
319
- "Content-Type": mimeType
320
- },
321
- expiresAt: new Date(Date.now() + expiration * 1e3)
322
- };
323
- }
324
- // ============================================================
325
- // Helper Methods
326
- // ============================================================
327
- /**
328
- * Generate a unique storage key with date-based prefix.
329
- *
330
- * Creates keys in format: {folder}/{year}/{month}/{uuid}-{sanitized-filename}
331
- *
332
- * @param filename - Original filename (will be sanitized)
333
- * @param folder - Optional folder/prefix for organizing uploads
334
- * @returns Generated storage key
335
- */
336
- generateKey(filename, folder) {
337
- const sanitized = this.sanitizeFilename(filename);
338
- const uuid = crypto.randomUUID();
339
- const date = /* @__PURE__ */ new Date();
340
- const year = date.getFullYear();
341
- const month = String(date.getMonth() + 1).padStart(2, "0");
342
- const prefix = folder ? `${folder}/${year}/${month}` : `${year}/${month}`;
343
- return `${prefix}/${uuid}-${sanitized}`;
344
- }
345
- /**
346
- * Sanitize filename to prevent directory traversal and S3 key issues.
347
- *
348
- * @param filename - Original filename
349
- * @returns Sanitized filename safe for S3 keys
350
- */
351
- sanitizeFilename(filename) {
352
- const basename = filename.split(/[/\\]/).pop() || filename;
353
- return basename.replace(/[^a-zA-Z0-9._-]/g, "-");
354
- }
355
- /**
356
- * Check if an error is a "not found" error from S3.
357
- *
358
- * @param error - Error to check
359
- * @returns true if error indicates file not found
360
- */
361
- isNotFoundError(error) {
362
- if (error && typeof error === "object") {
363
- const e = error;
364
- return e.name === "NotFound" || e.$metadata?.httpStatusCode === 404;
365
- }
366
- return false;
367
- }
368
- // ============================================================
369
- // Public Accessors
370
- // ============================================================
371
- /**
372
- * Get the S3 client instance.
373
- * Useful for advanced operations not covered by the adapter interface.
374
- */
375
- getClient() {
376
- return this.client;
377
- }
378
- /**
379
- * Get the bucket name.
380
- */
381
- getBucket() {
382
- return this.resolvedConfig.bucket;
383
- }
384
- /**
385
- * Get the AWS region.
386
- */
387
- getRegion() {
388
- return this.resolvedConfig.region;
389
- }
390
- /**
391
- * Check if this adapter is configured for Cloudflare R2.
392
- */
393
- isCloudflareR2() {
394
- return this.isR2;
395
- }
811
+ config;
812
+ client;
813
+ resolvedConfig;
814
+ isR2;
815
+ /**
816
+ * Create a new S3 storage adapter.
817
+ *
818
+ * @param config - S3 storage configuration
819
+ * @throws Error if bucket or region is not provided
820
+ */
821
+ constructor(config) {
822
+ this.config = config;
823
+ if (!config.bucket) throw new Error("@nextly/storage-s3: bucket is required");
824
+ if (!config.region) throw new Error("@nextly/storage-s3: region is required");
825
+ this.isR2 = config.endpoint?.includes("r2.cloudflarestorage.com") ?? false;
826
+ this.resolvedConfig = {
827
+ bucket: config.bucket,
828
+ region: config.region,
829
+ endpoint: config.endpoint,
830
+ forcePathStyle: config.forcePathStyle ?? false,
831
+ acl: config.acl ?? "private",
832
+ publicUrl: config.publicUrl,
833
+ cacheControl: config.cacheControl ?? "public, max-age=31536000",
834
+ contentDisposition: config.contentDisposition,
835
+ signedUrlExpiresIn: config.signedUrlExpiresIn ?? 3600
836
+ };
837
+ const credentials = this.buildCredentials();
838
+ this.client = new S3Client({
839
+ region: config.region,
840
+ endpoint: config.endpoint,
841
+ credentials,
842
+ forcePathStyle: this.resolvedConfig.forcePathStyle,
843
+ ...config.config
844
+ });
845
+ }
846
+ /**
847
+ * Build AWS credentials from config.
848
+ * Supports explicit credentials or falls back to SDK default chain.
849
+ */
850
+ buildCredentials() {
851
+ if (this.config.accessKeyId && this.config.secretAccessKey) return {
852
+ accessKeyId: this.config.accessKeyId,
853
+ secretAccessKey: this.config.secretAccessKey
854
+ };
855
+ if (this.config.config?.credentials) return;
856
+ }
857
+ /**
858
+ * Upload file to S3.
859
+ *
860
+ * Uses AWS SDK v3's Upload class from @aws-sdk/lib-storage which:
861
+ * - Automatically handles multipart upload for large files (>5MB)
862
+ * - Provides progress tracking capability
863
+ * - Includes retry logic
864
+ * - Optimizes upload performance
865
+ *
866
+ * @param buffer - File content as Buffer
867
+ * @param options - Upload options (filename, mimeType, folder, collection)
868
+ * @returns Upload result with URL and storage path
869
+ */
870
+ async upload(buffer, options) {
871
+ const key = this.generateKey(options.filename, options.folder);
872
+ const uploadParams = {
873
+ Bucket: this.resolvedConfig.bucket,
874
+ Key: key,
875
+ Body: buffer,
876
+ ContentType: options.contentType || options.mimeType,
877
+ CacheControl: this.resolvedConfig.cacheControl
878
+ };
879
+ if (!this.isR2) uploadParams.ACL = this.resolvedConfig.acl;
880
+ const disposition = options.contentDisposition ?? this.resolvedConfig.contentDisposition;
881
+ if (disposition) {
882
+ const filename = this.sanitizeFilename(options.filename);
883
+ uploadParams.ContentDisposition = disposition === "attachment" ? `attachment; filename="${filename}"` : "inline";
884
+ }
885
+ uploadParams.Metadata = { "original-filename": options.filename };
886
+ await new Upload({
887
+ client: this.client,
888
+ params: uploadParams
889
+ }).done();
890
+ return {
891
+ url: this.getPublicUrl(key),
892
+ path: key
893
+ };
894
+ }
895
+ /**
896
+ * Delete file from S3.
897
+ *
898
+ * @param filePath - Storage path/key to delete
899
+ */
900
+ async delete(filePath) {
901
+ const command = new DeleteObjectCommand({
902
+ Bucket: this.resolvedConfig.bucket,
903
+ Key: filePath
904
+ });
905
+ await this.client.send(command);
906
+ }
907
+ /**
908
+ * Bulk delete files from S3 using a single API call per 1000 keys.
909
+ *
910
+ * Uses AWS SDK v3's DeleteObjectsCommand which supports up to 1000 keys per
911
+ * request. Automatically batches larger arrays and collects per-key results.
912
+ *
913
+ * @param filePaths - Storage paths/keys to delete
914
+ * @returns Object with arrays of successful and failed deletions
915
+ */
916
+ async bulkDelete(filePaths) {
917
+ const successful = [];
918
+ const failed = [];
919
+ const maxBatchSize = 1e3;
920
+ for (let i = 0; i < filePaths.length; i += maxBatchSize) {
921
+ const batch = filePaths.slice(i, i + maxBatchSize);
922
+ const command = new DeleteObjectsCommand({
923
+ Bucket: this.resolvedConfig.bucket,
924
+ Delete: {
925
+ Objects: batch.map((key) => ({ Key: key })),
926
+ Quiet: false
927
+ }
928
+ });
929
+ const response = await this.client.send(command);
930
+ if (response.Errors && response.Errors.length > 0) {
931
+ for (const err of response.Errors) if (err.Key) failed.push({
932
+ filePath: err.Key,
933
+ error: err.Message ?? "Unknown S3 delete error"
934
+ });
935
+ }
936
+ if (response.Deleted) {
937
+ for (const del of response.Deleted) if (del.Key) successful.push(del.Key);
938
+ }
939
+ }
940
+ return {
941
+ successful,
942
+ failed
943
+ };
944
+ }
945
+ /**
946
+ * Check if file exists in S3.
947
+ *
948
+ * Uses HeadObject command which is more efficient than GetObject
949
+ * for existence checks (doesn't download the file).
950
+ *
951
+ * @param filePath - Storage path/key to check
952
+ * @returns true if file exists, false otherwise
953
+ */
954
+ async exists(filePath) {
955
+ try {
956
+ const command = new HeadObjectCommand({
957
+ Bucket: this.resolvedConfig.bucket,
958
+ Key: filePath
959
+ });
960
+ await this.client.send(command);
961
+ return true;
962
+ } catch (error) {
963
+ if (this.isNotFoundError(error)) return false;
964
+ throw error;
965
+ }
966
+ }
967
+ /**
968
+ * Get public URL for S3 file.
969
+ *
970
+ * Priority order:
971
+ * 1. Custom publicUrl (CDN or custom domain) if configured
972
+ * 2. Standard S3 URL based on region and bucket
973
+ *
974
+ * For R2: Requires publicUrl configuration (R2 has no default public URLs).
975
+ *
976
+ * @param filePath - Storage path/key
977
+ * @returns Public URL to access the file
978
+ * @throws Error if R2 is used without publicUrl configuration
979
+ */
980
+ /**
981
+ * Every object in the bucket, by key, with when it was last written, a page
982
+ * of up to 1,000 at a time.
983
+ */
984
+ async *list() {
985
+ let token;
986
+ do {
987
+ const page = await this.client.send(new ListObjectsV2Command({
988
+ Bucket: this.resolvedConfig.bucket,
989
+ ContinuationToken: token
990
+ }));
991
+ for (const object of page.Contents ?? []) if (object.Key) yield {
992
+ path: object.Key,
993
+ lastModified: object.LastModified
994
+ };
995
+ token = page.IsTruncated ? page.NextContinuationToken : void 0;
996
+ } while (token);
997
+ }
998
+ getPublicUrl(filePath) {
999
+ if (this.resolvedConfig.publicUrl) return `${this.resolvedConfig.publicUrl.replace(/\/$/, "")}/${filePath}`;
1000
+ if (this.isR2) throw new Error("@nextly/storage-s3: Cloudflare R2 requires publicUrl configuration.\n\nR2 does not have default public URLs like AWS S3. Configure one of:\n1. Public bucket URL: publicUrl: 'https://pub-xxx.r2.dev'\n2. Custom domain: publicUrl: 'https://cdn.example.com'\n\nSet up public access in the Cloudflare R2 dashboard.");
1001
+ return `https://${this.resolvedConfig.bucket}.s3.${this.resolvedConfig.region}.amazonaws.com/${filePath}`;
1002
+ }
1003
+ /**
1004
+ * Get storage type identifier.
1005
+ *
1006
+ * Returns "s3" for all S3-compatible services (AWS S3, R2, MinIO, etc.)
1007
+ * as they all use the S3 API.
1008
+ */
1009
+ getType() {
1010
+ return "s3";
1011
+ }
1012
+ /**
1013
+ * Get adapter info including capabilities.
1014
+ *
1015
+ * @returns Adapter info with type, name, and capability flags
1016
+ */
1017
+ getInfo() {
1018
+ return {
1019
+ type: "s3",
1020
+ name: "S3StorageAdapter",
1021
+ supportsSignedUrls: true,
1022
+ supportsClientUploads: true
1023
+ };
1024
+ }
1025
+ /**
1026
+ * Get file metadata from S3.
1027
+ *
1028
+ * Retrieves file information including size, content type, and timestamps
1029
+ * using the HeadObject command.
1030
+ *
1031
+ * @param filePath - Storage path/key
1032
+ * @returns File metadata or null if file not found
1033
+ */
1034
+ async getMetadata(filePath) {
1035
+ try {
1036
+ const command = new HeadObjectCommand({
1037
+ Bucket: this.resolvedConfig.bucket,
1038
+ Key: filePath
1039
+ });
1040
+ const response = await this.client.send(command);
1041
+ const filename = filePath.split("/").pop() || filePath;
1042
+ return {
1043
+ id: filePath,
1044
+ filename,
1045
+ originalFilename: response.Metadata?.["original-filename"] || filename,
1046
+ mimeType: response.ContentType || "application/octet-stream",
1047
+ size: response.ContentLength || 0,
1048
+ url: this.getPublicUrl(filePath),
1049
+ createdAt: response.LastModified?.toISOString() || (/* @__PURE__ */ new Date()).toISOString()
1050
+ };
1051
+ } catch (error) {
1052
+ if (this.isNotFoundError(error)) return null;
1053
+ throw error;
1054
+ }
1055
+ }
1056
+ /**
1057
+ * Read a stored object back as bytes, or `null` when it is not there.
1058
+ *
1059
+ * The contract declares this OPTIONAL and, until now, no adapter supplied
1060
+ * it — so a caller reaching for `adapter.read` got `undefined` and fell
1061
+ * through whatever branch followed. An optional member nothing implements is
1062
+ * a contract that reads as a capability and behaves as an absence.
1063
+ *
1064
+ * BUFFERS rather than streams, because that is the declared return type and
1065
+ * widening it here would make this adapter answer a different question from
1066
+ * its siblings. That bounds what it should be used for: an asset the server
1067
+ * must serve from its own origin — a font file, a small document — rather
1068
+ * than arbitrarily large media, which belongs behind {@link getSignedUrl} or
1069
+ * a public URL. A streaming variant is a separate contract member, not a
1070
+ * quiet change to this one.
1071
+ *
1072
+ * `null` for a missing key rather than a throw, matching
1073
+ * {@link getMetadata}: absence is an ordinary answer about the bucket, while
1074
+ * a credential or network failure is not, so only the first is folded into
1075
+ * the return value.
1076
+ *
1077
+ * @param filePath - Storage path/key
1078
+ * @returns The object's bytes, or `null` when no such key exists
1079
+ */
1080
+ async read(filePath, options) {
1081
+ try {
1082
+ const command = new GetObjectCommand({
1083
+ Bucket: this.resolvedConfig.bucket,
1084
+ Key: filePath
1085
+ });
1086
+ const response = await this.client.send(command, abortAfter(options));
1087
+ if (response.Body === void 0) return Buffer.alloc(0);
1088
+ const cap = resolveReadBounds(options).maxBytes;
1089
+ this.refuseOverCap(filePath, response.ContentLength, cap);
1090
+ return await this.readCapped(filePath, response.Body, cap);
1091
+ } catch (error) {
1092
+ if (error instanceof Error && error.name === "NoSuchBucket") throw error;
1093
+ if (this.isNotFoundError(error)) return null;
1094
+ throw error;
1095
+ }
1096
+ }
1097
+ /**
1098
+ * Generate signed URL for temporary private file access.
1099
+ *
1100
+ * Creates a pre-signed GetObject URL that grants temporary read access
1101
+ * to private files. Useful for serving files from private buckets.
1102
+ *
1103
+ * @param filePath - Storage path/key
1104
+ * @param expiresIn - URL validity duration in seconds (default: 3600)
1105
+ * @returns Pre-signed URL for downloading the file
1106
+ */
1107
+ async getSignedUrl(filePath, expiresIn) {
1108
+ const command = new GetObjectCommand({
1109
+ Bucket: this.resolvedConfig.bucket,
1110
+ Key: filePath
1111
+ });
1112
+ return getSignedUrl(this.client, command, { expiresIn: expiresIn ?? this.resolvedConfig.signedUrlExpiresIn });
1113
+ }
1114
+ /**
1115
+ * Generate pre-signed URL for client-side uploads.
1116
+ *
1117
+ * Creates a pre-signed PutObject URL that allows direct uploads from
1118
+ * the browser to S3, bypassing server-side upload limits (e.g., Vercel's 4.5MB).
1119
+ *
1120
+ * @param key - Storage path/key for the upload
1121
+ * @param mimeType - MIME type of the file being uploaded
1122
+ * @param expiresIn - URL validity duration in seconds (default: 3600)
1123
+ * @returns Client upload data with URL, method, and headers
1124
+ */
1125
+ async getPresignedUploadUrl(key, mimeType, expiresIn) {
1126
+ const expiration = expiresIn ?? this.resolvedConfig.signedUrlExpiresIn;
1127
+ const commandParams = {
1128
+ Bucket: this.resolvedConfig.bucket,
1129
+ Key: key,
1130
+ ContentType: mimeType,
1131
+ CacheControl: this.resolvedConfig.cacheControl
1132
+ };
1133
+ if (!this.isR2) commandParams.ACL = this.resolvedConfig.acl;
1134
+ const command = new PutObjectCommand(commandParams);
1135
+ return {
1136
+ uploadUrl: await getSignedUrl(this.client, command, { expiresIn: expiration }),
1137
+ path: key,
1138
+ method: "PUT",
1139
+ headers: { "Content-Type": mimeType },
1140
+ expiresAt: new Date(Date.now() + expiration * 1e3)
1141
+ };
1142
+ }
1143
+ /**
1144
+ * Generate a unique storage key with date-based prefix.
1145
+ *
1146
+ * Creates keys in format: {folder}/{year}/{month}/{uuid}-{sanitized-filename}
1147
+ *
1148
+ * @param filename - Original filename (will be sanitized)
1149
+ * @param folder - Optional folder/prefix for organizing uploads
1150
+ * @returns Generated storage key
1151
+ */
1152
+ generateKey(filename, folder) {
1153
+ const sanitized = this.sanitizeFilename(filename);
1154
+ const uuid = crypto.randomUUID();
1155
+ const date = /* @__PURE__ */ new Date();
1156
+ const year = date.getFullYear();
1157
+ const month = String(date.getMonth() + 1).padStart(2, "0");
1158
+ return `${folder ? `${folder}/${year}/${month}` : `${year}/${month}`}/${uuid}-${sanitized}`;
1159
+ }
1160
+ /**
1161
+ * Sanitize filename to prevent directory traversal and S3 key issues.
1162
+ *
1163
+ * @param filename - Original filename
1164
+ * @returns Sanitized filename safe for S3 keys
1165
+ */
1166
+ sanitizeFilename(filename) {
1167
+ return (filename.split(/[/\\]/).pop() || filename).replace(/[^a-zA-Z0-9._-]/g, "-");
1168
+ }
1169
+ /**
1170
+ * Check if an error is a "not found" error from S3.
1171
+ *
1172
+ * @param error - Error to check
1173
+ * @returns true if error indicates file not found
1174
+ */
1175
+ /**
1176
+ * The object's bytes, refusing once more than `cap` have actually arrived.
1177
+ *
1178
+ * `ContentLength` is OPTIONAL in the SDK's response type, and this adapter
1179
+ * explicitly supports MinIO, R2 and other compatible services — any of which
1180
+ * may omit it or report it wrongly. A preflight check against metadata is
1181
+ * therefore a courtesy that fails OPEN: trusting it alone leaves the cap
1182
+ * unenforced exactly where an unusual backend is involved, which is where a
1183
+ * caller most needs it.
1184
+ *
1185
+ * Counted while consuming, so an oversized body is abandoned partway rather
1186
+ * than after it has all been buffered — the cap exists to bound memory, and
1187
+ * one applied after `transformToByteArray` has already spent it.
1188
+ *
1189
+ * Falls back to buffering when the body is not async-iterable, which the SDK
1190
+ * types permit. Stated rather than hidden: on that path the cap bounds what a
1191
+ * caller RECEIVES rather than what the process allocates.
1192
+ */
1193
+ async readCapped(filePath, body, cap) {
1194
+ if (typeof body[Symbol.asyncIterator] !== "function") {
1195
+ const whole = Buffer.from(await body.transformToByteArray());
1196
+ if (whole.byteLength > cap) throw new StorageReadTooLargeError(filePath, cap, whole.byteLength);
1197
+ return whole;
1198
+ }
1199
+ const chunks = [];
1200
+ let received = 0;
1201
+ for await (const chunk of body) {
1202
+ received += chunk.byteLength;
1203
+ if (received > cap) throw new StorageReadTooLargeError(filePath, cap, received);
1204
+ chunks.push(Buffer.from(chunk));
1205
+ }
1206
+ return Buffer.concat(chunks);
1207
+ }
1208
+ /**
1209
+ * Refuse a read whose object is already known to exceed the caller's cap.
1210
+ *
1211
+ * Its own method rather than three conditions inside `read`, because the
1212
+ * decision has nothing to do with the surrounding error handling and reads
1213
+ * as noise there — and because `read`'s branching is the part a reviewer has
1214
+ * to hold in their head to check the absent-versus-unavailable distinction.
1215
+ *
1216
+ * Both `undefined` cases mean "no opinion" and pass: a caller that named no
1217
+ * cap has none, and a store that reported no length gives nothing to compare.
1218
+ * The second is deliberately permissive — refusing an unmeasured object would
1219
+ * reject valid reads whenever S3 omits the header.
1220
+ */
1221
+ refuseOverCap(filePath, declared, cap) {
1222
+ if (cap === void 0 || declared === void 0 || declared <= cap) return;
1223
+ throw new StorageReadTooLargeError(filePath, cap, declared);
1224
+ }
1225
+ isNotFoundError(error) {
1226
+ if (error && typeof error === "object") {
1227
+ const e = error;
1228
+ return e.name === "NotFound" || e.$metadata?.httpStatusCode === 404;
1229
+ }
1230
+ return false;
1231
+ }
1232
+ /**
1233
+ * Get the S3 client instance.
1234
+ * Useful for advanced operations not covered by the adapter interface.
1235
+ */
1236
+ getClient() {
1237
+ return this.client;
1238
+ }
1239
+ /**
1240
+ * Get the bucket name.
1241
+ */
1242
+ getBucket() {
1243
+ return this.resolvedConfig.bucket;
1244
+ }
1245
+ /**
1246
+ * Get the AWS region.
1247
+ */
1248
+ getRegion() {
1249
+ return this.resolvedConfig.region;
1250
+ }
1251
+ /**
1252
+ * Check if this adapter is configured for Cloudflare R2.
1253
+ */
1254
+ isCloudflareR2() {
1255
+ return this.isR2;
1256
+ }
396
1257
  };
397
-
398
1258
  // src/plugin.ts
1259
+ /**
1260
+ * Create an S3 storage plugin for Nextly.
1261
+ *
1262
+ * This factory function creates a StoragePlugin that can be added to
1263
+ * the `storage` array in `nextly.config.ts`. It supports:
1264
+ *
1265
+ * - AWS S3 (standard)
1266
+ * - Cloudflare R2 (S3-compatible)
1267
+ * - MinIO (S3-compatible, self-hosted)
1268
+ * - DigitalOcean Spaces (S3-compatible)
1269
+ * - Any other S3-compatible service
1270
+ *
1271
+ * @param config - S3 storage configuration
1272
+ * @returns A StoragePlugin that MediaStorage can register
1273
+ *
1274
+ * @throws Error if bucket is not provided (via adapter)
1275
+ * @throws Error if region is not provided (via adapter)
1276
+ */
399
1277
  function s3Storage(config) {
400
- if (config.enabled === false) {
401
- return {
402
- name: "s3-storage",
403
- type: "s3",
404
- collections: {},
405
- adapter: null
406
- };
407
- }
408
- const adapter = new S3StorageAdapter(config);
409
- const plugin = {
410
- name: "s3-storage",
411
- type: "s3",
412
- collections: config.collections,
413
- adapter,
414
- /**
415
- * Generate a pre-signed URL for client-side uploads.
416
- *
417
- * This allows files to be uploaded directly from the browser to S3,
418
- * bypassing server-side upload limits (e.g., Vercel's 4.5MB limit).
419
- *
420
- * @param filename - Original filename from the client
421
- * @param mimeType - MIME type of the file
422
- * @param collection - Collection slug this upload belongs to
423
- * @returns Client upload data with pre-signed URL
424
- */
425
- async getClientUploadUrl(filename, mimeType, collection) {
426
- const collectionConfig = config.collections[collection];
427
- const prefix = typeof collectionConfig === "object" ? collectionConfig.prefix : void 0;
428
- const key = generateStorageKey(filename, prefix);
429
- return adapter.getPresignedUploadUrl(key, mimeType);
430
- },
431
- /**
432
- * Generate a signed URL for private file downloads.
433
- *
434
- * Creates a time-limited URL for accessing files in private buckets.
435
- * Only works when collection has `signedDownloads: true`.
436
- *
437
- * @param path - Storage path/key of the file
438
- * @param expiresIn - URL validity duration in seconds
439
- * @returns Signed URL for downloading the file
440
- */
441
- async getSignedDownloadUrl(path, expiresIn) {
442
- return adapter.getSignedUrl(
443
- path,
444
- expiresIn ?? config.signedUrlExpiresIn ?? 3600
445
- );
446
- }
447
- };
448
- return plugin;
1278
+ if (config.enabled === false) return {
1279
+ name: "s3-storage",
1280
+ type: "s3",
1281
+ collections: {},
1282
+ adapter: null
1283
+ };
1284
+ const adapter = new S3StorageAdapter(config);
1285
+ return {
1286
+ name: "s3-storage",
1287
+ type: "s3",
1288
+ collections: config.collections,
1289
+ adapter,
1290
+ /**
1291
+ * Generate a pre-signed URL for client-side uploads.
1292
+ *
1293
+ * This allows files to be uploaded directly from the browser to S3,
1294
+ * bypassing server-side upload limits (e.g., Vercel's 4.5MB limit).
1295
+ *
1296
+ * @param filename - Original filename from the client
1297
+ * @param mimeType - MIME type of the file
1298
+ * @param collection - Collection slug this upload belongs to
1299
+ * @returns Client upload data with pre-signed URL
1300
+ */
1301
+ async getClientUploadUrl(filename, mimeType, collection) {
1302
+ const collectionConfig = config.collections[collection];
1303
+ const key = generateStorageKey(filename, typeof collectionConfig === "object" ? collectionConfig.prefix : void 0);
1304
+ return adapter.getPresignedUploadUrl(key, mimeType);
1305
+ },
1306
+ /**
1307
+ * Generate a signed URL for private file downloads.
1308
+ *
1309
+ * Creates a time-limited URL for accessing files in private buckets.
1310
+ * Only works when collection has `signedDownloads: true`.
1311
+ *
1312
+ * @param path - Storage path/key of the file
1313
+ * @param expiresIn - URL validity duration in seconds
1314
+ * @returns Signed URL for downloading the file
1315
+ */
1316
+ async getSignedDownloadUrl(path, expiresIn) {
1317
+ return adapter.getSignedUrl(path, expiresIn ?? config.signedUrlExpiresIn ?? 3600);
1318
+ }
1319
+ };
449
1320
  }
1321
+ /**
1322
+ * Generate a unique storage key with date-based prefix.
1323
+ *
1324
+ * Creates keys in format: {prefix}{year}/{month}/{uuid}-{sanitized-filename}
1325
+ * This matches the format used by S3StorageAdapter for consistency.
1326
+ *
1327
+ * @param filename - Original filename (will be sanitized)
1328
+ * @param prefix - Optional folder/prefix for organizing uploads
1329
+ * @returns Generated storage key
1330
+ */
450
1331
  function generateStorageKey(filename, prefix) {
451
- const sanitized = sanitizeFilename(filename);
452
- const uuid = crypto.randomUUID();
453
- const date = /* @__PURE__ */ new Date();
454
- const year = date.getFullYear();
455
- const month = String(date.getMonth() + 1).padStart(2, "0");
456
- const keyPrefix = prefix ? `${prefix}${year}/${month}` : `${year}/${month}`;
457
- return `${keyPrefix}/${uuid}-${sanitized}`;
1332
+ const sanitized = sanitizeFilename(filename);
1333
+ const uuid = crypto.randomUUID();
1334
+ const date = /* @__PURE__ */ new Date();
1335
+ const year = date.getFullYear();
1336
+ const month = String(date.getMonth() + 1).padStart(2, "0");
1337
+ return `${prefix ? `${prefix}${year}/${month}` : `${year}/${month}`}/${uuid}-${sanitized}`;
458
1338
  }
1339
+ /**
1340
+ * Sanitize filename to prevent directory traversal and S3 key issues.
1341
+ *
1342
+ * Removes path separators and replaces unsafe characters with hyphens.
1343
+ * Keeps only: a-z, A-Z, 0-9, dot, underscore, hyphen
1344
+ *
1345
+ * @param filename - Original filename
1346
+ * @returns Sanitized filename safe for S3 keys
1347
+ */
459
1348
  function sanitizeFilename(filename) {
460
- const basename = filename.split(/[/\\]/).pop() || filename;
461
- return basename.replace(/[^a-zA-Z0-9._-]/g, "-");
1349
+ return (filename.split(/[/\\]/).pop() || filename).replace(/[^a-zA-Z0-9._-]/g, "-");
462
1350
  }
463
-
464
1351
  // src/index.ts
465
- var PACKAGE_NAME = "@nextly/storage-s3";
466
- var PACKAGE_VERSION = "0.1.0";
467
-
1352
+ const PACKAGE_NAME = "@nextly/storage-s3";
1353
+ const PACKAGE_VERSION = "0.1.0";
468
1354
  export { PACKAGE_NAME, PACKAGE_VERSION, S3StorageAdapter, s3Storage };
469
- //# sourceMappingURL=index.mjs.map
1355
+
470
1356
  //# sourceMappingURL=index.mjs.map