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

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