@nextlyhq/storage-vercel-blob 0.0.2-alpha.7 → 0.0.2-alpha.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,394 +1,1706 @@
1
- import { put, del, head, list } from '@vercel/blob';
2
-
1
+ import { BlobNotFoundError, del, head, list, put } from "@vercel/blob";
2
+ // ../nextly/dist/nextly-error-D21_8kpX.mjs
3
+ function isDbError(err) {
4
+ if (!err || typeof err !== "object") return false;
5
+ const obj = err;
6
+ return obj.name === "DbError" && typeof obj.kind === "string";
7
+ }
8
+ /**
9
+ * The driver's own code for an error, wherever that driver puts it.
10
+ *
11
+ * Exported so callers that must distinguish one failure from another classify
12
+ * by the SAME extraction this module's mapping uses. A second reader would go
13
+ * looking in a different set of properties and disagree on exactly the drivers
14
+ * whose codes are hardest to find.
15
+ */
16
+ /**
17
+ * Whether an error is a duplicate-key rejection.
18
+ *
19
+ * Exposed because a plugin inserting into a table with a unique index has to
20
+ * tell "this row already exists" from "the database is broken", and the two
21
+ * arrive as the same thrown object. Derived from the existing SQLSTATE
22
+ * classification rather than by matching driver messages: those differ per
23
+ * driver and per version, and a plugin re-deriving it would be a second
24
+ * implementation of a question this module already answers.
25
+ */
26
+ /**
27
+ * Whether a driver code says the database was busy: the adapters' own code
28
+ * for a request that waited out `pool.connectionTimeoutMs`, the same on
29
+ * every dialect, or SQLITE_BUSY and its extended codes, another process
30
+ * holding the SQLite file past `busyTimeout`. Neither depends on the dialect,
31
+ * which is what lets {@link isDatabaseBusy} answer without one.
32
+ */
33
+ function isBusyCode(code) {
34
+ if (code === void 0) return false;
35
+ return code === "NEXTLY_POOL_WAIT_TIMEOUT" || code.toUpperCase().startsWith("SQLITE_BUSY");
36
+ }
37
+ /**
38
+ * Whether an error is the database being busy, however it arrives: a DbError
39
+ * of kind "busy", or the raw error an adapter or driver threw.
40
+ *
41
+ * For the boundaries that answer a request with whatever its work threw.
42
+ * `withDbErrors` converts only DbErrors, so a raw driver error reaches them
43
+ * unconverted, and without this it would read as an internal fault rather
44
+ * than a request worth retrying.
45
+ */
46
+ function isDatabaseBusy(error) {
47
+ if (isDbError(error)) return error.kind === "busy";
48
+ return isBusyCode(safeCode(error));
49
+ }
50
+ function safeCode(error) {
51
+ if (!error || typeof error !== "object") return void 0;
52
+ const e = error;
53
+ let c = e.code ?? e.sqlState ?? e.state ?? e.errno ?? void 0;
54
+ if (!c && typeof e.originalError?.code === "string") c = e.originalError.code;
55
+ if (!c && typeof e.cause?.code === "string") c = e.cause.code;
56
+ if (!c && typeof e.severity === "string" && typeof e.code === "string") c = e.code;
57
+ if (typeof c === "number") return String(c);
58
+ if (typeof c === "string" && c.length > 0) return c;
59
+ }
60
+ /**
61
+ * Canonical NextlyError codes and their HTTP status mappings.
62
+ *
63
+ * Plugin codes outside this enum must always pass an explicit `statusCode`
64
+ * to the NextlyError constructor (no enum lookup happens for unknown codes).
65
+ */
66
+ const NEXTLY_ERROR_STATUS = {
67
+ VALIDATION_ERROR: 400,
68
+ INVALID_INPUT: 400,
69
+ AUTH_REQUIRED: 401,
70
+ AUTH_INVALID_CREDENTIALS: 401,
71
+ TOKEN_EXPIRED: 401,
72
+ FORBIDDEN: 403,
73
+ EMAIL_NOT_VERIFIED: 403,
74
+ BUILDER_DISABLED: 403,
75
+ CSRF_FAILED: 403,
76
+ SETUP_TOKEN_REQUIRED: 403,
77
+ API_KEY_ROLE_ABOVE_CREATOR: 403,
78
+ NOT_FOUND: 404,
79
+ METHOD_NOT_ALLOWED: 405,
80
+ CONFLICT: 409,
81
+ DUPLICATE: 409,
82
+ RATE_LIMITED: 429,
83
+ PAYLOAD_TOO_LARGE: 413,
84
+ UNSUPPORTED_MEDIA_TYPE: 415,
85
+ BUSINESS_RULE_VIOLATION: 422,
86
+ INTERNAL_ERROR: 500,
87
+ DATABASE_ERROR: 500,
88
+ DATABASE_BUSY: 503,
89
+ EXTERNAL_SERVICE_ERROR: 502,
90
+ SERVICE_UNAVAILABLE: 503,
91
+ EXTERNAL_URL_BLOCKED: 400,
92
+ EXTERNAL_REQUEST_FAILED: 502,
93
+ FILENAME_INVALID: 400,
94
+ EXTENSION_BLOCKED: 400,
95
+ MIME_BLOCKED: 415,
96
+ MIME_NOT_ALLOWED: 415,
97
+ SIZE_EXCEEDED: 413,
98
+ STORAGE_READ_TOO_LARGE: 413,
99
+ STORAGE_READ_TIMEOUT: 504,
100
+ STORAGE_READ_UNREACHABLE: 502,
101
+ MAGIC_BYTE_MISMATCH: 400,
102
+ SVG_SANITIZATION_FAILED: 400,
103
+ UNSUPPORTED_FOR_BACKEND: 415,
104
+ NEXTLY_LEGACY_BOOKKEEPING_DETECTED: 409,
105
+ NEXTLY_UPGRADE_TABLE_NAME_COLLISION: 409,
106
+ NEXTLY_UPGRADE_IN_PROGRESS: 409,
107
+ NEXTLY_MIGRATE_LOCK_BUSY: 409,
108
+ NEXTLY_BASELINE_LOCK_NOT_HELD: 409,
109
+ NEXTLY_RESOLVE_LOCK_NOT_HELD: 409,
110
+ NEXTLY_BOOT_MIGRATIONS_NOT_RUN: 503,
111
+ NEXTLY_BOOT_MIGRATIONS_PENDING: 503,
112
+ NEXTLY_CORE_DESTRUCTIVE_REFUSED: 409,
113
+ NEXTLY_MIGRATION_DRIFT: 409,
114
+ NEXTLY_MIGRATION_APPLY_FAILED: 500,
115
+ NEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION: 409,
116
+ NEXTLY_MIGRATION_PARTIALLY_APPLIED: 500,
117
+ NEXTLY_MIGRATION_CONCURRENT_RUN: 409,
118
+ NEXTLY_MIGRATION_FILE_MISSING: 404,
119
+ NEXTLY_MIGRATION_SNAPSHOT_MISSING: 404,
120
+ NEXTLY_MIGRATION_RESOLVE_DRIFT: 409,
121
+ NEXTLY_MIGRATION_RESOLVE_PRECONDITION: 409,
122
+ NEXTLY_UI_SCHEMA_INVALID: 400,
123
+ NEXTLY_SCHEMA_SLUG_COLLISION: 409,
124
+ NEXTLY_SCHEMA_RELATION_TARGET_MISSING: 400,
125
+ NEXTLY_SCHEMA_RELATION_UNRESOLVED: 400,
126
+ NEXTLY_SCHEMA_EXTEND_TARGET_UNKNOWN: 400,
127
+ NEXTLY_SCHEMA_EXTEND_FIELD_DUPLICATE: 409,
128
+ NEXTLY_SCHEMA_CROSS_PLUGIN_RELATION: 409,
129
+ NEXTLY_SCHEMA_RENAME_UNKNOWN_TARGET: 400,
130
+ NEXTLY_PLUGIN_CLIENT_CONFIG_INVALID: 500,
131
+ NEXTLY_PLUGIN_ADMIN_WIDGET_INVALID: 500,
132
+ NEXTLY_ADMIN_COMPONENT_MAP_STALE: 500,
133
+ NEXTLY_PLUGIN_DOCUMENT_VIEW_INVALID: 500,
134
+ PLUGIN_RESOLUTION_ERROR: 500,
135
+ PLUGIN_DEPENDENCY_NOT_INSTALLED: 409,
136
+ PLUGIN_HAS_DEPENDENTS: 409,
137
+ PLUGIN_UNINSTALL_IRREVERSIBLE: 409,
138
+ PLUGIN_UNINSTALL_UNCONFIRMED: 409,
139
+ PLUGIN_SCHEMA_BEHIND: 409,
140
+ PLUGIN_SCHEMA_UNINSTALLED: 409,
141
+ PLUGIN_NOT_INSTALLED: 409,
142
+ PLUGIN_DISABLED: 409,
143
+ PLUGIN_UNINSTALL_UNFINISHED: 409,
144
+ PLUGIN_SCHEMA_VERSION_NOT_ADVANCED: 409,
145
+ PLUGIN_MIGRATION_DROPS_CREATED_SCHEMA: 409,
146
+ PLUGIN_MIGRATION_ADDS_UNFILLABLE_COLUMN: 409,
147
+ PLUGIN_MIGRATION_SQL_MISSING: 409,
148
+ PLUGIN_MIGRATIONS_UNAVAILABLE: 409,
149
+ DROP_OF_FOREIGN_TABLE: 409,
150
+ MIGRATION_CHECKSUM_MISMATCH: 409,
151
+ PLUGIN_MIGRATIONS_OUT_OF_ORDER: 409,
152
+ PLUGIN_MIGRATION_HISTORY_CHANGED: 409,
153
+ NEXTLY_ROUTE_COLLISION: 409,
154
+ NEXTLY_ROUTE_INVALID_PATH: 400,
155
+ NEXTLY_ROUTE_UNREACHABLE_ROOT: 400,
156
+ NEXTLY_ROUTE_INVALID_MOUNT: 400,
157
+ NEXTLY_EMAIL_TRANSPORT_UNAVAILABLE: 503,
158
+ NEXTLY_CONFIG_TOOLING_UNAVAILABLE: 503,
159
+ NEXTLY_POSTGRES_SCHEMA_MISMATCH: 500,
160
+ NEXTLY_POSTGRES_SCHEMA_UNSUPPORTED: 500
161
+ };
162
+ ({ ...Object.fromEntries([
163
+ "VALIDATION_ERROR",
164
+ "AUTH_REQUIRED",
165
+ "FORBIDDEN",
166
+ "NOT_FOUND",
167
+ "CONFLICT",
168
+ "PAYLOAD_TOO_LARGE",
169
+ "UNSUPPORTED_MEDIA_TYPE",
170
+ "RATE_LIMITED",
171
+ "EXTERNAL_SERVICE_ERROR",
172
+ "SERVICE_UNAVAILABLE"
173
+ ].map((code) => [NEXTLY_ERROR_STATUS[code], code])) });
174
+ /**
175
+ * The sentence a caller reads for a code, when the failure supplied none.
176
+ *
177
+ * Kept beside the status table because they answer the same question together:
178
+ * a code-less envelope's own `message` is NOT usable here. Those envelopes come
179
+ * from legacy converters that store a raw exception's text, so promoting it
180
+ * would put driver output, table names and internal paths on the wire -- the
181
+ * disclosure the public error shape exists to prevent (spec 13.8).
182
+ *
183
+ * Every entry is generic by design. The specific detail stays in `logContext`
184
+ * for the operator, against the same request id.
185
+ */
186
+ const GENERIC_PUBLIC_MESSAGE = {
187
+ VALIDATION_ERROR: "Validation failed.",
188
+ INVALID_INPUT: "The request could not be processed.",
189
+ AUTH_REQUIRED: "Authentication required.",
190
+ FORBIDDEN: "You don't have permission to perform this action.",
191
+ NOT_FOUND: "Not found.",
192
+ METHOD_NOT_ALLOWED: "That method is not allowed on this address.",
193
+ CONFLICT: "The resource has changed since you last loaded it. Please refresh and try again.",
194
+ DUPLICATE: "Resource already exists.",
195
+ PAYLOAD_TOO_LARGE: "The request is too large.",
196
+ UNSUPPORTED_MEDIA_TYPE: "That file type is not supported.",
197
+ RATE_LIMITED: "Too many requests. Please try again later.",
198
+ EXTERNAL_SERVICE_ERROR: "An upstream service failed.",
199
+ SERVICE_UNAVAILABLE: "The service is temporarily unavailable.",
200
+ DATABASE_BUSY: "The database is busy. Please try again shortly.",
201
+ INTERNAL_ERROR: "An unexpected error occurred."
202
+ };
203
+ /** The generic sentence for a code; the internal one for anything unlisted. */
204
+ function genericPublicMessage(code) {
205
+ return GENERIC_PUBLIC_MESSAGE[code] ?? GENERIC_PUBLIC_MESSAGE.INTERNAL_ERROR;
206
+ }
207
+ /**
208
+ * Default mapping from DbErrorKind to NextlyError contract. Used by
209
+ * `NextlyError.fromDatabaseError`. Public messages are intentionally generic
210
+ * per spec §13.8 — no DB driver text, no constraint names, no field hints.
211
+ *
212
+ * `satisfies Record<DbErrorKind, ...>` makes the mapping exhaustive at
213
+ * compile time: adding a new DbErrorKind without updating this table is a
214
+ * type error.
215
+ */
216
+ const DB_ERROR_MAPPING = {
217
+ "unique-violation": {
218
+ code: "DUPLICATE",
219
+ statusCode: 409,
220
+ publicMessage: "Resource already exists."
221
+ },
222
+ "fk-violation": {
223
+ code: "VALIDATION_ERROR",
224
+ statusCode: 400,
225
+ publicMessage: "Referenced record does not exist."
226
+ },
227
+ "not-null-violation": {
228
+ code: "VALIDATION_ERROR",
229
+ statusCode: 400,
230
+ publicMessage: "A required field is missing."
231
+ },
232
+ constraint: {
233
+ code: "VALIDATION_ERROR",
234
+ statusCode: 400,
235
+ publicMessage: "The provided data violates a constraint."
236
+ },
237
+ deadlock: {
238
+ code: "CONFLICT",
239
+ statusCode: 409,
240
+ publicMessage: "The operation could not be completed. Please retry."
241
+ },
242
+ "serialization-failure": {
243
+ code: "CONFLICT",
244
+ statusCode: 409,
245
+ publicMessage: "The operation could not be completed. Please retry."
246
+ },
247
+ busy: {
248
+ code: "DATABASE_BUSY",
249
+ statusCode: NEXTLY_ERROR_STATUS.DATABASE_BUSY,
250
+ publicMessage: genericPublicMessage("DATABASE_BUSY"),
251
+ publicData: { retryAfterSeconds: 5 }
252
+ },
253
+ timeout: {
254
+ code: "DATABASE_ERROR",
255
+ statusCode: 500,
256
+ publicMessage: "The operation timed out. Please try again."
257
+ },
258
+ "connection-lost": {
259
+ code: "DATABASE_ERROR",
260
+ statusCode: 500,
261
+ publicMessage: "A temporary database error occurred. Please try again."
262
+ },
263
+ syntax: {
264
+ code: "INTERNAL_ERROR",
265
+ statusCode: 500,
266
+ publicMessage: "An unexpected error occurred."
267
+ },
268
+ internal: {
269
+ code: "INTERNAL_ERROR",
270
+ statusCode: 500,
271
+ publicMessage: "An unexpected error occurred."
272
+ }
273
+ };
274
+ const NEXTLY_ERROR_BRAND = Symbol.for("nextly/NextlyError");
275
+ function hasBrand(value) {
276
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
277
+ return value[NEXTLY_ERROR_BRAND] === true;
278
+ }
279
+ /**
280
+ * Unified error class for Nextly. Used at every throw site across services,
281
+ * direct API, auth, and plugins. Carries two distinct payloads:
282
+ *
283
+ * - Public (`code`, `publicMessage`, `publicData`, `statusCode`, `messageKey`)
284
+ * sent in HTTP responses and Server Action results.
285
+ * - Log (`logMessage`, `logContext`, `cause`, stack trace)
286
+ * written to the server logger; never serialised to the wire.
287
+ *
288
+ * Use the static factories (notFound, forbidden, validation, ...) for the
289
+ * common cases. Use the free-form constructor for plugin codes or one-off
290
+ * shapes.
291
+ */
292
+ var NextlyError = class NextlyError extends Error {
293
+ code;
294
+ statusCode;
295
+ publicMessage;
296
+ publicData;
297
+ messageKey;
298
+ logMessage;
299
+ logContext;
300
+ cause;
301
+ timestamp;
302
+ constructor(opts) {
303
+ super(opts.publicMessage);
304
+ this.name = "NextlyError";
305
+ this.code = opts.code;
306
+ this.publicMessage = opts.publicMessage;
307
+ this.publicData = opts.publicData;
308
+ this.messageKey = opts.messageKey;
309
+ this.logMessage = opts.logMessage;
310
+ this.logContext = opts.logContext;
311
+ this.cause = opts.cause;
312
+ this.timestamp = /* @__PURE__ */ new Date();
313
+ this.statusCode = NextlyError.resolveStatusCode(opts);
314
+ Error.captureStackTrace?.(this, NextlyError);
315
+ }
316
+ static {
317
+ NextlyError.prototype[NEXTLY_ERROR_BRAND] = true;
318
+ }
319
+ static resolveStatusCode(opts) {
320
+ if (typeof opts.statusCode === "number") return opts.statusCode;
321
+ if (opts.code in NEXTLY_ERROR_STATUS) return NEXTLY_ERROR_STATUS[opts.code];
322
+ return 500;
323
+ }
324
+ /** HTTP-safe JSON. Strips logMessage / logContext / cause / stack. */
325
+ toResponseJSON(requestId) {
326
+ const json = {
327
+ code: String(this.code),
328
+ message: this.publicMessage,
329
+ requestId
330
+ };
331
+ if (this.messageKey) json.messageKey = this.messageKey;
332
+ if (this.publicData !== void 0) json.data = this.publicData;
333
+ return json;
334
+ }
335
+ /** Operator-facing JSON for log lines. Includes everything. */
336
+ toLogJSON(requestId) {
337
+ return {
338
+ code: this.code,
339
+ statusCode: this.statusCode,
340
+ publicMessage: this.publicMessage,
341
+ messageKey: this.messageKey,
342
+ logMessage: this.logMessage,
343
+ logContext: this.logContext,
344
+ cause: this.cause ? {
345
+ name: this.cause.name,
346
+ message: this.cause.message,
347
+ stack: this.cause.stack
348
+ } : void 0,
349
+ timestamp: this.timestamp.toISOString(),
350
+ requestId
351
+ };
352
+ }
353
+ static invalidCredentials(opts) {
354
+ return new NextlyError({
355
+ code: "AUTH_INVALID_CREDENTIALS",
356
+ publicMessage: "Invalid email or password.",
357
+ logMessage: "Login failed",
358
+ logContext: opts?.logContext
359
+ });
360
+ }
361
+ /**
362
+ * The password was correct and the address is unverified. Thrown only once
363
+ * the password is proven, so only someone who holds it learns the address
364
+ * is unverified; every other refusal stays
365
+ * {@link NextlyError.invalidCredentials}.
366
+ */
367
+ static emailNotVerified(opts) {
368
+ return new NextlyError({
369
+ code: "EMAIL_NOT_VERIFIED",
370
+ publicMessage: "Verify your email address to sign in. Check your inbox for the link.",
371
+ logMessage: "Login refused: email not verified",
372
+ logContext: opts?.logContext
373
+ });
374
+ }
375
+ static authRequired(opts) {
376
+ return new NextlyError({
377
+ code: "AUTH_REQUIRED",
378
+ publicMessage: "Authentication required.",
379
+ logContext: opts?.logContext
380
+ });
381
+ }
382
+ /**
383
+ * Distinct from `authRequired`: the caller was authenticated but the
384
+ * session token expired. Clients key on the TOKEN_EXPIRED *code* to
385
+ * silently refresh and retry rather than redirecting to login; the public
386
+ * message stays the generic spec §13.6 string ("Authentication required.")
387
+ * so the wire never reveals the session state — same as `authRequired`.
388
+ */
389
+ static tokenExpired(opts) {
390
+ return new NextlyError({
391
+ code: "TOKEN_EXPIRED",
392
+ publicMessage: "Authentication required.",
393
+ logContext: opts?.logContext
394
+ });
395
+ }
396
+ static notFound(opts) {
397
+ return new NextlyError({
398
+ code: "NOT_FOUND",
399
+ publicMessage: opts?.message ?? "Not found.",
400
+ cause: opts?.cause,
401
+ logContext: opts?.logContext
402
+ });
403
+ }
404
+ static forbidden(opts) {
405
+ return new NextlyError({
406
+ code: "FORBIDDEN",
407
+ publicMessage: "You don't have permission to perform this action.",
408
+ cause: opts?.cause,
409
+ logContext: opts?.logContext
410
+ });
411
+ }
412
+ /**
413
+ * A collection, Single or component defined in code, which is changed by
414
+ * changing its code and not from here. Forbidden, and the message says so:
415
+ * it is a fact about the thing, not about the caller's permissions, so it
416
+ * names no permission and no policy. The lock's detail goes to the log
417
+ * through `logContext`.
418
+ */
419
+ static definedInCode(opts) {
420
+ return new NextlyError({
421
+ code: "FORBIDDEN",
422
+ publicMessage: `This ${opts.thing} is defined in code, so it can't be ${opts.change === "change" ? "changed" : "deleted"} here.`,
423
+ logContext: opts.logContext
424
+ });
425
+ }
426
+ /**
427
+ * An autosave where the collection or Single does not autosave: its owner
428
+ * switched autosave off, or it keeps no drafts to autosave into. Forbidden,
429
+ * and the message says so, since it is a setting and not a permission.
430
+ */
431
+ static autosaveOff(opts) {
432
+ return new NextlyError({
433
+ code: "FORBIDDEN",
434
+ publicMessage: `Autosave is turned off for this ${opts.scopeKind === "single" ? "Single" : "collection"}.`,
435
+ logContext: opts.logContext
436
+ });
437
+ }
438
+ /**
439
+ * An API key refused because its role allows more than the person creating
440
+ * it may do. The sentence is FORBIDDEN's and names no permission; which one
441
+ * exceeded goes to the log through `logContext`. The code is its own, so a
442
+ * client can tell "choose a smaller role" from plain FORBIDDEN.
443
+ */
444
+ static apiKeyRoleAboveCreator(opts) {
445
+ return new NextlyError({
446
+ code: "API_KEY_ROLE_ABOVE_CREATOR",
447
+ publicMessage: genericPublicMessage("FORBIDDEN"),
448
+ logContext: opts?.logContext
449
+ });
450
+ }
451
+ /**
452
+ * A cookie-authenticated write refused because its origin or CSRF token did
453
+ * not check out. The public message names no detail of which check failed;
454
+ * that goes to the log through `logMessage`.
455
+ */
456
+ static csrfFailed(opts) {
457
+ return new NextlyError({
458
+ code: "CSRF_FAILED",
459
+ publicMessage: "This request could not be verified. Reload the page and try again.",
460
+ logMessage: opts?.logMessage,
461
+ logContext: opts?.logContext
462
+ });
463
+ }
464
+ /**
465
+ * A call the caller got wrong, where naming the mistake IS the value of the
466
+ * error.
467
+ *
468
+ * The only factory that takes its public message from the caller. The
469
+ * generic messages elsewhere exist so an HTTP response cannot leak internal
470
+ * detail; this one is for arguments and configuration a developer controls
471
+ * and must be told about — a missing option, an unusable combination — where
472
+ * `internal()` would reduce the one useful sentence to "An unexpected error
473
+ * occurred." Do not pass user-supplied data through it.
474
+ */
475
+ static invalidInput(opts) {
476
+ return new NextlyError({
477
+ code: "INVALID_INPUT",
478
+ publicMessage: opts.message,
479
+ logContext: opts.logContext
480
+ });
481
+ }
482
+ static validation(opts) {
483
+ return new NextlyError({
484
+ code: "VALIDATION_ERROR",
485
+ publicMessage: "Validation failed.",
486
+ publicData: { errors: opts.errors },
487
+ cause: opts.cause,
488
+ logContext: opts.logContext
489
+ });
490
+ }
491
+ static conflict(opts) {
492
+ return new NextlyError({
493
+ code: "CONFLICT",
494
+ publicMessage: opts?.message ?? "The resource has changed since you last loaded it. Please refresh and try again.",
495
+ publicData: opts?.data,
496
+ cause: opts?.cause,
497
+ logContext: {
498
+ reason: opts?.reason,
499
+ ...opts?.logContext
500
+ }
501
+ });
502
+ }
503
+ static duplicate(opts) {
504
+ return new NextlyError({
505
+ code: "DUPLICATE",
506
+ publicMessage: "Resource already exists.",
507
+ logContext: opts?.logContext
508
+ });
509
+ }
510
+ static rateLimited(opts) {
511
+ return new NextlyError({
512
+ code: "RATE_LIMITED",
513
+ publicMessage: "Too many requests. Please try again later.",
514
+ publicData: opts?.retryAfterSeconds !== void 0 ? { retryAfterSeconds: opts.retryAfterSeconds } : void 0,
515
+ logContext: opts?.logContext
516
+ });
517
+ }
518
+ /**
519
+ * A request that waited `pool.connectionTimeoutMs` for a database
520
+ * connection and was given none. The statement or transaction that waited
521
+ * never ran; work committed before it stays committed. The same error
522
+ * `fromDatabaseError` gives a busy DbError, from the same table row.
523
+ */
524
+ static databaseBusy(opts) {
525
+ const busy = DB_ERROR_MAPPING.busy;
526
+ return new NextlyError({
527
+ code: busy.code,
528
+ statusCode: busy.statusCode,
529
+ publicMessage: busy.publicMessage,
530
+ publicData: busy.publicData,
531
+ cause: opts?.cause,
532
+ logContext: opts?.logContext
533
+ });
534
+ }
535
+ /**
536
+ * What a request boundary answers with for a thrown value that is not a
537
+ * NextlyError: "database busy" when the request waited out its bound for a
538
+ * connection, which is retryable and no fault of the server's code, and an
539
+ * internal error for anything else.
540
+ *
541
+ * The busy case has to be read here because it usually arrives raw:
542
+ * `withDbErrors` converts only DbErrors, so a driver's error passes through
543
+ * services unconverted to the boundary that answers the request.
544
+ */
545
+ static fromUnexpected(error) {
546
+ return NextlyError.busyOr(error, () => NextlyError.internal({ cause: error instanceof Error ? error : void 0 }));
547
+ }
548
+ /**
549
+ * "Database busy" when `error` is a request that waited out its bound for
550
+ * a connection, and `otherwise()` for anything else.
551
+ *
552
+ * For a boundary that answers an unexpected failure with an error of its
553
+ * own choosing rather than an internal one (a 503 for a flow that must not
554
+ * answer on incomplete data), so that a busy database still answers there
555
+ * as it does everywhere else. `fromUnexpected` is this rule with the
556
+ * internal error as its fallback.
557
+ */
558
+ static busyOr(error, otherwise) {
559
+ if (!isDatabaseBusy(error)) return otherwise();
560
+ return NextlyError.databaseBusy({ cause: error instanceof Error ? error : void 0 });
561
+ }
562
+ static internal(opts) {
563
+ return new NextlyError({
564
+ code: "INTERNAL_ERROR",
565
+ publicMessage: "An unexpected error occurred.",
566
+ cause: opts?.cause,
567
+ logContext: opts?.logContext
568
+ });
569
+ }
570
+ static serviceUnavailable(opts) {
571
+ return new NextlyError({
572
+ code: "SERVICE_UNAVAILABLE",
573
+ publicMessage: opts?.publicMessage ?? "Service unavailable. Please try again later.",
574
+ logMessage: opts?.logMessage,
575
+ cause: opts?.cause,
576
+ logContext: opts?.logContext
577
+ });
578
+ }
579
+ /**
580
+ * Convert a DbError (or arbitrary unknown thrown by the DB layer) to a
581
+ * NextlyError with a generic public message and rich logContext. Used by
582
+ * `withDbErrors` for auto-conversion (Pattern A) and by services that
583
+ * catch DB errors at boundaries (Pattern B). Spec §8.2 mapping table.
584
+ *
585
+ * Never leaks DB driver text, constraint names, or table names into
586
+ * `publicMessage`. All DB context goes into `logContext`. The original
587
+ * DbError is preserved as `cause`.
588
+ */
589
+ static fromDatabaseError(error) {
590
+ if (isDbError(error)) {
591
+ const mapping = DB_ERROR_MAPPING[error.kind];
592
+ const logContext = {
593
+ dbKind: error.kind,
594
+ dialect: error.dialect
595
+ };
596
+ if (error.code !== void 0) logContext.dbCode = error.code;
597
+ if (error.meta !== void 0) logContext.meta = error.meta;
598
+ return new NextlyError({
599
+ code: mapping.code,
600
+ statusCode: mapping.statusCode,
601
+ publicMessage: mapping.publicMessage,
602
+ publicData: "publicData" in mapping ? mapping.publicData : void 0,
603
+ logMessage: "Database error",
604
+ logContext,
605
+ cause: error
606
+ });
607
+ }
608
+ return new NextlyError({
609
+ code: "INTERNAL_ERROR",
610
+ statusCode: 500,
611
+ publicMessage: "An unexpected error occurred.",
612
+ logMessage: "Non-DbError passed to fromDatabaseError",
613
+ cause: error instanceof Error ? error : void 0,
614
+ logContext: error instanceof Error ? void 0 : { value: String(error) }
615
+ });
616
+ }
617
+ static is(err) {
618
+ return hasBrand(err);
619
+ }
620
+ static isCode(err, code) {
621
+ return hasBrand(err) && err.code === code;
622
+ }
623
+ static isNotFound(err) {
624
+ return NextlyError.isCode(err, "NOT_FOUND");
625
+ }
626
+ static isValidation(err) {
627
+ return NextlyError.isCode(err, "VALIDATION_ERROR");
628
+ }
629
+ static isAuthRequired(err) {
630
+ return NextlyError.isCode(err, "AUTH_REQUIRED");
631
+ }
632
+ static isForbidden(err) {
633
+ return NextlyError.isCode(err, "FORBIDDEN");
634
+ }
635
+ static isConflict(err) {
636
+ return NextlyError.isCode(err, "CONFLICT");
637
+ }
638
+ static isRateLimited(err) {
639
+ return NextlyError.isCode(err, "RATE_LIMITED");
640
+ }
641
+ };
642
+ // ../nextly/dist/get-trusted-client-ip-CYEbmLA3.mjs
643
+ /**
644
+ * A dotted-quad IPv4 address as an unsigned 32-bit integer, or null when it is
645
+ * not one. Shared by the client-address, refresh-binding and outbound-URL
646
+ * prefix checks.
647
+ */
648
+ function ipv4ToInt(ip) {
649
+ const parts = ip.split(".");
650
+ if (parts.length !== 4) return null;
651
+ let acc = 0;
652
+ for (const p of parts) {
653
+ const n = Number(p);
654
+ if (!Number.isInteger(n) || n < 0 || n > 255) return null;
655
+ acc = acc << 8 | n;
656
+ }
657
+ return acc >>> 0;
658
+ }
659
+ // ../nextly/dist/validate-external-url-uHUKFZGh.mjs
660
+ const IPV4_RE = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;
661
+ /**
662
+ * IPv4 CIDR ranges that must NEVER be the destination of an outbound
663
+ * fetch sourced from a user-controllable URL. Listed roughly by RFC.
664
+ */
665
+ const PRIVATE_IPV4_CIDRS = [
666
+ "0.0.0.0/8",
667
+ "10.0.0.0/8",
668
+ "100.64.0.0/10",
669
+ "127.0.0.0/8",
670
+ "169.254.0.0/16",
671
+ "172.16.0.0/12",
672
+ "192.0.0.0/24",
673
+ "192.0.2.0/24",
674
+ "192.168.0.0/16",
675
+ "198.18.0.0/15",
676
+ "198.51.100.0/24",
677
+ "203.0.113.0/24",
678
+ "224.0.0.0/4",
679
+ "240.0.0.0/4"
680
+ ];
681
+ /**
682
+ * Cloud-metadata hostnames. These often resolve to private IPs and the
683
+ * private-IP block catches them, but we reject by hostname first so the
684
+ * error message is clear.
685
+ */
686
+ const CLOUD_METADATA_HOSTS = /* @__PURE__ */ new Set([
687
+ "metadata.google.internal",
688
+ "metadata.googleapis.com",
689
+ "metadata"
690
+ ]);
691
+ /**
692
+ * An outbound URL refused for SSRF safety. Extends `NextlyError` (the package's
693
+ * canonical error) so throw sites honor the error contract, while remaining a
694
+ * distinct class the callers (e.g. the form-builder webhook handler) match with
695
+ * `instanceof`.
696
+ */
697
+ var ExternalUrlError = class extends NextlyError {
698
+ url;
699
+ constructor(message, url) {
700
+ super({
701
+ code: "EXTERNAL_URL_BLOCKED",
702
+ publicMessage: message,
703
+ logContext: { url }
704
+ });
705
+ this.url = url;
706
+ this.name = "ExternalUrlError";
707
+ }
708
+ };
709
+ /** Validate a URL for outbound fetch. Throws `ExternalUrlError` on rejection. */
710
+ async function validateExternalUrl(rawUrl, options = {}) {
711
+ let parsed;
712
+ try {
713
+ parsed = new URL(rawUrl);
714
+ } catch {
715
+ throw new ExternalUrlError("Invalid URL", rawUrl);
716
+ }
717
+ const hostname = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
718
+ const isLocalhostHostname = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
719
+ const baseProtocols = options.allowedProtocols ?? ["https:"];
720
+ const protocols = options.allowLocalhost && isLocalhostHostname ? [...baseProtocols, "http:"] : baseProtocols;
721
+ if (!protocols.includes(parsed.protocol)) throw new ExternalUrlError(`Protocol ${parsed.protocol} not allowed (allowed: ${protocols.join(", ")})`, rawUrl);
722
+ if (CLOUD_METADATA_HOSTS.has(hostname)) throw new ExternalUrlError(`Cloud-metadata hostname rejected: ${parsed.hostname}`, rawUrl);
723
+ if (IPV4_RE.test(hostname)) {
724
+ if (!isPublicIpv4(hostname, options.allowLocalhost === true && hostname === "127.0.0.1")) throw new ExternalUrlError(`Resolved to non-public IP: ${hostname}`, rawUrl);
725
+ return {
726
+ url: parsed,
727
+ pinnedIp: hostname,
728
+ family: 4
729
+ };
730
+ }
731
+ if (hostname.includes(":")) {
732
+ if (!isPublicIpv6(hostname, options.allowLocalhost === true && hostname === "::1")) throw new ExternalUrlError(`Resolved to non-public IP: ${hostname}`, rawUrl);
733
+ return {
734
+ url: parsed,
735
+ pinnedIp: hostname,
736
+ family: 6
737
+ };
738
+ }
739
+ const { lookup } = await import("node:dns/promises");
740
+ let addresses;
741
+ try {
742
+ addresses = await lookup(hostname, { all: true });
743
+ } catch (err) {
744
+ throw new ExternalUrlError(`DNS lookup failed: ${err.message}`, rawUrl);
745
+ }
746
+ if (addresses.length === 0) throw new ExternalUrlError("No IPs returned for host", rawUrl);
747
+ for (const { address, family } of addresses) {
748
+ const allow = options.allowLocalhost === true && isLocalhostHostname && family === 4;
749
+ if (!(family === 4 ? isPublicIpv4(address, allow) : isPublicIpv6(address, allow))) throw new ExternalUrlError(`Resolved to non-public IP: ${address}`, rawUrl);
750
+ }
751
+ const first = addresses[0];
752
+ return {
753
+ url: parsed,
754
+ pinnedIp: first.address,
755
+ family: first.family === 6 ? 6 : 4
756
+ };
757
+ }
758
+ /** Default response body cap: reject anything larger before buffering it all. */
759
+ /**
760
+ * How many bytes a bounded external read may buffer, absent a caller's own cap.
761
+ *
762
+ * Exported for the same reason as the deadline below: an adapter that never
763
+ * touches `safeFetch` still owes callers this default, and restating the number
764
+ * gives the tree two that drift.
765
+ */
766
+ const DEFAULT_MAX_RESPONSE_BYTES = 10485760;
767
+ /** Default overall deadline covering DNS + connect + TLS + response. */
768
+ /**
769
+ * How long a bounded external read may take, absent a caller's own limit.
770
+ *
771
+ * Exported so a caller that must begin the clock EARLIER — a storage adapter
772
+ * bounding a metadata lookup as well as the fetch that follows — uses this
773
+ * number rather than restating it. Two spellings of one default agree today and
774
+ * drift the first time either is tuned.
775
+ */
776
+ const DEFAULT_TIMEOUT_MS = 3e4;
777
+ /**
778
+ * Raised for fetch-phase failures that are NOT SSRF rejections: an over-large
779
+ * response body, the overall deadline elapsing, or an undecodable content
780
+ * encoding. Extends `NextlyError` (the canonical error contract) while staying a
781
+ * distinct class, so a caller can tell "URL refused for safety"
782
+ * (`ExternalUrlError`) apart from "the request itself failed".
783
+ */
784
+ var SafeFetchError = class extends NextlyError {
785
+ url;
786
+ reason;
787
+ status;
788
+ constructor(message, url, reason, status) {
789
+ super({
790
+ code: "EXTERNAL_REQUEST_FAILED",
791
+ publicMessage: message,
792
+ logContext: {
793
+ url,
794
+ reason
795
+ }
796
+ });
797
+ this.url = url;
798
+ this.reason = reason;
799
+ this.status = status;
800
+ this.name = "SafeFetchError";
801
+ }
802
+ };
803
+ /**
804
+ * Build a `dns.lookup`-compatible function that ignores the hostname and
805
+ * always resolves to `ip`/`family`. Handing this to `http(s).request` forces
806
+ * the socket to dial the exact address `validateExternalUrl` already vetted,
807
+ * closing the DNS-rebinding window where a second resolution at connect time
808
+ * could return a private IP. Not re-exported from the package barrel; exported
809
+ * for the plugin `ctx.fetch` transport, which pins its vetted address the same
810
+ * way, and so the rebinding invariant can be unit-tested directly.
811
+ */
812
+ function createPinnedLookup(ip, family) {
813
+ return (_hostname, options, callback) => {
814
+ if (options && options.all) callback(null, [{
815
+ address: ip,
816
+ family
817
+ }]);
818
+ else callback(null, ip, family);
819
+ };
820
+ }
821
+ /**
822
+ * Validate `rawUrl` then fetch it with the validated IP pinned at the socket.
823
+ * The convenience wrapper for the common case (webhook delivery, email
824
+ * attachment fetch). Node-runtime only.
825
+ *
826
+ * DNS is resolved once by `validateExternalUrl`; `createPinnedLookup` forces
827
+ * the connection to that same address, so an attacker's DNS cannot rebind the
828
+ * request to a private host between validation and connect. Redirects are not
829
+ * followed, the body is capped at `maxResponseBytes`, and the request is
830
+ * bounded by `timeoutMs`.
831
+ */
832
+ async function safeFetch(rawUrl, options = {}) {
833
+ const { allowLocalhost, allowedProtocols, method, headers, body, signal, maxResponseBytes = DEFAULT_MAX_RESPONSE_BYTES, timeoutMs = DEFAULT_TIMEOUT_MS } = options;
834
+ const controller = new AbortController();
835
+ const forwardAbort = () => controller.abort(signal?.reason);
836
+ if (signal) {
837
+ if (signal.aborted) controller.abort(signal.reason);
838
+ else signal.addEventListener("abort", forwardAbort, { once: true });
839
+ }
840
+ const timer = setTimeout(() => controller.abort(new SafeFetchError(`Request exceeded ${timeoutMs}ms`, rawUrl, "timeout")), timeoutMs);
841
+ try {
842
+ return await pinnedFetch(await abortable(validateExternalUrl(rawUrl, {
843
+ allowLocalhost,
844
+ allowedProtocols
845
+ }), controller.signal), {
846
+ method,
847
+ headers,
848
+ body,
849
+ signal: controller.signal,
850
+ maxResponseBytes
851
+ });
852
+ } finally {
853
+ clearTimeout(timer);
854
+ if (signal) signal.removeEventListener("abort", forwardAbort);
855
+ }
856
+ }
857
+ /**
858
+ * The signal's abort reason as an `Error`. Our own aborts carry a
859
+ * `SafeFetchError` (timeout); a caller's `AbortController.abort()` carries a
860
+ * DOMException `AbortError`; anything else (a non-Error reason) is surfaced as
861
+ * a standard `AbortError` so downstream `name === "AbortError"` checks hold.
862
+ */
863
+ function abortError(signal) {
864
+ const reason = signal.reason;
865
+ if (reason instanceof Error) return reason;
866
+ return new DOMException("The operation was aborted", "AbortError");
867
+ }
868
+ /**
869
+ * Resolve `promise`, but reject with the signal's reason if it aborts first.
870
+ * Lets a phase that runs before the request (DNS validation) share the overall
871
+ * deadline and caller cancellation.
872
+ */
873
+ function abortable(promise, signal) {
874
+ if (signal.aborted) return Promise.reject(abortError(signal));
875
+ let onAbort;
876
+ const aborted = new Promise((_resolve, reject) => {
877
+ onAbort = () => reject(abortError(signal));
878
+ signal.addEventListener("abort", onAbort, { once: true });
879
+ });
880
+ return Promise.race([promise, aborted]).finally(() => signal.removeEventListener("abort", onAbort));
881
+ }
882
+ /**
883
+ * Issue the request over `node:http`/`node:https` with the validated IP pinned
884
+ * via a custom `lookup`, then adapt the Node response into a WHATWG `Response`.
885
+ * `agent: false` forces a fresh socket per call so no pooled connection can
886
+ * reuse a differently-resolved address. The overall deadline is enforced by the
887
+ * caller through `init.signal`, so there is no separate timer here.
888
+ */
889
+ async function pinnedFetch(validated, init) {
890
+ const { url, pinnedIp, family } = validated;
891
+ const httpMod = url.protocol === "https:" ? await import("node:https") : await import("node:http");
892
+ const zlib = await import("node:zlib");
893
+ const lookup = createPinnedLookup(pinnedIp, family);
894
+ const outHeaders = toOutgoingHeaders(init.headers);
895
+ if (init.body != null) {
896
+ delete outHeaders["transfer-encoding"];
897
+ outHeaders["content-length"] = String(typeof init.body === "string" ? Buffer.byteLength(init.body) : init.body.byteLength);
898
+ }
899
+ return new Promise((resolve, reject) => {
900
+ let settled = false;
901
+ const settle = (fn) => {
902
+ if (settled) return;
903
+ settled = true;
904
+ fn();
905
+ };
906
+ const failure = (err) => init.signal.aborted ? abortError(init.signal) : err;
907
+ const req = httpMod.request(url, {
908
+ method: init.method ?? "GET",
909
+ headers: outHeaders,
910
+ lookup,
911
+ agent: false,
912
+ signal: init.signal
913
+ }, (res) => {
914
+ const chunks = [];
915
+ let received = 0;
916
+ res.on("data", (chunk) => {
917
+ received += chunk.length;
918
+ if (received > init.maxResponseBytes) {
919
+ res.destroy();
920
+ req.destroy();
921
+ settle(() => reject(new SafeFetchError(`Response body exceeded ${init.maxResponseBytes} bytes`, url.href, "response-too-large", res.statusCode)));
922
+ return;
923
+ }
924
+ chunks.push(chunk);
925
+ });
926
+ res.on("end", () => {
927
+ const decoded = decodeBody(Buffer.concat(chunks), res.headers["content-encoding"], zlib, init.maxResponseBytes, url.href, res.statusCode);
928
+ if (decoded instanceof SafeFetchError) {
929
+ settle(() => reject(decoded));
930
+ return;
931
+ }
932
+ settle(() => resolve(toWhatwgResponse(res, decoded.body, decoded.decoded)));
933
+ });
934
+ res.on("error", (err) => settle(() => reject(failure(err))));
935
+ });
936
+ req.on("error", (err) => settle(() => reject(failure(err))));
937
+ if (!req.destroyed) {
938
+ if (init.body != null) req.write(init.body);
939
+ req.end();
940
+ }
941
+ });
942
+ }
943
+ /**
944
+ * Normalize a `HeadersInit` into Node's outgoing-header shape. Header names are
945
+ * lowercased (they are case-insensitive) so later framing checks
946
+ * (`content-length`) and the Host strip are reliable regardless of caller
947
+ * casing. A caller-supplied `Host` is dropped: it is derived from the validated
948
+ * URL, and honoring an override would let Host-based routing reach an internal
949
+ * vhost behind a validated public IP, defeating the SSRF pin.
950
+ */
951
+ function toOutgoingHeaders(headers) {
952
+ const out = {};
953
+ if (!headers) return out;
954
+ const add = (rawKey, value) => {
955
+ const key = rawKey.toLowerCase();
956
+ if (key === "host") return;
957
+ const existing = out[key];
958
+ out[key] = existing === void 0 ? value : [].concat(existing, value);
959
+ };
960
+ if (headers instanceof Headers) headers.forEach((value, key) => add(key, value));
961
+ else if (Array.isArray(headers)) for (const [key, value] of headers) add(key, value);
962
+ else for (const [key, value] of Object.entries(headers)) add(key, value);
963
+ return out;
964
+ }
965
+ /**
966
+ * Adapt a Node `IncomingMessage` + buffered body into a WHATWG `Response`.
967
+ * Total by construction: a header the WHATWG layer rejects is skipped and the
968
+ * status is clamped to a constructible range, so this never throws (a throw
969
+ * would otherwise escape the `end` handler as an uncaught error).
970
+ */
971
+ function toWhatwgResponse(res, body, stripContentHeaders) {
972
+ const headers = new Headers();
973
+ for (const [key, value] of Object.entries(res.headers)) {
974
+ if (value == null) continue;
975
+ const lower = key.toLowerCase();
976
+ if (stripContentHeaders && (lower === "content-encoding" || lower === "content-length")) continue;
977
+ const values = Array.isArray(value) ? value : [value];
978
+ for (const v of values) try {
979
+ headers.append(key, v);
980
+ } catch {}
981
+ }
982
+ const raw = res.statusCode ?? 502;
983
+ const status = raw >= 200 && raw <= 599 ? raw : 502;
984
+ const nullBody = status === 204 || status === 205 || status === 304;
985
+ const bytes = new Uint8Array(body.byteLength);
986
+ bytes.set(body);
987
+ return new Response(nullBody ? null : bytes, {
988
+ status,
989
+ statusText: res.statusMessage ?? "",
990
+ headers
991
+ });
992
+ }
993
+ /**
994
+ * Content-decode a response body per its `Content-Encoding`. node:http returns
995
+ * raw wire bytes (unlike global fetch), so gzip/deflate/br bodies are inflated
996
+ * here to preserve the previous behavior. `maxOutputLength` bounds the inflated
997
+ * size, turning a decompression bomb into a `SafeFetchError` rather than an OOM.
998
+ * Returns the (possibly decoded) buffer, or a `SafeFetchError` on failure.
999
+ */
1000
+ function decodeBody(buf, encoding, zlib, cap, url, status) {
1001
+ if (!encoding) return {
1002
+ body: buf,
1003
+ decoded: false
1004
+ };
1005
+ if (buf.length === 0) return {
1006
+ body: buf,
1007
+ decoded: true
1008
+ };
1009
+ const layers = encoding.split(",").map((e) => e.trim().toLowerCase()).filter(Boolean);
1010
+ const opts = { maxOutputLength: cap };
1011
+ let current = buf;
1012
+ let decoded = false;
1013
+ try {
1014
+ for (let i = layers.length - 1; i >= 0; i--) {
1015
+ const enc = layers[i];
1016
+ if (enc === "identity") continue;
1017
+ if (enc === "gzip" || enc === "x-gzip") current = zlib.gunzipSync(current, opts);
1018
+ else if (enc === "br") current = zlib.brotliDecompressSync(current, opts);
1019
+ else if (enc === "deflate") try {
1020
+ current = zlib.inflateSync(current, opts);
1021
+ } catch (inflateErr) {
1022
+ if (errorCode(inflateErr) === "ERR_BUFFER_TOO_LARGE") throw inflateErr;
1023
+ current = zlib.inflateRawSync(current, opts);
1024
+ }
1025
+ else {
1026
+ if (decoded) return new SafeFetchError(`Cannot fully decode content-encoding "${encoding}"`, url, "decode-failed", status);
1027
+ return {
1028
+ body: buf,
1029
+ decoded: false
1030
+ };
1031
+ }
1032
+ decoded = true;
1033
+ }
1034
+ return {
1035
+ body: current,
1036
+ decoded
1037
+ };
1038
+ } catch (err) {
1039
+ const tooLarge = errorCode(err) === "ERR_BUFFER_TOO_LARGE";
1040
+ return new SafeFetchError(tooLarge ? `Decoded ${encoding} response body exceeded the size cap` : `Failed to decode ${encoding} response body`, url, tooLarge ? "response-too-large" : "decode-failed", status);
1041
+ }
1042
+ }
1043
+ /** The `.code` of a Node system error, if present. */
1044
+ function errorCode(err) {
1045
+ if (err != null && typeof err === "object" && "code" in err) {
1046
+ const code = err.code;
1047
+ return typeof code === "string" ? code : void 0;
1048
+ }
1049
+ }
1050
+ function isIpv4InCidr(intIp, cidr) {
1051
+ const [addr, prefixRaw] = cidr.split("/");
1052
+ const intCidr = ipv4ToInt(addr);
1053
+ if (intCidr === null) return false;
1054
+ const prefix = Number(prefixRaw);
1055
+ if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false;
1056
+ const mask = prefix === 0 ? 0 : -1 >>> 32 - prefix << 32 - prefix;
1057
+ return (intIp & mask) >>> 0 === (intCidr & mask) >>> 0;
1058
+ }
1059
+ function isPublicIpv4(addr, allowLoopback) {
1060
+ const intIp = ipv4ToInt(addr);
1061
+ if (intIp === null) return false;
1062
+ if (allowLoopback && addr === "127.0.0.1") return true;
1063
+ for (const cidr of PRIVATE_IPV4_CIDRS) if (isIpv4InCidr(intIp, cidr)) return false;
1064
+ return true;
1065
+ }
1066
+ /**
1067
+ * Extract the embedded IPv4 of an IPv4-mapped IPv6 address, or null. Handles
1068
+ * both the dotted form (`::ffff:1.2.3.4`) and the hex form (`::ffff:7f00:1`)
1069
+ * that `URL.hostname` normalizes the dotted literal to — the latter would
1070
+ * otherwise skip the IPv4 denylist and pin, e.g., loopback as public.
1071
+ */
1072
+ function mappedIpv4(lower) {
1073
+ const dotted = lower.match(/^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
1074
+ if (dotted) return dotted[1];
1075
+ const hex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
1076
+ if (hex) {
1077
+ const hi = parseInt(hex[1], 16);
1078
+ const lo = parseInt(hex[2], 16);
1079
+ return [
1080
+ hi >> 8,
1081
+ hi & 255,
1082
+ lo >> 8,
1083
+ lo & 255
1084
+ ].join(".");
1085
+ }
1086
+ return null;
1087
+ }
1088
+ function isPublicIpv6(addr, allowLoopback) {
1089
+ const lower = addr.toLowerCase();
1090
+ if (allowLoopback && lower === "::1") return true;
1091
+ const mapped = mappedIpv4(lower);
1092
+ if (mapped) return isPublicIpv4(mapped, allowLoopback);
1093
+ if (lower === "::" || lower === "::1") return false;
1094
+ const firstHextet = lower.split(":")[0] || "";
1095
+ if (firstHextet.startsWith("fc") || firstHextet.startsWith("fd")) return false;
1096
+ if (firstHextet.startsWith("fe8") || firstHextet.startsWith("fe9")) return false;
1097
+ if (firstHextet.startsWith("fea") || firstHextet.startsWith("feb")) return false;
1098
+ if (firstHextet.startsWith("ff")) return false;
1099
+ return true;
1100
+ }
1101
+ // ../nextly/dist/storage/read-errors.mjs
1102
+ /**
1103
+ * The one way the storage layer says a read exceeded the caller's cap.
1104
+ *
1105
+ * `StorageReadOptions.maxBytes` is part of the adapter contract, so what happens
1106
+ * when it is exceeded belongs to the contract too. Without this each backend
1107
+ * refuses in its own vocabulary — the URL-addressed ones through a fetch error
1108
+ * carrying a `reason`, S3 through whatever its own code threw — and a caller
1109
+ * wanting to tell "too large" from "could not read" has to know which adapter it
1110
+ * is talking to. That is the thing an adapter contract exists to stop.
1111
+ *
1112
+ * Distinct from a generic internal failure because callers ACT on the
1113
+ * difference. The email attachment path answers an over-cap read with
1114
+ * `ATTACHMENT_SIZE_EXCEEDED`, which tells an author to attach something smaller;
1115
+ * a storage failure tells them nothing they can act on. Collapsing the two turns
1116
+ * a fixable refusal into an opaque error, which is the same conflation this
1117
+ * contract already draws between a missing key and an unreachable store.
1118
+ *
1119
+ * @module storage/read-errors
1120
+ */
1121
+ /**
1122
+ * A read refused because the object is larger than the caller allowed.
1123
+ *
1124
+ * Carries the numbers rather than only a message, so a caller can say what the
1125
+ * limit was without parsing prose — and so the message itself stays free of the
1126
+ * key, which should not travel to whoever asked for the file.
1127
+ */
1128
+ var StorageReadTooLargeError = class extends NextlyError {
1129
+ path;
1130
+ maxBytes;
1131
+ size;
1132
+ constructor(path, maxBytes, size) {
1133
+ super({
1134
+ code: "STORAGE_READ_TOO_LARGE",
1135
+ publicMessage: "The stored file is larger than the limit for this read.",
1136
+ logContext: {
1137
+ path,
1138
+ maxBytes,
1139
+ ...size === void 0 ? {} : { size }
1140
+ }
1141
+ });
1142
+ this.path = path;
1143
+ this.maxBytes = maxBytes;
1144
+ this.size = size;
1145
+ }
1146
+ };
1147
+ // ../nextly/dist/storage/fetch-stored-bytes.mjs
1148
+ /**
1149
+ * Reading bytes back from a storage service that only exposes them over HTTP.
1150
+ *
1151
+ * The local adapter reads from disk and S3 reads through its own SDK, so
1152
+ * neither needs this. The services that address a file by URL — Vercel Blob,
1153
+ * UploadThing — all end up doing the same three things, and doing them the same
1154
+ * way matters more than it looks: each step below is a place where the obvious
1155
+ * shortcut reports the wrong thing to a caller who may act on it.
1156
+ *
1157
+ * Built on {@link safeFetch} rather than on a bare `fetch`, because "read a
1158
+ * remote object into memory" already has an implementation here that caps the
1159
+ * body, bounds the request and refuses an address that resolves somewhere
1160
+ * private. A second capped fetch beside it would be two answers to one
1161
+ * question, and the two would drift the first time either learned something.
1162
+ * Measured: it costs an adapter package about 80K, against the 1MB the whole
1163
+ * storage barrel costs.
1164
+ *
1165
+ * @module storage/fetch-stored-bytes
1166
+ */
1167
+ /**
1168
+ * Fetch a stored object's bytes from the URL its service issued.
1169
+ *
1170
+ * Separates the two answers a read can have, which is the whole reason this is
1171
+ * a function rather than three lines inlined twice.
1172
+ *
1173
+ * `null` means the object is NOT THERE — an ordinary fact about the store. A
1174
+ * 404 is that answer even when the lookup just succeeded: these stores are
1175
+ * remote and concurrent, so an object can be deleted between resolving its
1176
+ * address and fetching it. Reporting that ordinary race as a server failure
1177
+ * would make a caller handle an error for something its own contract already
1178
+ * has a value for.
1179
+ *
1180
+ * Anything else THROWS. A dropped connection, a 5xx or a refused request says
1181
+ * nothing about whether the object exists, and reporting it as absence invites
1182
+ * a caller to treat a live file as deleted and write a replacement over it. The
1183
+ * two are easy to state apart and easy to lose when the fetch sits inside the
1184
+ * same `try` that catches the lookup.
1185
+ *
1186
+ * The URL is always one the SERVICE issued, never one assembled from a key.
1187
+ * These stores mint addresses carrying suffixes the adapter never chose, so a
1188
+ * derived URL is a guess at a string another system owns.
1189
+ *
1190
+ * @param url - The address the storage service reported for this object
1191
+ * @param context - What is being read, for the error message: usually the key
1192
+ * @param label - The service's name, so a failure says which store answered
1193
+ * @param options - Bounds for the read; see {@link StorageReadOptions}
1194
+ * @param signal - A deadline ALREADY RUNNING, covering an earlier phase too
1195
+ * @returns The object's bytes, or `null` when the store answers 404
1196
+ */
1197
+ async function fetchStoredBytes(url, context, label, options, signal) {
1198
+ let response;
1199
+ try {
1200
+ response = await safeFetch(url, {
1201
+ ...options?.maxBytes === void 0 ? {} : { maxResponseBytes: options.maxBytes },
1202
+ ...signal !== void 0 ? { signal } : options?.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
1203
+ });
1204
+ } catch (error) {
1205
+ const verdict = classifyFetchFailure(error);
1206
+ if (verdict === "absent") return null;
1207
+ if (verdict === "oversized") throw new StorageReadTooLargeError(context, resolveReadBounds(options).maxBytes);
1208
+ throw error;
1209
+ }
1210
+ if (response.status === 404) return null;
1211
+ if (!response.ok) throw NextlyError.internal({ logContext: {
1212
+ service: label,
1213
+ path: context,
1214
+ status: response.status,
1215
+ statusText: response.statusText
1216
+ } });
1217
+ return Buffer.from(await response.arrayBuffer());
1218
+ }
1219
+ /**
1220
+ * What a failed fetch actually says about the object.
1221
+ *
1222
+ * Its own function because the three answers are the whole point of this module
1223
+ * and they are easy to collapse into each other — each collapse having been a
1224
+ * real defect here rather than a hypothetical:
1225
+ *
1226
+ * - ABSENT. A 404 is absence whatever size its body was. `safeFetch` caps while
1227
+ * buffering, so a verbose CDN error page raises before a `Response` exists
1228
+ * and the status check further down is never reached; the object is still
1229
+ * gone, and must not become an error because the page explaining it was long.
1230
+ * - OVERSIZED. Only a SUCCESSFUL response that blew the cap. A failed response
1231
+ * can exceed it too, and translating on the reason alone reported a backend
1232
+ * outage as "your file is too big" — a cause the author would act on, wrongly.
1233
+ * - UNKNOWN. Everything else, including a too-large refusal carrying NO status:
1234
+ * that means the failure arrived before any status did, which says nothing
1235
+ * about whether the object was oversized.
1236
+ */
1237
+ function classifyFetchFailure(error) {
1238
+ if (!(error instanceof SafeFetchError)) return "unknown";
1239
+ if (error.status === 404) return "absent";
1240
+ const successful = error.status !== void 0 && error.status >= 200 && error.status < 300;
1241
+ return error.reason === "response-too-large" && successful ? "oversized" : "unknown";
1242
+ }
1243
+ /** The deadline a stored read runs under when the caller names none. */
1244
+ const DEFAULT_READ_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
1245
+ /** The byte cap a stored read runs under when the caller names none. */
1246
+ const DEFAULT_READ_MAX_BYTES = DEFAULT_MAX_RESPONSE_BYTES;
1247
+ /**
1248
+ * The bounds a read actually runs under, defaults filled in.
1249
+ *
1250
+ * ONE place, because every adapter needs the same answer and the ones that
1251
+ * derived it themselves diverged: the URL-backed pair inherited `safeFetch`'s
1252
+ * cap and deadline for free, while the local and S3 adapters — which never
1253
+ * touch `safeFetch` — applied NO bound at all when the caller named none.
1254
+ * `StorageReadOptions` promises the default either way, and a production caller
1255
+ * reading media without options got it from two of four backends.
1256
+ *
1257
+ * Filling the defaults here rather than per adapter is what makes the promise
1258
+ * true by construction rather than by four implementations agreeing.
1259
+ */
1260
+ function resolveReadBounds(options) {
1261
+ return {
1262
+ maxBytes: options?.maxBytes ?? DEFAULT_READ_MAX_BYTES,
1263
+ timeoutMs: options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS
1264
+ };
1265
+ }
3
1266
  // src/adapter.ts
1267
+ /**
1268
+ * Vercel Blob Storage Adapter
1269
+ *
1270
+ * Stores files on Vercel Blob Storage, a globally distributed object storage
1271
+ * service powered by Cloudflare R2. Optimized for Vercel deployments with
1272
+ * built-in CDN distribution.
1273
+ *
1274
+ * Features:
1275
+ * - Globally distributed CDN-backed storage
1276
+ * - Automatic file management with unique filenames
1277
+ * - Token-based authentication
1278
+ * - Client-side upload support (via handleUpload API)
1279
+ * - Serverless-friendly (no filesystem access required)
1280
+ *
1281
+ * @example Basic usage
1282
+ * ```typescript
1283
+ * const adapter = new VercelBlobStorageAdapter({
1284
+ * token: process.env.BLOB_READ_WRITE_TOKEN,
1285
+ * collections: { media: true }
1286
+ * });
1287
+ *
1288
+ * const result = await adapter.upload(buffer, {
1289
+ * filename: 'photo.jpg',
1290
+ * mimeType: 'image/jpeg'
1291
+ * });
1292
+ * // result.url: "https://abc123.public.blob.vercel-storage.com/photo-xyz.jpg"
1293
+ * ```
1294
+ */
1295
+ /**
1296
+ * Vercel Blob Storage Adapter
1297
+ *
1298
+ * Implements the IStorageAdapter interface for Vercel Blob Storage.
1299
+ * Provides file upload, deletion, existence checks, and metadata retrieval.
1300
+ */
4
1301
  var VercelBlobStorageAdapter = class {
5
- /**
6
- * Create a new Vercel Blob storage adapter.
7
- *
8
- * @param config - Vercel Blob storage configuration
9
- * @throws Error if token is not provided
10
- */
11
- constructor(config) {
12
- this.config = config;
13
- const token = config.token || process.env.BLOB_READ_WRITE_TOKEN || "";
14
- if (!token) {
15
- throw new Error(
16
- "@nextly/storage-vercel-blob: token is required.\n\nEither set the BLOB_READ_WRITE_TOKEN environment variable or pass token in config.\nGet your token from: Vercel Dashboard > Storage > Blob > Tokens"
17
- );
18
- }
19
- this.resolvedConfig = {
20
- token,
21
- addRandomSuffix: config.addRandomSuffix ?? true,
22
- cacheControlMaxAge: config.cacheControlMaxAge ?? 31536e3,
23
- access: config.access ?? "public",
24
- storeId: config.storeId,
25
- allowOverwrite: config.allowOverwrite ?? false,
26
- multipartThreshold: config.multipartThreshold ?? 5 * 1024 * 1024
27
- // 5MB
28
- };
29
- }
30
- resolvedConfig;
31
- // ============================================================
32
- // Core IStorageAdapter Methods
33
- // ============================================================
34
- /**
35
- * Upload file to Vercel Blob.
36
- *
37
- * Files are stored with globally distributed CDN backing.
38
- * By default, a random suffix is added to prevent filename collisions.
39
- *
40
- * @param buffer - File content as Buffer
41
- * @param options - Upload options (filename, mimeType, folder, collection)
42
- * @returns Upload result with URL and storage path
43
- */
44
- async upload(buffer, options) {
45
- const mimeType = (options.contentType || options.mimeType || "").toLowerCase().trim();
46
- const filename = (options.filename || "").toLowerCase();
47
- const ext = filename.includes(".") ? filename.slice(filename.lastIndexOf(".") + 1) : "";
48
- const isSvg = mimeType === "image/svg+xml" || ext === "svg" || ext === "svgz";
49
- const isHtml = mimeType === "text/html" || mimeType === "application/xhtml+xml" || ext === "html" || ext === "htm" || ext === "xhtml";
50
- if (isSvg || isHtml) {
51
- const kind = isSvg ? "SVG" : "HTML";
52
- throw new Error(
53
- `[nextly/storage-vercel-blob] ${kind} uploads are rejected on Vercel Blob \u2014 the platform cannot serve them with attachment-disposition or a restrictive CSP, so they would be stored XSS. Use the S3 / R2 adapter for ${kind} files, or convert to a raster format (PNG/WebP).`
54
- );
55
- }
56
- const pathname = this.buildPathname(options.filename, options.folder);
57
- const result = await put(pathname, buffer, {
58
- access: this.resolvedConfig.access,
59
- token: this.resolvedConfig.token,
60
- contentType: options.contentType || options.mimeType,
61
- addRandomSuffix: this.resolvedConfig.addRandomSuffix,
62
- cacheControlMaxAge: this.resolvedConfig.cacheControlMaxAge
63
- });
64
- return {
65
- url: result.url,
66
- path: result.url
67
- };
68
- }
69
- /**
70
- * Delete file from Vercel Blob.
71
- *
72
- * @param filePath - Full blob URL to delete
73
- */
74
- async delete(filePath) {
75
- await del(filePath, {
76
- token: this.resolvedConfig.token
77
- });
78
- }
79
- /**
80
- * Delete multiple files from Vercel Blob in chunked batches.
81
- *
82
- * Processes deletions in chunks of 10 concurrent calls using Promise.allSettled,
83
- * collecting successes and failures without short-circuiting.
84
- *
85
- * @param filePaths - Array of full blob URLs to delete
86
- * @returns BulkDeleteResult with successful and failed arrays
87
- */
88
- async bulkDelete(filePaths) {
89
- const successful = [];
90
- const failed = [];
91
- const chunkSize = 10;
92
- for (let i = 0; i < filePaths.length; i += chunkSize) {
93
- const chunk = filePaths.slice(i, i + chunkSize);
94
- const results = await Promise.allSettled(
95
- chunk.map((fp) => del(fp, { token: this.resolvedConfig.token }))
96
- );
97
- results.forEach((result, idx) => {
98
- const fp = chunk[idx];
99
- if (result.status === "fulfilled") {
100
- successful.push(fp);
101
- } else {
102
- failed.push({
103
- filePath: fp,
104
- error: result.reason instanceof Error ? result.reason.message : String(result.reason)
105
- });
106
- }
107
- });
108
- }
109
- return { successful, failed };
110
- }
111
- /**
112
- * Check if file exists in Vercel Blob.
113
- *
114
- * Uses the head() function which is efficient for existence checks.
115
- *
116
- * @param filePath - Full blob URL to check
117
- * @returns true if file exists, false otherwise
118
- */
119
- async exists(filePath) {
120
- try {
121
- await head(filePath, {
122
- token: this.resolvedConfig.token
123
- });
124
- return true;
125
- } catch {
126
- return false;
127
- }
128
- }
129
- /**
130
- * Get public URL for Vercel Blob file.
131
- *
132
- * Vercel Blob paths ARE the public URLs - they're already full HTTPS URLs
133
- * with CDN distribution.
134
- *
135
- * @param filePath - Full blob URL
136
- * @returns The same URL (Vercel Blob paths are already public URLs)
137
- */
138
- getPublicUrl(filePath) {
139
- return filePath;
140
- }
141
- /**
142
- * Get storage type identifier.
143
- */
144
- getType() {
145
- return "vercel-blob";
146
- }
147
- // ============================================================
148
- // Optional IStorageAdapter Methods
149
- // ============================================================
150
- /**
151
- * Get adapter info including capabilities.
152
- *
153
- * @returns Adapter info with type, name, and capability flags
154
- */
155
- getInfo() {
156
- return {
157
- type: "vercel-blob",
158
- name: "VercelBlobStorageAdapter",
159
- supportsSignedUrls: false,
160
- // Vercel Blob URLs are public by default
161
- supportsClientUploads: true
162
- // Via handleUpload API
163
- };
164
- }
165
- /**
166
- * Get file metadata from Vercel Blob.
167
- *
168
- * Retrieves file information including size, content type, and upload date.
169
- *
170
- * @param filePath - Full blob URL
171
- * @returns File metadata or null if file not found
172
- */
173
- async getMetadata(filePath) {
174
- try {
175
- const result = await head(filePath, {
176
- token: this.resolvedConfig.token
177
- });
178
- const filename = result.pathname.split("/").pop() || result.pathname;
179
- return {
180
- id: filePath,
181
- filename,
182
- originalFilename: filename,
183
- mimeType: result.contentType,
184
- size: result.size,
185
- url: result.url,
186
- createdAt: result.uploadedAt.toISOString()
187
- };
188
- } catch {
189
- return null;
190
- }
191
- }
192
- /**
193
- * Generate pre-signed URL for client-side uploads.
194
- *
195
- * Vercel Blob uses a different pattern for client uploads - they require
196
- * the handleUpload API which handles token generation server-side.
197
- *
198
- * This method is not implemented because Vercel Blob's client upload flow
199
- * requires server-side route handlers with handleUpload().
200
- *
201
- * @see https://vercel.com/docs/storage/vercel-blob/client-upload
202
- * @throws Error always - client uploads require handleUpload API
203
- */
204
- getPresignedUploadUrl(_key, _mimeType, _expiresIn) {
205
- return Promise.reject(
206
- new Error(
207
- "@nextly/storage-vercel-blob: Client uploads require the handleUpload API.\n\nVercel Blob uses a different pattern for client-side uploads that involves:\n1. A server-side route handler with handleUpload()\n2. The @vercel/blob/client upload() function\n\nSee: https://vercel.com/docs/storage/vercel-blob/client-upload\n\nFor server-side uploads, use the standard upload() method instead."
208
- )
209
- );
210
- }
211
- // ============================================================
212
- // Additional Methods
213
- // ============================================================
214
- /**
215
- * List blobs with optional prefix filter.
216
- *
217
- * Useful for browsing or batch operations on stored files.
218
- *
219
- * @param prefix - Optional prefix to filter results
220
- * @param options - List options (limit, cursor)
221
- * @returns List of blob metadata
222
- */
223
- async listBlobs(prefix, options) {
224
- const result = await list({
225
- token: this.resolvedConfig.token,
226
- prefix,
227
- limit: options?.limit,
228
- cursor: options?.cursor
229
- });
230
- return {
231
- blobs: result.blobs.map((blob) => ({
232
- url: blob.url,
233
- pathname: blob.pathname,
234
- size: blob.size,
235
- uploadedAt: blob.uploadedAt
236
- })),
237
- hasMore: result.hasMore,
238
- cursor: result.cursor
239
- };
240
- }
241
- // ============================================================
242
- // Helper Methods
243
- // ============================================================
244
- /**
245
- * Build pathname for Vercel Blob upload.
246
- *
247
- * Creates pathname in format: {folder}/{filename}
248
- * If no folder is provided, uses the filename directly.
249
- *
250
- * @param filename - Original filename (will be sanitized)
251
- * @param folder - Optional folder/prefix for organizing uploads
252
- * @returns Generated pathname
253
- * @throws Error if folder fails sanitization
254
- */
255
- buildPathname(filename, folder) {
256
- const sanitized = this.sanitizeFilename(filename);
257
- if (!folder) return sanitized;
258
- return `${this.sanitizeFolder(folder)}/${sanitized}`;
259
- }
260
- /**
261
- * Sanitize filename to prevent path traversal issues.
262
- *
263
- * @param filename - Original filename
264
- * @returns Sanitized filename
265
- */
266
- sanitizeFilename(filename) {
267
- const basename = filename.split(/[/\\]/).pop() || filename;
268
- return basename.replace(/[^a-zA-Z0-9._-]/g, "-");
269
- }
270
- /**
271
- * Reject folder values that would let a caller
272
- * escape the configured prefix via path traversal or weird
273
- * separators. Vercel Blob is flat-keyed so `/` is just part of the
274
- * pathname, but an attacker who controls `folder` could still:
275
- *
276
- * - Use `..` to chain a relative-traversal-style key.
277
- * - Use `\` (Windows separator) to confuse downstream tooling.
278
- * - Use control chars / null bytes to truncate the key.
279
- * - Use a leading `/` to look like an absolute path.
280
- *
281
- * Internal `/` segments stay allowed because callers legitimately
282
- * use nested folders (`docs/2026/...`); a leading `/`, empty
283
- * segments (`docs//x`), or `..` segments are rejected.
284
- *
285
- * @throws Error with a stable message so the storage facade can
286
- * surface a 400 instead of a 500.
287
- */
288
- sanitizeFolder(folder) {
289
- const trimmed = folder.replace(/\/+$/, "");
290
- if (!trimmed) {
291
- throw new Error("Folder must be a non-empty string.");
292
- }
293
- if (/[\\\0\x01-\x1f\x7f]/.test(trimmed)) {
294
- throw new Error(
295
- "Folder contains forbidden characters (backslash, control chars, or null bytes)."
296
- );
297
- }
298
- if (trimmed.startsWith("/")) {
299
- throw new Error("Folder must not start with `/`.");
300
- }
301
- const segments = trimmed.split("/");
302
- for (const segment of segments) {
303
- if (segment === "") {
304
- throw new Error("Folder must not contain empty segments (`//`).");
305
- }
306
- if (segment === "..") {
307
- throw new Error("Folder must not contain `..` segments.");
308
- }
309
- }
310
- return trimmed;
311
- }
312
- // ============================================================
313
- // Public Accessors
314
- // ============================================================
315
- /**
316
- * Get the configured token (masked for logging).
317
- */
318
- getTokenMasked() {
319
- const token = this.resolvedConfig.token;
320
- if (token.length <= 8) return "****";
321
- return `${token.slice(0, 4)}...${token.slice(-4)}`;
322
- }
323
- /**
324
- * Check if random suffix is enabled.
325
- */
326
- hasRandomSuffix() {
327
- return this.resolvedConfig.addRandomSuffix;
328
- }
329
- /**
330
- * Get configured cache control max age.
331
- */
332
- getCacheControlMaxAge() {
333
- return this.resolvedConfig.cacheControlMaxAge;
334
- }
1302
+ config;
1303
+ resolvedConfig;
1304
+ /**
1305
+ * Create a new Vercel Blob storage adapter.
1306
+ *
1307
+ * @param config - Vercel Blob storage configuration
1308
+ * @throws Error if token is not provided
1309
+ */
1310
+ constructor(config) {
1311
+ this.config = config;
1312
+ const token = config.token || process.env.BLOB_READ_WRITE_TOKEN || "";
1313
+ if (!token) throw new Error("@nextly/storage-vercel-blob: token is required.\n\nEither set the BLOB_READ_WRITE_TOKEN environment variable or pass token in config.\nGet your token from: Vercel Dashboard > Storage > Blob > Tokens");
1314
+ this.resolvedConfig = {
1315
+ token,
1316
+ addRandomSuffix: config.addRandomSuffix ?? true,
1317
+ cacheControlMaxAge: config.cacheControlMaxAge ?? 31536e3,
1318
+ access: config.access ?? "public",
1319
+ storeId: config.storeId,
1320
+ allowOverwrite: config.allowOverwrite ?? false,
1321
+ multipartThreshold: config.multipartThreshold ?? 5242880
1322
+ };
1323
+ }
1324
+ /**
1325
+ * Upload file to Vercel Blob.
1326
+ *
1327
+ * Files are stored with globally distributed CDN backing.
1328
+ * By default, a random suffix is added to prevent filename collisions.
1329
+ *
1330
+ * @param buffer - File content as Buffer
1331
+ * @param options - Upload options (filename, mimeType, folder, collection)
1332
+ * @returns Upload result with URL and storage path
1333
+ */
1334
+ async upload(buffer, options) {
1335
+ const mimeType = (options.contentType || options.mimeType || "").toLowerCase().trim();
1336
+ const filename = (options.filename || "").toLowerCase();
1337
+ const ext = filename.includes(".") ? filename.slice(filename.lastIndexOf(".") + 1) : "";
1338
+ if (mimeType === "text/html" || mimeType === "application/xhtml+xml" || ext === "html" || ext === "htm" || ext === "xhtml") throw NextlyError.validation({
1339
+ errors: [{
1340
+ path: "file",
1341
+ code: "UNSUPPORTED_FOR_BACKEND",
1342
+ message: "HTML files cannot be hosted on Vercel Blob. Use the S3 or R2 adapter, or upload as another format."
1343
+ }],
1344
+ logContext: {
1345
+ adapter: "vercel-blob",
1346
+ claimedMimeType: options.mimeType,
1347
+ reason: "vercel-blob-rejects-html",
1348
+ filename: options.filename
1349
+ }
1350
+ });
1351
+ const isSvg = mimeType === "image/svg+xml" || ext === "svg" || ext === "svgz";
1352
+ const pathname = this.buildPathname(options.filename, options.folder);
1353
+ const result = await put(pathname, buffer, {
1354
+ access: this.resolvedConfig.access,
1355
+ token: this.resolvedConfig.token,
1356
+ contentType: options.contentType || options.mimeType,
1357
+ addRandomSuffix: this.resolvedConfig.addRandomSuffix,
1358
+ cacheControlMaxAge: this.resolvedConfig.cacheControlMaxAge
1359
+ });
1360
+ return {
1361
+ url: isSvg && options.contentDisposition === "attachment" ? result.downloadUrl : result.url,
1362
+ path: result.url
1363
+ };
1364
+ }
1365
+ /**
1366
+ * Delete file from Vercel Blob.
1367
+ *
1368
+ * @param filePath - Full blob URL to delete
1369
+ */
1370
+ async delete(filePath) {
1371
+ await del(filePath, { token: this.resolvedConfig.token });
1372
+ }
1373
+ /**
1374
+ * Delete multiple files from Vercel Blob in chunked batches.
1375
+ *
1376
+ * Processes deletions in chunks of 10 concurrent calls using Promise.allSettled,
1377
+ * collecting successes and failures without short-circuiting.
1378
+ *
1379
+ * @param filePaths - Array of full blob URLs to delete
1380
+ * @returns BulkDeleteResult with successful and failed arrays
1381
+ */
1382
+ async bulkDelete(filePaths) {
1383
+ const successful = [];
1384
+ const failed = [];
1385
+ const chunkSize = 10;
1386
+ for (let i = 0; i < filePaths.length; i += chunkSize) {
1387
+ const chunk = filePaths.slice(i, i + chunkSize);
1388
+ (await Promise.allSettled(chunk.map((fp) => del(fp, { token: this.resolvedConfig.token })))).forEach((result, idx) => {
1389
+ const fp = chunk[idx];
1390
+ if (result.status === "fulfilled") successful.push(fp);
1391
+ else failed.push({
1392
+ filePath: fp,
1393
+ error: result.reason instanceof Error ? result.reason.message : String(result.reason)
1394
+ });
1395
+ });
1396
+ }
1397
+ return {
1398
+ successful,
1399
+ failed
1400
+ };
1401
+ }
1402
+ /**
1403
+ * Check if file exists in Vercel Blob.
1404
+ *
1405
+ * Uses the head() function which is efficient for existence checks.
1406
+ *
1407
+ * @param filePath - Full blob URL to check
1408
+ * @returns true if file exists, false otherwise
1409
+ */
1410
+ async exists(filePath) {
1411
+ try {
1412
+ await head(filePath, { token: this.resolvedConfig.token });
1413
+ return true;
1414
+ } catch {
1415
+ return false;
1416
+ }
1417
+ }
1418
+ /**
1419
+ * Read a stored blob back as bytes, or `null` when it is not there.
1420
+ *
1421
+ * A NETWORK round trip, unlike the local adapter's disk read, because the
1422
+ * bytes live on Vercel's CDN and there is no other way to reach them. That
1423
+ * cost is the reason a caller serving these from its own origin has to cache:
1424
+ * the privacy rule that forces same-origin serving does not also make the
1425
+ * fetch free, and an uncached proxy pays it on every request.
1426
+ *
1427
+ * The URL is taken from `head` rather than assembled from `filePath`,
1428
+ * because a blob's address is issued by the service — it carries a random
1429
+ * suffix this adapter never chose — so deriving one here would be guessing at
1430
+ * a string another system owns.
1431
+ *
1432
+ * `null` for a missing blob rather than a throw, matching {@link exists}.
1433
+ *
1434
+ * @param filePath - Blob path/key
1435
+ * @returns The blob's bytes, or `null` when it does not exist
1436
+ */
1437
+ async read(filePath, options) {
1438
+ const deadline = AbortSignal.timeout(options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS);
1439
+ let target;
1440
+ try {
1441
+ const meta = await head(filePath, {
1442
+ token: this.resolvedConfig.token,
1443
+ abortSignal: deadline
1444
+ });
1445
+ target = meta.downloadUrl ?? meta.url;
1446
+ } catch (error) {
1447
+ if (error instanceof BlobNotFoundError) return null;
1448
+ throw error;
1449
+ }
1450
+ return await fetchStoredBytes(target, filePath, "Vercel Blob", options, deadline);
1451
+ }
1452
+ /**
1453
+ * Get public URL for Vercel Blob file.
1454
+ *
1455
+ * Vercel Blob paths ARE the public URLs - they're already full HTTPS URLs
1456
+ * with CDN distribution.
1457
+ *
1458
+ * @param filePath - Full blob URL
1459
+ * @returns The same URL (Vercel Blob paths are already public URLs)
1460
+ */
1461
+ /**
1462
+ * Every blob in the store, by its URL (which is its stored path here), with
1463
+ * when it was uploaded, a page at a time.
1464
+ */
1465
+ async *list() {
1466
+ let cursor;
1467
+ do {
1468
+ const page = await this.listBlobs(void 0, { cursor });
1469
+ for (const blob of page.blobs) yield {
1470
+ path: blob.url,
1471
+ lastModified: blob.uploadedAt
1472
+ };
1473
+ cursor = page.hasMore ? page.cursor : void 0;
1474
+ } while (cursor);
1475
+ }
1476
+ getPublicUrl(filePath) {
1477
+ return filePath;
1478
+ }
1479
+ /**
1480
+ * Get storage type identifier.
1481
+ */
1482
+ getType() {
1483
+ return "vercel-blob";
1484
+ }
1485
+ /**
1486
+ * Get adapter info including capabilities.
1487
+ *
1488
+ * @returns Adapter info with type, name, and capability flags
1489
+ */
1490
+ getInfo() {
1491
+ return {
1492
+ type: "vercel-blob",
1493
+ name: "VercelBlobStorageAdapter",
1494
+ supportsSignedUrls: false,
1495
+ supportsClientUploads: true
1496
+ };
1497
+ }
1498
+ /**
1499
+ * Get file metadata from Vercel Blob.
1500
+ *
1501
+ * Retrieves file information including size, content type, and upload date.
1502
+ *
1503
+ * @param filePath - Full blob URL
1504
+ * @returns File metadata or null if file not found
1505
+ */
1506
+ async getMetadata(filePath) {
1507
+ try {
1508
+ const result = await head(filePath, { token: this.resolvedConfig.token });
1509
+ const filename = result.pathname.split("/").pop() || result.pathname;
1510
+ return {
1511
+ id: filePath,
1512
+ filename,
1513
+ originalFilename: filename,
1514
+ mimeType: result.contentType,
1515
+ size: result.size,
1516
+ url: result.url,
1517
+ createdAt: result.uploadedAt.toISOString()
1518
+ };
1519
+ } catch {
1520
+ return null;
1521
+ }
1522
+ }
1523
+ /**
1524
+ * Generate pre-signed URL for client-side uploads.
1525
+ *
1526
+ * Vercel Blob uses a different pattern for client uploads - they require
1527
+ * the handleUpload API which handles token generation server-side.
1528
+ *
1529
+ * This method is not implemented because Vercel Blob's client upload flow
1530
+ * requires server-side route handlers with handleUpload().
1531
+ *
1532
+ * @see https://vercel.com/docs/storage/vercel-blob/client-upload
1533
+ * @throws Error always - client uploads require handleUpload API
1534
+ */
1535
+ getPresignedUploadUrl(_key, _mimeType, _expiresIn) {
1536
+ return Promise.reject(/* @__PURE__ */ new Error("@nextly/storage-vercel-blob: Client uploads require the handleUpload API.\n\nVercel Blob uses a different pattern for client-side uploads that involves:\n1. A server-side route handler with handleUpload()\n2. The @vercel/blob/client upload() function\n\nSee: https://vercel.com/docs/storage/vercel-blob/client-upload\n\nFor server-side uploads, use the standard upload() method instead."));
1537
+ }
1538
+ /**
1539
+ * List blobs with optional prefix filter.
1540
+ *
1541
+ * Useful for browsing or batch operations on stored files.
1542
+ *
1543
+ * @param prefix - Optional prefix to filter results
1544
+ * @param options - List options (limit, cursor)
1545
+ * @returns List of blob metadata
1546
+ */
1547
+ async listBlobs(prefix, options) {
1548
+ const result = await list({
1549
+ token: this.resolvedConfig.token,
1550
+ prefix,
1551
+ limit: options?.limit,
1552
+ cursor: options?.cursor
1553
+ });
1554
+ return {
1555
+ blobs: result.blobs.map((blob) => ({
1556
+ url: blob.url,
1557
+ pathname: blob.pathname,
1558
+ size: blob.size,
1559
+ uploadedAt: blob.uploadedAt
1560
+ })),
1561
+ hasMore: result.hasMore,
1562
+ cursor: result.cursor
1563
+ };
1564
+ }
1565
+ /**
1566
+ * Build pathname for Vercel Blob upload.
1567
+ *
1568
+ * Creates pathname in format: {folder}/{filename}
1569
+ * If no folder is provided, uses the filename directly.
1570
+ *
1571
+ * @param filename - Original filename (will be sanitized)
1572
+ * @param folder - Optional folder/prefix for organizing uploads
1573
+ * @returns Generated pathname
1574
+ * @throws Error if folder fails sanitization
1575
+ */
1576
+ buildPathname(filename, folder) {
1577
+ const sanitized = this.sanitizeFilename(filename);
1578
+ if (!folder) return sanitized;
1579
+ return `${this.sanitizeFolder(folder)}/${sanitized}`;
1580
+ }
1581
+ /**
1582
+ * Sanitize filename to prevent path traversal issues.
1583
+ *
1584
+ * @param filename - Original filename
1585
+ * @returns Sanitized filename
1586
+ */
1587
+ sanitizeFilename(filename) {
1588
+ return (filename.split(/[/\\]/).pop() || filename).replace(/[^a-zA-Z0-9._-]/g, "-");
1589
+ }
1590
+ /**
1591
+ * Reject folder values that would let a caller
1592
+ * escape the configured prefix via path traversal or weird
1593
+ * separators. Vercel Blob is flat-keyed so `/` is just part of the
1594
+ * pathname, but an attacker who controls `folder` could still:
1595
+ *
1596
+ * - Use `..` to chain a relative-traversal-style key.
1597
+ * - Use `\` (Windows separator) to confuse downstream tooling.
1598
+ * - Use control chars / null bytes to truncate the key.
1599
+ * - Use a leading `/` to look like an absolute path.
1600
+ *
1601
+ * Internal `/` segments stay allowed because callers legitimately
1602
+ * use nested folders (`docs/2026/...`); a leading `/`, empty
1603
+ * segments (`docs//x`), or `..` segments are rejected.
1604
+ *
1605
+ * @throws Error with a stable message so the storage facade can
1606
+ * surface a 400 instead of a 500.
1607
+ */
1608
+ sanitizeFolder(folder) {
1609
+ const trimmed = folder.replace(/\/+$/, "");
1610
+ if (!trimmed) throw new Error("Folder must be a non-empty string.");
1611
+ if (/[\\\0\x01-\x1f\x7f]/.test(trimmed)) throw new Error("Folder contains forbidden characters (backslash, control chars, or null bytes).");
1612
+ if (trimmed.startsWith("/")) throw new Error("Folder must not start with `/`.");
1613
+ const segments = trimmed.split("/");
1614
+ for (const segment of segments) {
1615
+ if (segment === "") throw new Error("Folder must not contain empty segments (`//`).");
1616
+ if (segment === "..") throw new Error("Folder must not contain `..` segments.");
1617
+ }
1618
+ return trimmed;
1619
+ }
1620
+ /**
1621
+ * Get the configured token (masked for logging).
1622
+ */
1623
+ getTokenMasked() {
1624
+ const token = this.resolvedConfig.token;
1625
+ if (token.length <= 8) return "****";
1626
+ return `${token.slice(0, 4)}...${token.slice(-4)}`;
1627
+ }
1628
+ /**
1629
+ * Check if random suffix is enabled.
1630
+ */
1631
+ hasRandomSuffix() {
1632
+ return this.resolvedConfig.addRandomSuffix;
1633
+ }
1634
+ /**
1635
+ * Get configured cache control max age.
1636
+ */
1637
+ getCacheControlMaxAge() {
1638
+ return this.resolvedConfig.cacheControlMaxAge;
1639
+ }
335
1640
  };
336
-
337
1641
  // src/plugin.ts
1642
+ /**
1643
+ * Create a Vercel Blob storage plugin for Nextly.
1644
+ *
1645
+ * This factory function creates a StoragePlugin that can be added to
1646
+ * the `storage` array in `nextly.config.ts`. Vercel Blob is optimized
1647
+ * for Vercel deployments with:
1648
+ *
1649
+ * - Global CDN distribution
1650
+ * - Simple token-based authentication
1651
+ * - Client-side upload support (via handleUpload API)
1652
+ * - Automatic file management
1653
+ *
1654
+ * @param config - Vercel Blob storage configuration
1655
+ * @returns A StoragePlugin that MediaStorage can register
1656
+ *
1657
+ * @throws Error if token is not provided (via adapter)
1658
+ */
338
1659
  function vercelBlobStorage(config) {
339
- if (config.enabled === false) {
340
- return {
341
- name: "vercel-blob-storage",
342
- type: "vercel-blob",
343
- collections: {},
344
- adapter: null
345
- };
346
- }
347
- const adapter = new VercelBlobStorageAdapter(config);
348
- const plugin = {
349
- name: "vercel-blob-storage",
350
- type: "vercel-blob",
351
- collections: config.collections,
352
- adapter,
353
- /**
354
- * Generate upload URL for client-side uploads.
355
- *
356
- * Note: Vercel Blob uses a different pattern for client uploads.
357
- * Instead of pre-signed URLs, it uses the handleUpload() API which
358
- * requires server-side route handlers.
359
- *
360
- * This method throws an error explaining the correct approach.
361
- *
362
- * @see https://vercel.com/docs/storage/vercel-blob/client-upload
363
- */
364
- getClientUploadUrl(_filename, _mimeType, _collection) {
365
- return Promise.reject(
366
- new Error(
367
- "@nextly/storage-vercel-blob: Client uploads require the handleUpload API.\n\nVercel Blob uses a different pattern than S3 for client-side uploads:\n\n1. Create a server-side route handler with handleUpload()\n2. Use upload() from @vercel/blob/client on the frontend\n\nSee: https://vercel.com/docs/storage/vercel-blob/client-upload"
368
- )
369
- );
370
- },
371
- /**
372
- * Get signed download URL for file access.
373
- *
374
- * Note: Vercel Blob URLs are public by default and do not support
375
- * signed/temporary URLs. All uploaded blobs are accessible via their
376
- * public URL.
377
- *
378
- * @param path - Storage path (full blob URL)
379
- * @returns The same URL (Vercel Blob URLs are public)
380
- */
381
- getSignedDownloadUrl(path) {
382
- return Promise.resolve(path);
383
- }
384
- };
385
- return plugin;
1660
+ if (config.enabled === false) return {
1661
+ name: "vercel-blob-storage",
1662
+ type: "vercel-blob",
1663
+ collections: {},
1664
+ adapter: null
1665
+ };
1666
+ const adapter = new VercelBlobStorageAdapter(config);
1667
+ return {
1668
+ name: "vercel-blob-storage",
1669
+ type: "vercel-blob",
1670
+ collections: config.collections,
1671
+ adapter,
1672
+ /**
1673
+ * Generate upload URL for client-side uploads.
1674
+ *
1675
+ * Note: Vercel Blob uses a different pattern for client uploads.
1676
+ * Instead of pre-signed URLs, it uses the handleUpload() API which
1677
+ * requires server-side route handlers.
1678
+ *
1679
+ * This method throws an error explaining the correct approach.
1680
+ *
1681
+ * @see https://vercel.com/docs/storage/vercel-blob/client-upload
1682
+ */
1683
+ getClientUploadUrl(_filename, _mimeType, _collection) {
1684
+ return Promise.reject(/* @__PURE__ */ new Error("@nextly/storage-vercel-blob: Client uploads require the handleUpload API.\n\nVercel Blob uses a different pattern than S3 for client-side uploads:\n\n1. Create a server-side route handler with handleUpload()\n2. Use upload() from @vercel/blob/client on the frontend\n\nSee: https://vercel.com/docs/storage/vercel-blob/client-upload"));
1685
+ },
1686
+ /**
1687
+ * Get signed download URL for file access.
1688
+ *
1689
+ * Note: Vercel Blob URLs are public by default and do not support
1690
+ * signed/temporary URLs. All uploaded blobs are accessible via their
1691
+ * public URL.
1692
+ *
1693
+ * @param path - Storage path (full blob URL)
1694
+ * @returns The same URL (Vercel Blob URLs are public)
1695
+ */
1696
+ getSignedDownloadUrl(path) {
1697
+ return Promise.resolve(path);
1698
+ }
1699
+ };
386
1700
  }
387
-
388
1701
  // src/index.ts
389
- var PACKAGE_NAME = "@nextly/storage-vercel-blob";
390
- var PACKAGE_VERSION = "0.1.0";
391
-
1702
+ const PACKAGE_NAME = "@nextly/storage-vercel-blob";
1703
+ const PACKAGE_VERSION = "0.1.0";
392
1704
  export { PACKAGE_NAME, PACKAGE_VERSION, VercelBlobStorageAdapter, vercelBlobStorage };
393
- //# sourceMappingURL=index.mjs.map
1705
+
394
1706
  //# sourceMappingURL=index.mjs.map