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

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