@nextlyhq/storage-s3 0.0.2-alpha.8 → 0.0.2-alpha.81

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,1874 @@
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-D8GUAFzw.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
+ ACTION_NOT_AVAILABLE: 403,
82
+ NOT_FOUND: 404,
83
+ ENTITY_REMOVED_FROM_CODE: 409,
84
+ ENTITY_NOT_MIGRATED: 409,
85
+ METHOD_NOT_ALLOWED: 405,
86
+ RANGE_NOT_SATISFIABLE: 416,
87
+ CONFLICT: 409,
88
+ STALE_VERSION: 409,
89
+ COLLECTION_BEING_CHANGED: 409,
90
+ VERSION_REQUIRED: 428,
91
+ DUPLICATE: 409,
92
+ RATE_LIMITED: 429,
93
+ PAYLOAD_TOO_LARGE: 413,
94
+ UNSUPPORTED_MEDIA_TYPE: 415,
95
+ BUSINESS_RULE_VIOLATION: 422,
96
+ WORKFLOW_STEP_NOT_SUBMIT: 400,
97
+ WORKFLOW_NO_SUBMIT_STEP: 409,
98
+ INTERNAL_ERROR: 500,
99
+ DATABASE_ERROR: 500,
100
+ DATABASE_BUSY: 503,
101
+ RULE_COULD_NOT_RUN: 503,
102
+ EXTERNAL_SERVICE_ERROR: 502,
103
+ SERVICE_UNAVAILABLE: 503,
104
+ CONFIGURATION_ERROR: 500,
105
+ EXTERNAL_URL_BLOCKED: 400,
106
+ EXTERNAL_REQUEST_FAILED: 502,
107
+ FILENAME_INVALID: 400,
108
+ EXTENSION_BLOCKED: 400,
109
+ MIME_BLOCKED: 415,
110
+ MIME_NOT_ALLOWED: 415,
111
+ SIZE_EXCEEDED: 413,
112
+ STORAGE_READ_TOO_LARGE: 413,
113
+ STORAGE_READ_TIMEOUT: 504,
114
+ STORAGE_READ_UNREACHABLE: 502,
115
+ MAGIC_BYTE_MISMATCH: 400,
116
+ SVG_SANITIZATION_FAILED: 400,
117
+ UNSUPPORTED_FOR_BACKEND: 415,
118
+ NEXTLY_LEGACY_BOOKKEEPING_DETECTED: 409,
119
+ NEXTLY_UPGRADE_TABLE_NAME_COLLISION: 409,
120
+ NEXTLY_UPGRADE_IN_PROGRESS: 409,
121
+ NEXTLY_MIGRATE_LOCK_BUSY: 409,
122
+ NEXTLY_TABLE_BUSY: 409,
123
+ NEXTLY_LOCK_HELD_BY_THIS_PROCESS: 500,
124
+ NEXTLY_BASELINE_LOCK_NOT_HELD: 409,
125
+ NEXTLY_RESOLVE_LOCK_NOT_HELD: 409,
126
+ NEXTLY_BOOT_MIGRATIONS_NOT_RUN: 503,
127
+ NEXTLY_BOOT_MIGRATIONS_PENDING: 503,
128
+ NEXTLY_DATABASE_NOT_SET_UP: 503,
129
+ NEXTLY_DATABASE_NOT_MIGRATED: 503,
130
+ NEXTLY_CORE_DESTRUCTIVE_REFUSED: 409,
131
+ NEXTLY_CORE_UPGRADE_UNSUPPORTED: 409,
132
+ NEXTLY_CORE_UPGRADE_INCOMPLETE: 500,
133
+ NEXTLY_MIGRATION_DRIFT: 409,
134
+ NEXTLY_MIGRATION_APPLY_FAILED: 500,
135
+ NEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION: 409,
136
+ NEXTLY_MIGRATION_PARTIALLY_APPLIED: 500,
137
+ NEXTLY_MIGRATION_NOT_PROVEN: 409,
138
+ NEXTLY_MIGRATION_CONCURRENT_RUN: 409,
139
+ NEXTLY_MIGRATION_FILE_MISSING: 404,
140
+ NEXTLY_MIGRATION_SNAPSHOT_MISSING: 404,
141
+ NEXTLY_MIGRATION_RESOLVE_DRIFT: 409,
142
+ NEXTLY_MIGRATION_RESOLVE_PRECONDITION: 409,
143
+ NEXTLY_MIGRATION_HISTORY_REFUSED: 409,
144
+ NEXTLY_SCHEMA_CONVERSION_UNCONFIRMED: 409,
145
+ NEXTLY_UI_SCHEMA_INVALID: 400,
146
+ NEXTLY_SCHEMA_SLUG_COLLISION: 409,
147
+ NEXTLY_SCHEMA_RELATION_TARGET_MISSING: 400,
148
+ NEXTLY_SCHEMA_RELATION_UNRESOLVED: 400,
149
+ NEXTLY_SCHEMA_EXTEND_TARGET_UNKNOWN: 400,
150
+ NEXTLY_SCHEMA_EXTEND_FIELD_DUPLICATE: 409,
151
+ NEXTLY_SCHEMA_CROSS_PLUGIN_RELATION: 409,
152
+ NEXTLY_SCHEMA_RENAME_UNKNOWN_TARGET: 400,
153
+ NEXTLY_PLUGIN_CLIENT_CONFIG_INVALID: 500,
154
+ NEXTLY_PLUGIN_ADMIN_WIDGET_INVALID: 500,
155
+ NEXTLY_PLUGIN_REMOVED_WIDGET_CHANNEL: 500,
156
+ NEXTLY_PLUGIN_DOCUMENT_VIEW_INVALID: 500,
157
+ NEXTLY_PLUGIN_DOCUMENT_SURFACE_INVALID: 500,
158
+ PLUGIN_RESOLUTION_ERROR: 500,
159
+ PLUGIN_DEPENDENCY_NOT_INSTALLED: 409,
160
+ PLUGIN_HAS_DEPENDENTS: 409,
161
+ PLUGIN_UNINSTALL_WOULD_DROP_OTHERS: 409,
162
+ PLUGIN_UNINSTALL_IRREVERSIBLE: 409,
163
+ PLUGIN_UNINSTALL_UNCONFIRMED: 409,
164
+ PLUGIN_SCHEMA_BEHIND: 409,
165
+ PLUGIN_SCHEMA_UNINSTALLED: 409,
166
+ PLUGIN_NOT_INSTALLED: 409,
167
+ PLUGIN_DISABLED: 409,
168
+ PLUGIN_UNINSTALL_UNFINISHED: 409,
169
+ PLUGIN_SCHEMA_VERSION_NOT_ADVANCED: 409,
170
+ PLUGIN_MIGRATION_DROPS_CREATED_SCHEMA: 409,
171
+ PLUGIN_MIGRATION_ADDS_UNFILLABLE_COLUMN: 409,
172
+ PLUGIN_MIGRATION_SQL_MISSING: 409,
173
+ PLUGIN_MIGRATIONS_UNAVAILABLE: 409,
174
+ DROP_OF_FOREIGN_TABLE: 409,
175
+ MIGRATION_CHECKSUM_MISMATCH: 409,
176
+ PLUGIN_MIGRATIONS_OUT_OF_ORDER: 409,
177
+ PLUGIN_MIGRATION_HISTORY_CHANGED: 409,
178
+ NEXTLY_ROUTE_COLLISION: 409,
179
+ NEXTLY_ROUTE_INVALID_PATH: 400,
180
+ NEXTLY_ROUTE_UNREACHABLE_ROOT: 400,
181
+ NEXTLY_ROUTE_INVALID_MOUNT: 400,
182
+ NEXTLY_EMAIL_TRANSPORT_UNAVAILABLE: 503,
183
+ NEXTLY_CONFIG_TOOLING_UNAVAILABLE: 503,
184
+ NEXTLY_POSTGRES_SCHEMA_MISMATCH: 500,
185
+ NEXTLY_PER_LANGUAGE_STORAGE_CHANGED: 500,
186
+ NEXTLY_PER_LANGUAGE_STORAGE_MIXED: 500,
187
+ NEXTLY_PER_LANGUAGE_STORAGE_LANGUAGES_UNDECLARED: 500,
188
+ NEXTLY_LANGUAGE_CODES_COLLIDE: 500,
189
+ NEXTLY_LANGUAGE_CODES_NOT_UPGRADED: 500,
190
+ NEXTLY_UPGRADE_LOCALISATION_UNRESOLVED: 500,
191
+ NEXTLY_POSTGRES_SCHEMA_MOVED: 500
192
+ };
193
+ ({ ...Object.fromEntries([
194
+ "VALIDATION_ERROR",
195
+ "AUTH_REQUIRED",
196
+ "FORBIDDEN",
197
+ "NOT_FOUND",
198
+ "CONFLICT",
199
+ "VERSION_REQUIRED",
200
+ "PAYLOAD_TOO_LARGE",
201
+ "UNSUPPORTED_MEDIA_TYPE",
202
+ "RATE_LIMITED",
203
+ "EXTERNAL_SERVICE_ERROR",
204
+ "SERVICE_UNAVAILABLE"
205
+ ].map((code) => [NEXTLY_ERROR_STATUS[code], code])) });
206
+ /**
207
+ * The sentence a caller reads for a code, when the failure supplied none.
208
+ *
209
+ * Kept beside the status table because they answer the same question together:
210
+ * a code-less envelope's own `message` is NOT usable here. Those envelopes come
211
+ * from legacy converters that store a raw exception's text, so promoting it
212
+ * would put driver output, table names and internal paths on the wire -- the
213
+ * disclosure the public error shape exists to prevent (spec 13.8).
214
+ *
215
+ * Every entry is generic by design. The specific detail stays in `logContext`
216
+ * for the operator, against the same request id.
217
+ */
218
+ const GENERIC_PUBLIC_MESSAGE = {
219
+ VALIDATION_ERROR: "Validation failed.",
220
+ INVALID_INPUT: "The request could not be processed.",
221
+ AUTH_REQUIRED: "Authentication required.",
222
+ FORBIDDEN: "You don't have permission to perform this action.",
223
+ ACTION_NOT_AVAILABLE: "This action isn't available for this entry.",
224
+ NOT_FOUND: "Not found.",
225
+ METHOD_NOT_ALLOWED: "That method is not allowed on this address.",
226
+ RANGE_NOT_SATISFIABLE: "The requested range is outside the file.",
227
+ CONFLICT: "The resource has changed since you last loaded it. Please refresh and try again.",
228
+ DUPLICATE: "Resource already exists.",
229
+ PAYLOAD_TOO_LARGE: "The request is too large.",
230
+ UNSUPPORTED_MEDIA_TYPE: "That file type is not supported.",
231
+ RATE_LIMITED: "Too many requests. Please try again later.",
232
+ EXTERNAL_SERVICE_ERROR: "An upstream service failed.",
233
+ SERVICE_UNAVAILABLE: "The service is temporarily unavailable.",
234
+ DATABASE_BUSY: "The database is busy. Please try again shortly.",
235
+ RULE_COULD_NOT_RUN: "A check this request needs could not run. Please try again shortly.",
236
+ INTERNAL_ERROR: "An unexpected error occurred."
237
+ };
238
+ /** The generic sentence for a code; the internal one for anything unlisted. */
239
+ function genericPublicMessage(code) {
240
+ return GENERIC_PUBLIC_MESSAGE[code] ?? GENERIC_PUBLIC_MESSAGE.INTERNAL_ERROR;
241
+ }
242
+ /**
243
+ * Default mapping from DbErrorKind to NextlyError contract. Used by
244
+ * `NextlyError.fromDatabaseError`. Public messages are intentionally generic
245
+ * per spec §13.8 — no DB driver text, no constraint names, no field hints.
246
+ *
247
+ * `satisfies Record<DbErrorKind, ...>` makes the mapping exhaustive at
248
+ * compile time: adding a new DbErrorKind without updating this table is a
249
+ * type error.
250
+ */
251
+ const DB_ERROR_MAPPING = {
252
+ "unique-violation": {
253
+ code: "DUPLICATE",
254
+ statusCode: 409,
255
+ publicMessage: "Resource already exists."
256
+ },
257
+ "fk-violation": {
258
+ code: "VALIDATION_ERROR",
259
+ statusCode: 400,
260
+ publicMessage: "Referenced record does not exist."
261
+ },
262
+ "not-null-violation": {
263
+ code: "VALIDATION_ERROR",
264
+ statusCode: 400,
265
+ publicMessage: "A required field is missing."
266
+ },
267
+ constraint: {
268
+ code: "VALIDATION_ERROR",
269
+ statusCode: 400,
270
+ publicMessage: "The provided data violates a constraint."
271
+ },
272
+ deadlock: {
273
+ code: "CONFLICT",
274
+ statusCode: 409,
275
+ publicMessage: "The operation could not be completed. Please retry."
276
+ },
277
+ "serialization-failure": {
278
+ code: "CONFLICT",
279
+ statusCode: 409,
280
+ publicMessage: "The operation could not be completed. Please retry."
281
+ },
282
+ busy: {
283
+ code: "DATABASE_BUSY",
284
+ statusCode: NEXTLY_ERROR_STATUS.DATABASE_BUSY,
285
+ publicMessage: genericPublicMessage("DATABASE_BUSY"),
286
+ publicData: { retryAfterSeconds: 5 }
287
+ },
288
+ timeout: {
289
+ code: "DATABASE_ERROR",
290
+ statusCode: 500,
291
+ publicMessage: "The operation timed out. Please try again."
292
+ },
293
+ "connection-lost": {
294
+ code: "DATABASE_ERROR",
295
+ statusCode: 500,
296
+ publicMessage: "A temporary database error occurred. Please try again."
297
+ },
298
+ syntax: {
299
+ code: "INTERNAL_ERROR",
300
+ statusCode: 500,
301
+ publicMessage: "An unexpected error occurred."
302
+ },
303
+ internal: {
304
+ code: "INTERNAL_ERROR",
305
+ statusCode: 500,
306
+ publicMessage: "An unexpected error occurred."
307
+ }
308
+ };
309
+ const NEXTLY_ERROR_BRAND = Symbol.for("nextly/NextlyError");
310
+ function hasBrand(value) {
311
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
312
+ return value[NEXTLY_ERROR_BRAND] === true;
313
+ }
314
+ /**
315
+ * Unified error class for Nextly. Used at every throw site across services,
316
+ * direct API, auth, and plugins. Carries two distinct payloads:
317
+ *
318
+ * - Public (`code`, `publicMessage`, `publicData`, `statusCode`, `messageKey`)
319
+ * sent in HTTP responses and Server Action results.
320
+ * - Log (`logMessage`, `logContext`, `cause`, stack trace)
321
+ * written to the server logger; never serialised to the wire.
322
+ *
323
+ * Use the static factories (notFound, forbidden, validation, ...) for the
324
+ * common cases. Use the free-form constructor for plugin codes or one-off
325
+ * shapes.
326
+ */
327
+ var NextlyError = class NextlyError extends Error {
328
+ code;
329
+ statusCode;
330
+ publicMessage;
331
+ publicData;
332
+ messageKey;
333
+ logMessage;
334
+ logContext;
335
+ cause;
336
+ timestamp;
337
+ constructor(opts) {
338
+ super(opts.publicMessage);
339
+ this.name = "NextlyError";
340
+ this.code = opts.code;
341
+ this.publicMessage = opts.publicMessage;
342
+ this.publicData = opts.publicData;
343
+ this.messageKey = opts.messageKey;
344
+ this.logMessage = opts.logMessage;
345
+ this.logContext = opts.logContext;
346
+ this.cause = opts.cause;
347
+ this.timestamp = /* @__PURE__ */ new Date();
348
+ this.statusCode = NextlyError.resolveStatusCode(opts);
349
+ Error.captureStackTrace?.(this, NextlyError);
350
+ }
351
+ static {
352
+ NextlyError.prototype[NEXTLY_ERROR_BRAND] = true;
353
+ }
354
+ static resolveStatusCode(opts) {
355
+ if (typeof opts.statusCode === "number") return opts.statusCode;
356
+ if (opts.code in NEXTLY_ERROR_STATUS) return NEXTLY_ERROR_STATUS[opts.code];
357
+ return 500;
358
+ }
359
+ /** HTTP-safe JSON. Strips logMessage / logContext / cause / stack. */
360
+ toResponseJSON(requestId) {
361
+ const json = {
362
+ code: String(this.code),
363
+ message: this.publicMessage,
364
+ requestId
365
+ };
366
+ if (this.messageKey) json.messageKey = this.messageKey;
367
+ if (this.publicData !== void 0) json.data = this.publicData;
368
+ return json;
369
+ }
370
+ /** Operator-facing JSON for log lines. Includes everything. */
371
+ toLogJSON(requestId) {
372
+ return {
373
+ code: this.code,
374
+ statusCode: this.statusCode,
375
+ publicMessage: this.publicMessage,
376
+ messageKey: this.messageKey,
377
+ logMessage: this.logMessage,
378
+ logContext: this.logContext,
379
+ cause: this.cause ? {
380
+ name: this.cause.name,
381
+ message: this.cause.message,
382
+ stack: this.cause.stack
383
+ } : void 0,
384
+ timestamp: this.timestamp.toISOString(),
385
+ requestId
386
+ };
387
+ }
388
+ static invalidCredentials(opts) {
389
+ return new NextlyError({
390
+ code: "AUTH_INVALID_CREDENTIALS",
391
+ publicMessage: "Invalid email or password.",
392
+ logMessage: "Login failed",
393
+ logContext: opts?.logContext
394
+ });
395
+ }
396
+ /**
397
+ * The password was correct and the address is unverified. Thrown only once
398
+ * the password is proven, so only someone who holds it learns the address
399
+ * is unverified; every other refusal stays
400
+ * {@link NextlyError.invalidCredentials}.
401
+ */
402
+ static emailNotVerified(opts) {
403
+ return new NextlyError({
404
+ code: "EMAIL_NOT_VERIFIED",
405
+ publicMessage: "Verify your email address to sign in. Check your inbox for the link.",
406
+ logMessage: "Login refused: email not verified",
407
+ logContext: opts?.logContext
408
+ });
409
+ }
410
+ static authRequired(opts) {
411
+ return new NextlyError({
412
+ code: "AUTH_REQUIRED",
413
+ publicMessage: "Authentication required.",
414
+ logContext: opts?.logContext
415
+ });
416
+ }
417
+ /**
418
+ * Distinct from `authRequired`: the caller was authenticated but the
419
+ * session token expired. Clients key on the TOKEN_EXPIRED *code* to
420
+ * silently refresh and retry rather than redirecting to login; the public
421
+ * message stays the generic spec §13.6 string ("Authentication required.")
422
+ * so the wire never reveals the session state — same as `authRequired`.
423
+ */
424
+ static tokenExpired(opts) {
425
+ return new NextlyError({
426
+ code: "TOKEN_EXPIRED",
427
+ publicMessage: "Authentication required.",
428
+ logContext: opts?.logContext
429
+ });
430
+ }
431
+ static notFound(opts) {
432
+ return new NextlyError({
433
+ code: "NOT_FOUND",
434
+ publicMessage: opts?.message ?? "Not found.",
435
+ cause: opts?.cause,
436
+ logContext: opts?.logContext
437
+ });
438
+ }
439
+ static forbidden(opts) {
440
+ return new NextlyError({
441
+ code: "FORBIDDEN",
442
+ publicMessage: "You don't have permission to perform this action.",
443
+ publicData: opts?.publicData,
444
+ cause: opts?.cause,
445
+ logContext: opts?.logContext
446
+ });
447
+ }
448
+ /**
449
+ * Something only a signed-in person can do, asked by a caller that is not
450
+ * one: an API key, or a request acting as no person. Forbidden, and the
451
+ * message says so, since it is about what kind of caller asked, not about
452
+ * the caller's permissions. `doing` completes "Only a signed-in person can".
453
+ */
454
+ static personOnly(opts) {
455
+ return new NextlyError({
456
+ code: "FORBIDDEN",
457
+ publicMessage: `Only a signed-in person can ${opts.doing}.`,
458
+ logContext: opts.logContext
459
+ });
460
+ }
461
+ /**
462
+ * A role or permission built into Nextly, which is never changed or
463
+ * deleted. Forbidden, and the message says so: it is a fact about the role,
464
+ * not about the caller's permissions.
465
+ */
466
+ static builtIn(opts) {
467
+ const done = {
468
+ change: "changed",
469
+ delete: "deleted",
470
+ assign: "assigned",
471
+ inherit: "inherited"
472
+ }[opts.change];
473
+ return new NextlyError({
474
+ code: "FORBIDDEN",
475
+ publicMessage: `This ${opts.thing} is built in, so it can't be ${done}.`,
476
+ logContext: opts.logContext
477
+ });
478
+ }
479
+ /**
480
+ * A request from a site not allowed to make it: its own `Origin` names a
481
+ * site the installation does not allow. Forbidden, and the message says so;
482
+ * the origin is the caller's own, so naming its kind tells them nothing.
483
+ */
484
+ static originRefused(opts) {
485
+ return new NextlyError({
486
+ code: "FORBIDDEN",
487
+ publicMessage: "This request came from a site that isn't allowed to make it.",
488
+ logContext: opts?.logContext
489
+ });
490
+ }
491
+ /**
492
+ * A Single deleted without `force`: Singles hold a site's lasting settings,
493
+ * so they are not deleted from here, only by an admin or CLI clean-up that
494
+ * passes `force`. Forbidden, and the message says so.
495
+ */
496
+ static singleNotDeletable(opts) {
497
+ return new NextlyError({
498
+ code: "FORBIDDEN",
499
+ publicMessage: "A Single can't be deleted from here.",
500
+ logContext: opts?.logContext
501
+ });
502
+ }
503
+ /**
504
+ * A collection, Single or component defined in code, which is changed by
505
+ * changing its code and not from here. Forbidden, and the message says so:
506
+ * it is a fact about the thing, not about the caller's permissions, so it
507
+ * names no permission and no policy. The lock's detail goes to the log
508
+ * through `logContext`.
509
+ */
510
+ static definedInCode(opts) {
511
+ return new NextlyError({
512
+ code: "FORBIDDEN",
513
+ publicMessage: `This ${opts.thing} is defined in code, so it can't be ${opts.change === "change" ? "changed" : "deleted"} here.`,
514
+ logContext: opts.logContext
515
+ });
516
+ }
517
+ /**
518
+ * A write to an entry of a collection or Single removed from code: its
519
+ * registry row says the app's code defines it, and the running configuration
520
+ * no longer declares it. Its entries are read-only until it is retired or
521
+ * declared again, so the message names the entity, says what happened and
522
+ * gives both ways out. `publicData` carries the kind and the slug, which the
523
+ * caller named, so a client can mark the entity without parsing the sentence.
524
+ */
525
+ static removedFromCode(opts) {
526
+ const thing = opts.kind === "single" ? "Single" : "collection";
527
+ const its = opts.kind === "single" ? "it" : "its entries";
528
+ return new NextlyError({
529
+ code: "ENTITY_REMOVED_FROM_CODE",
530
+ publicMessage: `The ${thing} "${opts.slug}" was removed from code, so ${its} can't be changed. To retire it, run \`nextly migrate:create\` and then \`nextly migrate\`. To keep it, declare it again in nextly.config.ts.`,
531
+ publicData: {
532
+ kind: opts.kind,
533
+ slug: opts.slug
534
+ },
535
+ logContext: {
536
+ kind: opts.kind,
537
+ slug: opts.slug,
538
+ ...opts.logContext
539
+ }
540
+ });
541
+ }
542
+ /**
543
+ * A read or write of a collection or Single the database has not been
544
+ * migrated for: the column of one of its declared fields is missing, its
545
+ * table is missing, or this running instance never registered it (an
546
+ * entity a migration added after the instance started). The message names
547
+ * the entity, the field or the table, and `nextly migrate`; the driver's
548
+ * error stays on `cause`, for the log, so no SQL reaches the answer.
549
+ */
550
+ static notMigrated(opts) {
551
+ const { cause, logContext, ...publicData } = opts;
552
+ const entity = `${publicData.kind === "single" ? "Single" : "collection"} "${publicData.slug}"`;
553
+ const field = publicData.field === void 0 ? "a field" : `the field "${publicData.field}"`;
554
+ const table = publicData.table === void 0 ? "" : ` "${publicData.table}"`;
555
+ const publicMessage = publicData.reason === "column" ? `The database has not been migrated for ${field} of the ${entity}. Run \`nextly migrate\`.` : publicData.reason === "table" ? `The database has not been migrated for the ${entity}: its table${table} does not exist. Run \`nextly migrate\`.` : `The ${entity}${publicData.table === void 0 ? "" : ` (table "${publicData.table}")`} is not registered in this running instance. Run \`nextly migrate\`, then restart the server.`;
556
+ return new NextlyError({
557
+ code: "ENTITY_NOT_MIGRATED",
558
+ publicMessage,
559
+ publicData,
560
+ logMessage: "The database has not been migrated for this entity",
561
+ logContext: {
562
+ ...publicData,
563
+ ...logContext
564
+ },
565
+ cause
566
+ });
567
+ }
568
+ /**
569
+ * An autosave where the collection or Single does not autosave: its owner
570
+ * switched autosave off, or it keeps no drafts to autosave into. Forbidden,
571
+ * and the message says so, since it is a setting and not a permission.
572
+ */
573
+ static autosaveOff(opts) {
574
+ return new NextlyError({
575
+ code: "FORBIDDEN",
576
+ publicMessage: `Autosave is turned off for this ${opts.scopeKind === "single" ? "Single" : "collection"}.`,
577
+ logContext: opts.logContext
578
+ });
579
+ }
580
+ /**
581
+ * A submit for review naming a step that does not submit: an approval, a
582
+ * request for changes or a move. Its own code, so a caller that may only
583
+ * submit is told this is not a step it can take this way, never the refusal
584
+ * the step itself would meet. Names the step, the caller's own word.
585
+ */
586
+ static stepNotSubmit(opts) {
587
+ return new NextlyError({
588
+ code: "WORKFLOW_STEP_NOT_SUBMIT",
589
+ publicMessage: "That step does not submit for review.",
590
+ publicData: { step: opts.step },
591
+ logContext: opts.logContext
592
+ });
593
+ }
594
+ /**
595
+ * A submit for review naming no step, of a part whose stage no submit step
596
+ * leaves: content already in review, or a workflow that enters review by
597
+ * another kind of step. Names the part and its stage, which a read of the
598
+ * document tells the caller anyway.
599
+ */
600
+ static noSubmitStep(opts) {
601
+ return new NextlyError({
602
+ code: "WORKFLOW_NO_SUBMIT_STEP",
603
+ publicMessage: "No step submits this content for review from the stage it is in.",
604
+ publicData: {
605
+ part: opts.part,
606
+ stage: opts.stage
607
+ },
608
+ logContext: opts.logContext
609
+ });
610
+ }
611
+ /**
612
+ * An API key refused because its role allows more than the person creating
613
+ * it may do. The sentence is FORBIDDEN's and names no permission; which one
614
+ * exceeded goes to the log through `logContext`. The code is its own, so a
615
+ * client can tell "choose a smaller role" from plain FORBIDDEN.
616
+ */
617
+ static apiKeyRoleAboveCreator(opts) {
618
+ return new NextlyError({
619
+ code: "API_KEY_ROLE_ABOVE_CREATOR",
620
+ publicMessage: genericPublicMessage("FORBIDDEN"),
621
+ logContext: opts?.logContext
622
+ });
623
+ }
624
+ /**
625
+ * A cookie-authenticated write refused because its origin or CSRF token did
626
+ * not check out. The public message names no detail of which check failed;
627
+ * that goes to the log through `logMessage`.
628
+ */
629
+ static csrfFailed(opts) {
630
+ return new NextlyError({
631
+ code: "CSRF_FAILED",
632
+ publicMessage: "This request could not be verified. Reload the page and try again.",
633
+ logMessage: opts?.logMessage,
634
+ logContext: opts?.logContext
635
+ });
636
+ }
637
+ /**
638
+ * A call the caller got wrong, where naming the mistake IS the value of the
639
+ * error.
640
+ *
641
+ * The only factory that takes its public message from the caller. The
642
+ * generic messages elsewhere exist so an HTTP response cannot leak internal
643
+ * detail; this one is for arguments and configuration a developer controls
644
+ * and must be told about — a missing option, an unusable combination — where
645
+ * `internal()` would reduce the one useful sentence to "An unexpected error
646
+ * occurred." Do not pass user-supplied data through it.
647
+ */
648
+ static invalidInput(opts) {
649
+ return new NextlyError({
650
+ code: "INVALID_INPUT",
651
+ publicMessage: opts.message,
652
+ logContext: opts.logContext
653
+ });
654
+ }
655
+ static validation(opts) {
656
+ return new NextlyError({
657
+ code: "VALIDATION_ERROR",
658
+ publicMessage: "Validation failed.",
659
+ publicData: { errors: opts.errors },
660
+ cause: opts.cause,
661
+ logContext: opts.logContext
662
+ });
663
+ }
664
+ static conflict(opts) {
665
+ return new NextlyError({
666
+ code: "CONFLICT",
667
+ publicMessage: opts?.message ?? "The resource has changed since you last loaded it. Please refresh and try again.",
668
+ publicData: opts?.data,
669
+ cause: opts?.cause,
670
+ logContext: {
671
+ reason: opts?.reason,
672
+ ...opts?.logContext
673
+ }
674
+ });
675
+ }
676
+ /**
677
+ * An update made from a version of the document that is no longer its
678
+ * current one. Never retried: the same version stays out of date, so the
679
+ * caller must read the document again and decide.
680
+ *
681
+ * @experimental
682
+ */
683
+ /**
684
+ * An update that said neither which version of a document it was made from
685
+ * nor that it overwrites whatever is stored. Without `bulk`, an update of
686
+ * one document, which sends back the version it read. `bulk` names an
687
+ * update that writes the same values to many documents, which can carry no
688
+ * one document's version: by its ids, which can be given a version each
689
+ * (`keys.revs`), or by a query, which cannot. The keys are the write path's
690
+ * to name, so the message spells them as the request does.
691
+ *
692
+ * @experimental
693
+ */
694
+ static versionRequired(opts) {
695
+ const { version, overwrite, revs } = opts.keys;
696
+ if (opts.bulk === void 0) {
697
+ const one = {
698
+ versionKey: version,
699
+ overwriteKey: overwrite
700
+ };
701
+ return new NextlyError({
702
+ code: "VERSION_REQUIRED",
703
+ publicMessage: `This update must say which version of the document it changes. Send back the \`${version}\` from your last read of it, or set \`${overwrite}: true\` to replace whatever is stored.`,
704
+ publicData: one,
705
+ logContext: opts.logContext
706
+ });
707
+ }
708
+ const byIds = opts.bulk === "ids";
709
+ const data = {
710
+ versionKey: version,
711
+ overwriteKey: overwrite,
712
+ ...byIds ? { revsKey: revs } : {}
713
+ };
714
+ const message = `An update that writes the same values to many documents must set \`${overwrite}: true\`: it can't carry each document's version. Or update each document with its own \`${version}\`.`;
715
+ return new NextlyError({
716
+ code: "VERSION_REQUIRED",
717
+ publicMessage: byIds ? `${message} Or give each document's \`${version}\` in \`${revs}\`.` : message,
718
+ publicData: data,
719
+ logContext: opts.logContext
720
+ });
721
+ }
722
+ static staleVersion(opts) {
723
+ return new NextlyError({
724
+ code: "STALE_VERSION",
725
+ publicMessage: `This document changed since the version you gave. Its current version is ${opts.data.currentVersion}.`,
726
+ publicData: opts.data,
727
+ logContext: opts.logContext
728
+ });
729
+ }
730
+ /**
731
+ * `message` replaces the generic sentence where the caller can name what is
732
+ * already taken without leaking anything, such as a public address and the
733
+ * page holding it.
734
+ */
735
+ static duplicate(opts) {
736
+ return new NextlyError({
737
+ code: "DUPLICATE",
738
+ publicMessage: opts?.message ?? "Resource already exists.",
739
+ logContext: opts?.logContext
740
+ });
741
+ }
742
+ static rateLimited(opts) {
743
+ return new NextlyError({
744
+ code: "RATE_LIMITED",
745
+ publicMessage: "Too many requests. Please try again later.",
746
+ publicData: opts?.retryAfterSeconds !== void 0 ? { retryAfterSeconds: opts.retryAfterSeconds } : void 0,
747
+ logContext: opts?.logContext
748
+ });
749
+ }
750
+ /**
751
+ * A request that waited `pool.connectionTimeoutMs` for a database
752
+ * connection and was given none. The statement or transaction that waited
753
+ * never ran; work committed before it stays committed. The same error
754
+ * `fromDatabaseError` gives a busy DbError, from the same table row.
755
+ */
756
+ static databaseBusy(opts) {
757
+ const busy = DB_ERROR_MAPPING.busy;
758
+ return new NextlyError({
759
+ code: busy.code,
760
+ statusCode: busy.statusCode,
761
+ publicMessage: busy.publicMessage,
762
+ publicData: busy.publicData,
763
+ cause: opts?.cause,
764
+ logContext: opts?.logContext
765
+ });
766
+ }
767
+ /**
768
+ * An access or field rule the request needs could not run, because its own
769
+ * database query waited out the bound for a connection. Not a refusal: the
770
+ * rule never answered. Names the collection or Single whose rule it is, and
771
+ * the field for a field's rule, and says when to retry.
772
+ */
773
+ static ruleCouldNotRun(opts) {
774
+ const publicData = {
775
+ subject: opts.subject,
776
+ ...opts.field !== void 0 ? { field: opts.field } : {},
777
+ retryAfterSeconds: 5
778
+ };
779
+ return new NextlyError({
780
+ code: "RULE_COULD_NOT_RUN",
781
+ statusCode: NEXTLY_ERROR_STATUS.RULE_COULD_NOT_RUN,
782
+ publicMessage: genericPublicMessage("RULE_COULD_NOT_RUN"),
783
+ publicData,
784
+ cause: opts.cause,
785
+ logContext: opts.logContext
786
+ });
787
+ }
788
+ /**
789
+ * What a request boundary answers with for a thrown value that is not a
790
+ * NextlyError: "database busy" when the request waited out its bound for a
791
+ * connection, which is retryable and no fault of the server's code, and an
792
+ * internal error for anything else.
793
+ *
794
+ * The busy case has to be read here because it usually arrives raw:
795
+ * `withDbErrors` converts only DbErrors, so a driver's error passes through
796
+ * services unconverted to the boundary that answers the request.
797
+ */
798
+ static fromUnexpected(error) {
799
+ return NextlyError.busyOr(error, () => NextlyError.internal({ cause: error instanceof Error ? error : void 0 }));
800
+ }
801
+ /**
802
+ * "Database busy" when `error` is a request that waited out its bound for
803
+ * a connection, and `otherwise()` for anything else.
804
+ *
805
+ * For a boundary that answers an unexpected failure with an error of its
806
+ * own choosing rather than an internal one (a 503 for a flow that must not
807
+ * answer on incomplete data), so that a busy database still answers there
808
+ * as it does everywhere else. `fromUnexpected` is this rule with the
809
+ * internal error as its fallback.
810
+ */
811
+ static busyOr(error, otherwise) {
812
+ if (!isDatabaseBusy(error)) return otherwise();
813
+ return NextlyError.databaseBusy({ cause: error instanceof Error ? error : void 0 });
814
+ }
815
+ static internal(opts) {
816
+ return new NextlyError({
817
+ code: "INTERNAL_ERROR",
818
+ publicMessage: "An unexpected error occurred.",
819
+ cause: opts?.cause,
820
+ logContext: opts?.logContext
821
+ });
822
+ }
823
+ /**
824
+ * The app is set up so nextly cannot work: a missing `config`, or a Next.js
825
+ * or React outside the supported ranges. The public message stays generic;
826
+ * what to change goes in `logMessage`, for the operator.
827
+ */
828
+ static configuration(opts) {
829
+ return new NextlyError({
830
+ code: "CONFIGURATION_ERROR",
831
+ publicMessage: "Server configuration error.",
832
+ logMessage: opts.logMessage,
833
+ logContext: opts.logContext
834
+ });
835
+ }
836
+ /**
837
+ * A service outside Nextly failed, such as an email provider, where trying again may help: the
838
+ * job queue records it as an attempt's error and tries again.
839
+ */
840
+ static externalService(opts) {
841
+ return new NextlyError({
842
+ code: "EXTERNAL_SERVICE_ERROR",
843
+ publicMessage: opts.publicMessage,
844
+ logMessage: opts.logMessage,
845
+ cause: opts.cause,
846
+ logContext: opts.logContext
847
+ });
848
+ }
849
+ static serviceUnavailable(opts) {
850
+ return new NextlyError({
851
+ code: "SERVICE_UNAVAILABLE",
852
+ publicMessage: opts?.publicMessage ?? "Service unavailable. Please try again later.",
853
+ logMessage: opts?.logMessage,
854
+ cause: opts?.cause,
855
+ logContext: opts?.logContext
856
+ });
857
+ }
858
+ /**
859
+ * Convert a DbError (or arbitrary unknown thrown by the DB layer) to a
860
+ * NextlyError with a generic public message and rich logContext. Used by
861
+ * `withDbErrors` for auto-conversion (Pattern A) and by services that
862
+ * catch DB errors at boundaries (Pattern B). Spec §8.2 mapping table.
863
+ *
864
+ * Never leaks DB driver text, constraint names, or table names into
865
+ * `publicMessage`. All DB context goes into `logContext`. The original
866
+ * DbError is preserved as `cause`.
867
+ */
868
+ static fromDatabaseError(error) {
869
+ if (isDbError(error)) {
870
+ const mapping = DB_ERROR_MAPPING[error.kind];
871
+ const logContext = {
872
+ dbKind: error.kind,
873
+ dialect: error.dialect
874
+ };
875
+ if (error.code !== void 0) logContext.dbCode = error.code;
876
+ if (error.meta !== void 0) logContext.meta = error.meta;
877
+ return new NextlyError({
878
+ code: mapping.code,
879
+ statusCode: mapping.statusCode,
880
+ publicMessage: mapping.publicMessage,
881
+ publicData: "publicData" in mapping ? mapping.publicData : void 0,
882
+ logMessage: "Database error",
883
+ logContext,
884
+ cause: error
885
+ });
886
+ }
887
+ return new NextlyError({
888
+ code: "INTERNAL_ERROR",
889
+ statusCode: 500,
890
+ publicMessage: "An unexpected error occurred.",
891
+ logMessage: "Non-DbError passed to fromDatabaseError",
892
+ cause: error instanceof Error ? error : void 0,
893
+ logContext: error instanceof Error ? void 0 : { value: String(error) }
894
+ });
895
+ }
896
+ static is(err) {
897
+ return hasBrand(err);
898
+ }
899
+ static isCode(err, code) {
900
+ return hasBrand(err) && err.code === code;
901
+ }
902
+ static isNotFound(err) {
903
+ return NextlyError.isCode(err, "NOT_FOUND");
904
+ }
905
+ static isValidation(err) {
906
+ return NextlyError.isCode(err, "VALIDATION_ERROR");
907
+ }
908
+ static isAuthRequired(err) {
909
+ return NextlyError.isCode(err, "AUTH_REQUIRED");
910
+ }
911
+ static isForbidden(err) {
912
+ return NextlyError.isCode(err, "FORBIDDEN");
913
+ }
914
+ static isConflict(err) {
915
+ return NextlyError.isCode(err, "CONFLICT");
916
+ }
917
+ static isRateLimited(err) {
918
+ return NextlyError.isCode(err, "RATE_LIMITED");
919
+ }
920
+ };
921
+ // ../nextly/dist/validate-external-url-Dpn-k4nU.mjs
922
+ /** Default response body cap: reject anything larger before buffering it all. */
923
+ /**
924
+ * How many bytes a bounded external read may buffer, absent a caller's own cap.
925
+ *
926
+ * Exported for the same reason as the deadline below: an adapter that never
927
+ * touches `safeFetch` still owes callers this default, and restating the number
928
+ * gives the tree two that drift.
929
+ */
930
+ const DEFAULT_MAX_RESPONSE_BYTES = 10485760;
931
+ /** Default overall deadline covering DNS + connect + TLS + response. */
932
+ /**
933
+ * How long a bounded external read may take, absent a caller's own limit.
934
+ *
935
+ * Exported so a caller that must begin the clock EARLIER — a storage adapter
936
+ * bounding a metadata lookup as well as the fetch that follows — uses this
937
+ * number rather than restating it. Two spellings of one default agree today and
938
+ * drift the first time either is tuned.
939
+ */
940
+ const DEFAULT_TIMEOUT_MS = 3e4;
941
+ // ../nextly/dist/storage/read-errors.mjs
942
+ /**
943
+ * The one way the storage layer says a read exceeded the caller's cap.
944
+ *
945
+ * `StorageReadOptions.maxBytes` is part of the adapter contract, so what happens
946
+ * when it is exceeded belongs to the contract too. Without this each backend
947
+ * refuses in its own vocabulary — the URL-addressed ones through a fetch error
948
+ * carrying a `reason`, S3 through whatever its own code threw — and a caller
949
+ * wanting to tell "too large" from "could not read" has to know which adapter it
950
+ * is talking to. That is the thing an adapter contract exists to stop.
951
+ *
952
+ * Distinct from a generic internal failure because callers ACT on the
953
+ * difference. The email attachment path answers an over-cap read with
954
+ * `ATTACHMENT_SIZE_EXCEEDED`, which tells an author to attach something smaller;
955
+ * a storage failure tells them nothing they can act on. Collapsing the two turns
956
+ * a fixable refusal into an opaque error, which is the same conflation this
957
+ * contract already draws between a missing key and an unreachable store.
958
+ *
959
+ * @module storage/read-errors
960
+ */
961
+ /**
962
+ * A read refused because the object is larger than the caller allowed.
963
+ *
964
+ * Carries the numbers rather than only a message, so a caller can say what the
965
+ * limit was without parsing prose — and so the message itself stays free of the
966
+ * key, which should not travel to whoever asked for the file.
967
+ */
968
+ var StorageReadTooLargeError = class extends NextlyError {
969
+ path;
970
+ maxBytes;
971
+ size;
972
+ constructor(path, maxBytes, size) {
973
+ super({
974
+ code: "STORAGE_READ_TOO_LARGE",
975
+ publicMessage: "The stored file is larger than the limit for this read.",
976
+ logContext: {
977
+ path,
978
+ maxBytes,
979
+ ...size === void 0 ? {} : { size }
980
+ }
981
+ });
982
+ this.path = path;
983
+ this.maxBytes = maxBytes;
984
+ this.size = size;
985
+ }
986
+ };
987
+ // ../nextly/dist/storage/fetch-stored-bytes.mjs
988
+ /** The deadline a stored read runs under when the caller names none. */
989
+ const DEFAULT_READ_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
990
+ /** The byte cap a stored read runs under when the caller names none. */
991
+ const DEFAULT_READ_MAX_BYTES = DEFAULT_MAX_RESPONSE_BYTES;
992
+ /**
993
+ * The bounds a read actually runs under, defaults filled in.
994
+ *
995
+ * ONE place, because every adapter needs the same answer and the ones that
996
+ * derived it themselves diverged: the URL-backed pair inherited `safeFetch`'s
997
+ * cap and deadline for free, while the local and S3 adapters — which never
998
+ * touch `safeFetch` — applied NO bound at all when the caller named none.
999
+ * `StorageReadOptions` promises the default either way, and a production caller
1000
+ * reading media without options got it from two of four backends.
1001
+ *
1002
+ * Filling the defaults here rather than per adapter is what makes the promise
1003
+ * true by construction rather than by four implementations agreeing.
1004
+ */
1005
+ function resolveReadBounds(options) {
1006
+ return {
1007
+ maxBytes: options?.maxBytes ?? DEFAULT_READ_MAX_BYTES,
1008
+ timeoutMs: options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS
1009
+ };
1010
+ }
1011
+ // src/storage-key.ts
1012
+ /**
1013
+ * The key a new file is stored under in the bucket.
1014
+ *
1015
+ * One definition for both ways a file arrives: a server upload
1016
+ * (`S3StorageAdapter.upload`, given the collection's prefix as `folder`) and a
1017
+ * direct browser upload (the plugin's `getClientUploadUrl`, which builds the
1018
+ * key before signing it), so the two cannot disagree about the slash after
1019
+ * the prefix and store one collection's files in two places.
1020
+ *
1021
+ * @module storage-key
1022
+ */
1023
+ /**
1024
+ * Sanitize a filename to prevent directory traversal and S3 key issues.
1025
+ *
1026
+ * Keeps only the basename, and replaces every character outside
1027
+ * `a-z A-Z 0-9 . _ -` with a hyphen.
1028
+ *
1029
+ * @param filename - Original filename
1030
+ * @returns Sanitized filename safe for S3 keys
1031
+ */
1032
+ function sanitizeFilename(filename) {
1033
+ return (filename.split(/[/\\]/).pop() || filename).replace(/[^a-zA-Z0-9._-]/g, "-");
1034
+ }
1035
+ /**
1036
+ * The folder without its trailing slashes, so `"proofs"` and `"proofs/"` name
1037
+ * the same folder and a folder of only slashes names none.
1038
+ *
1039
+ * Trimmed by a loop rather than a pattern: the value is configuration, and a
1040
+ * loop has no backtracking for a long run of slashes to exploit.
1041
+ */
1042
+ function folderName(folder) {
1043
+ if (!folder) return "";
1044
+ let end = folder.length;
1045
+ while (end > 0 && folder[end - 1] === "/") end--;
1046
+ return folder.slice(0, end);
1047
+ }
1048
+ /**
1049
+ * Generate a unique storage key with a date-based layout.
1050
+ *
1051
+ * Creates keys in the format `{folder}/{year}/{month}/{uuid}-{sanitized-filename}`,
1052
+ * or `{year}/{month}/{uuid}-{sanitized-filename}` with no folder. The folder
1053
+ * may be written with or without a trailing slash; the key has exactly one.
1054
+ *
1055
+ * @param filename - Original filename (will be sanitized)
1056
+ * @param folder - Optional folder/prefix for organizing uploads
1057
+ * @returns Generated storage key
1058
+ */
1059
+ function generateStorageKey(filename, folder) {
1060
+ const sanitized = sanitizeFilename(filename);
1061
+ const uuid = crypto.randomUUID();
1062
+ const date = /* @__PURE__ */ new Date();
1063
+ const year = date.getFullYear();
1064
+ const month = String(date.getMonth() + 1).padStart(2, "0");
1065
+ const name = folderName(folder);
1066
+ return `${name ? `${name}/${year}/${month}` : `${year}/${month}`}/${uuid}-${sanitized}`;
1067
+ }
7
1068
  // src/adapter.ts
1069
+ /**
1070
+ * S3 Storage Adapter
1071
+ *
1072
+ * Stores files on AWS S3 or S3-compatible services (Cloudflare R2, MinIO, DigitalOcean Spaces).
1073
+ * Uses AWS SDK v3 with automatic multipart upload for large files (>5MB).
1074
+ *
1075
+ * Features:
1076
+ * - Automatic multipart upload via @aws-sdk/lib-storage
1077
+ * - Pre-signed URL generation for client-side uploads
1078
+ * - Signed URL generation for private file access
1079
+ * - Cloudflare R2 support (S3-compatible API)
1080
+ * - Custom endpoint support (MinIO, DigitalOcean Spaces)
1081
+ * - CDN URL override support
1082
+ * - File metadata retrieval
1083
+ *
1084
+ * @example AWS S3
1085
+ * ```typescript
1086
+ * const adapter = new S3StorageAdapter({
1087
+ * bucket: 'my-media-bucket',
1088
+ * region: 'us-east-1',
1089
+ * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
1090
+ * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
1091
+ * collections: { media: true }
1092
+ * });
1093
+ * ```
1094
+ *
1095
+ * @example Cloudflare R2
1096
+ * ```typescript
1097
+ * const adapter = new S3StorageAdapter({
1098
+ * bucket: 'my-media',
1099
+ * region: 'auto',
1100
+ * accessKeyId: process.env.R2_ACCESS_KEY_ID!,
1101
+ * secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
1102
+ * endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
1103
+ * publicUrl: 'https://pub-abc.r2.dev',
1104
+ * collections: { media: true }
1105
+ * });
1106
+ * ```
1107
+ *
1108
+ * @example MinIO (self-hosted)
1109
+ * ```typescript
1110
+ * const adapter = new S3StorageAdapter({
1111
+ * bucket: 'my-bucket',
1112
+ * region: 'us-east-1',
1113
+ * accessKeyId: process.env.MINIO_ACCESS_KEY!,
1114
+ * secretAccessKey: process.env.MINIO_SECRET_KEY!,
1115
+ * endpoint: 'http://localhost:9000',
1116
+ * forcePathStyle: true,
1117
+ * collections: { media: true }
1118
+ * });
1119
+ * ```
1120
+ */
1121
+ /**
1122
+ * The Cache-Control a private object is stored and answered with: no cache,
1123
+ * shared or the browser's own, may keep a copy, so every later request has to
1124
+ * come back through Nextly's checked route.
1125
+ */
1126
+ const PRIVATE_CACHE_CONTROL = "private, no-store";
1127
+ /**
1128
+ * S3 Storage Adapter
1129
+ *
1130
+ * Implements the IStorageAdapter interface for AWS S3 and S3-compatible services.
1131
+ * Provides full support for uploads, downloads, signed URLs, and client-side uploads.
1132
+ */
1133
+ /**
1134
+ * The SDK request options carrying the caller's deadline, or none.
1135
+ *
1136
+ * A free function rather than a branch inside `read`, because it is the only
1137
+ * part of that method with nothing to do with telling an absent key apart from
1138
+ * an unreachable bucket — which is the distinction a reader has to hold in
1139
+ * their head there.
1140
+ *
1141
+ * `AbortSignal.timeout` rather than a controller and a `setTimeout`: it needs no
1142
+ * clearing, so it cannot leak a timer when the read resolves first. The signal
1143
+ * covers the BODY as well as the request, because the SDK threads it through
1144
+ * the response stream — and a backend that answers headers promptly and then
1145
+ * stalls mid-transfer is exactly the case a request-only deadline misses.
1146
+ */
1147
+ function abortAfter(options) {
1148
+ return { abortSignal: AbortSignal.timeout(resolveReadBounds(options).timeoutMs) };
1149
+ }
8
1150
  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
- }
1151
+ config;
1152
+ client = null;
1153
+ resolvedConfig;
1154
+ isR2;
1155
+ /**
1156
+ * Create a new S3 storage adapter.
1157
+ *
1158
+ * The bucket and region are deliberately NOT checked here, and the SDK
1159
+ * client is deliberately not built. This constructor runs while the host's
1160
+ * config file is evaluated, so a throw would stop every command —
1161
+ * including the schema-only ones that never touch storage. Both the checks
1162
+ * and the client construction move to the first storage operation
1163
+ * ({@link ensureClient} and {@link ensureConfigured}), which refuse with
1164
+ * the same messages a missing bucket or region has always produced.
1165
+ *
1166
+ * @param config - S3 storage configuration
1167
+ */
1168
+ constructor(config) {
1169
+ this.config = config;
1170
+ this.isR2 = config.endpoint?.includes("r2.cloudflarestorage.com") ?? false;
1171
+ this.resolvedConfig = {
1172
+ bucket: config.bucket,
1173
+ region: config.region,
1174
+ endpoint: config.endpoint,
1175
+ forcePathStyle: config.forcePathStyle ?? false,
1176
+ acl: config.acl ?? "private",
1177
+ publicUrl: config.publicUrl,
1178
+ cacheControl: config.cacheControl ?? "public, max-age=31536000",
1179
+ contentDisposition: config.contentDisposition,
1180
+ signedUrlExpiresIn: config.signedUrlExpiresIn ?? 3600
1181
+ };
1182
+ }
1183
+ /**
1184
+ * Validate that bucket and region are present.
1185
+ *
1186
+ * @throws Error if bucket is not provided
1187
+ * @throws Error if region is not provided
1188
+ */
1189
+ ensureConfigured() {
1190
+ if (!this.config.bucket) throw new Error("@nextly/storage-s3: bucket is required");
1191
+ if (!this.config.region) throw new Error("@nextly/storage-s3: region is required");
1192
+ }
1193
+ /**
1194
+ * Validate the stored configuration and build the SDK client, at the
1195
+ * first use that needs them.
1196
+ *
1197
+ * The refusals are the ones the constructor used to throw, in the same
1198
+ * order, so an operator with a genuinely misconfigured deployment sees
1199
+ * the message they have always seen — at the moment the value was
1200
+ * actually needed rather than at config load. The client is built once
1201
+ * and reused.
1202
+ *
1203
+ * @throws Error if bucket is not provided
1204
+ * @throws Error if region is not provided
1205
+ */
1206
+ ensureClient() {
1207
+ if (this.client) return this.client;
1208
+ this.ensureConfigured();
1209
+ const credentials = this.buildCredentials();
1210
+ this.client = new _aws_sdk_client_s3.S3Client({
1211
+ region: this.config.region,
1212
+ endpoint: this.config.endpoint,
1213
+ credentials,
1214
+ forcePathStyle: this.resolvedConfig.forcePathStyle,
1215
+ ...this.config.config
1216
+ });
1217
+ return this.client;
1218
+ }
1219
+ /**
1220
+ * Build AWS credentials from config.
1221
+ * Supports explicit credentials or falls back to SDK default chain.
1222
+ */
1223
+ buildCredentials() {
1224
+ if (this.config.accessKeyId && this.config.secretAccessKey) return {
1225
+ accessKeyId: this.config.accessKeyId,
1226
+ secretAccessKey: this.config.secretAccessKey
1227
+ };
1228
+ if (this.config.config?.credentials) return;
1229
+ }
1230
+ /**
1231
+ * Upload file to S3.
1232
+ *
1233
+ * Uses AWS SDK v3's Upload class from @aws-sdk/lib-storage which:
1234
+ * - Automatically handles multipart upload for large files (>5MB)
1235
+ * - Provides progress tracking capability
1236
+ * - Includes retry logic
1237
+ * - Optimizes upload performance
1238
+ *
1239
+ * @param buffer - File content as Buffer
1240
+ * @param options - Upload options (filename, mimeType, folder, collection)
1241
+ * @returns Upload result with URL and storage path
1242
+ */
1243
+ async upload(buffer, options) {
1244
+ const client = this.ensureClient();
1245
+ const key = generateStorageKey(options.filename, options.folder);
1246
+ const uploadParams = {
1247
+ Bucket: this.resolvedConfig.bucket,
1248
+ Key: key,
1249
+ Body: buffer,
1250
+ ContentType: options.contentType || options.mimeType,
1251
+ CacheControl: this.resolvedConfig.cacheControl
1252
+ };
1253
+ if (!this.isR2) uploadParams.ACL = this.resolvedConfig.acl;
1254
+ const disposition = options.contentDisposition ?? this.resolvedConfig.contentDisposition;
1255
+ if (disposition) {
1256
+ const filename = sanitizeFilename(options.filename);
1257
+ uploadParams.ContentDisposition = disposition === "attachment" ? `attachment; filename="${filename}"` : "inline";
1258
+ }
1259
+ uploadParams.Metadata = { "original-filename": options.filename };
1260
+ const url = this.getPublicUrl(key);
1261
+ await new _aws_sdk_lib_storage.Upload({
1262
+ client,
1263
+ params: uploadParams
1264
+ }).done();
1265
+ return {
1266
+ url,
1267
+ path: key
1268
+ };
1269
+ }
1270
+ /**
1271
+ * Write bytes at exactly `filePath`, beside a file already in the bucket.
1272
+ *
1273
+ * Core uses it to keep a file made from a stored one, such as a resized
1274
+ * copy of an image, under a key derived from the original's. One request,
1275
+ * since such a file is small, with the same cache setting and access as an
1276
+ * upload, so it is served the way its original is.
1277
+ *
1278
+ * @experimental
1279
+ */
1280
+ async uploadAt(filePath, buffer, options) {
1281
+ const client = this.ensureClient();
1282
+ const params = {
1283
+ Bucket: this.resolvedConfig.bucket,
1284
+ Key: filePath,
1285
+ Body: buffer,
1286
+ ContentType: options.mimeType,
1287
+ CacheControl: this.resolvedConfig.cacheControl
1288
+ };
1289
+ if (!this.isR2) params.ACL = this.resolvedConfig.acl;
1290
+ const url = this.getPublicUrl(filePath);
1291
+ await client.send(new _aws_sdk_client_s3.PutObjectCommand(params));
1292
+ return {
1293
+ url,
1294
+ path: filePath
1295
+ };
1296
+ }
1297
+ /**
1298
+ * Store a private file at exactly `key`, the key core made for it.
1299
+ *
1300
+ * Unlike {@link upload}: no public address is formed (so an R2 bucket needs
1301
+ * no `publicUrl`), the original file name goes into neither the key nor the
1302
+ * object's metadata, the object is stored never to be cached, and its ACL is
1303
+ * `private` whatever the adapter's own `acl` says (R2 has no ACLs, and keeps
1304
+ * a bucket private unless public access is turned on for it).
1305
+ *
1306
+ * @experimental
1307
+ */
1308
+ async putPrivate(key, buffer, options) {
1309
+ const client = this.ensureClient();
1310
+ const params = {
1311
+ Bucket: this.resolvedConfig.bucket,
1312
+ Key: key,
1313
+ Body: buffer,
1314
+ ContentType: options.mimeType,
1315
+ CacheControl: PRIVATE_CACHE_CONTROL
1316
+ };
1317
+ if (!this.isR2) params.ACL = "private";
1318
+ await new _aws_sdk_lib_storage.Upload({
1319
+ client,
1320
+ params
1321
+ }).done();
1322
+ }
1323
+ /**
1324
+ * A pre-signed URL a browser sends one private file to, at exactly `key`.
1325
+ * Binds the type and exact length as {@link getPresignedUploadUrl} does,
1326
+ * and writes the object private and never cached.
1327
+ *
1328
+ * @experimental
1329
+ */
1330
+ async getPrivateUploadUrl(key, mimeType, options) {
1331
+ return this.presignPut(key, mimeType, {
1332
+ cacheControl: PRIVATE_CACHE_CONTROL,
1333
+ acl: "private",
1334
+ expiresIn: options.expiresIn,
1335
+ contentLength: options.contentLength
1336
+ });
1337
+ }
1338
+ /**
1339
+ * A link to a private file that lasts `options.expiresIn` seconds (at most
1340
+ * the configured `signedUrlExpiresIn`). The bucket answers it with the
1341
+ * given Content-Disposition and type, and with a Cache-Control that lets no
1342
+ * cache keep it, whatever the object itself was stored with.
1343
+ *
1344
+ * @experimental
1345
+ */
1346
+ async getPrivateDownloadUrl(key, options) {
1347
+ const client = this.ensureClient();
1348
+ const command = new _aws_sdk_client_s3.GetObjectCommand({
1349
+ Bucket: this.resolvedConfig.bucket,
1350
+ Key: key,
1351
+ ResponseContentDisposition: options.contentDisposition,
1352
+ ResponseCacheControl: PRIVATE_CACHE_CONTROL,
1353
+ ...options.contentType !== void 0 ? { ResponseContentType: options.contentType } : {}
1354
+ });
1355
+ return (0, _aws_sdk_s3_request_presigner.getSignedUrl)(client, command, { expiresIn: Math.min(options.expiresIn, this.resolvedConfig.signedUrlExpiresIn) });
1356
+ }
1357
+ /**
1358
+ * Delete file from S3.
1359
+ *
1360
+ * @param filePath - Storage path/key to delete
1361
+ */
1362
+ async delete(filePath) {
1363
+ const client = this.ensureClient();
1364
+ const command = new _aws_sdk_client_s3.DeleteObjectCommand({
1365
+ Bucket: this.resolvedConfig.bucket,
1366
+ Key: filePath
1367
+ });
1368
+ await client.send(command);
1369
+ }
1370
+ /**
1371
+ * Bulk delete files from S3 using a single API call per 1000 keys.
1372
+ *
1373
+ * Uses AWS SDK v3's DeleteObjectsCommand which supports up to 1000 keys per
1374
+ * request. Automatically batches larger arrays and collects per-key results.
1375
+ *
1376
+ * @param filePaths - Storage paths/keys to delete
1377
+ * @returns Object with arrays of successful and failed deletions
1378
+ */
1379
+ async bulkDelete(filePaths) {
1380
+ const client = this.ensureClient();
1381
+ const successful = [];
1382
+ const failed = [];
1383
+ const maxBatchSize = 1e3;
1384
+ for (let i = 0; i < filePaths.length; i += maxBatchSize) {
1385
+ const batch = filePaths.slice(i, i + maxBatchSize);
1386
+ const command = new _aws_sdk_client_s3.DeleteObjectsCommand({
1387
+ Bucket: this.resolvedConfig.bucket,
1388
+ Delete: {
1389
+ Objects: batch.map((key) => ({ Key: key })),
1390
+ Quiet: false
1391
+ }
1392
+ });
1393
+ const response = await client.send(command);
1394
+ if (response.Errors && response.Errors.length > 0) {
1395
+ for (const err of response.Errors) if (err.Key) failed.push({
1396
+ filePath: err.Key,
1397
+ error: err.Message ?? "Unknown S3 delete error"
1398
+ });
1399
+ }
1400
+ if (response.Deleted) {
1401
+ for (const del of response.Deleted) if (del.Key) successful.push(del.Key);
1402
+ }
1403
+ }
1404
+ return {
1405
+ successful,
1406
+ failed
1407
+ };
1408
+ }
1409
+ /**
1410
+ * Check if file exists in S3.
1411
+ *
1412
+ * Uses HeadObject command which is more efficient than GetObject
1413
+ * for existence checks (doesn't download the file).
1414
+ *
1415
+ * @param filePath - Storage path/key to check
1416
+ * @returns true if file exists, false otherwise
1417
+ */
1418
+ async exists(filePath) {
1419
+ const client = this.ensureClient();
1420
+ try {
1421
+ const command = new _aws_sdk_client_s3.HeadObjectCommand({
1422
+ Bucket: this.resolvedConfig.bucket,
1423
+ Key: filePath
1424
+ });
1425
+ await client.send(command);
1426
+ return true;
1427
+ } catch (error) {
1428
+ if (this.isNotFoundError(error)) return false;
1429
+ throw error;
1430
+ }
1431
+ }
1432
+ /**
1433
+ * Get public URL for S3 file.
1434
+ *
1435
+ * Priority order:
1436
+ * 1. Custom publicUrl (CDN or custom domain) if configured
1437
+ * 2. Standard S3 URL based on region and bucket
1438
+ *
1439
+ * For R2: Requires publicUrl configuration (R2 has no default public URLs).
1440
+ *
1441
+ * @param filePath - Storage path/key
1442
+ * @returns Public URL to access the file
1443
+ * @throws Error if R2 is used without publicUrl configuration
1444
+ */
1445
+ /**
1446
+ * Every object in the bucket, by key, with when it was last written, a page
1447
+ * of up to 1,000 at a time.
1448
+ */
1449
+ async *list() {
1450
+ const client = this.ensureClient();
1451
+ let token;
1452
+ do {
1453
+ const page = await client.send(new _aws_sdk_client_s3.ListObjectsV2Command({
1454
+ Bucket: this.resolvedConfig.bucket,
1455
+ ContinuationToken: token
1456
+ }));
1457
+ for (const object of page.Contents ?? []) if (object.Key) yield {
1458
+ path: object.Key,
1459
+ lastModified: object.LastModified
1460
+ };
1461
+ token = page.IsTruncated ? page.NextContinuationToken : void 0;
1462
+ } while (token);
1463
+ }
1464
+ getPublicUrl(filePath) {
1465
+ this.ensureConfigured();
1466
+ if (this.resolvedConfig.publicUrl) return `${this.resolvedConfig.publicUrl.replace(/\/$/, "")}/${filePath}`;
1467
+ 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. A collection of private files needs none: its files have no public address.");
1468
+ return `https://${this.resolvedConfig.bucket}.s3.${this.resolvedConfig.region}.amazonaws.com/${filePath}`;
1469
+ }
1470
+ /**
1471
+ * Get storage type identifier.
1472
+ *
1473
+ * Returns "s3" for all S3-compatible services (AWS S3, R2, MinIO, etc.)
1474
+ * as they all use the S3 API.
1475
+ */
1476
+ getType() {
1477
+ return "s3";
1478
+ }
1479
+ /**
1480
+ * Get adapter info including capabilities.
1481
+ *
1482
+ * @returns Adapter info with type, name, and capability flags
1483
+ */
1484
+ getInfo() {
1485
+ return {
1486
+ type: "s3",
1487
+ name: "S3StorageAdapter",
1488
+ supportsSignedUrls: true,
1489
+ supportsClientUploads: true,
1490
+ supportsPrivateFiles: !this.resolvedConfig.publicUrl
1491
+ };
1492
+ }
1493
+ /**
1494
+ * Get file metadata from S3.
1495
+ *
1496
+ * Retrieves file information including size, content type, and timestamps
1497
+ * using the HeadObject command.
1498
+ *
1499
+ * @param filePath - Storage path/key
1500
+ * @returns File metadata or null if file not found
1501
+ */
1502
+ async getMetadata(filePath) {
1503
+ const client = this.ensureClient();
1504
+ try {
1505
+ const command = new _aws_sdk_client_s3.HeadObjectCommand({
1506
+ Bucket: this.resolvedConfig.bucket,
1507
+ Key: filePath
1508
+ });
1509
+ const response = await client.send(command);
1510
+ const filename = filePath.split("/").pop() || filePath;
1511
+ return {
1512
+ id: filePath,
1513
+ filename,
1514
+ originalFilename: response.Metadata?.["original-filename"] || filename,
1515
+ mimeType: response.ContentType || "application/octet-stream",
1516
+ size: response.ContentLength || 0,
1517
+ url: this.getPublicUrl(filePath),
1518
+ createdAt: response.LastModified?.toISOString() || (/* @__PURE__ */ new Date()).toISOString()
1519
+ };
1520
+ } catch (error) {
1521
+ if (this.isNotFoundError(error)) return null;
1522
+ throw error;
1523
+ }
1524
+ }
1525
+ /**
1526
+ * Read a stored object back as bytes, or `null` when it is not there.
1527
+ *
1528
+ * The contract declares this OPTIONAL and, until now, no adapter supplied
1529
+ * it — so a caller reaching for `adapter.read` got `undefined` and fell
1530
+ * through whatever branch followed. An optional member nothing implements is
1531
+ * a contract that reads as a capability and behaves as an absence.
1532
+ *
1533
+ * BUFFERS rather than streams, because that is the declared return type and
1534
+ * widening it here would make this adapter answer a different question from
1535
+ * its siblings. That bounds what it should be used for: an asset the server
1536
+ * must serve from its own origin — a font file, a small document — rather
1537
+ * than arbitrarily large media, which belongs behind {@link getSignedUrl} or
1538
+ * a public URL. A streaming variant is a separate contract member, not a
1539
+ * quiet change to this one.
1540
+ *
1541
+ * `null` for a missing key rather than a throw, matching
1542
+ * {@link getMetadata}: absence is an ordinary answer about the bucket, while
1543
+ * a credential or network failure is not, so only the first is folded into
1544
+ * the return value.
1545
+ *
1546
+ * @param filePath - Storage path/key
1547
+ * @returns The object's bytes, or `null` when no such key exists
1548
+ */
1549
+ async read(filePath, options) {
1550
+ const client = this.ensureClient();
1551
+ try {
1552
+ const command = new _aws_sdk_client_s3.GetObjectCommand({
1553
+ Bucket: this.resolvedConfig.bucket,
1554
+ Key: filePath
1555
+ });
1556
+ const response = await client.send(command, abortAfter(options));
1557
+ if (response.Body === void 0) return Buffer.alloc(0);
1558
+ const cap = resolveReadBounds(options).maxBytes;
1559
+ this.refuseOverCap(filePath, response.ContentLength, cap);
1560
+ return await this.readCapped(filePath, response.Body, cap);
1561
+ } catch (error) {
1562
+ if (error instanceof Error && error.name === "NoSuchBucket") throw error;
1563
+ if (this.isNotFoundError(error)) return null;
1564
+ throw error;
1565
+ }
1566
+ }
1567
+ /**
1568
+ * The stored object's size and type, without reading it, or `null` when the
1569
+ * key is not in the bucket. A missing bucket throws rather than reading as a
1570
+ * missing key, as for {@link read}.
1571
+ *
1572
+ * @experimental
1573
+ */
1574
+ async head(filePath) {
1575
+ const client = this.ensureClient();
1576
+ try {
1577
+ const response = await client.send(new _aws_sdk_client_s3.HeadObjectCommand({
1578
+ Bucket: this.resolvedConfig.bucket,
1579
+ Key: filePath
1580
+ }));
1581
+ if (response.ContentLength === void 0) throw new Error("@nextly/storage-s3: the bucket did not report the object's size");
1582
+ return {
1583
+ size: response.ContentLength,
1584
+ ...response.ContentType !== void 0 ? { contentType: response.ContentType } : {},
1585
+ ...response.LastModified !== void 0 ? { lastModified: response.LastModified } : {}
1586
+ };
1587
+ } catch (error) {
1588
+ if (error instanceof Error && error.name === "NoSuchBucket") throw error;
1589
+ if (this.isNotFoundError(error)) return null;
1590
+ throw error;
1591
+ }
1592
+ }
1593
+ /**
1594
+ * The stored object as a stream, or `null` when the key is not in the
1595
+ * bucket, for a response that should not buffer a whole file.
1596
+ *
1597
+ * The deadline covers the bucket's answer only, then is cleared: the body
1598
+ * flows as fast as its reader takes it, and a deadline on the whole
1599
+ * transfer would cut off a slow but healthy download.
1600
+ *
1601
+ * @experimental
1602
+ */
1603
+ async readStream(filePath, options) {
1604
+ const client = this.ensureClient();
1605
+ const answered = new AbortController();
1606
+ const timer = setTimeout(() => answered.abort(), resolveReadBounds(options).timeoutMs);
1607
+ try {
1608
+ const response = await client.send(new _aws_sdk_client_s3.GetObjectCommand({
1609
+ Bucket: this.resolvedConfig.bucket,
1610
+ Key: filePath
1611
+ }), { abortSignal: answered.signal });
1612
+ if (response.Body === void 0) return new ReadableStream({ start: (controller) => controller.close() });
1613
+ return response.Body.transformToWebStream();
1614
+ } catch (error) {
1615
+ if (error instanceof Error && error.name === "NoSuchBucket") throw error;
1616
+ if (this.isNotFoundError(error)) return null;
1617
+ throw error;
1618
+ } finally {
1619
+ clearTimeout(timer);
1620
+ }
1621
+ }
1622
+ /**
1623
+ * Generate signed URL for temporary private file access.
1624
+ *
1625
+ * Creates a pre-signed GetObject URL that grants temporary read access
1626
+ * to private files. Useful for serving files from private buckets.
1627
+ *
1628
+ * @param filePath - Storage path/key
1629
+ * @param expiresIn - URL validity duration in seconds (default: 3600)
1630
+ * @returns Pre-signed URL for downloading the file
1631
+ */
1632
+ async getSignedUrl(filePath, expiresIn) {
1633
+ const client = this.ensureClient();
1634
+ const command = new _aws_sdk_client_s3.GetObjectCommand({
1635
+ Bucket: this.resolvedConfig.bucket,
1636
+ Key: filePath
1637
+ });
1638
+ return (0, _aws_sdk_s3_request_presigner.getSignedUrl)(client, command, { expiresIn: expiresIn ?? this.resolvedConfig.signedUrlExpiresIn });
1639
+ }
1640
+ /**
1641
+ * Generate pre-signed URL for client-side uploads.
1642
+ *
1643
+ * Creates a pre-signed PutObject URL that allows direct uploads from
1644
+ * the browser to S3, bypassing server-side upload limits (e.g., Vercel's 4.5MB).
1645
+ *
1646
+ * The signature covers the `Content-Type` and, given `options.contentLength`,
1647
+ * the `Content-Length`: the bytes never pass Nextly's upload checks, so S3
1648
+ * itself refuses a body of another type or length. The browser sets the
1649
+ * length from the body; it is not a header the client sends.
1650
+ *
1651
+ * It covers the configured `Cache-Control` too, which is returned in
1652
+ * `headers`: S3 stores an object's Cache-Control only from the upload
1653
+ * request's own header, so a browser upload is served with the same caching
1654
+ * as a server one only when the client sends it. The client must send every
1655
+ * header in `headers`, as it is; one left out fails the signature.
1656
+ *
1657
+ * @param key - Storage path/key for the upload
1658
+ * @param mimeType - MIME type of the file being uploaded
1659
+ * @param expiresIn - URL validity in seconds, at most the configured
1660
+ * `signedUrlExpiresIn` (its default)
1661
+ * @param options - `contentLength`: the exact size the upload may have
1662
+ * @returns Client upload data with URL, method, and headers
1663
+ */
1664
+ async getPresignedUploadUrl(key, mimeType, expiresIn, options) {
1665
+ return this.presignPut(key, mimeType, {
1666
+ cacheControl: this.resolvedConfig.cacheControl,
1667
+ acl: this.resolvedConfig.acl,
1668
+ expiresIn,
1669
+ contentLength: options?.contentLength
1670
+ });
1671
+ }
1672
+ /**
1673
+ * Sign one direct upload at exactly `key`: the type, the length when given,
1674
+ * and the Cache-Control are signed, so S3 refuses a body that differs. The
1675
+ * one signer for public and private uploads alike, which differ only in the
1676
+ * caching and access they write.
1677
+ */
1678
+ async presignPut(key, mimeType, put) {
1679
+ const client = this.ensureClient();
1680
+ const longest = this.resolvedConfig.signedUrlExpiresIn;
1681
+ const expiration = Math.min(put.expiresIn ?? longest, longest);
1682
+ const commandParams = {
1683
+ Bucket: this.resolvedConfig.bucket,
1684
+ Key: key,
1685
+ ContentType: mimeType,
1686
+ CacheControl: put.cacheControl,
1687
+ ...put.contentLength !== void 0 ? { ContentLength: put.contentLength } : {}
1688
+ };
1689
+ if (!this.isR2) commandParams.ACL = put.acl;
1690
+ const command = new _aws_sdk_client_s3.PutObjectCommand(commandParams);
1691
+ return {
1692
+ uploadUrl: await (0, _aws_sdk_s3_request_presigner.getSignedUrl)(client, command, {
1693
+ expiresIn: expiration,
1694
+ signableHeaders: /* @__PURE__ */ new Set([
1695
+ "content-type",
1696
+ "content-length",
1697
+ "cache-control"
1698
+ ])
1699
+ }),
1700
+ path: key,
1701
+ method: "PUT",
1702
+ headers: {
1703
+ "Content-Type": mimeType,
1704
+ "Cache-Control": put.cacheControl
1705
+ },
1706
+ expiresAt: new Date(Date.now() + expiration * 1e3)
1707
+ };
1708
+ }
1709
+ /**
1710
+ * Check if an error is a "not found" error from S3.
1711
+ *
1712
+ * @param error - Error to check
1713
+ * @returns true if error indicates file not found
1714
+ */
1715
+ /**
1716
+ * The object's bytes, refusing once more than `cap` have actually arrived.
1717
+ *
1718
+ * `ContentLength` is OPTIONAL in the SDK's response type, and this adapter
1719
+ * explicitly supports MinIO, R2 and other compatible services — any of which
1720
+ * may omit it or report it wrongly. A preflight check against metadata is
1721
+ * therefore a courtesy that fails OPEN: trusting it alone leaves the cap
1722
+ * unenforced exactly where an unusual backend is involved, which is where a
1723
+ * caller most needs it.
1724
+ *
1725
+ * Counted while consuming, so an oversized body is abandoned partway rather
1726
+ * than after it has all been buffered — the cap exists to bound memory, and
1727
+ * one applied after `transformToByteArray` has already spent it.
1728
+ *
1729
+ * Falls back to buffering when the body is not async-iterable, which the SDK
1730
+ * types permit. Stated rather than hidden: on that path the cap bounds what a
1731
+ * caller RECEIVES rather than what the process allocates.
1732
+ */
1733
+ async readCapped(filePath, body, cap) {
1734
+ if (typeof body[Symbol.asyncIterator] !== "function") {
1735
+ const whole = Buffer.from(await body.transformToByteArray());
1736
+ if (whole.byteLength > cap) throw new StorageReadTooLargeError(filePath, cap, whole.byteLength);
1737
+ return whole;
1738
+ }
1739
+ const chunks = [];
1740
+ let received = 0;
1741
+ for await (const chunk of body) {
1742
+ received += chunk.byteLength;
1743
+ if (received > cap) throw new StorageReadTooLargeError(filePath, cap, received);
1744
+ chunks.push(Buffer.from(chunk));
1745
+ }
1746
+ return Buffer.concat(chunks);
1747
+ }
1748
+ /**
1749
+ * Refuse a read whose object is already known to exceed the caller's cap.
1750
+ *
1751
+ * Its own method rather than three conditions inside `read`, because the
1752
+ * decision has nothing to do with the surrounding error handling and reads
1753
+ * as noise there — and because `read`'s branching is the part a reviewer has
1754
+ * to hold in their head to check the absent-versus-unavailable distinction.
1755
+ *
1756
+ * Both `undefined` cases mean "no opinion" and pass: a caller that named no
1757
+ * cap has none, and a store that reported no length gives nothing to compare.
1758
+ * The second is deliberately permissive — refusing an unmeasured object would
1759
+ * reject valid reads whenever S3 omits the header.
1760
+ */
1761
+ refuseOverCap(filePath, declared, cap) {
1762
+ if (cap === void 0 || declared === void 0 || declared <= cap) return;
1763
+ throw new StorageReadTooLargeError(filePath, cap, declared);
1764
+ }
1765
+ isNotFoundError(error) {
1766
+ if (error && typeof error === "object") {
1767
+ const e = error;
1768
+ return e.name === "NotFound" || e.$metadata?.httpStatusCode === 404;
1769
+ }
1770
+ return false;
1771
+ }
1772
+ /**
1773
+ * Get the S3 client instance.
1774
+ * Useful for advanced operations not covered by the adapter interface.
1775
+ *
1776
+ * Handing out the client is itself a use of the adapter, so a caller
1777
+ * without the configuration a client needs is refused here like any
1778
+ * other operation.
1779
+ */
1780
+ getClient() {
1781
+ return this.ensureClient();
1782
+ }
1783
+ /**
1784
+ * Get the bucket name.
1785
+ */
1786
+ getBucket() {
1787
+ return this.resolvedConfig.bucket;
1788
+ }
1789
+ /**
1790
+ * Get the AWS region.
1791
+ */
1792
+ getRegion() {
1793
+ return this.resolvedConfig.region;
1794
+ }
1795
+ /**
1796
+ * Check if this adapter is configured for Cloudflare R2.
1797
+ */
1798
+ isCloudflareR2() {
1799
+ return this.isR2;
1800
+ }
398
1801
  };
399
-
400
1802
  // src/plugin.ts
1803
+ /**
1804
+ * Create an S3 storage plugin for Nextly.
1805
+ *
1806
+ * This factory function creates a StoragePlugin that can be added to
1807
+ * the `storage` array in `nextly.config.ts`. It supports:
1808
+ *
1809
+ * - AWS S3 (standard)
1810
+ * - Cloudflare R2 (S3-compatible)
1811
+ * - MinIO (S3-compatible, self-hosted)
1812
+ * - DigitalOcean Spaces (S3-compatible)
1813
+ * - Any other S3-compatible service
1814
+ *
1815
+ * @param config - S3 storage configuration
1816
+ * @returns A StoragePlugin that MediaStorage can register
1817
+ *
1818
+ * Constructing the plugin never requires the bucket or region: a missing
1819
+ * one is refused when storage is first used, not while the config loads.
1820
+ */
401
1821
  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;
1822
+ if (config.enabled === false) return {
1823
+ name: "s3-storage",
1824
+ type: "s3",
1825
+ collections: {},
1826
+ adapter: null
1827
+ };
1828
+ const adapter = new S3StorageAdapter(config);
1829
+ return {
1830
+ name: "s3-storage",
1831
+ type: "s3",
1832
+ collections: config.collections,
1833
+ adapter,
1834
+ /**
1835
+ * Generate a pre-signed URL for client-side uploads.
1836
+ *
1837
+ * This allows files to be uploaded directly from the browser to S3,
1838
+ * bypassing server-side upload limits (e.g., Vercel's 4.5MB limit).
1839
+ *
1840
+ * @param filename - Original filename from the client
1841
+ * @param mimeType - MIME type of the file
1842
+ * @param collection - Collection slug this upload belongs to
1843
+ * @param options - The file's exact size, and the URL's lifetime
1844
+ * @returns Client upload data with pre-signed URL
1845
+ */
1846
+ async getClientUploadUrl(filename, mimeType, collection, options) {
1847
+ const collectionConfig = config.collections[collection];
1848
+ const key = generateStorageKey(filename, typeof collectionConfig === "object" ? collectionConfig.prefix : void 0);
1849
+ return adapter.getPresignedUploadUrl(key, mimeType, options?.expiresIn, { contentLength: options?.size });
1850
+ },
1851
+ /**
1852
+ * Generate a signed URL for private file downloads.
1853
+ *
1854
+ * Creates a time-limited URL for accessing files in private buckets.
1855
+ * Only works when collection has `signedDownloads: true`.
1856
+ *
1857
+ * @param path - Storage path/key of the file
1858
+ * @param expiresIn - URL validity duration in seconds
1859
+ * @returns Signed URL for downloading the file
1860
+ */
1861
+ async getSignedDownloadUrl(path, expiresIn) {
1862
+ return adapter.getSignedUrl(path, expiresIn ?? config.signedUrlExpiresIn ?? 3600);
1863
+ }
1864
+ };
451
1865
  }
452
- 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}`;
460
- }
461
- function sanitizeFilename(filename) {
462
- const basename = filename.split(/[/\\]/).pop() || filename;
463
- return basename.replace(/[^a-zA-Z0-9._-]/g, "-");
464
- }
465
-
466
1866
  // src/index.ts
467
- var PACKAGE_NAME = "@nextly/storage-s3";
468
- var PACKAGE_VERSION = "0.1.0";
469
-
1867
+ const PACKAGE_NAME = "@nextly/storage-s3";
1868
+ const PACKAGE_VERSION = "0.1.0";
470
1869
  exports.PACKAGE_NAME = PACKAGE_NAME;
471
1870
  exports.PACKAGE_VERSION = PACKAGE_VERSION;
472
1871
  exports.S3StorageAdapter = S3StorageAdapter;
473
1872
  exports.s3Storage = s3Storage;
474
- //# sourceMappingURL=index.cjs.map
1873
+
475
1874
  //# sourceMappingURL=index.cjs.map