@nextlyhq/storage-s3 0.0.2-alpha.67 → 0.0.2-alpha.69

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