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

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