@nextlyhq/storage-s3 0.0.2-alpha.76 → 0.0.2-alpha.77

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["S3Client","Upload","DeleteObjectCommand","DeleteObjectsCommand","HeadObjectCommand","ListObjectsV2Command","GetObjectCommand","getSignedUrl","PutObjectCommand","iterable"],"sources":["../../nextly/dist/nextly-error-CezzIwjj.mjs","../../nextly/dist/validate-external-url-BGTmyj1s.mjs","../../nextly/dist/storage/read-errors.mjs","../../nextly/dist/storage/fetch-stored-bytes.mjs","../src/adapter.ts","../src/plugin.ts","../src/index.ts"],"sourcesContent":["import { t as __exportAll } from \"./rolldown-runtime-BJohB4LM.mjs\";\n// src/database/pool-wait-code.ts\n/**\n* The code an adapter gives the error it raises when a request has waited out\n* `pool.connectionTimeoutMs` for a database connection, as core reads it.\n*\n* Read here rather than imported from `@nextlyhq/adapter-drizzle/types`, where\n* the adapters define it, because the module that reads it\n* (`database/errors.ts`) is reached from `NextlyError` and so from every\n* client-safe entry: a runtime import of a database package there puts that\n* package in the admin's browser bundle. A leaf with no imports keeps this\n* reachable without the adapter.\n*\n* The same string as the adapters' `POOL_WAIT_TIMEOUT_CODE`, held to it by\n* `errors/__tests__/database-busy.test.ts`, so the two cannot drift apart\n* unnoticed.\n*/\nconst POOL_WAIT_TIMEOUT_CODE = \"NEXTLY_POOL_WAIT_TIMEOUT\";\n// src/database/errors.ts\nvar DbError = class extends Error {\n\tkind;\n\tdialect;\n\tcode;\n\tmeta;\n\tcause;\n\tconstructor(args) {\n\t\tsuper(args.message);\n\t\tthis.name = \"DbError\";\n\t\tthis.kind = args.kind;\n\t\tthis.dialect = args.dialect;\n\t\tthis.code = args.code;\n\t\tthis.meta = args.meta;\n\t\tthis.cause = args.cause;\n\t}\n};\nfunction isDbError(err) {\n\tif (!err || typeof err !== \"object\") return false;\n\tconst obj = err;\n\treturn obj.name === \"DbError\" && typeof obj.kind === \"string\";\n}\nfunction toDbError(dialect, error, meta) {\n\tif (isDbError(error)) return error;\n\tconst code = safeCode(error);\n\tconst rawMsg = error != null && typeof error === \"object\" && \"message\" in error ? error.message : void 0;\n\tconst message = typeof rawMsg === \"string\" ? rawMsg : \"Database error\";\n\tlet kind = \"internal\";\n\tif (isBusyCode(code)) return new DbError({\n\t\tmessage,\n\t\tkind: \"busy\",\n\t\tdialect,\n\t\tcode,\n\t\tmeta,\n\t\tcause: error\n\t});\n\tswitch (dialect) {\n\t\tcase \"postgresql\":\n\t\t\tkind = mapPostgresCodeToKind(code);\n\t\t\tbreak;\n\t\tcase \"mysql\":\n\t\t\tkind = mapMySqlCodeToKind(code);\n\t\t\tbreak;\n\t\tcase \"sqlite\": kind = mapSqliteCodeToKind(code);\n\t}\n\tif ((dialect === \"mysql\" || dialect === \"sqlite\") && (kind === \"constraint\" || kind === \"internal\") && isLikelyUniqueViolationMessage(dialect, message)) kind = \"unique-violation\";\n\tif (kind === \"internal\" && code) {\n\t\tconst c = code.toUpperCase();\n\t\tif (c === \"ECONNRESET\" || c.includes(\"PROTOCOL_CONNECTION_LOST\")) kind = \"connection-lost\";\n\t\telse if (c === \"ETIMEDOUT\") kind = \"timeout\";\n\t}\n\treturn new DbError({\n\t\tmessage,\n\t\tkind,\n\t\tdialect,\n\t\tcode,\n\t\tmeta,\n\t\tcause: error\n\t});\n}\n/**\n* The driver's own code for an error, wherever that driver puts it.\n*\n* Exported so callers that must distinguish one failure from another classify\n* by the SAME extraction this module's mapping uses. A second reader would go\n* looking in a different set of properties and disagree on exactly the drivers\n* whose codes are hardest to find.\n*/\n/**\n* Whether an error is a duplicate-key rejection.\n*\n* Exposed because a plugin inserting into a table with a unique index has to\n* tell \"this row already exists\" from \"the database is broken\", and the two\n* arrive as the same thrown object. Derived from the existing SQLSTATE\n* classification rather than by matching driver messages: those differ per\n* driver and per version, and a plugin re-deriving it would be a second\n* implementation of a question this module already answers.\n*/\n/**\n* Whether a driver code says the database was busy: the adapters' own code\n* for a request that waited out `pool.connectionTimeoutMs`, the same on\n* every dialect, or SQLITE_BUSY and its extended codes, another process\n* holding the SQLite file past `busyTimeout`. Neither depends on the dialect,\n* which is what lets {@link isDatabaseBusy} answer without one.\n*/\nfunction isBusyCode(code) {\n\tif (code === void 0) return false;\n\treturn code === \"NEXTLY_POOL_WAIT_TIMEOUT\" || code.toUpperCase().startsWith(\"SQLITE_BUSY\");\n}\n/**\n* Whether an error is the database being busy, however it arrives: a DbError\n* of kind \"busy\", or the raw error an adapter or driver threw.\n*\n* For the boundaries that answer a request with whatever its work threw.\n* `withDbErrors` converts only DbErrors, so a raw driver error reaches them\n* unconverted, and without this it would read as an internal fault rather\n* than a request worth retrying.\n*/\nfunction isDatabaseBusy(error) {\n\tif (isDbError(error)) return error.kind === \"busy\";\n\treturn isBusyCode(safeCode(error));\n}\nfunction isUniqueViolation(dialect, error) {\n\treturn toDbError(dialect, error).kind === \"unique-violation\";\n}\nfunction safeCode(error) {\n\tif (!error || typeof error !== \"object\") return void 0;\n\tconst e = error;\n\tlet c = e.code ?? e.sqlState ?? e.state ?? e.errno ?? void 0;\n\tif (!c && typeof e.originalError?.code === \"string\") c = e.originalError.code;\n\tif (!c && typeof e.cause?.code === \"string\") c = e.cause.code;\n\tif (!c && typeof e.severity === \"string\" && typeof e.code === \"string\") c = e.code;\n\tif (typeof c === \"number\") return String(c);\n\tif (typeof c === \"string\" && c.length > 0) return c;\n}\nfunction mapPostgresCodeToKind(code) {\n\tif (!code) return \"internal\";\n\tconst c = code.toUpperCase();\n\tif (c === \"40P01\") return \"deadlock\";\n\tif (c === \"40001\") return \"serialization-failure\";\n\tif (c === \"57014\") return \"timeout\";\n\tif (c === \"23505\") return \"unique-violation\";\n\tif (c === \"23503\") return \"fk-violation\";\n\tif (c === \"23502\") return \"not-null-violation\";\n\tif (c === \"42601\") return \"syntax\";\n\tif (c.startsWith(\"08\") || c === \"57P01\") return \"connection-lost\";\n\tif (c.startsWith(\"23\")) return \"constraint\";\n\treturn \"internal\";\n}\nfunction mapMySqlCodeToKind(code) {\n\tif (!code) return \"internal\";\n\tconst c = code.toUpperCase();\n\tif (c === \"1213\" || c === \"ER_LOCK_DEADLOCK\") return \"deadlock\";\n\tif (c === \"1205\" || c === \"ER_LOCK_WAIT_TIMEOUT\") return \"timeout\";\n\tif (c === \"1062\" || c === \"ER_DUP_ENTRY\") return \"unique-violation\";\n\tif (c === \"23000\") return \"constraint\";\n\tif (c === \"1064\" || c === \"ER_PARSE_ERROR\") return \"syntax\";\n\tif (c === \"1452\" || c === \"ER_NO_REFERENCED_ROW_2\") return \"fk-violation\";\n\tif (c === \"1451\" || c === \"ER_ROW_IS_REFERENCED_2\") return \"fk-violation\";\n\tif (c === \"ECONNRESET\" || c.includes(\"PROTOCOL_CONNECTION_LOST\")) return \"connection-lost\";\n\tif (c === \"ETIMEDOUT\") return \"timeout\";\n\treturn \"internal\";\n}\nfunction mapSqliteCodeToKind(code) {\n\tif (!code) return \"internal\";\n\tconst c = code.toUpperCase();\n\tif (c === \"SQLITE_LOCKED\") return \"deadlock\";\n\tif (c === \"SQLITE_CONSTRAINT_UNIQUE\") return \"unique-violation\";\n\tif (c === \"SQLITE_CONSTRAINT_PRIMARYKEY\") return \"unique-violation\";\n\tif (c === \"SQLITE_CONSTRAINT_FOREIGNKEY\") return \"fk-violation\";\n\tif (c === \"SQLITE_CONSTRAINT_NOTNULL\") return \"not-null-violation\";\n\tif (c === \"SQLITE_INTERRUPT\") return \"timeout\";\n\tif (c === \"SQLITE_ERROR\") return \"syntax\";\n\tif (c.startsWith(\"SQLITE_CONSTRAINT\")) return \"constraint\";\n\treturn \"internal\";\n}\nfunction isLikelyUniqueViolationMessage(dialect, message) {\n\tconst m = message.toLowerCase();\n\tif (dialect === \"mysql\") return m.includes(\"duplicate entry\") || m.includes(\"duplicate key\");\n\tif (dialect === \"sqlite\") return m.includes(\"unique constraint failed\");\n\treturn false;\n}\n// src/errors/error-codes.ts\n/**\n* Canonical NextlyError codes and their HTTP status mappings.\n*\n* Plugin codes outside this enum must always pass an explicit `statusCode`\n* to the NextlyError constructor (no enum lookup happens for unknown codes).\n*/\nconst NEXTLY_ERROR_STATUS = {\n\tVALIDATION_ERROR: 400,\n\tINVALID_INPUT: 400,\n\tAUTH_REQUIRED: 401,\n\tAUTH_INVALID_CREDENTIALS: 401,\n\tTOKEN_EXPIRED: 401,\n\tFORBIDDEN: 403,\n\tEMAIL_NOT_VERIFIED: 403,\n\tBUILDER_DISABLED: 403,\n\tCSRF_FAILED: 403,\n\tSETUP_TOKEN_REQUIRED: 403,\n\tAPI_KEY_ROLE_ABOVE_CREATOR: 403,\n\tACTION_NOT_AVAILABLE: 403,\n\tNOT_FOUND: 404,\n\tENTITY_REMOVED_FROM_CODE: 409,\n\tENTITY_NOT_MIGRATED: 409,\n\tMETHOD_NOT_ALLOWED: 405,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tCONFLICT: 409,\n\tSTALE_VERSION: 409,\n\tVERSION_REQUIRED: 428,\n\tDUPLICATE: 409,\n\tRATE_LIMITED: 429,\n\tPAYLOAD_TOO_LARGE: 413,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tBUSINESS_RULE_VIOLATION: 422,\n\tINTERNAL_ERROR: 500,\n\tDATABASE_ERROR: 500,\n\tDATABASE_BUSY: 503,\n\tRULE_COULD_NOT_RUN: 503,\n\tEXTERNAL_SERVICE_ERROR: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tCONFIGURATION_ERROR: 500,\n\tEXTERNAL_URL_BLOCKED: 400,\n\tEXTERNAL_REQUEST_FAILED: 502,\n\tFILENAME_INVALID: 400,\n\tEXTENSION_BLOCKED: 400,\n\tMIME_BLOCKED: 415,\n\tMIME_NOT_ALLOWED: 415,\n\tSIZE_EXCEEDED: 413,\n\tSTORAGE_READ_TOO_LARGE: 413,\n\tSTORAGE_READ_TIMEOUT: 504,\n\tSTORAGE_READ_UNREACHABLE: 502,\n\tMAGIC_BYTE_MISMATCH: 400,\n\tSVG_SANITIZATION_FAILED: 400,\n\tUNSUPPORTED_FOR_BACKEND: 415,\n\tNEXTLY_LEGACY_BOOKKEEPING_DETECTED: 409,\n\tNEXTLY_UPGRADE_TABLE_NAME_COLLISION: 409,\n\tNEXTLY_UPGRADE_IN_PROGRESS: 409,\n\tNEXTLY_MIGRATE_LOCK_BUSY: 409,\n\tNEXTLY_BASELINE_LOCK_NOT_HELD: 409,\n\tNEXTLY_RESOLVE_LOCK_NOT_HELD: 409,\n\tNEXTLY_BOOT_MIGRATIONS_NOT_RUN: 503,\n\tNEXTLY_BOOT_MIGRATIONS_PENDING: 503,\n\tNEXTLY_DATABASE_NOT_SET_UP: 503,\n\tNEXTLY_DATABASE_NOT_MIGRATED: 503,\n\tNEXTLY_CORE_DESTRUCTIVE_REFUSED: 409,\n\tNEXTLY_MIGRATION_DRIFT: 409,\n\tNEXTLY_MIGRATION_APPLY_FAILED: 500,\n\tNEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION: 409,\n\tNEXTLY_MIGRATION_PARTIALLY_APPLIED: 500,\n\tNEXTLY_MIGRATION_CONCURRENT_RUN: 409,\n\tNEXTLY_MIGRATION_FILE_MISSING: 404,\n\tNEXTLY_MIGRATION_SNAPSHOT_MISSING: 404,\n\tNEXTLY_MIGRATION_RESOLVE_DRIFT: 409,\n\tNEXTLY_MIGRATION_RESOLVE_PRECONDITION: 409,\n\tNEXTLY_MIGRATION_HISTORY_REFUSED: 409,\n\tNEXTLY_SCHEMA_CONVERSION_UNCONFIRMED: 409,\n\tNEXTLY_UI_SCHEMA_INVALID: 400,\n\tNEXTLY_SCHEMA_SLUG_COLLISION: 409,\n\tNEXTLY_SCHEMA_RELATION_TARGET_MISSING: 400,\n\tNEXTLY_SCHEMA_RELATION_UNRESOLVED: 400,\n\tNEXTLY_SCHEMA_EXTEND_TARGET_UNKNOWN: 400,\n\tNEXTLY_SCHEMA_EXTEND_FIELD_DUPLICATE: 409,\n\tNEXTLY_SCHEMA_CROSS_PLUGIN_RELATION: 409,\n\tNEXTLY_SCHEMA_RENAME_UNKNOWN_TARGET: 400,\n\tNEXTLY_PLUGIN_CLIENT_CONFIG_INVALID: 500,\n\tNEXTLY_PLUGIN_ADMIN_WIDGET_INVALID: 500,\n\tNEXTLY_PLUGIN_REMOVED_WIDGET_CHANNEL: 500,\n\tNEXTLY_PLUGIN_DOCUMENT_VIEW_INVALID: 500,\n\tNEXTLY_PLUGIN_DOCUMENT_SURFACE_INVALID: 500,\n\tPLUGIN_RESOLUTION_ERROR: 500,\n\tPLUGIN_DEPENDENCY_NOT_INSTALLED: 409,\n\tPLUGIN_HAS_DEPENDENTS: 409,\n\tPLUGIN_UNINSTALL_WOULD_DROP_OTHERS: 409,\n\tPLUGIN_UNINSTALL_IRREVERSIBLE: 409,\n\tPLUGIN_UNINSTALL_UNCONFIRMED: 409,\n\tPLUGIN_SCHEMA_BEHIND: 409,\n\tPLUGIN_SCHEMA_UNINSTALLED: 409,\n\tPLUGIN_NOT_INSTALLED: 409,\n\tPLUGIN_DISABLED: 409,\n\tPLUGIN_UNINSTALL_UNFINISHED: 409,\n\tPLUGIN_SCHEMA_VERSION_NOT_ADVANCED: 409,\n\tPLUGIN_MIGRATION_DROPS_CREATED_SCHEMA: 409,\n\tPLUGIN_MIGRATION_ADDS_UNFILLABLE_COLUMN: 409,\n\tPLUGIN_MIGRATION_SQL_MISSING: 409,\n\tPLUGIN_MIGRATIONS_UNAVAILABLE: 409,\n\tDROP_OF_FOREIGN_TABLE: 409,\n\tMIGRATION_CHECKSUM_MISMATCH: 409,\n\tPLUGIN_MIGRATIONS_OUT_OF_ORDER: 409,\n\tPLUGIN_MIGRATION_HISTORY_CHANGED: 409,\n\tNEXTLY_ROUTE_COLLISION: 409,\n\tNEXTLY_ROUTE_INVALID_PATH: 400,\n\tNEXTLY_ROUTE_UNREACHABLE_ROOT: 400,\n\tNEXTLY_ROUTE_INVALID_MOUNT: 400,\n\tNEXTLY_EMAIL_TRANSPORT_UNAVAILABLE: 503,\n\tNEXTLY_CONFIG_TOOLING_UNAVAILABLE: 503,\n\tNEXTLY_POSTGRES_SCHEMA_MISMATCH: 500,\n\tNEXTLY_PER_LANGUAGE_STORAGE_CHANGED: 500,\n\tNEXTLY_PER_LANGUAGE_STORAGE_MIXED: 500,\n\tNEXTLY_PER_LANGUAGE_STORAGE_LANGUAGES_UNDECLARED: 500,\n\tNEXTLY_POSTGRES_SCHEMA_UNSUPPORTED: 500\n};\n/**\n* The codes that REPRESENT their status, when a failure names none.\n*\n* A service that returns `{ success: false, statusCode }` without a code leaves\n* every boundary to infer one, and three boundaries inferring separately is how\n* the same 401 became `AUTH_REQUIRED` through the Direct API and\n* `INTERNAL_ERROR` through the REST dispatcher. This list is the ONE inference,\n* so they cannot disagree.\n*\n* Listed as CODES, not as status numbers: the number for each comes from\n* {@link NEXTLY_ERROR_STATUS} below, so a code whose canonical status changes\n* carries its inference with it instead of leaving a stale literal here.\n*\n* Several codes share a status -- 409 is both `CONFLICT` and `DUPLICATE`, 400\n* is both `VALIDATION_ERROR` and `INVALID_INPUT` -- so this is a choice, not a\n* mechanical inversion. Each entry is the reading that is still safe if the\n* other was meant: `CONFLICT` says \"reload\", which is unhelpful for a name\n* clash, while `DUPLICATE` would say \"already exists\", which is WRONG for a\n* stale write. A producer that knows which it means sets `code` and is\n* believed, and this list is never consulted for it.\n*/\nconst CANONICAL_CODE_FOR_STATUS = [\n\t\"VALIDATION_ERROR\",\n\t\"AUTH_REQUIRED\",\n\t\"FORBIDDEN\",\n\t\"NOT_FOUND\",\n\t\"CONFLICT\",\n\t\"VERSION_REQUIRED\",\n\t\"PAYLOAD_TOO_LARGE\",\n\t\"UNSUPPORTED_MEDIA_TYPE\",\n\t\"RATE_LIMITED\",\n\t\"EXTERNAL_SERVICE_ERROR\",\n\t\"SERVICE_UNAVAILABLE\"\n];\n/**\n* 422, which no canonical code claims.\n*\n* `INVALID_INPUT` answers 400 in this system, so it cannot supply this key the\n* way the codes above supply theirs. Legacy envelopes nonetheless use 422 for\n* \"understood but unprocessable\", and reading it as an internal error would\n* report the caller's own mistake as a server fault. Named rather than inlined\n* so it is visibly the one entry that is NOT derived.\n*/\nconst LEGACY_UNPROCESSABLE_STATUS = 422;\nconst STATUS_TO_CODE = {\n\t...Object.fromEntries(CANONICAL_CODE_FOR_STATUS.map((code) => [NEXTLY_ERROR_STATUS[code], code])),\n\t[LEGACY_UNPROCESSABLE_STATUS]: \"INVALID_INPUT\"\n};\n/**\n* The canonical code for a status, for a failure that named none.\n*\n* Anything outside the table is an internal error: an unrecognised status from\n* a legacy envelope says nothing a caller can act on, and inventing a specific\n* code for it would assert a meaning no producer expressed.\n*/\nfunction statusToErrorCode(statusCode) {\n\treturn STATUS_TO_CODE[statusCode] ?? \"INTERNAL_ERROR\";\n}\n/**\n* The sentence a caller reads for a code, when the failure supplied none.\n*\n* Kept beside the status table because they answer the same question together:\n* a code-less envelope's own `message` is NOT usable here. Those envelopes come\n* from legacy converters that store a raw exception's text, so promoting it\n* would put driver output, table names and internal paths on the wire -- the\n* disclosure the public error shape exists to prevent (spec 13.8).\n*\n* Every entry is generic by design. The specific detail stays in `logContext`\n* for the operator, against the same request id.\n*/\nconst GENERIC_PUBLIC_MESSAGE = {\n\tVALIDATION_ERROR: \"Validation failed.\",\n\tINVALID_INPUT: \"The request could not be processed.\",\n\tAUTH_REQUIRED: \"Authentication required.\",\n\tFORBIDDEN: \"You don't have permission to perform this action.\",\n\tACTION_NOT_AVAILABLE: \"This action isn't available for this entry.\",\n\tNOT_FOUND: \"Not found.\",\n\tMETHOD_NOT_ALLOWED: \"That method is not allowed on this address.\",\n\tRANGE_NOT_SATISFIABLE: \"The requested range is outside the file.\",\n\tCONFLICT: \"The resource has changed since you last loaded it. Please refresh and try again.\",\n\tDUPLICATE: \"Resource already exists.\",\n\tPAYLOAD_TOO_LARGE: \"The request is too large.\",\n\tUNSUPPORTED_MEDIA_TYPE: \"That file type is not supported.\",\n\tRATE_LIMITED: \"Too many requests. Please try again later.\",\n\tEXTERNAL_SERVICE_ERROR: \"An upstream service failed.\",\n\tSERVICE_UNAVAILABLE: \"The service is temporarily unavailable.\",\n\tDATABASE_BUSY: \"The database is busy. Please try again shortly.\",\n\tRULE_COULD_NOT_RUN: \"A check this request needs could not run. Please try again shortly.\",\n\tINTERNAL_ERROR: \"An unexpected error occurred.\"\n};\n/** The generic sentence for a code; the internal one for anything unlisted. */\nfunction genericPublicMessage(code) {\n\treturn GENERIC_PUBLIC_MESSAGE[code] ?? GENERIC_PUBLIC_MESSAGE.INTERNAL_ERROR;\n}\n// src/errors/retry-after.ts\n/**\n* The seconds an error asks its caller to wait before retrying, or\n* `undefined` when it carries no retry hint.\n*\n* Read from the error's public data rather than from its code, so every error\n* that carries a hint is answered with the header, and a code that comes to\n* carry one needs no change here.\n*/\nfunction retryAfterSeconds(error) {\n\tconst data = error.publicData;\n\tif (data && typeof data === \"object\" && \"retryAfterSeconds\" in data && typeof data.retryAfterSeconds === \"number\") return data.retryAfterSeconds;\n}\n/**\n* The Retry-After header for an error: none when it carries no retry hint.\n* Spread into a response's headers by every builder that answers one.\n*/\nfunction retryAfterHeader(error) {\n\tconst seconds = retryAfterSeconds(error);\n\treturn seconds === void 0 ? {} : { \"retry-after\": String(seconds) };\n}\n// src/errors/nextly-error.ts\nvar nextly_error_exports = /* @__PURE__ */ __exportAll({ NextlyError: () => NextlyError });\n/**\n* Default mapping from DbErrorKind to NextlyError contract. Used by\n* `NextlyError.fromDatabaseError`. Public messages are intentionally generic\n* per spec §13.8 — no DB driver text, no constraint names, no field hints.\n*\n* `satisfies Record<DbErrorKind, ...>` makes the mapping exhaustive at\n* compile time: adding a new DbErrorKind without updating this table is a\n* type error.\n*/\nconst DB_ERROR_MAPPING = {\n\t\"unique-violation\": {\n\t\tcode: \"DUPLICATE\",\n\t\tstatusCode: 409,\n\t\tpublicMessage: \"Resource already exists.\"\n\t},\n\t\"fk-violation\": {\n\t\tcode: \"VALIDATION_ERROR\",\n\t\tstatusCode: 400,\n\t\tpublicMessage: \"Referenced record does not exist.\"\n\t},\n\t\"not-null-violation\": {\n\t\tcode: \"VALIDATION_ERROR\",\n\t\tstatusCode: 400,\n\t\tpublicMessage: \"A required field is missing.\"\n\t},\n\tconstraint: {\n\t\tcode: \"VALIDATION_ERROR\",\n\t\tstatusCode: 400,\n\t\tpublicMessage: \"The provided data violates a constraint.\"\n\t},\n\tdeadlock: {\n\t\tcode: \"CONFLICT\",\n\t\tstatusCode: 409,\n\t\tpublicMessage: \"The operation could not be completed. Please retry.\"\n\t},\n\t\"serialization-failure\": {\n\t\tcode: \"CONFLICT\",\n\t\tstatusCode: 409,\n\t\tpublicMessage: \"The operation could not be completed. Please retry.\"\n\t},\n\tbusy: {\n\t\tcode: \"DATABASE_BUSY\",\n\t\tstatusCode: NEXTLY_ERROR_STATUS.DATABASE_BUSY,\n\t\tpublicMessage: genericPublicMessage(\"DATABASE_BUSY\"),\n\t\tpublicData: { retryAfterSeconds: 5 }\n\t},\n\ttimeout: {\n\t\tcode: \"DATABASE_ERROR\",\n\t\tstatusCode: 500,\n\t\tpublicMessage: \"The operation timed out. Please try again.\"\n\t},\n\t\"connection-lost\": {\n\t\tcode: \"DATABASE_ERROR\",\n\t\tstatusCode: 500,\n\t\tpublicMessage: \"A temporary database error occurred. Please try again.\"\n\t},\n\tsyntax: {\n\t\tcode: \"INTERNAL_ERROR\",\n\t\tstatusCode: 500,\n\t\tpublicMessage: \"An unexpected error occurred.\"\n\t},\n\tinternal: {\n\t\tcode: \"INTERNAL_ERROR\",\n\t\tstatusCode: 500,\n\t\tpublicMessage: \"An unexpected error occurred.\"\n\t}\n};\nconst NEXTLY_ERROR_BRAND = Symbol.for(\"nextly/NextlyError\");\nfunction hasBrand(value) {\n\tif (value === null || typeof value !== \"object\" && typeof value !== \"function\") return false;\n\treturn value[NEXTLY_ERROR_BRAND] === true;\n}\n/**\n* Unified error class for Nextly. Used at every throw site across services,\n* direct API, auth, and plugins. Carries two distinct payloads:\n*\n* - Public (`code`, `publicMessage`, `publicData`, `statusCode`, `messageKey`)\n* sent in HTTP responses and Server Action results.\n* - Log (`logMessage`, `logContext`, `cause`, stack trace)\n* written to the server logger; never serialised to the wire.\n*\n* Use the static factories (notFound, forbidden, validation, ...) for the\n* common cases. Use the free-form constructor for plugin codes or one-off\n* shapes.\n*/\nvar NextlyError = class NextlyError extends Error {\n\tcode;\n\tstatusCode;\n\tpublicMessage;\n\tpublicData;\n\tmessageKey;\n\tlogMessage;\n\tlogContext;\n\tcause;\n\ttimestamp;\n\tconstructor(opts) {\n\t\tsuper(opts.publicMessage);\n\t\tthis.name = \"NextlyError\";\n\t\tthis.code = opts.code;\n\t\tthis.publicMessage = opts.publicMessage;\n\t\tthis.publicData = opts.publicData;\n\t\tthis.messageKey = opts.messageKey;\n\t\tthis.logMessage = opts.logMessage;\n\t\tthis.logContext = opts.logContext;\n\t\tthis.cause = opts.cause;\n\t\tthis.timestamp = /* @__PURE__ */ new Date();\n\t\tthis.statusCode = NextlyError.resolveStatusCode(opts);\n\t\tError.captureStackTrace?.(this, NextlyError);\n\t}\n\tstatic {\n\t\tNextlyError.prototype[NEXTLY_ERROR_BRAND] = true;\n\t}\n\tstatic resolveStatusCode(opts) {\n\t\tif (typeof opts.statusCode === \"number\") return opts.statusCode;\n\t\tif (opts.code in NEXTLY_ERROR_STATUS) return NEXTLY_ERROR_STATUS[opts.code];\n\t\treturn 500;\n\t}\n\t/** HTTP-safe JSON. Strips logMessage / logContext / cause / stack. */\n\ttoResponseJSON(requestId) {\n\t\tconst json = {\n\t\t\tcode: String(this.code),\n\t\t\tmessage: this.publicMessage,\n\t\t\trequestId\n\t\t};\n\t\tif (this.messageKey) json.messageKey = this.messageKey;\n\t\tif (this.publicData !== void 0) json.data = this.publicData;\n\t\treturn json;\n\t}\n\t/** Operator-facing JSON for log lines. Includes everything. */\n\ttoLogJSON(requestId) {\n\t\treturn {\n\t\t\tcode: this.code,\n\t\t\tstatusCode: this.statusCode,\n\t\t\tpublicMessage: this.publicMessage,\n\t\t\tmessageKey: this.messageKey,\n\t\t\tlogMessage: this.logMessage,\n\t\t\tlogContext: this.logContext,\n\t\t\tcause: this.cause ? {\n\t\t\t\tname: this.cause.name,\n\t\t\t\tmessage: this.cause.message,\n\t\t\t\tstack: this.cause.stack\n\t\t\t} : void 0,\n\t\t\ttimestamp: this.timestamp.toISOString(),\n\t\t\trequestId\n\t\t};\n\t}\n\tstatic invalidCredentials(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"AUTH_INVALID_CREDENTIALS\",\n\t\t\tpublicMessage: \"Invalid email or password.\",\n\t\t\tlogMessage: \"Login failed\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* The password was correct and the address is unverified. Thrown only once\n\t* the password is proven, so only someone who holds it learns the address\n\t* is unverified; every other refusal stays\n\t* {@link NextlyError.invalidCredentials}.\n\t*/\n\tstatic emailNotVerified(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"EMAIL_NOT_VERIFIED\",\n\t\t\tpublicMessage: \"Verify your email address to sign in. Check your inbox for the link.\",\n\t\t\tlogMessage: \"Login refused: email not verified\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\tstatic authRequired(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"AUTH_REQUIRED\",\n\t\t\tpublicMessage: \"Authentication required.\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* Distinct from `authRequired`: the caller was authenticated but the\n\t* session token expired. Clients key on the TOKEN_EXPIRED *code* to\n\t* silently refresh and retry rather than redirecting to login; the public\n\t* message stays the generic spec §13.6 string (\"Authentication required.\")\n\t* so the wire never reveals the session state — same as `authRequired`.\n\t*/\n\tstatic tokenExpired(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"TOKEN_EXPIRED\",\n\t\t\tpublicMessage: \"Authentication required.\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\tstatic notFound(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"NOT_FOUND\",\n\t\t\tpublicMessage: opts?.message ?? \"Not found.\",\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\tstatic forbidden(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: \"You don't have permission to perform this action.\",\n\t\t\tpublicData: opts?.publicData,\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* Something only a signed-in person can do, asked by a caller that is not\n\t* one: an API key, or a request acting as no person. Forbidden, and the\n\t* message says so, since it is about what kind of caller asked, not about\n\t* the caller's permissions. `doing` completes \"Only a signed-in person can\".\n\t*/\n\tstatic personOnly(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: `Only a signed-in person can ${opts.doing}.`,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* A role or permission built into Nextly, which is never changed or\n\t* deleted. Forbidden, and the message says so: it is a fact about the role,\n\t* not about the caller's permissions.\n\t*/\n\tstatic builtIn(opts) {\n\t\tconst done = {\n\t\t\tchange: \"changed\",\n\t\t\tdelete: \"deleted\",\n\t\t\tassign: \"assigned\",\n\t\t\tinherit: \"inherited\"\n\t\t}[opts.change];\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: `This ${opts.thing} is built in, so it can't be ${done}.`,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* A request from a site not allowed to make it: its own `Origin` names a\n\t* site the installation does not allow. Forbidden, and the message says so;\n\t* the origin is the caller's own, so naming its kind tells them nothing.\n\t*/\n\tstatic originRefused(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: \"This request came from a site that isn't allowed to make it.\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* A Single deleted without `force`: Singles hold a site's lasting settings,\n\t* so they are not deleted from here, only by an admin or CLI clean-up that\n\t* passes `force`. Forbidden, and the message says so.\n\t*/\n\tstatic singleNotDeletable(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: \"A Single can't be deleted from here.\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* A collection, Single or component defined in code, which is changed by\n\t* changing its code and not from here. Forbidden, and the message says so:\n\t* it is a fact about the thing, not about the caller's permissions, so it\n\t* names no permission and no policy. The lock's detail goes to the log\n\t* through `logContext`.\n\t*/\n\tstatic definedInCode(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: `This ${opts.thing} is defined in code, so it can't be ${opts.change === \"change\" ? \"changed\" : \"deleted\"} here.`,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* A write to an entry of a collection or Single removed from code: its\n\t* registry row says the app's code defines it, and the running configuration\n\t* no longer declares it. Its entries are read-only until it is retired or\n\t* declared again, so the message names the entity, says what happened and\n\t* gives both ways out. `publicData` carries the kind and the slug, which the\n\t* caller named, so a client can mark the entity without parsing the sentence.\n\t*/\n\tstatic removedFromCode(opts) {\n\t\tconst thing = opts.kind === \"single\" ? \"Single\" : \"collection\";\n\t\tconst its = opts.kind === \"single\" ? \"it\" : \"its entries\";\n\t\treturn new NextlyError({\n\t\t\tcode: \"ENTITY_REMOVED_FROM_CODE\",\n\t\t\tpublicMessage: `The ${thing} \"${opts.slug}\" was removed from code, so ${its} can't be changed. To retire it, run \\`nextly migrate:create\\` and then \\`nextly migrate\\`. To keep it, declare it again in nextly.config.ts.`,\n\t\t\tpublicData: {\n\t\t\t\tkind: opts.kind,\n\t\t\t\tslug: opts.slug\n\t\t\t},\n\t\t\tlogContext: {\n\t\t\t\tkind: opts.kind,\n\t\t\t\tslug: opts.slug,\n\t\t\t\t...opts.logContext\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* A read or write of a collection or Single the database has not been\n\t* migrated for: the column of one of its declared fields is missing, its\n\t* table is missing, or this running instance never registered it (an\n\t* entity a migration added after the instance started). The message names\n\t* the entity, the field or the table, and `nextly migrate`; the driver's\n\t* error stays on `cause`, for the log, so no SQL reaches the answer.\n\t*/\n\tstatic notMigrated(opts) {\n\t\tconst { cause, logContext, ...publicData } = opts;\n\t\tconst entity = `${publicData.kind === \"single\" ? \"Single\" : \"collection\"} \"${publicData.slug}\"`;\n\t\tconst field = publicData.field === void 0 ? \"a field\" : `the field \"${publicData.field}\"`;\n\t\tconst table = publicData.table === void 0 ? \"\" : ` \"${publicData.table}\"`;\n\t\tconst publicMessage = publicData.reason === \"column\" ? `The database has not been migrated for ${field} of the ${entity}. Run \\`nextly migrate\\`.` : publicData.reason === \"table\" ? `The database has not been migrated for the ${entity}: its table${table} does not exist. Run \\`nextly migrate\\`.` : `The ${entity}${publicData.table === void 0 ? \"\" : ` (table \"${publicData.table}\")`} is not registered in this running instance. Run \\`nextly migrate\\`, then restart the server.`;\n\t\treturn new NextlyError({\n\t\t\tcode: \"ENTITY_NOT_MIGRATED\",\n\t\t\tpublicMessage,\n\t\t\tpublicData,\n\t\t\tlogMessage: \"The database has not been migrated for this entity\",\n\t\t\tlogContext: {\n\t\t\t\t...publicData,\n\t\t\t\t...logContext\n\t\t\t},\n\t\t\tcause\n\t\t});\n\t}\n\t/**\n\t* An autosave where the collection or Single does not autosave: its owner\n\t* switched autosave off, or it keeps no drafts to autosave into. Forbidden,\n\t* and the message says so, since it is a setting and not a permission.\n\t*/\n\tstatic autosaveOff(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: `Autosave is turned off for this ${opts.scopeKind === \"single\" ? \"Single\" : \"collection\"}.`,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* An API key refused because its role allows more than the person creating\n\t* it may do. The sentence is FORBIDDEN's and names no permission; which one\n\t* exceeded goes to the log through `logContext`. The code is its own, so a\n\t* client can tell \"choose a smaller role\" from plain FORBIDDEN.\n\t*/\n\tstatic apiKeyRoleAboveCreator(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"API_KEY_ROLE_ABOVE_CREATOR\",\n\t\t\tpublicMessage: genericPublicMessage(\"FORBIDDEN\"),\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* A cookie-authenticated write refused because its origin or CSRF token did\n\t* not check out. The public message names no detail of which check failed;\n\t* that goes to the log through `logMessage`.\n\t*/\n\tstatic csrfFailed(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"CSRF_FAILED\",\n\t\t\tpublicMessage: \"This request could not be verified. Reload the page and try again.\",\n\t\t\tlogMessage: opts?.logMessage,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* A call the caller got wrong, where naming the mistake IS the value of the\n\t* error.\n\t*\n\t* The only factory that takes its public message from the caller. The\n\t* generic messages elsewhere exist so an HTTP response cannot leak internal\n\t* detail; this one is for arguments and configuration a developer controls\n\t* and must be told about — a missing option, an unusable combination — where\n\t* `internal()` would reduce the one useful sentence to \"An unexpected error\n\t* occurred.\" Do not pass user-supplied data through it.\n\t*/\n\tstatic invalidInput(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"INVALID_INPUT\",\n\t\t\tpublicMessage: opts.message,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\tstatic validation(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tpublicMessage: \"Validation failed.\",\n\t\t\tpublicData: { errors: opts.errors },\n\t\t\tcause: opts.cause,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\tstatic conflict(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"CONFLICT\",\n\t\t\tpublicMessage: opts?.message ?? \"The resource has changed since you last loaded it. Please refresh and try again.\",\n\t\t\tpublicData: opts?.data,\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: {\n\t\t\t\treason: opts?.reason,\n\t\t\t\t...opts?.logContext\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* An update made from a version of the document that is no longer its\n\t* current one. Never retried: the same version stays out of date, so the\n\t* caller must read the document again and decide.\n\t*\n\t* @experimental\n\t*/\n\t/**\n\t* An update that said neither which version of a document it was made from\n\t* nor that it overwrites whatever is stored. Without `bulk`, an update of\n\t* one document, which sends back the version it read. `bulk` names an\n\t* update that writes the same values to many documents, which can carry no\n\t* one document's version: by its ids, which can be given a version each\n\t* (`keys.revs`), or by a query, which cannot. The keys are the write path's\n\t* to name, so the message spells them as the request does.\n\t*\n\t* @experimental\n\t*/\n\tstatic versionRequired(opts) {\n\t\tconst { version, overwrite, revs } = opts.keys;\n\t\tif (opts.bulk === void 0) {\n\t\t\tconst one = {\n\t\t\t\tversionKey: version,\n\t\t\t\toverwriteKey: overwrite\n\t\t\t};\n\t\t\treturn new NextlyError({\n\t\t\t\tcode: \"VERSION_REQUIRED\",\n\t\t\t\tpublicMessage: `This update must say which version of the document it changes. Send back the \\`${version}\\` from your last read of it, or set \\`${overwrite}: true\\` to replace whatever is stored.`,\n\t\t\t\tpublicData: one,\n\t\t\t\tlogContext: opts.logContext\n\t\t\t});\n\t\t}\n\t\tconst byIds = opts.bulk === \"ids\";\n\t\tconst data = {\n\t\t\tversionKey: version,\n\t\t\toverwriteKey: overwrite,\n\t\t\t...byIds ? { revsKey: revs } : {}\n\t\t};\n\t\tconst message = `An update that writes the same values to many documents must set \\`${overwrite}: true\\`: it can't carry each document's version. Or update each document with its own \\`${version}\\`.`;\n\t\treturn new NextlyError({\n\t\t\tcode: \"VERSION_REQUIRED\",\n\t\t\tpublicMessage: byIds ? `${message} Or give each document's \\`${version}\\` in \\`${revs}\\`.` : message,\n\t\t\tpublicData: data,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\tstatic staleVersion(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"STALE_VERSION\",\n\t\t\tpublicMessage: `This document changed since the version you gave. Its current version is ${opts.data.currentVersion}.`,\n\t\t\tpublicData: opts.data,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* `message` replaces the generic sentence where the caller can name what is\n\t* already taken without leaking anything, such as a public address and the\n\t* page holding it.\n\t*/\n\tstatic duplicate(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"DUPLICATE\",\n\t\t\tpublicMessage: opts?.message ?? \"Resource already exists.\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\tstatic rateLimited(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"RATE_LIMITED\",\n\t\t\tpublicMessage: \"Too many requests. Please try again later.\",\n\t\t\tpublicData: opts?.retryAfterSeconds !== void 0 ? { retryAfterSeconds: opts.retryAfterSeconds } : void 0,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* A request that waited `pool.connectionTimeoutMs` for a database\n\t* connection and was given none. The statement or transaction that waited\n\t* never ran; work committed before it stays committed. The same error\n\t* `fromDatabaseError` gives a busy DbError, from the same table row.\n\t*/\n\tstatic databaseBusy(opts) {\n\t\tconst busy = DB_ERROR_MAPPING.busy;\n\t\treturn new NextlyError({\n\t\t\tcode: busy.code,\n\t\t\tstatusCode: busy.statusCode,\n\t\t\tpublicMessage: busy.publicMessage,\n\t\t\tpublicData: busy.publicData,\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* An access or field rule the request needs could not run, because its own\n\t* database query waited out the bound for a connection. Not a refusal: the\n\t* rule never answered. Names the collection or Single whose rule it is, and\n\t* the field for a field's rule, and says when to retry.\n\t*/\n\tstatic ruleCouldNotRun(opts) {\n\t\tconst publicData = {\n\t\t\tsubject: opts.subject,\n\t\t\t...opts.field !== void 0 ? { field: opts.field } : {},\n\t\t\tretryAfterSeconds: 5\n\t\t};\n\t\treturn new NextlyError({\n\t\t\tcode: \"RULE_COULD_NOT_RUN\",\n\t\t\tstatusCode: NEXTLY_ERROR_STATUS.RULE_COULD_NOT_RUN,\n\t\t\tpublicMessage: genericPublicMessage(\"RULE_COULD_NOT_RUN\"),\n\t\t\tpublicData,\n\t\t\tcause: opts.cause,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* What a request boundary answers with for a thrown value that is not a\n\t* NextlyError: \"database busy\" when the request waited out its bound for a\n\t* connection, which is retryable and no fault of the server's code, and an\n\t* internal error for anything else.\n\t*\n\t* The busy case has to be read here because it usually arrives raw:\n\t* `withDbErrors` converts only DbErrors, so a driver's error passes through\n\t* services unconverted to the boundary that answers the request.\n\t*/\n\tstatic fromUnexpected(error) {\n\t\treturn NextlyError.busyOr(error, () => NextlyError.internal({ cause: error instanceof Error ? error : void 0 }));\n\t}\n\t/**\n\t* \"Database busy\" when `error` is a request that waited out its bound for\n\t* a connection, and `otherwise()` for anything else.\n\t*\n\t* For a boundary that answers an unexpected failure with an error of its\n\t* own choosing rather than an internal one (a 503 for a flow that must not\n\t* answer on incomplete data), so that a busy database still answers there\n\t* as it does everywhere else. `fromUnexpected` is this rule with the\n\t* internal error as its fallback.\n\t*/\n\tstatic busyOr(error, otherwise) {\n\t\tif (!isDatabaseBusy(error)) return otherwise();\n\t\treturn NextlyError.databaseBusy({ cause: error instanceof Error ? error : void 0 });\n\t}\n\tstatic internal(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"INTERNAL_ERROR\",\n\t\t\tpublicMessage: \"An unexpected error occurred.\",\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* The app is set up so nextly cannot work: a missing `config`, or a Next.js\n\t* or React outside the supported ranges. The public message stays generic;\n\t* what to change goes in `logMessage`, for the operator.\n\t*/\n\tstatic configuration(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"CONFIGURATION_ERROR\",\n\t\t\tpublicMessage: \"Server configuration error.\",\n\t\t\tlogMessage: opts.logMessage,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* A service outside Nextly failed, such as an email provider, where trying again may help: the\n\t* job queue records it as an attempt's error and tries again.\n\t*/\n\tstatic externalService(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"EXTERNAL_SERVICE_ERROR\",\n\t\t\tpublicMessage: opts.publicMessage,\n\t\t\tlogMessage: opts.logMessage,\n\t\t\tcause: opts.cause,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\tstatic serviceUnavailable(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"SERVICE_UNAVAILABLE\",\n\t\t\tpublicMessage: opts?.publicMessage ?? \"Service unavailable. Please try again later.\",\n\t\t\tlogMessage: opts?.logMessage,\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* Convert a DbError (or arbitrary unknown thrown by the DB layer) to a\n\t* NextlyError with a generic public message and rich logContext. Used by\n\t* `withDbErrors` for auto-conversion (Pattern A) and by services that\n\t* catch DB errors at boundaries (Pattern B). Spec §8.2 mapping table.\n\t*\n\t* Never leaks DB driver text, constraint names, or table names into\n\t* `publicMessage`. All DB context goes into `logContext`. The original\n\t* DbError is preserved as `cause`.\n\t*/\n\tstatic fromDatabaseError(error) {\n\t\tif (isDbError(error)) {\n\t\t\tconst mapping = DB_ERROR_MAPPING[error.kind];\n\t\t\tconst logContext = {\n\t\t\t\tdbKind: error.kind,\n\t\t\t\tdialect: error.dialect\n\t\t\t};\n\t\t\tif (error.code !== void 0) logContext.dbCode = error.code;\n\t\t\tif (error.meta !== void 0) logContext.meta = error.meta;\n\t\t\treturn new NextlyError({\n\t\t\t\tcode: mapping.code,\n\t\t\t\tstatusCode: mapping.statusCode,\n\t\t\t\tpublicMessage: mapping.publicMessage,\n\t\t\t\tpublicData: \"publicData\" in mapping ? mapping.publicData : void 0,\n\t\t\t\tlogMessage: \"Database error\",\n\t\t\t\tlogContext,\n\t\t\t\tcause: error\n\t\t\t});\n\t\t}\n\t\treturn new NextlyError({\n\t\t\tcode: \"INTERNAL_ERROR\",\n\t\t\tstatusCode: 500,\n\t\t\tpublicMessage: \"An unexpected error occurred.\",\n\t\t\tlogMessage: \"Non-DbError passed to fromDatabaseError\",\n\t\t\tcause: error instanceof Error ? error : void 0,\n\t\t\tlogContext: error instanceof Error ? void 0 : { value: String(error) }\n\t\t});\n\t}\n\tstatic is(err) {\n\t\treturn hasBrand(err);\n\t}\n\tstatic isCode(err, code) {\n\t\treturn hasBrand(err) && err.code === code;\n\t}\n\tstatic isNotFound(err) {\n\t\treturn NextlyError.isCode(err, \"NOT_FOUND\");\n\t}\n\tstatic isValidation(err) {\n\t\treturn NextlyError.isCode(err, \"VALIDATION_ERROR\");\n\t}\n\tstatic isAuthRequired(err) {\n\t\treturn NextlyError.isCode(err, \"AUTH_REQUIRED\");\n\t}\n\tstatic isForbidden(err) {\n\t\treturn NextlyError.isCode(err, \"FORBIDDEN\");\n\t}\n\tstatic isConflict(err) {\n\t\treturn NextlyError.isCode(err, \"CONFLICT\");\n\t}\n\tstatic isRateLimited(err) {\n\t\treturn NextlyError.isCode(err, \"RATE_LIMITED\");\n\t}\n};\nexport { NEXTLY_ERROR_STATUS as a, DbError as c, isUniqueViolation as d, safeCode as f, retryAfterSeconds as i, isDatabaseBusy as l, POOL_WAIT_TIMEOUT_CODE as m, nextly_error_exports as n, genericPublicMessage as o, toDbError as p, retryAfterHeader as r, statusToErrorCode as s, NextlyError as t, isDbError as u };\n","import { t as NextlyError } from \"./nextly-error-CezzIwjj.mjs\";\nimport { i as ipv4ToInt } from \"./get-trusted-client-ip-CYEbmLA3.mjs\";\n// src/utils/validate-external-url.ts\nconst 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)$/;\n/**\n* IPv4 CIDR ranges that must NEVER be the destination of an outbound\n* fetch sourced from a user-controllable URL. Listed roughly by RFC.\n*/\nconst PRIVATE_IPV4_CIDRS = [\n\t\"0.0.0.0/8\",\n\t\"10.0.0.0/8\",\n\t\"100.64.0.0/10\",\n\t\"127.0.0.0/8\",\n\t\"169.254.0.0/16\",\n\t\"172.16.0.0/12\",\n\t\"192.0.0.0/24\",\n\t\"192.0.2.0/24\",\n\t\"192.168.0.0/16\",\n\t\"198.18.0.0/15\",\n\t\"198.51.100.0/24\",\n\t\"203.0.113.0/24\",\n\t\"224.0.0.0/4\",\n\t\"240.0.0.0/4\"\n];\n/**\n* Cloud-metadata hostnames. These often resolve to private IPs and the\n* private-IP block catches them, but we reject by hostname first so the\n* error message is clear.\n*/\nconst CLOUD_METADATA_HOSTS = /* @__PURE__ */ new Set([\n\t\"metadata.google.internal\",\n\t\"metadata.googleapis.com\",\n\t\"metadata\"\n]);\n/**\n* An outbound URL refused for SSRF safety. Extends `NextlyError` (the package's\n* canonical error) so throw sites honor the error contract, while remaining a\n* distinct class the callers (e.g. the form-builder webhook handler) match with\n* `instanceof`.\n*/\nvar ExternalUrlError = class extends NextlyError {\n\turl;\n\tconstructor(message, url) {\n\t\tsuper({\n\t\t\tcode: \"EXTERNAL_URL_BLOCKED\",\n\t\t\tpublicMessage: message,\n\t\t\tlogContext: { url }\n\t\t});\n\t\tthis.url = url;\n\t\tthis.name = \"ExternalUrlError\";\n\t}\n};\n/** Validate a URL for outbound fetch. Throws `ExternalUrlError` on rejection. */\nasync function validateExternalUrl(rawUrl, options = {}) {\n\tlet parsed;\n\ttry {\n\t\tparsed = new URL(rawUrl);\n\t} catch {\n\t\tthrow new ExternalUrlError(\"Invalid URL\", rawUrl);\n\t}\n\tconst hostname = parsed.hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n\tconst isLocalhostHostname = hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"::1\";\n\tconst baseProtocols = options.allowedProtocols ?? [\"https:\"];\n\tconst protocols = options.allowLocalhost && isLocalhostHostname ? [...baseProtocols, \"http:\"] : baseProtocols;\n\tif (!protocols.includes(parsed.protocol)) throw new ExternalUrlError(`Protocol ${parsed.protocol} not allowed (allowed: ${protocols.join(\", \")})`, rawUrl);\n\tif (CLOUD_METADATA_HOSTS.has(hostname)) throw new ExternalUrlError(`Cloud-metadata hostname rejected: ${parsed.hostname}`, rawUrl);\n\tif (IPV4_RE.test(hostname)) {\n\t\tif (!isPublicIpv4(hostname, options.allowLocalhost === true && hostname === \"127.0.0.1\")) throw new ExternalUrlError(`Resolved to non-public IP: ${hostname}`, rawUrl);\n\t\treturn {\n\t\t\turl: parsed,\n\t\t\tpinnedIp: hostname,\n\t\t\tfamily: 4\n\t\t};\n\t}\n\tif (hostname.includes(\":\")) {\n\t\tif (!isPublicIpv6(hostname, options.allowLocalhost === true && hostname === \"::1\")) throw new ExternalUrlError(`Resolved to non-public IP: ${hostname}`, rawUrl);\n\t\treturn {\n\t\t\turl: parsed,\n\t\t\tpinnedIp: hostname,\n\t\t\tfamily: 6\n\t\t};\n\t}\n\tconst { lookup } = await import(\"node:dns/promises\");\n\tlet addresses;\n\ttry {\n\t\taddresses = await lookup(hostname, { all: true });\n\t} catch (err) {\n\t\tthrow new ExternalUrlError(`DNS lookup failed: ${err.message}`, rawUrl);\n\t}\n\tif (addresses.length === 0) throw new ExternalUrlError(\"No IPs returned for host\", rawUrl);\n\tfor (const { address, family } of addresses) {\n\t\tconst allow = options.allowLocalhost === true && isLocalhostHostname && family === 4;\n\t\tif (!(family === 4 ? isPublicIpv4(address, allow) : isPublicIpv6(address, allow))) throw new ExternalUrlError(`Resolved to non-public IP: ${address}`, rawUrl);\n\t}\n\tconst first = addresses[0];\n\treturn {\n\t\turl: parsed,\n\t\tpinnedIp: first.address,\n\t\tfamily: first.family === 6 ? 6 : 4\n\t};\n}\n/** Default response body cap: reject anything larger before buffering it all. */\n/**\n* How many bytes a bounded external read may buffer, absent a caller's own cap.\n*\n* Exported for the same reason as the deadline below: an adapter that never\n* touches `safeFetch` still owes callers this default, and restating the number\n* gives the tree two that drift.\n*/\nconst DEFAULT_MAX_RESPONSE_BYTES = 10485760;\n/** Default overall deadline covering DNS + connect + TLS + response. */\n/**\n* How long a bounded external read may take, absent a caller's own limit.\n*\n* Exported so a caller that must begin the clock EARLIER — a storage adapter\n* bounding a metadata lookup as well as the fetch that follows — uses this\n* number rather than restating it. Two spellings of one default agree today and\n* drift the first time either is tuned.\n*/\nconst DEFAULT_TIMEOUT_MS = 3e4;\n/**\n* Raised for fetch-phase failures that are NOT SSRF rejections: an over-large\n* response body, the overall deadline elapsing, or an undecodable content\n* encoding. Extends `NextlyError` (the canonical error contract) while staying a\n* distinct class, so a caller can tell \"URL refused for safety\"\n* (`ExternalUrlError`) apart from \"the request itself failed\".\n*/\nvar SafeFetchError = class extends NextlyError {\n\turl;\n\treason;\n\tstatus;\n\tconstructor(message, url, reason, status) {\n\t\tsuper({\n\t\t\tcode: \"EXTERNAL_REQUEST_FAILED\",\n\t\t\tpublicMessage: message,\n\t\t\tlogContext: {\n\t\t\t\turl,\n\t\t\t\treason\n\t\t\t}\n\t\t});\n\t\tthis.url = url;\n\t\tthis.reason = reason;\n\t\tthis.status = status;\n\t\tthis.name = \"SafeFetchError\";\n\t}\n};\n/**\n* Build a `dns.lookup`-compatible function that ignores the hostname and\n* always resolves to `ip`/`family`. Handing this to `http(s).request` forces\n* the socket to dial the exact address `validateExternalUrl` already vetted,\n* closing the DNS-rebinding window where a second resolution at connect time\n* could return a private IP. Not re-exported from the package barrel; exported\n* for the plugin `ctx.fetch` transport, which pins its vetted address the same\n* way, and so the rebinding invariant can be unit-tested directly.\n*/\nfunction createPinnedLookup(ip, family) {\n\treturn (_hostname, options, callback) => {\n\t\tif (options && options.all) callback(null, [{\n\t\t\taddress: ip,\n\t\t\tfamily\n\t\t}]);\n\t\telse callback(null, ip, family);\n\t};\n}\n/**\n* Validate `rawUrl` then fetch it with the validated IP pinned at the socket.\n* The convenience wrapper for the common case (webhook delivery, email\n* attachment fetch). Node-runtime only.\n*\n* DNS is resolved once by `validateExternalUrl`; `createPinnedLookup` forces\n* the connection to that same address, so an attacker's DNS cannot rebind the\n* request to a private host between validation and connect. Redirects are not\n* followed, the body is capped at `maxResponseBytes`, and the request is\n* bounded by `timeoutMs`.\n*/\nasync function safeFetch(rawUrl, options = {}) {\n\tconst { allowLocalhost, allowedProtocols, method, headers, body, signal, maxResponseBytes = DEFAULT_MAX_RESPONSE_BYTES, timeoutMs = DEFAULT_TIMEOUT_MS } = options;\n\tconst controller = new AbortController();\n\tconst forwardAbort = () => controller.abort(signal?.reason);\n\tif (signal) {\n\t\tif (signal.aborted) controller.abort(signal.reason);\n\t\telse signal.addEventListener(\"abort\", forwardAbort, { once: true });\n\t}\n\tconst timer = setTimeout(() => controller.abort(new SafeFetchError(`Request exceeded ${timeoutMs}ms`, rawUrl, \"timeout\")), timeoutMs);\n\ttry {\n\t\treturn await pinnedFetch(await abortable(validateExternalUrl(rawUrl, {\n\t\t\tallowLocalhost,\n\t\t\tallowedProtocols\n\t\t}), controller.signal), {\n\t\t\tmethod,\n\t\t\theaders,\n\t\t\tbody,\n\t\t\tsignal: controller.signal,\n\t\t\tmaxResponseBytes\n\t\t});\n\t} finally {\n\t\tclearTimeout(timer);\n\t\tif (signal) signal.removeEventListener(\"abort\", forwardAbort);\n\t}\n}\n/**\n* The signal's abort reason as an `Error`. Our own aborts carry a\n* `SafeFetchError` (timeout); a caller's `AbortController.abort()` carries a\n* DOMException `AbortError`; anything else (a non-Error reason) is surfaced as\n* a standard `AbortError` so downstream `name === \"AbortError\"` checks hold.\n*/\nfunction abortError(signal) {\n\tconst reason = signal.reason;\n\tif (reason instanceof Error) return reason;\n\treturn new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n/**\n* Resolve `promise`, but reject with the signal's reason if it aborts first.\n* Lets a phase that runs before the request (DNS validation) share the overall\n* deadline and caller cancellation.\n*/\nfunction abortable(promise, signal) {\n\tif (signal.aborted) return Promise.reject(abortError(signal));\n\tlet onAbort;\n\tconst aborted = new Promise((_resolve, reject) => {\n\t\tonAbort = () => reject(abortError(signal));\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n\treturn Promise.race([promise, aborted]).finally(() => signal.removeEventListener(\"abort\", onAbort));\n}\n/**\n* Issue the request over `node:http`/`node:https` with the validated IP pinned\n* via a custom `lookup`, then adapt the Node response into a WHATWG `Response`.\n* `agent: false` forces a fresh socket per call so no pooled connection can\n* reuse a differently-resolved address. The overall deadline is enforced by the\n* caller through `init.signal`, so there is no separate timer here.\n*/\nasync function pinnedFetch(validated, init) {\n\tconst { url, pinnedIp, family } = validated;\n\tconst httpMod = url.protocol === \"https:\" ? await import(\"node:https\") : await import(\"node:http\");\n\tconst zlib = await import(\"node:zlib\");\n\tconst lookup = createPinnedLookup(pinnedIp, family);\n\tconst outHeaders = toOutgoingHeaders(init.headers);\n\tif (init.body != null) {\n\t\tdelete outHeaders[\"transfer-encoding\"];\n\t\toutHeaders[\"content-length\"] = String(typeof init.body === \"string\" ? Buffer.byteLength(init.body) : init.body.byteLength);\n\t}\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst settle = (fn) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tfn();\n\t\t};\n\t\tconst failure = (err) => init.signal.aborted ? abortError(init.signal) : err;\n\t\tconst req = httpMod.request(url, {\n\t\t\tmethod: init.method ?? \"GET\",\n\t\t\theaders: outHeaders,\n\t\t\tlookup,\n\t\t\tagent: false,\n\t\t\tsignal: init.signal\n\t\t}, (res) => {\n\t\t\tconst chunks = [];\n\t\t\tlet received = 0;\n\t\t\tres.on(\"data\", (chunk) => {\n\t\t\t\treceived += chunk.length;\n\t\t\t\tif (received > init.maxResponseBytes) {\n\t\t\t\t\tres.destroy();\n\t\t\t\t\treq.destroy();\n\t\t\t\t\tsettle(() => reject(new SafeFetchError(`Response body exceeded ${init.maxResponseBytes} bytes`, url.href, \"response-too-large\", res.statusCode)));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tchunks.push(chunk);\n\t\t\t});\n\t\t\tres.on(\"end\", () => {\n\t\t\t\tconst decoded = decodeBody(Buffer.concat(chunks), res.headers[\"content-encoding\"], zlib, init.maxResponseBytes, url.href, res.statusCode);\n\t\t\t\tif (decoded instanceof SafeFetchError) {\n\t\t\t\t\tsettle(() => reject(decoded));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettle(() => resolve(toWhatwgResponse(res, decoded.body, decoded.decoded)));\n\t\t\t});\n\t\t\tres.on(\"error\", (err) => settle(() => reject(failure(err))));\n\t\t});\n\t\treq.on(\"error\", (err) => settle(() => reject(failure(err))));\n\t\tif (!req.destroyed) {\n\t\t\tif (init.body != null) req.write(init.body);\n\t\t\treq.end();\n\t\t}\n\t});\n}\n/**\n* Normalize a `HeadersInit` into Node's outgoing-header shape. Header names are\n* lowercased (they are case-insensitive) so later framing checks\n* (`content-length`) and the Host strip are reliable regardless of caller\n* casing. A caller-supplied `Host` is dropped: it is derived from the validated\n* URL, and honoring an override would let Host-based routing reach an internal\n* vhost behind a validated public IP, defeating the SSRF pin.\n*/\nfunction toOutgoingHeaders(headers) {\n\tconst out = {};\n\tif (!headers) return out;\n\tconst add = (rawKey, value) => {\n\t\tconst key = rawKey.toLowerCase();\n\t\tif (key === \"host\") return;\n\t\tconst existing = out[key];\n\t\tout[key] = existing === void 0 ? value : [].concat(existing, value);\n\t};\n\tif (headers instanceof Headers) headers.forEach((value, key) => add(key, value));\n\telse if (Array.isArray(headers)) for (const [key, value] of headers) add(key, value);\n\telse for (const [key, value] of Object.entries(headers)) add(key, value);\n\treturn out;\n}\n/**\n* Adapt a Node `IncomingMessage` + buffered body into a WHATWG `Response`.\n* Total by construction: a header the WHATWG layer rejects is skipped and the\n* status is clamped to a constructible range, so this never throws (a throw\n* would otherwise escape the `end` handler as an uncaught error).\n*/\nfunction toWhatwgResponse(res, body, stripContentHeaders) {\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(res.headers)) {\n\t\tif (value == null) continue;\n\t\tconst lower = key.toLowerCase();\n\t\tif (stripContentHeaders && (lower === \"content-encoding\" || lower === \"content-length\")) continue;\n\t\tconst values = Array.isArray(value) ? value : [value];\n\t\tfor (const v of values) try {\n\t\t\theaders.append(key, v);\n\t\t} catch {}\n\t}\n\tconst raw = res.statusCode ?? 502;\n\tconst status = raw >= 200 && raw <= 599 ? raw : 502;\n\tconst nullBody = status === 204 || status === 205 || status === 304;\n\tconst bytes = new Uint8Array(body.byteLength);\n\tbytes.set(body);\n\treturn new Response(nullBody ? null : bytes, {\n\t\tstatus,\n\t\tstatusText: res.statusMessage ?? \"\",\n\t\theaders\n\t});\n}\n/**\n* Content-decode a response body per its `Content-Encoding`. node:http returns\n* raw wire bytes (unlike global fetch), so gzip/deflate/br bodies are inflated\n* here to preserve the previous behavior. `maxOutputLength` bounds the inflated\n* size, turning a decompression bomb into a `SafeFetchError` rather than an OOM.\n* Returns the (possibly decoded) buffer, or a `SafeFetchError` on failure.\n*/\nfunction decodeBody(buf, encoding, zlib, cap, url, status) {\n\tif (!encoding) return {\n\t\tbody: buf,\n\t\tdecoded: false\n\t};\n\tif (buf.length === 0) return {\n\t\tbody: buf,\n\t\tdecoded: true\n\t};\n\tconst layers = encoding.split(\",\").map((e) => e.trim().toLowerCase()).filter(Boolean);\n\tconst opts = { maxOutputLength: cap };\n\tlet current = buf;\n\tlet decoded = false;\n\ttry {\n\t\tfor (let i = layers.length - 1; i >= 0; i--) {\n\t\t\tconst enc = layers[i];\n\t\t\tif (enc === \"identity\") continue;\n\t\t\tif (enc === \"gzip\" || enc === \"x-gzip\") current = zlib.gunzipSync(current, opts);\n\t\t\telse if (enc === \"br\") current = zlib.brotliDecompressSync(current, opts);\n\t\t\telse if (enc === \"deflate\") try {\n\t\t\t\tcurrent = zlib.inflateSync(current, opts);\n\t\t\t} catch (inflateErr) {\n\t\t\t\tif (errorCode(inflateErr) === \"ERR_BUFFER_TOO_LARGE\") throw inflateErr;\n\t\t\t\tcurrent = zlib.inflateRawSync(current, opts);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (decoded) return new SafeFetchError(`Cannot fully decode content-encoding \"${encoding}\"`, url, \"decode-failed\", status);\n\t\t\t\treturn {\n\t\t\t\t\tbody: buf,\n\t\t\t\t\tdecoded: false\n\t\t\t\t};\n\t\t\t}\n\t\t\tdecoded = true;\n\t\t}\n\t\treturn {\n\t\t\tbody: current,\n\t\t\tdecoded\n\t\t};\n\t} catch (err) {\n\t\tconst tooLarge = errorCode(err) === \"ERR_BUFFER_TOO_LARGE\";\n\t\treturn 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);\n\t}\n}\n/** The `.code` of a Node system error, if present. */\nfunction errorCode(err) {\n\tif (err != null && typeof err === \"object\" && \"code\" in err) {\n\t\tconst code = err.code;\n\t\treturn typeof code === \"string\" ? code : void 0;\n\t}\n}\nfunction isIpv4InCidr(intIp, cidr) {\n\tconst [addr, prefixRaw] = cidr.split(\"/\");\n\tconst intCidr = ipv4ToInt(addr);\n\tif (intCidr === null) return false;\n\tconst prefix = Number(prefixRaw);\n\tif (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false;\n\tconst mask = prefix === 0 ? 0 : -1 >>> 32 - prefix << 32 - prefix;\n\treturn (intIp & mask) >>> 0 === (intCidr & mask) >>> 0;\n}\nfunction isPublicIpv4(addr, allowLoopback) {\n\tconst intIp = ipv4ToInt(addr);\n\tif (intIp === null) return false;\n\tif (allowLoopback && addr === \"127.0.0.1\") return true;\n\tfor (const cidr of PRIVATE_IPV4_CIDRS) if (isIpv4InCidr(intIp, cidr)) return false;\n\treturn true;\n}\n/**\n* Extract the embedded IPv4 of an IPv4-mapped IPv6 address, or null. Handles\n* both the dotted form (`::ffff:1.2.3.4`) and the hex form (`::ffff:7f00:1`)\n* that `URL.hostname` normalizes the dotted literal to — the latter would\n* otherwise skip the IPv4 denylist and pin, e.g., loopback as public.\n*/\nfunction mappedIpv4(lower) {\n\tconst dotted = lower.match(/^::ffff:(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$/);\n\tif (dotted) return dotted[1];\n\tconst hex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n\tif (hex) {\n\t\tconst hi = parseInt(hex[1], 16);\n\t\tconst lo = parseInt(hex[2], 16);\n\t\treturn [\n\t\t\thi >> 8,\n\t\t\thi & 255,\n\t\t\tlo >> 8,\n\t\t\tlo & 255\n\t\t].join(\".\");\n\t}\n\treturn null;\n}\nfunction isPublicIpv6(addr, allowLoopback) {\n\tconst lower = addr.toLowerCase();\n\tif (allowLoopback && lower === \"::1\") return true;\n\tconst mapped = mappedIpv4(lower);\n\tif (mapped) return isPublicIpv4(mapped, allowLoopback);\n\tif (lower === \"::\" || lower === \"::1\") return false;\n\tconst firstHextet = lower.split(\":\")[0] || \"\";\n\tif (firstHextet.startsWith(\"fc\") || firstHextet.startsWith(\"fd\")) return false;\n\tif (firstHextet.startsWith(\"fe8\") || firstHextet.startsWith(\"fe9\")) return false;\n\tif (firstHextet.startsWith(\"fea\") || firstHextet.startsWith(\"feb\")) return false;\n\tif (firstHextet.startsWith(\"ff\")) return false;\n\treturn true;\n}\nexport { createPinnedLookup as a, SafeFetchError as i, DEFAULT_TIMEOUT_MS as n, safeFetch as o, ExternalUrlError as r, validateExternalUrl as s, DEFAULT_MAX_RESPONSE_BYTES as t };\n","import { t as NextlyError } from \"../nextly-error-CezzIwjj.mjs\";\n// src/storage/read-errors.ts\n/**\n* The one way the storage layer says a read exceeded the caller's cap.\n*\n* `StorageReadOptions.maxBytes` is part of the adapter contract, so what happens\n* when it is exceeded belongs to the contract too. Without this each backend\n* refuses in its own vocabulary — the URL-addressed ones through a fetch error\n* carrying a `reason`, S3 through whatever its own code threw — and a caller\n* wanting to tell \"too large\" from \"could not read\" has to know which adapter it\n* is talking to. That is the thing an adapter contract exists to stop.\n*\n* Distinct from a generic internal failure because callers ACT on the\n* difference. The email attachment path answers an over-cap read with\n* `ATTACHMENT_SIZE_EXCEEDED`, which tells an author to attach something smaller;\n* a storage failure tells them nothing they can act on. Collapsing the two turns\n* a fixable refusal into an opaque error, which is the same conflation this\n* contract already draws between a missing key and an unreachable store.\n*\n* @module storage/read-errors\n*/\n/**\n* A read refused because the object is larger than the caller allowed.\n*\n* Carries the numbers rather than only a message, so a caller can say what the\n* limit was without parsing prose — and so the message itself stays free of the\n* key, which should not travel to whoever asked for the file.\n*/\nvar StorageReadTooLargeError = class extends NextlyError {\n\tpath;\n\tmaxBytes;\n\tsize;\n\tconstructor(path, maxBytes, size) {\n\t\tsuper({\n\t\t\tcode: \"STORAGE_READ_TOO_LARGE\",\n\t\t\tpublicMessage: \"The stored file is larger than the limit for this read.\",\n\t\t\tlogContext: {\n\t\t\t\tpath,\n\t\t\t\tmaxBytes,\n\t\t\t\t...size === void 0 ? {} : { size }\n\t\t\t}\n\t\t});\n\t\tthis.path = path;\n\t\tthis.maxBytes = maxBytes;\n\t\tthis.size = size;\n\t}\n};\n/**\n* Whether a thrown value is the over-cap refusal.\n*\n* A predicate rather than leaving every caller to write `instanceof`, because\n* this module can be loaded twice — a narrow entry point and a barrel are\n* different module instances, and `instanceof` across them is false for objects\n* that are otherwise identical. Callers that ask here cannot be caught by that.\n*/\nfunction isStorageReadTooLarge(error) {\n\treturn NextlyError.is(error) && error.code === \"STORAGE_READ_TOO_LARGE\";\n}\n/**\n* A read abandoned because the backend did not answer in time.\n*\n* Carried as the abort REASON rather than raised afterwards, which is what\n* makes it reach the caller at all: `AbortSignal.timeout` rejects with a\n* platform `DOMException`, and product code in this package answers in\n* `NextlyError` so a caller can classify what it caught without matching on a\n* name the runtime chose. `safeFetch` already aborts this way for the same\n* reason.\n*\n* Distinct from the over-cap refusal above by what each one KNOWS. The over-cap\n* refusal has measured the object and found it larger than the caller allowed.\n* This one knows only that the read did not finish in time: it may never have\n* opened the object, or may have taken some of it and been cut off part way, so\n* neither the object's size nor its existence follows from this error.\n*/\nvar StorageReadTimeoutError = class extends NextlyError {\n\tpath;\n\ttimeoutMs;\n\tconstructor(path, timeoutMs) {\n\t\tsuper({\n\t\t\tcode: \"STORAGE_READ_TIMEOUT\",\n\t\t\tpublicMessage: \"The stored file could not be read in time.\",\n\t\t\tlogContext: {\n\t\t\t\tpath,\n\t\t\t\ttimeoutMs\n\t\t\t}\n\t\t});\n\t\tthis.path = path;\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n};\n/**\n* Whether a thrown value is the deadline refusal.\n*\n* A predicate for the same reason as `isStorageReadTooLarge`: a narrow entry\n* point and a barrel are different module instances, and `instanceof` across\n* them is false for objects that are otherwise identical.\n*/\nfunction isStorageReadTimeout(error) {\n\treturn NextlyError.is(error) && error.code === \"STORAGE_READ_TIMEOUT\";\n}\nexport { StorageReadTimeoutError, StorageReadTooLargeError, isStorageReadTimeout, isStorageReadTooLarge };\n","import { t as NextlyError } from \"../nextly-error-CezzIwjj.mjs\";\nimport { i as SafeFetchError, n as DEFAULT_TIMEOUT_MS, o as safeFetch, t as DEFAULT_MAX_RESPONSE_BYTES } from \"../validate-external-url-BGTmyj1s.mjs\";\nimport { StorageReadTimeoutError, StorageReadTooLargeError } from \"./read-errors.mjs\";\n// src/storage/fetch-stored-bytes.ts\n/**\n* Reading bytes back from a storage service that only exposes them over HTTP.\n*\n* The local adapter reads from disk and S3 reads through its own SDK, so\n* neither needs this. The services that address a file by URL — Vercel Blob,\n* UploadThing — all end up doing the same three things, and doing them the same\n* way matters more than it looks: each step below is a place where the obvious\n* shortcut reports the wrong thing to a caller who may act on it.\n*\n* Built on {@link safeFetch} rather than on a bare `fetch`, because \"read a\n* remote object into memory\" already has an implementation here that caps the\n* body, bounds the request and refuses an address that resolves somewhere\n* private. A second capped fetch beside it would be two answers to one\n* question, and the two would drift the first time either learned something.\n* Measured: it costs an adapter package about 80K, against the 1MB the whole\n* storage barrel costs.\n*\n* @module storage/fetch-stored-bytes\n*/\n/**\n* Fetch a stored object's bytes from the URL its service issued.\n*\n* Separates the two answers a read can have, which is the whole reason this is\n* a function rather than three lines inlined twice.\n*\n* `null` means the object is NOT THERE — an ordinary fact about the store. A\n* 404 is that answer even when the lookup just succeeded: these stores are\n* remote and concurrent, so an object can be deleted between resolving its\n* address and fetching it. Reporting that ordinary race as a server failure\n* would make a caller handle an error for something its own contract already\n* has a value for.\n*\n* Anything else THROWS. A dropped connection, a 5xx or a refused request says\n* nothing about whether the object exists, and reporting it as absence invites\n* a caller to treat a live file as deleted and write a replacement over it. The\n* two are easy to state apart and easy to lose when the fetch sits inside the\n* same `try` that catches the lookup.\n*\n* The URL is always one the SERVICE issued, never one assembled from a key.\n* These stores mint addresses carrying suffixes the adapter never chose, so a\n* derived URL is a guess at a string another system owns.\n*\n* @param url - The address the storage service reported for this object\n* @param context - What is being read, for the error message: usually the key\n* @param label - The service's name, so a failure says which store answered\n* @param options - Bounds for the read; see {@link StorageReadOptions}\n* @param signal - A deadline ALREADY RUNNING, covering an earlier phase too\n* @returns The object's bytes, or `null` when the store answers 404\n*/\nasync function fetchStoredBytes(url, context, label, options, signal) {\n\tlet response;\n\ttry {\n\t\tresponse = await safeFetch(url, {\n\t\t\t...options?.maxBytes === void 0 ? {} : { maxResponseBytes: options.maxBytes },\n\t\t\t...signal !== void 0 ? { signal } : options?.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }\n\t\t});\n\t} catch (error) {\n\t\tconst verdict = classifyFetchFailure(error);\n\t\tif (verdict === \"absent\") return null;\n\t\tif (verdict === \"oversized\") throw new StorageReadTooLargeError(context, resolveReadBounds(options).maxBytes);\n\t\tthrow error;\n\t}\n\tif (response.status === 404) return null;\n\tif (!response.ok) throw NextlyError.internal({ logContext: {\n\t\tservice: label,\n\t\tpath: context,\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText\n\t} });\n\treturn Buffer.from(await response.arrayBuffer());\n}\n/**\n* What a failed fetch actually says about the object.\n*\n* Its own function because the three answers are the whole point of this module\n* and they are easy to collapse into each other — each collapse having been a\n* real defect here rather than a hypothetical:\n*\n* - ABSENT. A 404 is absence whatever size its body was. `safeFetch` caps while\n* buffering, so a verbose CDN error page raises before a `Response` exists\n* and the status check further down is never reached; the object is still\n* gone, and must not become an error because the page explaining it was long.\n* - OVERSIZED. Only a SUCCESSFUL response that blew the cap. A failed response\n* can exceed it too, and translating on the reason alone reported a backend\n* outage as \"your file is too big\" — a cause the author would act on, wrongly.\n* - UNKNOWN. Everything else, including a too-large refusal carrying NO status:\n* that means the failure arrived before any status did, which says nothing\n* about whether the object was oversized.\n*/\nfunction classifyFetchFailure(error) {\n\tif (!(error instanceof SafeFetchError)) return \"unknown\";\n\tif (error.status === 404) return \"absent\";\n\tconst successful = error.status !== void 0 && error.status >= 200 && error.status < 300;\n\treturn error.reason === \"response-too-large\" && successful ? \"oversized\" : \"unknown\";\n}\n/** The deadline a stored read runs under when the caller names none. */\nconst DEFAULT_READ_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;\n/** The byte cap a stored read runs under when the caller names none. */\nconst DEFAULT_READ_MAX_BYTES = DEFAULT_MAX_RESPONSE_BYTES;\n/**\n* The bounds a read actually runs under, defaults filled in.\n*\n* ONE place, because every adapter needs the same answer and the ones that\n* derived it themselves diverged: the URL-backed pair inherited `safeFetch`'s\n* cap and deadline for free, while the local and S3 adapters — which never\n* touch `safeFetch` — applied NO bound at all when the caller named none.\n* `StorageReadOptions` promises the default either way, and a production caller\n* reading media without options got it from two of four backends.\n*\n* Filling the defaults here rather than per adapter is what makes the promise\n* true by construction rather than by four implementations agreeing.\n*/\nfunction resolveReadBounds(options) {\n\treturn {\n\t\tmaxBytes: options?.maxBytes ?? DEFAULT_READ_MAX_BYTES,\n\t\ttimeoutMs: options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS\n\t};\n}\n/**\n* A deadline that aborts with a NextlyError rather than a platform exception.\n*\n* `AbortSignal.timeout` rejects with a `DOMException` named `TimeoutError`, and\n* product code in this package answers in `NextlyError` — so a caller can\n* classify what it caught rather than matching a name the runtime chose. Built\n* here rather than per adapter so every storage deadline says the same thing.\n*\n* The timer is unreferenced so a pending deadline is never a reason the process\n* stays alive, and the returned `cancel` clears it once the read settles — the\n* unref alone would leave one scheduled per read for the whole timeout.\n*\n* @param timeoutMs - How long the read may take\n* @param context - What is being read, carried into the refusal's log side\n*/\nfunction deadlineSignal(timeoutMs, context) {\n\tconst controller = new AbortController();\n\tconst timer = setTimeout(() => {\n\t\tcontroller.abort(new StorageReadTimeoutError(context, timeoutMs));\n\t}, timeoutMs);\n\ttimer.unref?.();\n\treturn {\n\t\tsignal: controller.signal,\n\t\tcancel: () => {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t};\n}\n/**\n* Stop waiting on a promise once the deadline fires.\n*\n* For a lookup whose SDK cannot be cancelled. UploadThing 7.7.4's\n* `getFileUrls` reads only `keyType` and forwards no signal, so handing it one\n* bounds nothing — the option is accepted and ignored, which reads as covered\n* and behaves as absent.\n*\n* This RACES rather than cancels, and the difference is worth stating plainly:\n* the underlying request keeps running to completion in the background. What it\n* buys is that `read` returns within the deadline it advertised, instead of\n* holding its caller for as long as a stalled backend feels like. That is the\n* promise the contract actually makes; genuinely cancelling the work needs an\n* SDK that accepts cancellation, and this one does not.\n*/\nasync function withDeadline(work, signal) {\n\tif (signal === void 0) return await work;\n\treturn await Promise.race([work, new Promise((_, reject) => {\n\t\tif (signal.aborted) {\n\t\t\treject(signal.reason);\n\t\t\treturn;\n\t\t}\n\t\tsignal.addEventListener(\"abort\", () => reject(signal.reason), { once: true });\n\t})]);\n}\nexport { DEFAULT_READ_MAX_BYTES, DEFAULT_READ_TIMEOUT_MS, classifyFetchFailure, deadlineSignal, fetchStoredBytes, resolveReadBounds, withDeadline };\n","/**\n * S3 Storage Adapter\n *\n * Stores files on AWS S3 or S3-compatible services (Cloudflare R2, MinIO, DigitalOcean Spaces).\n * Uses AWS SDK v3 with automatic multipart upload for large files (>5MB).\n *\n * Features:\n * - Automatic multipart upload via @aws-sdk/lib-storage\n * - Pre-signed URL generation for client-side uploads\n * - Signed URL generation for private file access\n * - Cloudflare R2 support (S3-compatible API)\n * - Custom endpoint support (MinIO, DigitalOcean Spaces)\n * - CDN URL override support\n * - File metadata retrieval\n *\n * @example AWS S3\n * ```typescript\n * const adapter = new S3StorageAdapter({\n * bucket: 'my-media-bucket',\n * region: 'us-east-1',\n * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,\n * collections: { media: true }\n * });\n * ```\n *\n * @example Cloudflare R2\n * ```typescript\n * const adapter = new S3StorageAdapter({\n * bucket: 'my-media',\n * region: 'auto',\n * accessKeyId: process.env.R2_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,\n * endpoint: `https://${accountId}.r2.cloudflarestorage.com`,\n * publicUrl: 'https://pub-abc.r2.dev',\n * collections: { media: true }\n * });\n * ```\n *\n * @example MinIO (self-hosted)\n * ```typescript\n * const adapter = new S3StorageAdapter({\n * bucket: 'my-bucket',\n * region: 'us-east-1',\n * accessKeyId: process.env.MINIO_ACCESS_KEY!,\n * secretAccessKey: process.env.MINIO_SECRET_KEY!,\n * endpoint: 'http://localhost:9000',\n * forcePathStyle: true,\n * collections: { media: true }\n * });\n * ```\n */\n\nimport {\n S3Client,\n DeleteObjectCommand,\n DeleteObjectsCommand,\n ListObjectsV2Command,\n HeadObjectCommand,\n GetObjectCommand,\n PutObjectCommand,\n type PutObjectCommandInput,\n type GetObjectCommandOutput,\n} from \"@aws-sdk/client-s3\";\nimport { Upload } from \"@aws-sdk/lib-storage\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport type {\n StorageReadOptions,\n IStorageAdapter,\n UploadOptions,\n UploadResult,\n StorageAdapterInfo,\n ClientUploadData,\n FileMetadata,\n BulkDeleteResult,\n StoredFileEntry,\n} from \"nextly/storage\";\nimport { resolveReadBounds } from \"nextly/storage/fetch-stored-bytes\";\nimport { StorageReadTooLargeError } from \"nextly/storage/read-errors\";\n\nimport type { S3StorageConfig, ResolvedS3Config } from \"./types\";\n\n// ============================================================\n// S3 Storage Adapter\n// ============================================================\n\n/**\n * S3 Storage Adapter\n *\n * Implements the IStorageAdapter interface for AWS S3 and S3-compatible services.\n * Provides full support for uploads, downloads, signed URLs, and client-side uploads.\n */\n/**\n * The SDK request options carrying the caller's deadline, or none.\n *\n * A free function rather than a branch inside `read`, because it is the only\n * part of that method with nothing to do with telling an absent key apart from\n * an unreachable bucket — which is the distinction a reader has to hold in\n * their head there.\n *\n * `AbortSignal.timeout` rather than a controller and a `setTimeout`: it needs no\n * clearing, so it cannot leak a timer when the read resolves first. The signal\n * covers the BODY as well as the request, because the SDK threads it through\n * the response stream — and a backend that answers headers promptly and then\n * stalls mid-transfer is exactly the case a request-only deadline misses.\n */\nfunction abortAfter(options?: StorageReadOptions): {\n abortSignal: AbortSignal;\n} {\n /*\n * ALWAYS a signal, defaulted through the shared resolver.\n * `StorageReadOptions` promises the deadline whether or not a caller names\n * one, and the URL-backed adapters keep that promise by inheriting\n * `safeFetch`'s. Returning nothing here left the no-options read — which is\n * what the media pipeline does — able to hang on a stalled bucket forever.\n */\n return {\n abortSignal: AbortSignal.timeout(resolveReadBounds(options).timeoutMs),\n };\n}\n\nexport class S3StorageAdapter implements IStorageAdapter {\n private client: S3Client | null = null;\n private resolvedConfig: ResolvedS3Config;\n private isR2: boolean;\n\n /**\n * Create a new S3 storage adapter.\n *\n * The bucket and region are deliberately NOT checked here, and the SDK\n * client is deliberately not built. This constructor runs while the host's\n * config file is evaluated, so a throw would stop every command —\n * including the schema-only ones that never touch storage. Both the checks\n * and the client construction move to the first storage operation\n * ({@link ensureClient} and {@link ensureConfigured}), which refuse with\n * the same messages a missing bucket or region has always produced.\n *\n * @param config - S3 storage configuration\n */\n constructor(private config: S3StorageConfig) {\n // Detect if this is Cloudflare R2\n this.isR2 = config.endpoint?.includes(\"r2.cloudflarestorage.com\") ?? false;\n\n // Resolve config with defaults\n this.resolvedConfig = {\n bucket: config.bucket,\n region: config.region,\n endpoint: config.endpoint,\n forcePathStyle: config.forcePathStyle ?? false,\n acl: config.acl ?? \"private\",\n publicUrl: config.publicUrl,\n cacheControl: config.cacheControl ?? \"public, max-age=31536000\",\n contentDisposition: config.contentDisposition,\n signedUrlExpiresIn: config.signedUrlExpiresIn ?? 3600,\n };\n }\n\n /**\n * Validate that bucket and region are present.\n *\n * @throws Error if bucket is not provided\n * @throws Error if region is not provided\n */\n private ensureConfigured(): void {\n if (!this.config.bucket) {\n throw new Error(\"@nextly/storage-s3: bucket is required\");\n }\n if (!this.config.region) {\n throw new Error(\"@nextly/storage-s3: region is required\");\n }\n }\n\n /**\n * Validate the stored configuration and build the SDK client, at the\n * first use that needs them.\n *\n * The refusals are the ones the constructor used to throw, in the same\n * order, so an operator with a genuinely misconfigured deployment sees\n * the message they have always seen — at the moment the value was\n * actually needed rather than at config load. The client is built once\n * and reused.\n *\n * @throws Error if bucket is not provided\n * @throws Error if region is not provided\n */\n private ensureClient(): S3Client {\n if (this.client) return this.client;\n\n this.ensureConfigured();\n\n // Build credentials\n const credentials = this.buildCredentials();\n\n this.client = new S3Client({\n region: this.config.region,\n endpoint: this.config.endpoint,\n credentials,\n forcePathStyle: this.resolvedConfig.forcePathStyle,\n ...this.config.config,\n });\n return this.client;\n }\n\n /**\n * Build AWS credentials from config.\n * Supports explicit credentials or falls back to SDK default chain.\n */\n private buildCredentials():\n | { accessKeyId: string; secretAccessKey: string }\n | undefined {\n if (this.config.accessKeyId && this.config.secretAccessKey) {\n return {\n accessKeyId: this.config.accessKeyId,\n secretAccessKey: this.config.secretAccessKey,\n };\n }\n\n // Check if credentials are in the config object\n if (this.config.config?.credentials) {\n return undefined; // Let SDK use the provided config.credentials\n }\n\n // Fall back to SDK default credential chain (env vars, IAM roles, etc.)\n return undefined;\n }\n\n // ============================================================\n // Core IStorageAdapter Methods\n // ============================================================\n\n /**\n * Upload file to S3.\n *\n * Uses AWS SDK v3's Upload class from @aws-sdk/lib-storage which:\n * - Automatically handles multipart upload for large files (>5MB)\n * - Provides progress tracking capability\n * - Includes retry logic\n * - Optimizes upload performance\n *\n * @param buffer - File content as Buffer\n * @param options - Upload options (filename, mimeType, folder, collection)\n * @returns Upload result with URL and storage path\n */\n async upload(buffer: Buffer, options: UploadOptions): Promise<UploadResult> {\n const client = this.ensureClient();\n const key = this.generateKey(options.filename, options.folder);\n\n // Build upload parameters\n const uploadParams: PutObjectCommandInput = {\n Bucket: this.resolvedConfig.bucket,\n Key: key,\n Body: buffer,\n ContentType: options.contentType || options.mimeType,\n CacheControl: this.resolvedConfig.cacheControl,\n };\n\n // Add ACL if not R2 (R2 ignores ACL settings)\n if (!this.isR2) {\n uploadParams.ACL = this.resolvedConfig.acl;\n }\n\n // Add Content-Disposition: per-file override takes priority, then global config\n const disposition =\n options.contentDisposition ?? this.resolvedConfig.contentDisposition;\n if (disposition) {\n const filename = this.sanitizeFilename(options.filename);\n uploadParams.ContentDisposition =\n disposition === \"attachment\"\n ? `attachment; filename=\"${filename}\"`\n : \"inline\";\n }\n\n // Store original filename in metadata for later retrieval\n uploadParams.Metadata = {\n \"original-filename\": options.filename,\n };\n\n // Use Upload for automatic multipart handling\n const upload = new Upload({\n client,\n params: uploadParams,\n });\n\n await upload.done();\n\n return {\n url: this.getPublicUrl(key),\n path: key,\n };\n }\n\n /**\n * Delete file from S3.\n *\n * @param filePath - Storage path/key to delete\n */\n async delete(filePath: string): Promise<void> {\n const client = this.ensureClient();\n const command = new DeleteObjectCommand({\n Bucket: this.resolvedConfig.bucket,\n Key: filePath,\n });\n\n await client.send(command);\n }\n\n /**\n * Bulk delete files from S3 using a single API call per 1000 keys.\n *\n * Uses AWS SDK v3's DeleteObjectsCommand which supports up to 1000 keys per\n * request. Automatically batches larger arrays and collects per-key results.\n *\n * @param filePaths - Storage paths/keys to delete\n * @returns Object with arrays of successful and failed deletions\n */\n async bulkDelete(filePaths: string[]): Promise<BulkDeleteResult> {\n const client = this.ensureClient();\n const successful: string[] = [];\n const failed: Array<{ filePath: string; error: string }> = [];\n const maxBatchSize = 1000; // AWS limit\n\n for (let i = 0; i < filePaths.length; i += maxBatchSize) {\n const batch = filePaths.slice(i, i + maxBatchSize);\n const command = new DeleteObjectsCommand({\n Bucket: this.resolvedConfig.bucket,\n Delete: {\n Objects: batch.map(key => ({ Key: key })),\n Quiet: false,\n },\n });\n\n const response = await client.send(command);\n\n if (response.Errors && response.Errors.length > 0) {\n for (const err of response.Errors) {\n if (err.Key) {\n failed.push({\n filePath: err.Key,\n error: err.Message ?? \"Unknown S3 delete error\",\n });\n }\n }\n }\n\n if (response.Deleted) {\n for (const del of response.Deleted) {\n if (del.Key) {\n successful.push(del.Key);\n }\n }\n }\n }\n\n return { successful, failed };\n }\n\n /**\n * Check if file exists in S3.\n *\n * Uses HeadObject command which is more efficient than GetObject\n * for existence checks (doesn't download the file).\n *\n * @param filePath - Storage path/key to check\n * @returns true if file exists, false otherwise\n */\n async exists(filePath: string): Promise<boolean> {\n const client = this.ensureClient();\n try {\n const command = new HeadObjectCommand({\n Bucket: this.resolvedConfig.bucket,\n Key: filePath,\n });\n\n await client.send(command);\n return true;\n } catch (error: unknown) {\n // HeadObject returns 404 if object doesn't exist\n if (this.isNotFoundError(error)) {\n return false;\n }\n // Re-throw other errors (permissions, network, etc.)\n throw error;\n }\n }\n\n /**\n * Get public URL for S3 file.\n *\n * Priority order:\n * 1. Custom publicUrl (CDN or custom domain) if configured\n * 2. Standard S3 URL based on region and bucket\n *\n * For R2: Requires publicUrl configuration (R2 has no default public URLs).\n *\n * @param filePath - Storage path/key\n * @returns Public URL to access the file\n * @throws Error if R2 is used without publicUrl configuration\n */\n /**\n * Every object in the bucket, by key, with when it was last written, a page\n * of up to 1,000 at a time.\n */\n async *list(): AsyncIterable<StoredFileEntry> {\n const client = this.ensureClient();\n let token: string | undefined;\n do {\n const page = await client.send(\n new ListObjectsV2Command({\n Bucket: this.resolvedConfig.bucket,\n ContinuationToken: token,\n })\n );\n for (const object of page.Contents ?? []) {\n if (object.Key) {\n yield { path: object.Key, lastModified: object.LastModified };\n }\n }\n token = page.IsTruncated ? page.NextContinuationToken : undefined;\n } while (token);\n }\n\n getPublicUrl(filePath: string): string {\n // A URL is derived from the bucket and region, so a missing one is\n // refused here exactly as an upload or read would refuse. A check-only\n // helper is used so forming a URL does not needlessly build the full\n // S3 client.\n this.ensureConfigured();\n\n // Use custom CDN/public URL if configured\n if (this.resolvedConfig.publicUrl) {\n const baseUrl = this.resolvedConfig.publicUrl.replace(/\\/$/, \"\");\n return `${baseUrl}/${filePath}`;\n }\n\n // R2 requires custom domain or public bucket URL\n if (this.isR2) {\n throw new Error(\n \"@nextly/storage-s3: Cloudflare R2 requires publicUrl configuration.\\n\\n\" +\n \"R2 does not have default public URLs like AWS S3. Configure one of:\\n\" +\n \"1. Public bucket URL: publicUrl: 'https://pub-xxx.r2.dev'\\n\" +\n \"2. Custom domain: publicUrl: 'https://cdn.example.com'\\n\\n\" +\n \"Set up public access in the Cloudflare R2 dashboard.\"\n );\n }\n\n // Standard S3 URL format\n // https://bucket.s3.region.amazonaws.com/key\n return `https://${this.resolvedConfig.bucket}.s3.${this.resolvedConfig.region}.amazonaws.com/${filePath}`;\n }\n\n /**\n * Get storage type identifier.\n *\n * Returns \"s3\" for all S3-compatible services (AWS S3, R2, MinIO, etc.)\n * as they all use the S3 API.\n */\n getType(): \"s3\" {\n return \"s3\";\n }\n\n // ============================================================\n // Optional IStorageAdapter Methods\n // ============================================================\n\n /**\n * Get adapter info including capabilities.\n *\n * @returns Adapter info with type, name, and capability flags\n */\n getInfo(): StorageAdapterInfo {\n return {\n type: \"s3\",\n name: \"S3StorageAdapter\",\n supportsSignedUrls: true,\n supportsClientUploads: true,\n };\n }\n\n /**\n * Get file metadata from S3.\n *\n * Retrieves file information including size, content type, and timestamps\n * using the HeadObject command.\n *\n * @param filePath - Storage path/key\n * @returns File metadata or null if file not found\n */\n async getMetadata(filePath: string): Promise<FileMetadata | null> {\n const client = this.ensureClient();\n try {\n const command = new HeadObjectCommand({\n Bucket: this.resolvedConfig.bucket,\n Key: filePath,\n });\n\n const response = await client.send(command);\n const filename = filePath.split(\"/\").pop() || filePath;\n\n return {\n id: filePath,\n filename,\n originalFilename: response.Metadata?.[\"original-filename\"] || filename,\n mimeType: response.ContentType || \"application/octet-stream\",\n size: response.ContentLength || 0,\n url: this.getPublicUrl(filePath),\n createdAt:\n response.LastModified?.toISOString() || new Date().toISOString(),\n };\n } catch (error: unknown) {\n if (this.isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Read a stored object back as bytes, or `null` when it is not there.\n *\n * The contract declares this OPTIONAL and, until now, no adapter supplied\n * it — so a caller reaching for `adapter.read` got `undefined` and fell\n * through whatever branch followed. An optional member nothing implements is\n * a contract that reads as a capability and behaves as an absence.\n *\n * BUFFERS rather than streams, because that is the declared return type and\n * widening it here would make this adapter answer a different question from\n * its siblings. That bounds what it should be used for: an asset the server\n * must serve from its own origin — a font file, a small document — rather\n * than arbitrarily large media, which belongs behind {@link getSignedUrl} or\n * a public URL. A streaming variant is a separate contract member, not a\n * quiet change to this one.\n *\n * `null` for a missing key rather than a throw, matching\n * {@link getMetadata}: absence is an ordinary answer about the bucket, while\n * a credential or network failure is not, so only the first is folded into\n * the return value.\n *\n * @param filePath - Storage path/key\n * @returns The object's bytes, or `null` when no such key exists\n */\n async read(\n filePath: string,\n options?: StorageReadOptions\n ): Promise<Buffer | null> {\n const client = this.ensureClient();\n try {\n const command = new GetObjectCommand({\n Bucket: this.resolvedConfig.bucket,\n Key: filePath,\n });\n\n /*\n * The caller's deadline reaches the SDK, or it is advertised and inert.\n * `StorageReadOptions` promises a bound, and the URL-backed adapters keep\n * it by handing `timeoutMs` to `safeFetch`; without this the same option\n * does nothing here, so a stalled bucket holds the read open past a\n * deadline the caller was told applied — the worst kind of option, one\n * that validates and then has no effect.\n *\n * Aborting covers the BODY as well as the request. `transformToByteArray`\n * pulls the stream after `send` resolves, and a backend that answers\n * headers promptly and then stalls mid-transfer is exactly the case a\n * request-only timeout misses.\n */\n const response = await client.send(command, abortAfter(options));\n /*\n * An empty body is not a missing object, and the two must not collapse.\n * `GetObject` on a zero-byte key succeeds with no stream to transform,\n * so returning `null` here would report a stored empty file as absent —\n * and a caller deleting \"missing\" keys would then delete a real one.\n */\n if (response.Body === undefined) return Buffer.alloc(0);\n\n /*\n * Refused on the LENGTH the store reports, before the body is pulled\n * down. `transformToByteArray` buffers the whole object, so a caller that\n * knows its own limit has to be able to stop an oversized read rather\n * than discover the size after paying for it — which is what an\n * attachment path does when it checks a size only after buffering.\n */\n const cap = resolveReadBounds(options).maxBytes;\n // Cheap refusal first, where the store told us the size up front.\n this.refuseOverCap(filePath, response.ContentLength, cap);\n return await this.readCapped(filePath, response.Body, cap);\n } catch (error: unknown) {\n /*\n * Only an OBJECT-level absence becomes `null`. `isNotFoundError` treats\n * any 404 as missing, and `NoSuchBucket` is a 404 — so a bucket that was\n * deleted, renamed or mistyped would report every key in it as absent,\n * which is the configuration failure this method's contract exists to\n * tell apart from an ordinary miss. Named explicitly rather than by\n * status, because the status cannot separate them.\n */\n if (error instanceof Error && error.name === \"NoSuchBucket\") throw error;\n if (this.isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Generate signed URL for temporary private file access.\n *\n * Creates a pre-signed GetObject URL that grants temporary read access\n * to private files. Useful for serving files from private buckets.\n *\n * @param filePath - Storage path/key\n * @param expiresIn - URL validity duration in seconds (default: 3600)\n * @returns Pre-signed URL for downloading the file\n */\n async getSignedUrl(filePath: string, expiresIn?: number): Promise<string> {\n const client = this.ensureClient();\n const command = new GetObjectCommand({\n Bucket: this.resolvedConfig.bucket,\n Key: filePath,\n });\n\n return getSignedUrl(client, command, {\n expiresIn: expiresIn ?? this.resolvedConfig.signedUrlExpiresIn,\n });\n }\n\n /**\n * Generate pre-signed URL for client-side uploads.\n *\n * Creates a pre-signed PutObject URL that allows direct uploads from\n * the browser to S3, bypassing server-side upload limits (e.g., Vercel's 4.5MB).\n *\n * @param key - Storage path/key for the upload\n * @param mimeType - MIME type of the file being uploaded\n * @param expiresIn - URL validity duration in seconds (default: 3600)\n * @returns Client upload data with URL, method, and headers\n */\n async getPresignedUploadUrl(\n key: string,\n mimeType: string,\n expiresIn?: number\n ): Promise<ClientUploadData> {\n const client = this.ensureClient();\n const expiration = expiresIn ?? this.resolvedConfig.signedUrlExpiresIn;\n\n // Build PutObject command parameters\n const commandParams: PutObjectCommandInput = {\n Bucket: this.resolvedConfig.bucket,\n Key: key,\n ContentType: mimeType,\n CacheControl: this.resolvedConfig.cacheControl,\n };\n\n // Add ACL if not R2\n if (!this.isR2) {\n commandParams.ACL = this.resolvedConfig.acl;\n }\n\n const command = new PutObjectCommand(commandParams);\n\n const uploadUrl = await getSignedUrl(client, command, {\n expiresIn: expiration,\n });\n\n return {\n uploadUrl,\n path: key,\n method: \"PUT\",\n headers: {\n \"Content-Type\": mimeType,\n },\n expiresAt: new Date(Date.now() + expiration * 1000),\n };\n }\n\n // ============================================================\n // Helper Methods\n // ============================================================\n\n /**\n * Generate a unique storage key with date-based prefix.\n *\n * Creates keys in format: {folder}/{year}/{month}/{uuid}-{sanitized-filename}\n *\n * @param filename - Original filename (will be sanitized)\n * @param folder - Optional folder/prefix for organizing uploads\n * @returns Generated storage key\n */\n private generateKey(filename: string, folder?: string): string {\n const sanitized = this.sanitizeFilename(filename);\n const uuid = crypto.randomUUID();\n const date = new Date();\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n\n const prefix = folder ? `${folder}/${year}/${month}` : `${year}/${month}`;\n\n return `${prefix}/${uuid}-${sanitized}`;\n }\n\n /**\n * Sanitize filename to prevent directory traversal and S3 key issues.\n *\n * @param filename - Original filename\n * @returns Sanitized filename safe for S3 keys\n */\n private sanitizeFilename(filename: string): string {\n const basename = filename.split(/[/\\\\]/).pop() || filename;\n return basename.replace(/[^a-zA-Z0-9._-]/g, \"-\");\n }\n\n /**\n * Check if an error is a \"not found\" error from S3.\n *\n * @param error - Error to check\n * @returns true if error indicates file not found\n */\n /**\n * The object's bytes, refusing once more than `cap` have actually arrived.\n *\n * `ContentLength` is OPTIONAL in the SDK's response type, and this adapter\n * explicitly supports MinIO, R2 and other compatible services — any of which\n * may omit it or report it wrongly. A preflight check against metadata is\n * therefore a courtesy that fails OPEN: trusting it alone leaves the cap\n * unenforced exactly where an unusual backend is involved, which is where a\n * caller most needs it.\n *\n * Counted while consuming, so an oversized body is abandoned partway rather\n * than after it has all been buffered — the cap exists to bound memory, and\n * one applied after `transformToByteArray` has already spent it.\n *\n * Falls back to buffering when the body is not async-iterable, which the SDK\n * types permit. Stated rather than hidden: on that path the cap bounds what a\n * caller RECEIVES rather than what the process allocates.\n */\n private async readCapped(\n filePath: string,\n body: NonNullable<GetObjectCommandOutput[\"Body\"]>,\n cap: number\n ): Promise<Buffer> {\n /*\n * Probed rather than assumed. The SDK types the body as a union whose Node\n * member is async-iterable and whose browser members are not, and this\n * package supports compatible services whose transport may differ — so the\n * capability is read off the value in hand instead of from the type.\n */\n const iterable = body as Partial<AsyncIterable<Uint8Array>>;\n if (typeof iterable[Symbol.asyncIterator] !== \"function\") {\n const whole = Buffer.from(await body.transformToByteArray());\n if (whole.byteLength > cap) {\n throw new StorageReadTooLargeError(filePath, cap, whole.byteLength);\n }\n return whole;\n }\n\n const chunks: Buffer[] = [];\n let received = 0;\n for await (const chunk of body as AsyncIterable<Uint8Array>) {\n received += chunk.byteLength;\n if (received > cap) {\n throw new StorageReadTooLargeError(filePath, cap, received);\n }\n chunks.push(Buffer.from(chunk));\n }\n return Buffer.concat(chunks);\n }\n\n /**\n * Refuse a read whose object is already known to exceed the caller's cap.\n *\n * Its own method rather than three conditions inside `read`, because the\n * decision has nothing to do with the surrounding error handling and reads\n * as noise there — and because `read`'s branching is the part a reviewer has\n * to hold in their head to check the absent-versus-unavailable distinction.\n *\n * Both `undefined` cases mean \"no opinion\" and pass: a caller that named no\n * cap has none, and a store that reported no length gives nothing to compare.\n * The second is deliberately permissive — refusing an unmeasured object would\n * reject valid reads whenever S3 omits the header.\n */\n private refuseOverCap(\n filePath: string,\n declared: number | undefined,\n cap: number | undefined\n ): void {\n if (cap === undefined || declared === undefined || declared <= cap) return;\n /*\n * The SHARED refusal rather than a generic internal error, because callers\n * act on the difference. The email attachment path answers an over-cap read\n * with a size error the author can do something about; anything else is\n * wrapped as an opaque storage failure, so throwing `internal` here would\n * turn a fixable refusal into one that tells them nothing.\n */\n throw new StorageReadTooLargeError(filePath, cap, declared);\n }\n\n private isNotFoundError(error: unknown): boolean {\n if (error && typeof error === \"object\") {\n const e = error as {\n name?: string;\n $metadata?: { httpStatusCode?: number };\n };\n return e.name === \"NotFound\" || e.$metadata?.httpStatusCode === 404;\n }\n return false;\n }\n\n // ============================================================\n // Public Accessors\n // ============================================================\n\n /**\n * Get the S3 client instance.\n * Useful for advanced operations not covered by the adapter interface.\n *\n * Handing out the client is itself a use of the adapter, so a caller\n * without the configuration a client needs is refused here like any\n * other operation.\n */\n getClient(): S3Client {\n return this.ensureClient();\n }\n\n /**\n * Get the bucket name.\n */\n getBucket(): string {\n return this.resolvedConfig.bucket;\n }\n\n /**\n * Get the AWS region.\n */\n getRegion(): string {\n return this.resolvedConfig.region;\n }\n\n /**\n * Check if this adapter is configured for Cloudflare R2.\n */\n isCloudflareR2(): boolean {\n return this.isR2;\n }\n}\n","/**\n * S3 Storage Plugin\n *\n * Factory function that creates a storage plugin for AWS S3 and S3-compatible services.\n * Returns a StoragePlugin that can be registered with MediaStorage.\n *\n * @example Basic usage with AWS S3\n * ```typescript\n * import { s3Storage } from '@nextly/storage-s3'\n * import { defineConfig } from 'nextly/config'\n *\n * export default defineConfig({\n * storage: [\n * s3Storage({\n * bucket: process.env.S3_BUCKET!,\n * region: process.env.AWS_REGION!,\n * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,\n * collections: {\n * media: true\n * }\n * })\n * ]\n * })\n * ```\n *\n * @example With Cloudflare R2\n * ```typescript\n * s3Storage({\n * bucket: process.env.R2_BUCKET!,\n * region: 'auto',\n * accessKeyId: process.env.R2_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,\n * endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,\n * publicUrl: process.env.R2_PUBLIC_URL,\n * collections: { media: true }\n * })\n * ```\n *\n * @example With collection-specific configuration\n * ```typescript\n * s3Storage({\n * bucket: 'my-bucket',\n * region: 'us-east-1',\n * collections: {\n * // Simple enable with defaults\n * media: true,\n *\n * // Full configuration for private documents\n * 'private-docs': {\n * prefix: 'private/',\n * clientUploads: true,\n * signedDownloads: true,\n * signedUrlExpiresIn: 3600\n * }\n * }\n * })\n * ```\n *\n * @packageDocumentation\n */\n\nimport type { StoragePlugin, ClientUploadData } from \"nextly/storage\";\n\nimport { S3StorageAdapter } from \"./adapter\";\nimport type { S3StorageConfig } from \"./types\";\n\n// ============================================================\n// Plugin Factory Function\n// ============================================================\n\n/**\n * Create an S3 storage plugin for Nextly.\n *\n * This factory function creates a StoragePlugin that can be added to\n * the `storage` array in `nextly.config.ts`. It supports:\n *\n * - AWS S3 (standard)\n * - Cloudflare R2 (S3-compatible)\n * - MinIO (S3-compatible, self-hosted)\n * - DigitalOcean Spaces (S3-compatible)\n * - Any other S3-compatible service\n *\n * @param config - S3 storage configuration\n * @returns A StoragePlugin that MediaStorage can register\n *\n * Constructing the plugin never requires the bucket or region: a missing\n * one is refused when storage is first used, not while the config loads.\n */\nexport function s3Storage(config: S3StorageConfig): StoragePlugin {\n // Handle disabled plugin\n // When disabled, return a plugin with no collections and null adapter\n // MediaStorage.registerPlugin() checks for null adapter and skips registration\n if (config.enabled === false) {\n return {\n name: \"s3-storage\",\n type: \"s3\",\n collections: {},\n adapter: null as unknown as StoragePlugin[\"adapter\"],\n };\n }\n\n // Create the S3 adapter\n // Adapter constructor validates required config (bucket, region)\n const adapter = new S3StorageAdapter(config);\n\n // Build and return the plugin\n const plugin: StoragePlugin = {\n name: \"s3-storage\",\n type: \"s3\",\n collections: config.collections,\n adapter,\n\n /**\n * Generate a pre-signed URL for client-side uploads.\n *\n * This allows files to be uploaded directly from the browser to S3,\n * bypassing server-side upload limits (e.g., Vercel's 4.5MB limit).\n *\n * @param filename - Original filename from the client\n * @param mimeType - MIME type of the file\n * @param collection - Collection slug this upload belongs to\n * @returns Client upload data with pre-signed URL\n */\n async getClientUploadUrl(\n filename: string,\n mimeType: string,\n collection: string\n ): Promise<ClientUploadData> {\n // Get collection-specific configuration\n const collectionConfig = config.collections[collection];\n const prefix =\n typeof collectionConfig === \"object\"\n ? collectionConfig.prefix\n : undefined;\n\n // Generate storage key matching adapter's format\n // Format: {prefix}{year}/{month}/{uuid}-{sanitized-filename}\n const key = generateStorageKey(filename, prefix);\n\n // Get pre-signed upload URL from adapter\n return adapter.getPresignedUploadUrl(key, mimeType);\n },\n\n /**\n * Generate a signed URL for private file downloads.\n *\n * Creates a time-limited URL for accessing files in private buckets.\n * Only works when collection has `signedDownloads: true`.\n *\n * @param path - Storage path/key of the file\n * @param expiresIn - URL validity duration in seconds\n * @returns Signed URL for downloading the file\n */\n async getSignedDownloadUrl(\n path: string,\n expiresIn?: number\n ): Promise<string> {\n return adapter.getSignedUrl(\n path,\n expiresIn ?? config.signedUrlExpiresIn ?? 3600\n );\n },\n };\n\n return plugin;\n}\n\n// ============================================================\n// Helper Functions\n// ============================================================\n\n/**\n * Generate a unique storage key with date-based prefix.\n *\n * Creates keys in format: {prefix}{year}/{month}/{uuid}-{sanitized-filename}\n * This matches the format used by S3StorageAdapter for consistency.\n *\n * @param filename - Original filename (will be sanitized)\n * @param prefix - Optional folder/prefix for organizing uploads\n * @returns Generated storage key\n */\nfunction generateStorageKey(filename: string, prefix?: string): string {\n const sanitized = sanitizeFilename(filename);\n const uuid = crypto.randomUUID();\n const date = new Date();\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n\n const keyPrefix = prefix ? `${prefix}${year}/${month}` : `${year}/${month}`;\n\n return `${keyPrefix}/${uuid}-${sanitized}`;\n}\n\n/**\n * Sanitize filename to prevent directory traversal and S3 key issues.\n *\n * Removes path separators and replaces unsafe characters with hyphens.\n * Keeps only: a-z, A-Z, 0-9, dot, underscore, hyphen\n *\n * @param filename - Original filename\n * @returns Sanitized filename safe for S3 keys\n */\nfunction sanitizeFilename(filename: string): string {\n // Extract basename (remove any path components)\n const basename = filename.split(/[/\\\\]/).pop() || filename;\n // Replace unsafe characters with hyphens\n return basename.replace(/[^a-zA-Z0-9._-]/g, \"-\");\n}\n","/**\n * @nextly/storage-s3\n *\n * AWS S3 storage adapter for Nextly CMS.\n * Also works with S3-compatible services like Cloudflare R2, MinIO, and DigitalOcean Spaces.\n *\n * @example Basic usage with AWS S3\n * ```typescript\n * import { s3Storage } from '@nextly/storage-s3'\n * import { defineConfig } from 'nextly/config'\n *\n * export default defineConfig({\n * storage: [\n * s3Storage({\n * bucket: process.env.S3_BUCKET!,\n * region: process.env.AWS_REGION!,\n * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,\n * collections: {\n * media: true\n * }\n * })\n * ]\n * })\n * ```\n *\n * @example With Cloudflare R2\n * ```typescript\n * s3Storage({\n * bucket: process.env.R2_BUCKET!,\n * region: 'auto',\n * accessKeyId: process.env.R2_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,\n * endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,\n * publicUrl: process.env.R2_PUBLIC_URL,\n * collections: { media: true }\n * })\n * ```\n *\n * @example With MinIO\n * ```typescript\n * s3Storage({\n * bucket: 'my-bucket',\n * region: 'us-east-1',\n * accessKeyId: process.env.MINIO_ACCESS_KEY!,\n * secretAccessKey: process.env.MINIO_SECRET_KEY!,\n * endpoint: 'http://localhost:9000',\n * forcePathStyle: true,\n * collections: { media: true }\n * })\n * ```\n *\n * @packageDocumentation\n */\n\n// ============================================================\n// S3 Storage Plugin Export (Primary API)\n// ============================================================\n\nexport { s3Storage } from \"./plugin\";\n\n// ============================================================\n// S3 Storage Adapter Export\n// ============================================================\n\nexport { S3StorageAdapter } from \"./adapter\";\n\n// ============================================================\n// S3 Types Export\n// ============================================================\n\nexport type {\n S3StorageConfig,\n S3ObjectACL,\n S3CollectionConfig,\n S3CollectionStorageMap,\n ResolvedS3Config,\n} from \"./types\";\n\n// ============================================================\n// Package Metadata\n// ============================================================\n\nexport const PACKAGE_NAME = \"@nextly/storage-s3\";\nexport const PACKAGE_VERSION = \"0.1.0\";\n"],"mappings":";;;;;AAmCA,SAAS,UAAU,KAAK;CACvB,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO;CAC5C,MAAM,MAAM;CACZ,OAAO,IAAI,SAAS,aAAa,OAAO,IAAI,SAAS;AACtD;;;;;;;;;;;;;;;;;;;;;;;;;;AAgEA,SAAS,WAAW,MAAM;CACzB,IAAI,SAAS,KAAK,GAAG,OAAO;CAC5B,OAAO,SAAS,8BAA8B,KAAK,YAAY,CAAC,CAAC,WAAW,aAAa;AAC1F;;;;;;;;;;AAUA,SAAS,eAAe,OAAO;CAC9B,IAAI,UAAU,KAAK,GAAG,OAAO,MAAM,SAAS;CAC5C,OAAO,WAAW,SAAS,KAAK,CAAC;AAClC;AAIA,SAAS,SAAS,OAAO;CACxB,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO,KAAK;CACrD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,OAAO,YAAY;GAQ5C,MAAM,MAAM,mBAAmB,UAN7B,OAAO,qBAAqB,WACxB,iBAAiB,SACjB,KAAA,CAIyC;GAG/C,OAAO,QAAQ,sBAAsB,KAAK,QAAQ;EACpD;;;;;;;;;;;EAYA,MAAM,qBACJ,MACA,WACiB;GACjB,OAAO,QAAQ,aACb,MACA,aAAa,OAAO,sBAAsB,IAC5C;EACF;CAGU;AACd;;;;;;;;;;;AAgBA,SAAS,mBAAmB,UAAkB,QAAyB;CACrE,MAAM,YAAY,iBAAiB,QAAQ;CAC3C,MAAM,OAAO,OAAO,WAAW;CAC/B,MAAM,uBAAO,IAAI,KAAK;CACtB,MAAM,OAAO,KAAK,YAAY;CAC9B,MAAM,QAAQ,OAAO,KAAK,SAAS,IAAI,CAAC,CAAC,CAAC,SAAS,GAAG,GAAG;CAIzD,OAAO,GAFW,SAAS,GAAG,SAAS,KAAK,GAAG,UAAU,GAAG,KAAK,GAAG,QAEhD,GAAG,KAAK,GAAG;AACjC;;;;;;;;;;AAWA,SAAS,iBAAiB,UAA0B;CAIlD,QAFiB,SAAS,MAAM,OAAO,CAAC,CAAC,IAAI,KAAK,SAAA,CAElC,QAAQ,oBAAoB,GAAG;AACjD;;AC7HA,MAAa,eAAe;AAC5B,MAAa,kBAAkB"}
1
+ {"version":3,"file":"index.cjs","names":["S3Client","Upload","DeleteObjectCommand","DeleteObjectsCommand","HeadObjectCommand","ListObjectsV2Command","GetObjectCommand","getSignedUrl","PutObjectCommand","iterable"],"sources":["../../nextly/dist/nextly-error-C_MDZmJc.mjs","../../nextly/dist/validate-external-url-DF_HNT6F.mjs","../../nextly/dist/storage/read-errors.mjs","../../nextly/dist/storage/fetch-stored-bytes.mjs","../src/adapter.ts","../src/plugin.ts","../src/index.ts"],"sourcesContent":["import { t as __exportAll } from \"./rolldown-runtime-BJohB4LM.mjs\";\n// src/database/pool-wait-code.ts\n/**\n* The code an adapter gives the error it raises when a request has waited out\n* `pool.connectionTimeoutMs` for a database connection, as core reads it.\n*\n* Read here rather than imported from `@nextlyhq/adapter-drizzle/types`, where\n* the adapters define it, because the module that reads it\n* (`database/errors.ts`) is reached from `NextlyError` and so from every\n* client-safe entry: a runtime import of a database package there puts that\n* package in the admin's browser bundle. A leaf with no imports keeps this\n* reachable without the adapter.\n*\n* The same string as the adapters' `POOL_WAIT_TIMEOUT_CODE`, held to it by\n* `errors/__tests__/database-busy.test.ts`, so the two cannot drift apart\n* unnoticed.\n*/\nconst POOL_WAIT_TIMEOUT_CODE = \"NEXTLY_POOL_WAIT_TIMEOUT\";\n// src/database/errors.ts\nvar DbError = class extends Error {\n\tkind;\n\tdialect;\n\tcode;\n\tmeta;\n\tcause;\n\tconstructor(args) {\n\t\tsuper(args.message);\n\t\tthis.name = \"DbError\";\n\t\tthis.kind = args.kind;\n\t\tthis.dialect = args.dialect;\n\t\tthis.code = args.code;\n\t\tthis.meta = args.meta;\n\t\tthis.cause = args.cause;\n\t}\n};\nfunction isDbError(err) {\n\tif (!err || typeof err !== \"object\") return false;\n\tconst obj = err;\n\treturn obj.name === \"DbError\" && typeof obj.kind === \"string\";\n}\nfunction toDbError(dialect, error, meta) {\n\tif (isDbError(error)) return error;\n\tconst code = safeCode(error);\n\tconst rawMsg = error != null && typeof error === \"object\" && \"message\" in error ? error.message : void 0;\n\tconst message = typeof rawMsg === \"string\" ? rawMsg : \"Database error\";\n\tlet kind = \"internal\";\n\tif (isBusyCode(code)) return new DbError({\n\t\tmessage,\n\t\tkind: \"busy\",\n\t\tdialect,\n\t\tcode,\n\t\tmeta,\n\t\tcause: error\n\t});\n\tswitch (dialect) {\n\t\tcase \"postgresql\":\n\t\t\tkind = mapPostgresCodeToKind(code);\n\t\t\tbreak;\n\t\tcase \"mysql\":\n\t\t\tkind = mapMySqlCodeToKind(code);\n\t\t\tbreak;\n\t\tcase \"sqlite\": kind = mapSqliteCodeToKind(code);\n\t}\n\tif ((dialect === \"mysql\" || dialect === \"sqlite\") && (kind === \"constraint\" || kind === \"internal\") && isLikelyUniqueViolationMessage(dialect, message)) kind = \"unique-violation\";\n\tif (dialect === \"sqlite\" && kind === \"constraint\" && message.toLowerCase().includes(\"foreign key constraint failed\")) kind = \"fk-violation\";\n\tif (kind === \"internal\" && code) {\n\t\tconst c = code.toUpperCase();\n\t\tif (c === \"ECONNRESET\" || c.includes(\"PROTOCOL_CONNECTION_LOST\")) kind = \"connection-lost\";\n\t\telse if (c === \"ETIMEDOUT\") kind = \"timeout\";\n\t}\n\treturn new DbError({\n\t\tmessage,\n\t\tkind,\n\t\tdialect,\n\t\tcode,\n\t\tmeta,\n\t\tcause: error\n\t});\n}\n/**\n* The driver's own code for an error, wherever that driver puts it.\n*\n* Exported so callers that must distinguish one failure from another classify\n* by the SAME extraction this module's mapping uses. A second reader would go\n* looking in a different set of properties and disagree on exactly the drivers\n* whose codes are hardest to find.\n*/\n/**\n* Whether an error is a duplicate-key rejection.\n*\n* Exposed because a plugin inserting into a table with a unique index has to\n* tell \"this row already exists\" from \"the database is broken\", and the two\n* arrive as the same thrown object. Derived from the existing SQLSTATE\n* classification rather than by matching driver messages: those differ per\n* driver and per version, and a plugin re-deriving it would be a second\n* implementation of a question this module already answers.\n*/\n/**\n* Whether a driver code says the database was busy: the adapters' own code\n* for a request that waited out `pool.connectionTimeoutMs`, the same on\n* every dialect, or SQLITE_BUSY and its extended codes, another process\n* holding the SQLite file past `busyTimeout`. Neither depends on the dialect,\n* which is what lets {@link isDatabaseBusy} answer without one.\n*/\nfunction isBusyCode(code) {\n\tif (code === void 0) return false;\n\treturn code === \"NEXTLY_POOL_WAIT_TIMEOUT\" || code.toUpperCase().startsWith(\"SQLITE_BUSY\");\n}\n/**\n* Whether an error is the database being busy, however it arrives: a DbError\n* of kind \"busy\", or the raw error an adapter or driver threw.\n*\n* For the boundaries that answer a request with whatever its work threw.\n* `withDbErrors` converts only DbErrors, so a raw driver error reaches them\n* unconverted, and without this it would read as an internal fault rather\n* than a request worth retrying.\n*/\nfunction isDatabaseBusy(error) {\n\tif (isDbError(error)) return error.kind === \"busy\";\n\treturn isBusyCode(safeCode(error));\n}\nfunction isUniqueViolation(dialect, error) {\n\treturn toDbError(dialect, error).kind === \"unique-violation\";\n}\nfunction safeCode(error) {\n\tif (!error || typeof error !== \"object\") return void 0;\n\tconst e = error;\n\tlet c = e.code ?? e.sqlState ?? e.state ?? e.errno ?? void 0;\n\tif (!c && typeof e.originalError?.code === \"string\") c = e.originalError.code;\n\tif (!c && typeof e.cause?.code === \"string\") c = e.cause.code;\n\tif (!c && typeof e.severity === \"string\" && typeof e.code === \"string\") c = e.code;\n\tif (typeof c === \"number\") return String(c);\n\tif (typeof c === \"string\" && c.length > 0) return c;\n}\nfunction mapPostgresCodeToKind(code) {\n\tif (!code) return \"internal\";\n\tconst c = code.toUpperCase();\n\tif (c === \"40P01\") return \"deadlock\";\n\tif (c === \"40001\") return \"serialization-failure\";\n\tif (c === \"57014\") return \"timeout\";\n\tif (c === \"23505\") return \"unique-violation\";\n\tif (c === \"23503\") return \"fk-violation\";\n\tif (c === \"23502\") return \"not-null-violation\";\n\tif (c === \"42601\") return \"syntax\";\n\tif (c.startsWith(\"08\") || c === \"57P01\") return \"connection-lost\";\n\tif (c.startsWith(\"23\")) return \"constraint\";\n\treturn \"internal\";\n}\nfunction mapMySqlCodeToKind(code) {\n\tif (!code) return \"internal\";\n\tconst c = code.toUpperCase();\n\tif (c === \"1213\" || c === \"ER_LOCK_DEADLOCK\") return \"deadlock\";\n\tif (c === \"1205\" || c === \"ER_LOCK_WAIT_TIMEOUT\") return \"timeout\";\n\tif (c === \"1062\" || c === \"ER_DUP_ENTRY\") return \"unique-violation\";\n\tif (c === \"23000\") return \"constraint\";\n\tif (c === \"1064\" || c === \"ER_PARSE_ERROR\") return \"syntax\";\n\tif (c === \"1452\" || c === \"ER_NO_REFERENCED_ROW_2\") return \"fk-violation\";\n\tif (c === \"1451\" || c === \"ER_ROW_IS_REFERENCED_2\") return \"fk-violation\";\n\tif (c === \"ECONNRESET\" || c.includes(\"PROTOCOL_CONNECTION_LOST\")) return \"connection-lost\";\n\tif (c === \"ETIMEDOUT\") return \"timeout\";\n\treturn \"internal\";\n}\nfunction mapSqliteCodeToKind(code) {\n\tif (!code) return \"internal\";\n\tconst c = code.toUpperCase();\n\tif (c === \"SQLITE_LOCKED\") return \"deadlock\";\n\tif (c === \"SQLITE_CONSTRAINT_UNIQUE\") return \"unique-violation\";\n\tif (c === \"SQLITE_CONSTRAINT_PRIMARYKEY\") return \"unique-violation\";\n\tif (c === \"SQLITE_CONSTRAINT_FOREIGNKEY\") return \"fk-violation\";\n\tif (c === \"SQLITE_CONSTRAINT_NOTNULL\") return \"not-null-violation\";\n\tif (c === \"SQLITE_INTERRUPT\") return \"timeout\";\n\tif (c === \"SQLITE_ERROR\") return \"syntax\";\n\tif (c.startsWith(\"SQLITE_CONSTRAINT\")) return \"constraint\";\n\treturn \"internal\";\n}\nfunction isLikelyUniqueViolationMessage(dialect, message) {\n\tconst m = message.toLowerCase();\n\tif (dialect === \"mysql\") return m.includes(\"duplicate entry\") || m.includes(\"duplicate key\");\n\tif (dialect === \"sqlite\") return m.includes(\"unique constraint failed\");\n\treturn false;\n}\n// src/errors/error-codes.ts\n/**\n* Canonical NextlyError codes and their HTTP status mappings.\n*\n* Plugin codes outside this enum must always pass an explicit `statusCode`\n* to the NextlyError constructor (no enum lookup happens for unknown codes).\n*/\nconst NEXTLY_ERROR_STATUS = {\n\tVALIDATION_ERROR: 400,\n\tINVALID_INPUT: 400,\n\tAUTH_REQUIRED: 401,\n\tAUTH_INVALID_CREDENTIALS: 401,\n\tTOKEN_EXPIRED: 401,\n\tFORBIDDEN: 403,\n\tEMAIL_NOT_VERIFIED: 403,\n\tBUILDER_DISABLED: 403,\n\tCSRF_FAILED: 403,\n\tSETUP_TOKEN_REQUIRED: 403,\n\tAPI_KEY_ROLE_ABOVE_CREATOR: 403,\n\tACTION_NOT_AVAILABLE: 403,\n\tNOT_FOUND: 404,\n\tENTITY_REMOVED_FROM_CODE: 409,\n\tENTITY_NOT_MIGRATED: 409,\n\tMETHOD_NOT_ALLOWED: 405,\n\tRANGE_NOT_SATISFIABLE: 416,\n\tCONFLICT: 409,\n\tSTALE_VERSION: 409,\n\tVERSION_REQUIRED: 428,\n\tDUPLICATE: 409,\n\tRATE_LIMITED: 429,\n\tPAYLOAD_TOO_LARGE: 413,\n\tUNSUPPORTED_MEDIA_TYPE: 415,\n\tBUSINESS_RULE_VIOLATION: 422,\n\tINTERNAL_ERROR: 500,\n\tDATABASE_ERROR: 500,\n\tDATABASE_BUSY: 503,\n\tRULE_COULD_NOT_RUN: 503,\n\tEXTERNAL_SERVICE_ERROR: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tCONFIGURATION_ERROR: 500,\n\tEXTERNAL_URL_BLOCKED: 400,\n\tEXTERNAL_REQUEST_FAILED: 502,\n\tFILENAME_INVALID: 400,\n\tEXTENSION_BLOCKED: 400,\n\tMIME_BLOCKED: 415,\n\tMIME_NOT_ALLOWED: 415,\n\tSIZE_EXCEEDED: 413,\n\tSTORAGE_READ_TOO_LARGE: 413,\n\tSTORAGE_READ_TIMEOUT: 504,\n\tSTORAGE_READ_UNREACHABLE: 502,\n\tMAGIC_BYTE_MISMATCH: 400,\n\tSVG_SANITIZATION_FAILED: 400,\n\tUNSUPPORTED_FOR_BACKEND: 415,\n\tNEXTLY_LEGACY_BOOKKEEPING_DETECTED: 409,\n\tNEXTLY_UPGRADE_TABLE_NAME_COLLISION: 409,\n\tNEXTLY_UPGRADE_IN_PROGRESS: 409,\n\tNEXTLY_MIGRATE_LOCK_BUSY: 409,\n\tNEXTLY_TABLE_BUSY: 409,\n\tNEXTLY_LOCK_HELD_BY_THIS_PROCESS: 500,\n\tNEXTLY_BASELINE_LOCK_NOT_HELD: 409,\n\tNEXTLY_RESOLVE_LOCK_NOT_HELD: 409,\n\tNEXTLY_BOOT_MIGRATIONS_NOT_RUN: 503,\n\tNEXTLY_BOOT_MIGRATIONS_PENDING: 503,\n\tNEXTLY_DATABASE_NOT_SET_UP: 503,\n\tNEXTLY_DATABASE_NOT_MIGRATED: 503,\n\tNEXTLY_CORE_DESTRUCTIVE_REFUSED: 409,\n\tNEXTLY_MIGRATION_DRIFT: 409,\n\tNEXTLY_MIGRATION_APPLY_FAILED: 500,\n\tNEXTLY_MIGRATION_FOREIGN_KEY_VIOLATION: 409,\n\tNEXTLY_MIGRATION_PARTIALLY_APPLIED: 500,\n\tNEXTLY_MIGRATION_CONCURRENT_RUN: 409,\n\tNEXTLY_MIGRATION_FILE_MISSING: 404,\n\tNEXTLY_MIGRATION_SNAPSHOT_MISSING: 404,\n\tNEXTLY_MIGRATION_RESOLVE_DRIFT: 409,\n\tNEXTLY_MIGRATION_RESOLVE_PRECONDITION: 409,\n\tNEXTLY_MIGRATION_HISTORY_REFUSED: 409,\n\tNEXTLY_SCHEMA_CONVERSION_UNCONFIRMED: 409,\n\tNEXTLY_UI_SCHEMA_INVALID: 400,\n\tNEXTLY_SCHEMA_SLUG_COLLISION: 409,\n\tNEXTLY_SCHEMA_RELATION_TARGET_MISSING: 400,\n\tNEXTLY_SCHEMA_RELATION_UNRESOLVED: 400,\n\tNEXTLY_SCHEMA_EXTEND_TARGET_UNKNOWN: 400,\n\tNEXTLY_SCHEMA_EXTEND_FIELD_DUPLICATE: 409,\n\tNEXTLY_SCHEMA_CROSS_PLUGIN_RELATION: 409,\n\tNEXTLY_SCHEMA_RENAME_UNKNOWN_TARGET: 400,\n\tNEXTLY_PLUGIN_CLIENT_CONFIG_INVALID: 500,\n\tNEXTLY_PLUGIN_ADMIN_WIDGET_INVALID: 500,\n\tNEXTLY_PLUGIN_REMOVED_WIDGET_CHANNEL: 500,\n\tNEXTLY_PLUGIN_DOCUMENT_VIEW_INVALID: 500,\n\tNEXTLY_PLUGIN_DOCUMENT_SURFACE_INVALID: 500,\n\tPLUGIN_RESOLUTION_ERROR: 500,\n\tPLUGIN_DEPENDENCY_NOT_INSTALLED: 409,\n\tPLUGIN_HAS_DEPENDENTS: 409,\n\tPLUGIN_UNINSTALL_WOULD_DROP_OTHERS: 409,\n\tPLUGIN_UNINSTALL_IRREVERSIBLE: 409,\n\tPLUGIN_UNINSTALL_UNCONFIRMED: 409,\n\tPLUGIN_SCHEMA_BEHIND: 409,\n\tPLUGIN_SCHEMA_UNINSTALLED: 409,\n\tPLUGIN_NOT_INSTALLED: 409,\n\tPLUGIN_DISABLED: 409,\n\tPLUGIN_UNINSTALL_UNFINISHED: 409,\n\tPLUGIN_SCHEMA_VERSION_NOT_ADVANCED: 409,\n\tPLUGIN_MIGRATION_DROPS_CREATED_SCHEMA: 409,\n\tPLUGIN_MIGRATION_ADDS_UNFILLABLE_COLUMN: 409,\n\tPLUGIN_MIGRATION_SQL_MISSING: 409,\n\tPLUGIN_MIGRATIONS_UNAVAILABLE: 409,\n\tDROP_OF_FOREIGN_TABLE: 409,\n\tMIGRATION_CHECKSUM_MISMATCH: 409,\n\tPLUGIN_MIGRATIONS_OUT_OF_ORDER: 409,\n\tPLUGIN_MIGRATION_HISTORY_CHANGED: 409,\n\tNEXTLY_ROUTE_COLLISION: 409,\n\tNEXTLY_ROUTE_INVALID_PATH: 400,\n\tNEXTLY_ROUTE_UNREACHABLE_ROOT: 400,\n\tNEXTLY_ROUTE_INVALID_MOUNT: 400,\n\tNEXTLY_EMAIL_TRANSPORT_UNAVAILABLE: 503,\n\tNEXTLY_CONFIG_TOOLING_UNAVAILABLE: 503,\n\tNEXTLY_POSTGRES_SCHEMA_MISMATCH: 500,\n\tNEXTLY_PER_LANGUAGE_STORAGE_CHANGED: 500,\n\tNEXTLY_PER_LANGUAGE_STORAGE_MIXED: 500,\n\tNEXTLY_PER_LANGUAGE_STORAGE_LANGUAGES_UNDECLARED: 500,\n\tNEXTLY_POSTGRES_SCHEMA_MOVED: 500\n};\n/**\n* The codes that REPRESENT their status, when a failure names none.\n*\n* A service that returns `{ success: false, statusCode }` without a code leaves\n* every boundary to infer one, and three boundaries inferring separately is how\n* the same 401 became `AUTH_REQUIRED` through the Direct API and\n* `INTERNAL_ERROR` through the REST dispatcher. This list is the ONE inference,\n* so they cannot disagree.\n*\n* Listed as CODES, not as status numbers: the number for each comes from\n* {@link NEXTLY_ERROR_STATUS} below, so a code whose canonical status changes\n* carries its inference with it instead of leaving a stale literal here.\n*\n* Several codes share a status -- 409 is both `CONFLICT` and `DUPLICATE`, 400\n* is both `VALIDATION_ERROR` and `INVALID_INPUT` -- so this is a choice, not a\n* mechanical inversion. Each entry is the reading that is still safe if the\n* other was meant: `CONFLICT` says \"reload\", which is unhelpful for a name\n* clash, while `DUPLICATE` would say \"already exists\", which is WRONG for a\n* stale write. A producer that knows which it means sets `code` and is\n* believed, and this list is never consulted for it.\n*/\nconst CANONICAL_CODE_FOR_STATUS = [\n\t\"VALIDATION_ERROR\",\n\t\"AUTH_REQUIRED\",\n\t\"FORBIDDEN\",\n\t\"NOT_FOUND\",\n\t\"CONFLICT\",\n\t\"VERSION_REQUIRED\",\n\t\"PAYLOAD_TOO_LARGE\",\n\t\"UNSUPPORTED_MEDIA_TYPE\",\n\t\"RATE_LIMITED\",\n\t\"EXTERNAL_SERVICE_ERROR\",\n\t\"SERVICE_UNAVAILABLE\"\n];\n/**\n* 422, which no canonical code claims.\n*\n* `INVALID_INPUT` answers 400 in this system, so it cannot supply this key the\n* way the codes above supply theirs. Legacy envelopes nonetheless use 422 for\n* \"understood but unprocessable\", and reading it as an internal error would\n* report the caller's own mistake as a server fault. Named rather than inlined\n* so it is visibly the one entry that is NOT derived.\n*/\nconst LEGACY_UNPROCESSABLE_STATUS = 422;\nconst STATUS_TO_CODE = {\n\t...Object.fromEntries(CANONICAL_CODE_FOR_STATUS.map((code) => [NEXTLY_ERROR_STATUS[code], code])),\n\t[LEGACY_UNPROCESSABLE_STATUS]: \"INVALID_INPUT\"\n};\n/**\n* The canonical code for a status, for a failure that named none.\n*\n* Anything outside the table is an internal error: an unrecognised status from\n* a legacy envelope says nothing a caller can act on, and inventing a specific\n* code for it would assert a meaning no producer expressed.\n*/\nfunction statusToErrorCode(statusCode) {\n\treturn STATUS_TO_CODE[statusCode] ?? \"INTERNAL_ERROR\";\n}\n/**\n* The sentence a caller reads for a code, when the failure supplied none.\n*\n* Kept beside the status table because they answer the same question together:\n* a code-less envelope's own `message` is NOT usable here. Those envelopes come\n* from legacy converters that store a raw exception's text, so promoting it\n* would put driver output, table names and internal paths on the wire -- the\n* disclosure the public error shape exists to prevent (spec 13.8).\n*\n* Every entry is generic by design. The specific detail stays in `logContext`\n* for the operator, against the same request id.\n*/\nconst GENERIC_PUBLIC_MESSAGE = {\n\tVALIDATION_ERROR: \"Validation failed.\",\n\tINVALID_INPUT: \"The request could not be processed.\",\n\tAUTH_REQUIRED: \"Authentication required.\",\n\tFORBIDDEN: \"You don't have permission to perform this action.\",\n\tACTION_NOT_AVAILABLE: \"This action isn't available for this entry.\",\n\tNOT_FOUND: \"Not found.\",\n\tMETHOD_NOT_ALLOWED: \"That method is not allowed on this address.\",\n\tRANGE_NOT_SATISFIABLE: \"The requested range is outside the file.\",\n\tCONFLICT: \"The resource has changed since you last loaded it. Please refresh and try again.\",\n\tDUPLICATE: \"Resource already exists.\",\n\tPAYLOAD_TOO_LARGE: \"The request is too large.\",\n\tUNSUPPORTED_MEDIA_TYPE: \"That file type is not supported.\",\n\tRATE_LIMITED: \"Too many requests. Please try again later.\",\n\tEXTERNAL_SERVICE_ERROR: \"An upstream service failed.\",\n\tSERVICE_UNAVAILABLE: \"The service is temporarily unavailable.\",\n\tDATABASE_BUSY: \"The database is busy. Please try again shortly.\",\n\tRULE_COULD_NOT_RUN: \"A check this request needs could not run. Please try again shortly.\",\n\tINTERNAL_ERROR: \"An unexpected error occurred.\"\n};\n/** The generic sentence for a code; the internal one for anything unlisted. */\nfunction genericPublicMessage(code) {\n\treturn GENERIC_PUBLIC_MESSAGE[code] ?? GENERIC_PUBLIC_MESSAGE.INTERNAL_ERROR;\n}\n// src/errors/retry-after.ts\n/**\n* The seconds an error asks its caller to wait before retrying, or\n* `undefined` when it carries no retry hint.\n*\n* Read from the error's public data rather than from its code, so every error\n* that carries a hint is answered with the header, and a code that comes to\n* carry one needs no change here.\n*/\nfunction retryAfterSeconds(error) {\n\tconst data = error.publicData;\n\tif (data && typeof data === \"object\" && \"retryAfterSeconds\" in data && typeof data.retryAfterSeconds === \"number\") return data.retryAfterSeconds;\n}\n/**\n* The Retry-After header for an error: none when it carries no retry hint.\n* Spread into a response's headers by every builder that answers one.\n*/\nfunction retryAfterHeader(error) {\n\tconst seconds = retryAfterSeconds(error);\n\treturn seconds === void 0 ? {} : { \"retry-after\": String(seconds) };\n}\n// src/errors/nextly-error.ts\nvar nextly_error_exports = /* @__PURE__ */ __exportAll({ NextlyError: () => NextlyError });\n/**\n* Default mapping from DbErrorKind to NextlyError contract. Used by\n* `NextlyError.fromDatabaseError`. Public messages are intentionally generic\n* per spec §13.8 — no DB driver text, no constraint names, no field hints.\n*\n* `satisfies Record<DbErrorKind, ...>` makes the mapping exhaustive at\n* compile time: adding a new DbErrorKind without updating this table is a\n* type error.\n*/\nconst DB_ERROR_MAPPING = {\n\t\"unique-violation\": {\n\t\tcode: \"DUPLICATE\",\n\t\tstatusCode: 409,\n\t\tpublicMessage: \"Resource already exists.\"\n\t},\n\t\"fk-violation\": {\n\t\tcode: \"VALIDATION_ERROR\",\n\t\tstatusCode: 400,\n\t\tpublicMessage: \"Referenced record does not exist.\"\n\t},\n\t\"not-null-violation\": {\n\t\tcode: \"VALIDATION_ERROR\",\n\t\tstatusCode: 400,\n\t\tpublicMessage: \"A required field is missing.\"\n\t},\n\tconstraint: {\n\t\tcode: \"VALIDATION_ERROR\",\n\t\tstatusCode: 400,\n\t\tpublicMessage: \"The provided data violates a constraint.\"\n\t},\n\tdeadlock: {\n\t\tcode: \"CONFLICT\",\n\t\tstatusCode: 409,\n\t\tpublicMessage: \"The operation could not be completed. Please retry.\"\n\t},\n\t\"serialization-failure\": {\n\t\tcode: \"CONFLICT\",\n\t\tstatusCode: 409,\n\t\tpublicMessage: \"The operation could not be completed. Please retry.\"\n\t},\n\tbusy: {\n\t\tcode: \"DATABASE_BUSY\",\n\t\tstatusCode: NEXTLY_ERROR_STATUS.DATABASE_BUSY,\n\t\tpublicMessage: genericPublicMessage(\"DATABASE_BUSY\"),\n\t\tpublicData: { retryAfterSeconds: 5 }\n\t},\n\ttimeout: {\n\t\tcode: \"DATABASE_ERROR\",\n\t\tstatusCode: 500,\n\t\tpublicMessage: \"The operation timed out. Please try again.\"\n\t},\n\t\"connection-lost\": {\n\t\tcode: \"DATABASE_ERROR\",\n\t\tstatusCode: 500,\n\t\tpublicMessage: \"A temporary database error occurred. Please try again.\"\n\t},\n\tsyntax: {\n\t\tcode: \"INTERNAL_ERROR\",\n\t\tstatusCode: 500,\n\t\tpublicMessage: \"An unexpected error occurred.\"\n\t},\n\tinternal: {\n\t\tcode: \"INTERNAL_ERROR\",\n\t\tstatusCode: 500,\n\t\tpublicMessage: \"An unexpected error occurred.\"\n\t}\n};\nconst NEXTLY_ERROR_BRAND = Symbol.for(\"nextly/NextlyError\");\nfunction hasBrand(value) {\n\tif (value === null || typeof value !== \"object\" && typeof value !== \"function\") return false;\n\treturn value[NEXTLY_ERROR_BRAND] === true;\n}\n/**\n* Unified error class for Nextly. Used at every throw site across services,\n* direct API, auth, and plugins. Carries two distinct payloads:\n*\n* - Public (`code`, `publicMessage`, `publicData`, `statusCode`, `messageKey`)\n* sent in HTTP responses and Server Action results.\n* - Log (`logMessage`, `logContext`, `cause`, stack trace)\n* written to the server logger; never serialised to the wire.\n*\n* Use the static factories (notFound, forbidden, validation, ...) for the\n* common cases. Use the free-form constructor for plugin codes or one-off\n* shapes.\n*/\nvar NextlyError = class NextlyError extends Error {\n\tcode;\n\tstatusCode;\n\tpublicMessage;\n\tpublicData;\n\tmessageKey;\n\tlogMessage;\n\tlogContext;\n\tcause;\n\ttimestamp;\n\tconstructor(opts) {\n\t\tsuper(opts.publicMessage);\n\t\tthis.name = \"NextlyError\";\n\t\tthis.code = opts.code;\n\t\tthis.publicMessage = opts.publicMessage;\n\t\tthis.publicData = opts.publicData;\n\t\tthis.messageKey = opts.messageKey;\n\t\tthis.logMessage = opts.logMessage;\n\t\tthis.logContext = opts.logContext;\n\t\tthis.cause = opts.cause;\n\t\tthis.timestamp = /* @__PURE__ */ new Date();\n\t\tthis.statusCode = NextlyError.resolveStatusCode(opts);\n\t\tError.captureStackTrace?.(this, NextlyError);\n\t}\n\tstatic {\n\t\tNextlyError.prototype[NEXTLY_ERROR_BRAND] = true;\n\t}\n\tstatic resolveStatusCode(opts) {\n\t\tif (typeof opts.statusCode === \"number\") return opts.statusCode;\n\t\tif (opts.code in NEXTLY_ERROR_STATUS) return NEXTLY_ERROR_STATUS[opts.code];\n\t\treturn 500;\n\t}\n\t/** HTTP-safe JSON. Strips logMessage / logContext / cause / stack. */\n\ttoResponseJSON(requestId) {\n\t\tconst json = {\n\t\t\tcode: String(this.code),\n\t\t\tmessage: this.publicMessage,\n\t\t\trequestId\n\t\t};\n\t\tif (this.messageKey) json.messageKey = this.messageKey;\n\t\tif (this.publicData !== void 0) json.data = this.publicData;\n\t\treturn json;\n\t}\n\t/** Operator-facing JSON for log lines. Includes everything. */\n\ttoLogJSON(requestId) {\n\t\treturn {\n\t\t\tcode: this.code,\n\t\t\tstatusCode: this.statusCode,\n\t\t\tpublicMessage: this.publicMessage,\n\t\t\tmessageKey: this.messageKey,\n\t\t\tlogMessage: this.logMessage,\n\t\t\tlogContext: this.logContext,\n\t\t\tcause: this.cause ? {\n\t\t\t\tname: this.cause.name,\n\t\t\t\tmessage: this.cause.message,\n\t\t\t\tstack: this.cause.stack\n\t\t\t} : void 0,\n\t\t\ttimestamp: this.timestamp.toISOString(),\n\t\t\trequestId\n\t\t};\n\t}\n\tstatic invalidCredentials(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"AUTH_INVALID_CREDENTIALS\",\n\t\t\tpublicMessage: \"Invalid email or password.\",\n\t\t\tlogMessage: \"Login failed\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* The password was correct and the address is unverified. Thrown only once\n\t* the password is proven, so only someone who holds it learns the address\n\t* is unverified; every other refusal stays\n\t* {@link NextlyError.invalidCredentials}.\n\t*/\n\tstatic emailNotVerified(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"EMAIL_NOT_VERIFIED\",\n\t\t\tpublicMessage: \"Verify your email address to sign in. Check your inbox for the link.\",\n\t\t\tlogMessage: \"Login refused: email not verified\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\tstatic authRequired(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"AUTH_REQUIRED\",\n\t\t\tpublicMessage: \"Authentication required.\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* Distinct from `authRequired`: the caller was authenticated but the\n\t* session token expired. Clients key on the TOKEN_EXPIRED *code* to\n\t* silently refresh and retry rather than redirecting to login; the public\n\t* message stays the generic spec §13.6 string (\"Authentication required.\")\n\t* so the wire never reveals the session state — same as `authRequired`.\n\t*/\n\tstatic tokenExpired(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"TOKEN_EXPIRED\",\n\t\t\tpublicMessage: \"Authentication required.\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\tstatic notFound(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"NOT_FOUND\",\n\t\t\tpublicMessage: opts?.message ?? \"Not found.\",\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\tstatic forbidden(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: \"You don't have permission to perform this action.\",\n\t\t\tpublicData: opts?.publicData,\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* Something only a signed-in person can do, asked by a caller that is not\n\t* one: an API key, or a request acting as no person. Forbidden, and the\n\t* message says so, since it is about what kind of caller asked, not about\n\t* the caller's permissions. `doing` completes \"Only a signed-in person can\".\n\t*/\n\tstatic personOnly(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: `Only a signed-in person can ${opts.doing}.`,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* A role or permission built into Nextly, which is never changed or\n\t* deleted. Forbidden, and the message says so: it is a fact about the role,\n\t* not about the caller's permissions.\n\t*/\n\tstatic builtIn(opts) {\n\t\tconst done = {\n\t\t\tchange: \"changed\",\n\t\t\tdelete: \"deleted\",\n\t\t\tassign: \"assigned\",\n\t\t\tinherit: \"inherited\"\n\t\t}[opts.change];\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: `This ${opts.thing} is built in, so it can't be ${done}.`,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* A request from a site not allowed to make it: its own `Origin` names a\n\t* site the installation does not allow. Forbidden, and the message says so;\n\t* the origin is the caller's own, so naming its kind tells them nothing.\n\t*/\n\tstatic originRefused(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: \"This request came from a site that isn't allowed to make it.\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* A Single deleted without `force`: Singles hold a site's lasting settings,\n\t* so they are not deleted from here, only by an admin or CLI clean-up that\n\t* passes `force`. Forbidden, and the message says so.\n\t*/\n\tstatic singleNotDeletable(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: \"A Single can't be deleted from here.\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* A collection, Single or component defined in code, which is changed by\n\t* changing its code and not from here. Forbidden, and the message says so:\n\t* it is a fact about the thing, not about the caller's permissions, so it\n\t* names no permission and no policy. The lock's detail goes to the log\n\t* through `logContext`.\n\t*/\n\tstatic definedInCode(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: `This ${opts.thing} is defined in code, so it can't be ${opts.change === \"change\" ? \"changed\" : \"deleted\"} here.`,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* A write to an entry of a collection or Single removed from code: its\n\t* registry row says the app's code defines it, and the running configuration\n\t* no longer declares it. Its entries are read-only until it is retired or\n\t* declared again, so the message names the entity, says what happened and\n\t* gives both ways out. `publicData` carries the kind and the slug, which the\n\t* caller named, so a client can mark the entity without parsing the sentence.\n\t*/\n\tstatic removedFromCode(opts) {\n\t\tconst thing = opts.kind === \"single\" ? \"Single\" : \"collection\";\n\t\tconst its = opts.kind === \"single\" ? \"it\" : \"its entries\";\n\t\treturn new NextlyError({\n\t\t\tcode: \"ENTITY_REMOVED_FROM_CODE\",\n\t\t\tpublicMessage: `The ${thing} \"${opts.slug}\" was removed from code, so ${its} can't be changed. To retire it, run \\`nextly migrate:create\\` and then \\`nextly migrate\\`. To keep it, declare it again in nextly.config.ts.`,\n\t\t\tpublicData: {\n\t\t\t\tkind: opts.kind,\n\t\t\t\tslug: opts.slug\n\t\t\t},\n\t\t\tlogContext: {\n\t\t\t\tkind: opts.kind,\n\t\t\t\tslug: opts.slug,\n\t\t\t\t...opts.logContext\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* A read or write of a collection or Single the database has not been\n\t* migrated for: the column of one of its declared fields is missing, its\n\t* table is missing, or this running instance never registered it (an\n\t* entity a migration added after the instance started). The message names\n\t* the entity, the field or the table, and `nextly migrate`; the driver's\n\t* error stays on `cause`, for the log, so no SQL reaches the answer.\n\t*/\n\tstatic notMigrated(opts) {\n\t\tconst { cause, logContext, ...publicData } = opts;\n\t\tconst entity = `${publicData.kind === \"single\" ? \"Single\" : \"collection\"} \"${publicData.slug}\"`;\n\t\tconst field = publicData.field === void 0 ? \"a field\" : `the field \"${publicData.field}\"`;\n\t\tconst table = publicData.table === void 0 ? \"\" : ` \"${publicData.table}\"`;\n\t\tconst publicMessage = publicData.reason === \"column\" ? `The database has not been migrated for ${field} of the ${entity}. Run \\`nextly migrate\\`.` : publicData.reason === \"table\" ? `The database has not been migrated for the ${entity}: its table${table} does not exist. Run \\`nextly migrate\\`.` : `The ${entity}${publicData.table === void 0 ? \"\" : ` (table \"${publicData.table}\")`} is not registered in this running instance. Run \\`nextly migrate\\`, then restart the server.`;\n\t\treturn new NextlyError({\n\t\t\tcode: \"ENTITY_NOT_MIGRATED\",\n\t\t\tpublicMessage,\n\t\t\tpublicData,\n\t\t\tlogMessage: \"The database has not been migrated for this entity\",\n\t\t\tlogContext: {\n\t\t\t\t...publicData,\n\t\t\t\t...logContext\n\t\t\t},\n\t\t\tcause\n\t\t});\n\t}\n\t/**\n\t* An autosave where the collection or Single does not autosave: its owner\n\t* switched autosave off, or it keeps no drafts to autosave into. Forbidden,\n\t* and the message says so, since it is a setting and not a permission.\n\t*/\n\tstatic autosaveOff(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"FORBIDDEN\",\n\t\t\tpublicMessage: `Autosave is turned off for this ${opts.scopeKind === \"single\" ? \"Single\" : \"collection\"}.`,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* An API key refused because its role allows more than the person creating\n\t* it may do. The sentence is FORBIDDEN's and names no permission; which one\n\t* exceeded goes to the log through `logContext`. The code is its own, so a\n\t* client can tell \"choose a smaller role\" from plain FORBIDDEN.\n\t*/\n\tstatic apiKeyRoleAboveCreator(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"API_KEY_ROLE_ABOVE_CREATOR\",\n\t\t\tpublicMessage: genericPublicMessage(\"FORBIDDEN\"),\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* A cookie-authenticated write refused because its origin or CSRF token did\n\t* not check out. The public message names no detail of which check failed;\n\t* that goes to the log through `logMessage`.\n\t*/\n\tstatic csrfFailed(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"CSRF_FAILED\",\n\t\t\tpublicMessage: \"This request could not be verified. Reload the page and try again.\",\n\t\t\tlogMessage: opts?.logMessage,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* A call the caller got wrong, where naming the mistake IS the value of the\n\t* error.\n\t*\n\t* The only factory that takes its public message from the caller. The\n\t* generic messages elsewhere exist so an HTTP response cannot leak internal\n\t* detail; this one is for arguments and configuration a developer controls\n\t* and must be told about — a missing option, an unusable combination — where\n\t* `internal()` would reduce the one useful sentence to \"An unexpected error\n\t* occurred.\" Do not pass user-supplied data through it.\n\t*/\n\tstatic invalidInput(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"INVALID_INPUT\",\n\t\t\tpublicMessage: opts.message,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\tstatic validation(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"VALIDATION_ERROR\",\n\t\t\tpublicMessage: \"Validation failed.\",\n\t\t\tpublicData: { errors: opts.errors },\n\t\t\tcause: opts.cause,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\tstatic conflict(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"CONFLICT\",\n\t\t\tpublicMessage: opts?.message ?? \"The resource has changed since you last loaded it. Please refresh and try again.\",\n\t\t\tpublicData: opts?.data,\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: {\n\t\t\t\treason: opts?.reason,\n\t\t\t\t...opts?.logContext\n\t\t\t}\n\t\t});\n\t}\n\t/**\n\t* An update made from a version of the document that is no longer its\n\t* current one. Never retried: the same version stays out of date, so the\n\t* caller must read the document again and decide.\n\t*\n\t* @experimental\n\t*/\n\t/**\n\t* An update that said neither which version of a document it was made from\n\t* nor that it overwrites whatever is stored. Without `bulk`, an update of\n\t* one document, which sends back the version it read. `bulk` names an\n\t* update that writes the same values to many documents, which can carry no\n\t* one document's version: by its ids, which can be given a version each\n\t* (`keys.revs`), or by a query, which cannot. The keys are the write path's\n\t* to name, so the message spells them as the request does.\n\t*\n\t* @experimental\n\t*/\n\tstatic versionRequired(opts) {\n\t\tconst { version, overwrite, revs } = opts.keys;\n\t\tif (opts.bulk === void 0) {\n\t\t\tconst one = {\n\t\t\t\tversionKey: version,\n\t\t\t\toverwriteKey: overwrite\n\t\t\t};\n\t\t\treturn new NextlyError({\n\t\t\t\tcode: \"VERSION_REQUIRED\",\n\t\t\t\tpublicMessage: `This update must say which version of the document it changes. Send back the \\`${version}\\` from your last read of it, or set \\`${overwrite}: true\\` to replace whatever is stored.`,\n\t\t\t\tpublicData: one,\n\t\t\t\tlogContext: opts.logContext\n\t\t\t});\n\t\t}\n\t\tconst byIds = opts.bulk === \"ids\";\n\t\tconst data = {\n\t\t\tversionKey: version,\n\t\t\toverwriteKey: overwrite,\n\t\t\t...byIds ? { revsKey: revs } : {}\n\t\t};\n\t\tconst message = `An update that writes the same values to many documents must set \\`${overwrite}: true\\`: it can't carry each document's version. Or update each document with its own \\`${version}\\`.`;\n\t\treturn new NextlyError({\n\t\t\tcode: \"VERSION_REQUIRED\",\n\t\t\tpublicMessage: byIds ? `${message} Or give each document's \\`${version}\\` in \\`${revs}\\`.` : message,\n\t\t\tpublicData: data,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\tstatic staleVersion(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"STALE_VERSION\",\n\t\t\tpublicMessage: `This document changed since the version you gave. Its current version is ${opts.data.currentVersion}.`,\n\t\t\tpublicData: opts.data,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* `message` replaces the generic sentence where the caller can name what is\n\t* already taken without leaking anything, such as a public address and the\n\t* page holding it.\n\t*/\n\tstatic duplicate(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"DUPLICATE\",\n\t\t\tpublicMessage: opts?.message ?? \"Resource already exists.\",\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\tstatic rateLimited(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"RATE_LIMITED\",\n\t\t\tpublicMessage: \"Too many requests. Please try again later.\",\n\t\t\tpublicData: opts?.retryAfterSeconds !== void 0 ? { retryAfterSeconds: opts.retryAfterSeconds } : void 0,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* A request that waited `pool.connectionTimeoutMs` for a database\n\t* connection and was given none. The statement or transaction that waited\n\t* never ran; work committed before it stays committed. The same error\n\t* `fromDatabaseError` gives a busy DbError, from the same table row.\n\t*/\n\tstatic databaseBusy(opts) {\n\t\tconst busy = DB_ERROR_MAPPING.busy;\n\t\treturn new NextlyError({\n\t\t\tcode: busy.code,\n\t\t\tstatusCode: busy.statusCode,\n\t\t\tpublicMessage: busy.publicMessage,\n\t\t\tpublicData: busy.publicData,\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* An access or field rule the request needs could not run, because its own\n\t* database query waited out the bound for a connection. Not a refusal: the\n\t* rule never answered. Names the collection or Single whose rule it is, and\n\t* the field for a field's rule, and says when to retry.\n\t*/\n\tstatic ruleCouldNotRun(opts) {\n\t\tconst publicData = {\n\t\t\tsubject: opts.subject,\n\t\t\t...opts.field !== void 0 ? { field: opts.field } : {},\n\t\t\tretryAfterSeconds: 5\n\t\t};\n\t\treturn new NextlyError({\n\t\t\tcode: \"RULE_COULD_NOT_RUN\",\n\t\t\tstatusCode: NEXTLY_ERROR_STATUS.RULE_COULD_NOT_RUN,\n\t\t\tpublicMessage: genericPublicMessage(\"RULE_COULD_NOT_RUN\"),\n\t\t\tpublicData,\n\t\t\tcause: opts.cause,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* What a request boundary answers with for a thrown value that is not a\n\t* NextlyError: \"database busy\" when the request waited out its bound for a\n\t* connection, which is retryable and no fault of the server's code, and an\n\t* internal error for anything else.\n\t*\n\t* The busy case has to be read here because it usually arrives raw:\n\t* `withDbErrors` converts only DbErrors, so a driver's error passes through\n\t* services unconverted to the boundary that answers the request.\n\t*/\n\tstatic fromUnexpected(error) {\n\t\treturn NextlyError.busyOr(error, () => NextlyError.internal({ cause: error instanceof Error ? error : void 0 }));\n\t}\n\t/**\n\t* \"Database busy\" when `error` is a request that waited out its bound for\n\t* a connection, and `otherwise()` for anything else.\n\t*\n\t* For a boundary that answers an unexpected failure with an error of its\n\t* own choosing rather than an internal one (a 503 for a flow that must not\n\t* answer on incomplete data), so that a busy database still answers there\n\t* as it does everywhere else. `fromUnexpected` is this rule with the\n\t* internal error as its fallback.\n\t*/\n\tstatic busyOr(error, otherwise) {\n\t\tif (!isDatabaseBusy(error)) return otherwise();\n\t\treturn NextlyError.databaseBusy({ cause: error instanceof Error ? error : void 0 });\n\t}\n\tstatic internal(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"INTERNAL_ERROR\",\n\t\t\tpublicMessage: \"An unexpected error occurred.\",\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* The app is set up so nextly cannot work: a missing `config`, or a Next.js\n\t* or React outside the supported ranges. The public message stays generic;\n\t* what to change goes in `logMessage`, for the operator.\n\t*/\n\tstatic configuration(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"CONFIGURATION_ERROR\",\n\t\t\tpublicMessage: \"Server configuration error.\",\n\t\t\tlogMessage: opts.logMessage,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\t/**\n\t* A service outside Nextly failed, such as an email provider, where trying again may help: the\n\t* job queue records it as an attempt's error and tries again.\n\t*/\n\tstatic externalService(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"EXTERNAL_SERVICE_ERROR\",\n\t\t\tpublicMessage: opts.publicMessage,\n\t\t\tlogMessage: opts.logMessage,\n\t\t\tcause: opts.cause,\n\t\t\tlogContext: opts.logContext\n\t\t});\n\t}\n\tstatic serviceUnavailable(opts) {\n\t\treturn new NextlyError({\n\t\t\tcode: \"SERVICE_UNAVAILABLE\",\n\t\t\tpublicMessage: opts?.publicMessage ?? \"Service unavailable. Please try again later.\",\n\t\t\tlogMessage: opts?.logMessage,\n\t\t\tcause: opts?.cause,\n\t\t\tlogContext: opts?.logContext\n\t\t});\n\t}\n\t/**\n\t* Convert a DbError (or arbitrary unknown thrown by the DB layer) to a\n\t* NextlyError with a generic public message and rich logContext. Used by\n\t* `withDbErrors` for auto-conversion (Pattern A) and by services that\n\t* catch DB errors at boundaries (Pattern B). Spec §8.2 mapping table.\n\t*\n\t* Never leaks DB driver text, constraint names, or table names into\n\t* `publicMessage`. All DB context goes into `logContext`. The original\n\t* DbError is preserved as `cause`.\n\t*/\n\tstatic fromDatabaseError(error) {\n\t\tif (isDbError(error)) {\n\t\t\tconst mapping = DB_ERROR_MAPPING[error.kind];\n\t\t\tconst logContext = {\n\t\t\t\tdbKind: error.kind,\n\t\t\t\tdialect: error.dialect\n\t\t\t};\n\t\t\tif (error.code !== void 0) logContext.dbCode = error.code;\n\t\t\tif (error.meta !== void 0) logContext.meta = error.meta;\n\t\t\treturn new NextlyError({\n\t\t\t\tcode: mapping.code,\n\t\t\t\tstatusCode: mapping.statusCode,\n\t\t\t\tpublicMessage: mapping.publicMessage,\n\t\t\t\tpublicData: \"publicData\" in mapping ? mapping.publicData : void 0,\n\t\t\t\tlogMessage: \"Database error\",\n\t\t\t\tlogContext,\n\t\t\t\tcause: error\n\t\t\t});\n\t\t}\n\t\treturn new NextlyError({\n\t\t\tcode: \"INTERNAL_ERROR\",\n\t\t\tstatusCode: 500,\n\t\t\tpublicMessage: \"An unexpected error occurred.\",\n\t\t\tlogMessage: \"Non-DbError passed to fromDatabaseError\",\n\t\t\tcause: error instanceof Error ? error : void 0,\n\t\t\tlogContext: error instanceof Error ? void 0 : { value: String(error) }\n\t\t});\n\t}\n\tstatic is(err) {\n\t\treturn hasBrand(err);\n\t}\n\tstatic isCode(err, code) {\n\t\treturn hasBrand(err) && err.code === code;\n\t}\n\tstatic isNotFound(err) {\n\t\treturn NextlyError.isCode(err, \"NOT_FOUND\");\n\t}\n\tstatic isValidation(err) {\n\t\treturn NextlyError.isCode(err, \"VALIDATION_ERROR\");\n\t}\n\tstatic isAuthRequired(err) {\n\t\treturn NextlyError.isCode(err, \"AUTH_REQUIRED\");\n\t}\n\tstatic isForbidden(err) {\n\t\treturn NextlyError.isCode(err, \"FORBIDDEN\");\n\t}\n\tstatic isConflict(err) {\n\t\treturn NextlyError.isCode(err, \"CONFLICT\");\n\t}\n\tstatic isRateLimited(err) {\n\t\treturn NextlyError.isCode(err, \"RATE_LIMITED\");\n\t}\n};\nexport { NEXTLY_ERROR_STATUS as a, DbError as c, isUniqueViolation as d, safeCode as f, retryAfterSeconds as i, isDatabaseBusy as l, POOL_WAIT_TIMEOUT_CODE as m, nextly_error_exports as n, genericPublicMessage as o, toDbError as p, retryAfterHeader as r, statusToErrorCode as s, NextlyError as t, isDbError as u };\n","import { t as NextlyError } from \"./nextly-error-C_MDZmJc.mjs\";\nimport { i as ipv4ToInt } from \"./get-trusted-client-ip-CYEbmLA3.mjs\";\n// src/utils/validate-external-url.ts\nconst 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)$/;\n/**\n* IPv4 CIDR ranges that must NEVER be the destination of an outbound\n* fetch sourced from a user-controllable URL. Listed roughly by RFC.\n*/\nconst PRIVATE_IPV4_CIDRS = [\n\t\"0.0.0.0/8\",\n\t\"10.0.0.0/8\",\n\t\"100.64.0.0/10\",\n\t\"127.0.0.0/8\",\n\t\"169.254.0.0/16\",\n\t\"172.16.0.0/12\",\n\t\"192.0.0.0/24\",\n\t\"192.0.2.0/24\",\n\t\"192.168.0.0/16\",\n\t\"198.18.0.0/15\",\n\t\"198.51.100.0/24\",\n\t\"203.0.113.0/24\",\n\t\"224.0.0.0/4\",\n\t\"240.0.0.0/4\"\n];\n/**\n* Cloud-metadata hostnames. These often resolve to private IPs and the\n* private-IP block catches them, but we reject by hostname first so the\n* error message is clear.\n*/\nconst CLOUD_METADATA_HOSTS = /* @__PURE__ */ new Set([\n\t\"metadata.google.internal\",\n\t\"metadata.googleapis.com\",\n\t\"metadata\"\n]);\n/**\n* An outbound URL refused for SSRF safety. Extends `NextlyError` (the package's\n* canonical error) so throw sites honor the error contract, while remaining a\n* distinct class the callers (e.g. the form-builder webhook handler) match with\n* `instanceof`.\n*/\nvar ExternalUrlError = class extends NextlyError {\n\turl;\n\tconstructor(message, url) {\n\t\tsuper({\n\t\t\tcode: \"EXTERNAL_URL_BLOCKED\",\n\t\t\tpublicMessage: message,\n\t\t\tlogContext: { url }\n\t\t});\n\t\tthis.url = url;\n\t\tthis.name = \"ExternalUrlError\";\n\t}\n};\n/** Validate a URL for outbound fetch. Throws `ExternalUrlError` on rejection. */\nasync function validateExternalUrl(rawUrl, options = {}) {\n\tlet parsed;\n\ttry {\n\t\tparsed = new URL(rawUrl);\n\t} catch {\n\t\tthrow new ExternalUrlError(\"Invalid URL\", rawUrl);\n\t}\n\tconst hostname = parsed.hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n\tconst isLocalhostHostname = hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"::1\";\n\tconst baseProtocols = options.allowedProtocols ?? [\"https:\"];\n\tconst protocols = options.allowLocalhost && isLocalhostHostname ? [...baseProtocols, \"http:\"] : baseProtocols;\n\tif (!protocols.includes(parsed.protocol)) throw new ExternalUrlError(`Protocol ${parsed.protocol} not allowed (allowed: ${protocols.join(\", \")})`, rawUrl);\n\tif (CLOUD_METADATA_HOSTS.has(hostname)) throw new ExternalUrlError(`Cloud-metadata hostname rejected: ${parsed.hostname}`, rawUrl);\n\tif (IPV4_RE.test(hostname)) {\n\t\tif (!isPublicIpv4(hostname, options.allowLocalhost === true && hostname === \"127.0.0.1\")) throw new ExternalUrlError(`Resolved to non-public IP: ${hostname}`, rawUrl);\n\t\treturn {\n\t\t\turl: parsed,\n\t\t\tpinnedIp: hostname,\n\t\t\tfamily: 4\n\t\t};\n\t}\n\tif (hostname.includes(\":\")) {\n\t\tif (!isPublicIpv6(hostname, options.allowLocalhost === true && hostname === \"::1\")) throw new ExternalUrlError(`Resolved to non-public IP: ${hostname}`, rawUrl);\n\t\treturn {\n\t\t\turl: parsed,\n\t\t\tpinnedIp: hostname,\n\t\t\tfamily: 6\n\t\t};\n\t}\n\tconst { lookup } = await import(\"node:dns/promises\");\n\tlet addresses;\n\ttry {\n\t\taddresses = await lookup(hostname, { all: true });\n\t} catch (err) {\n\t\tthrow new ExternalUrlError(`DNS lookup failed: ${err.message}`, rawUrl);\n\t}\n\tif (addresses.length === 0) throw new ExternalUrlError(\"No IPs returned for host\", rawUrl);\n\tfor (const { address, family } of addresses) {\n\t\tconst allow = options.allowLocalhost === true && isLocalhostHostname && family === 4;\n\t\tif (!(family === 4 ? isPublicIpv4(address, allow) : isPublicIpv6(address, allow))) throw new ExternalUrlError(`Resolved to non-public IP: ${address}`, rawUrl);\n\t}\n\tconst first = addresses[0];\n\treturn {\n\t\turl: parsed,\n\t\tpinnedIp: first.address,\n\t\tfamily: first.family === 6 ? 6 : 4\n\t};\n}\n/** Default response body cap: reject anything larger before buffering it all. */\n/**\n* How many bytes a bounded external read may buffer, absent a caller's own cap.\n*\n* Exported for the same reason as the deadline below: an adapter that never\n* touches `safeFetch` still owes callers this default, and restating the number\n* gives the tree two that drift.\n*/\nconst DEFAULT_MAX_RESPONSE_BYTES = 10485760;\n/** Default overall deadline covering DNS + connect + TLS + response. */\n/**\n* How long a bounded external read may take, absent a caller's own limit.\n*\n* Exported so a caller that must begin the clock EARLIER — a storage adapter\n* bounding a metadata lookup as well as the fetch that follows — uses this\n* number rather than restating it. Two spellings of one default agree today and\n* drift the first time either is tuned.\n*/\nconst DEFAULT_TIMEOUT_MS = 3e4;\n/**\n* Raised for fetch-phase failures that are NOT SSRF rejections: an over-large\n* response body, the overall deadline elapsing, or an undecodable content\n* encoding. Extends `NextlyError` (the canonical error contract) while staying a\n* distinct class, so a caller can tell \"URL refused for safety\"\n* (`ExternalUrlError`) apart from \"the request itself failed\".\n*/\nvar SafeFetchError = class extends NextlyError {\n\turl;\n\treason;\n\tstatus;\n\tconstructor(message, url, reason, status) {\n\t\tsuper({\n\t\t\tcode: \"EXTERNAL_REQUEST_FAILED\",\n\t\t\tpublicMessage: message,\n\t\t\tlogContext: {\n\t\t\t\turl,\n\t\t\t\treason\n\t\t\t}\n\t\t});\n\t\tthis.url = url;\n\t\tthis.reason = reason;\n\t\tthis.status = status;\n\t\tthis.name = \"SafeFetchError\";\n\t}\n};\n/**\n* Build a `dns.lookup`-compatible function that ignores the hostname and\n* always resolves to `ip`/`family`. Handing this to `http(s).request` forces\n* the socket to dial the exact address `validateExternalUrl` already vetted,\n* closing the DNS-rebinding window where a second resolution at connect time\n* could return a private IP. Not re-exported from the package barrel; exported\n* for the plugin `ctx.fetch` transport, which pins its vetted address the same\n* way, and so the rebinding invariant can be unit-tested directly.\n*/\nfunction createPinnedLookup(ip, family) {\n\treturn (_hostname, options, callback) => {\n\t\tif (options && options.all) callback(null, [{\n\t\t\taddress: ip,\n\t\t\tfamily\n\t\t}]);\n\t\telse callback(null, ip, family);\n\t};\n}\n/**\n* Validate `rawUrl` then fetch it with the validated IP pinned at the socket.\n* The convenience wrapper for the common case (webhook delivery, email\n* attachment fetch). Node-runtime only.\n*\n* DNS is resolved once by `validateExternalUrl`; `createPinnedLookup` forces\n* the connection to that same address, so an attacker's DNS cannot rebind the\n* request to a private host between validation and connect. Redirects are not\n* followed, the body is capped at `maxResponseBytes`, and the request is\n* bounded by `timeoutMs`.\n*/\nasync function safeFetch(rawUrl, options = {}) {\n\tconst { allowLocalhost, allowedProtocols, method, headers, body, signal, maxResponseBytes = DEFAULT_MAX_RESPONSE_BYTES, timeoutMs = DEFAULT_TIMEOUT_MS } = options;\n\tconst controller = new AbortController();\n\tconst forwardAbort = () => controller.abort(signal?.reason);\n\tif (signal) {\n\t\tif (signal.aborted) controller.abort(signal.reason);\n\t\telse signal.addEventListener(\"abort\", forwardAbort, { once: true });\n\t}\n\tconst timer = setTimeout(() => controller.abort(new SafeFetchError(`Request exceeded ${timeoutMs}ms`, rawUrl, \"timeout\")), timeoutMs);\n\ttry {\n\t\treturn await pinnedFetch(await abortable(validateExternalUrl(rawUrl, {\n\t\t\tallowLocalhost,\n\t\t\tallowedProtocols\n\t\t}), controller.signal), {\n\t\t\tmethod,\n\t\t\theaders,\n\t\t\tbody,\n\t\t\tsignal: controller.signal,\n\t\t\tmaxResponseBytes\n\t\t});\n\t} finally {\n\t\tclearTimeout(timer);\n\t\tif (signal) signal.removeEventListener(\"abort\", forwardAbort);\n\t}\n}\n/**\n* The signal's abort reason as an `Error`. Our own aborts carry a\n* `SafeFetchError` (timeout); a caller's `AbortController.abort()` carries a\n* DOMException `AbortError`; anything else (a non-Error reason) is surfaced as\n* a standard `AbortError` so downstream `name === \"AbortError\"` checks hold.\n*/\nfunction abortError(signal) {\n\tconst reason = signal.reason;\n\tif (reason instanceof Error) return reason;\n\treturn new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n/**\n* Resolve `promise`, but reject with the signal's reason if it aborts first.\n* Lets a phase that runs before the request (DNS validation) share the overall\n* deadline and caller cancellation.\n*/\nfunction abortable(promise, signal) {\n\tif (signal.aborted) return Promise.reject(abortError(signal));\n\tlet onAbort;\n\tconst aborted = new Promise((_resolve, reject) => {\n\t\tonAbort = () => reject(abortError(signal));\n\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n\treturn Promise.race([promise, aborted]).finally(() => signal.removeEventListener(\"abort\", onAbort));\n}\n/**\n* Issue the request over `node:http`/`node:https` with the validated IP pinned\n* via a custom `lookup`, then adapt the Node response into a WHATWG `Response`.\n* `agent: false` forces a fresh socket per call so no pooled connection can\n* reuse a differently-resolved address. The overall deadline is enforced by the\n* caller through `init.signal`, so there is no separate timer here.\n*/\nasync function pinnedFetch(validated, init) {\n\tconst { url, pinnedIp, family } = validated;\n\tconst httpMod = url.protocol === \"https:\" ? await import(\"node:https\") : await import(\"node:http\");\n\tconst zlib = await import(\"node:zlib\");\n\tconst lookup = createPinnedLookup(pinnedIp, family);\n\tconst outHeaders = toOutgoingHeaders(init.headers);\n\tif (init.body != null) {\n\t\tdelete outHeaders[\"transfer-encoding\"];\n\t\toutHeaders[\"content-length\"] = String(typeof init.body === \"string\" ? Buffer.byteLength(init.body) : init.body.byteLength);\n\t}\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst settle = (fn) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tfn();\n\t\t};\n\t\tconst failure = (err) => init.signal.aborted ? abortError(init.signal) : err;\n\t\tconst req = httpMod.request(url, {\n\t\t\tmethod: init.method ?? \"GET\",\n\t\t\theaders: outHeaders,\n\t\t\tlookup,\n\t\t\tagent: false,\n\t\t\tsignal: init.signal\n\t\t}, (res) => {\n\t\t\tconst chunks = [];\n\t\t\tlet received = 0;\n\t\t\tres.on(\"data\", (chunk) => {\n\t\t\t\treceived += chunk.length;\n\t\t\t\tif (received > init.maxResponseBytes) {\n\t\t\t\t\tres.destroy();\n\t\t\t\t\treq.destroy();\n\t\t\t\t\tsettle(() => reject(new SafeFetchError(`Response body exceeded ${init.maxResponseBytes} bytes`, url.href, \"response-too-large\", res.statusCode)));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tchunks.push(chunk);\n\t\t\t});\n\t\t\tres.on(\"end\", () => {\n\t\t\t\tconst decoded = decodeBody(Buffer.concat(chunks), res.headers[\"content-encoding\"], zlib, init.maxResponseBytes, url.href, res.statusCode);\n\t\t\t\tif (decoded instanceof SafeFetchError) {\n\t\t\t\t\tsettle(() => reject(decoded));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettle(() => resolve(toWhatwgResponse(res, decoded.body, decoded.decoded)));\n\t\t\t});\n\t\t\tres.on(\"error\", (err) => settle(() => reject(failure(err))));\n\t\t});\n\t\treq.on(\"error\", (err) => settle(() => reject(failure(err))));\n\t\tif (!req.destroyed) {\n\t\t\tif (init.body != null) req.write(init.body);\n\t\t\treq.end();\n\t\t}\n\t});\n}\n/**\n* Normalize a `HeadersInit` into Node's outgoing-header shape. Header names are\n* lowercased (they are case-insensitive) so later framing checks\n* (`content-length`) and the Host strip are reliable regardless of caller\n* casing. A caller-supplied `Host` is dropped: it is derived from the validated\n* URL, and honoring an override would let Host-based routing reach an internal\n* vhost behind a validated public IP, defeating the SSRF pin.\n*/\nfunction toOutgoingHeaders(headers) {\n\tconst out = {};\n\tif (!headers) return out;\n\tconst add = (rawKey, value) => {\n\t\tconst key = rawKey.toLowerCase();\n\t\tif (key === \"host\") return;\n\t\tconst existing = out[key];\n\t\tout[key] = existing === void 0 ? value : [].concat(existing, value);\n\t};\n\tif (headers instanceof Headers) headers.forEach((value, key) => add(key, value));\n\telse if (Array.isArray(headers)) for (const [key, value] of headers) add(key, value);\n\telse for (const [key, value] of Object.entries(headers)) add(key, value);\n\treturn out;\n}\n/**\n* Adapt a Node `IncomingMessage` + buffered body into a WHATWG `Response`.\n* Total by construction: a header the WHATWG layer rejects is skipped and the\n* status is clamped to a constructible range, so this never throws (a throw\n* would otherwise escape the `end` handler as an uncaught error).\n*/\nfunction toWhatwgResponse(res, body, stripContentHeaders) {\n\tconst headers = new Headers();\n\tfor (const [key, value] of Object.entries(res.headers)) {\n\t\tif (value == null) continue;\n\t\tconst lower = key.toLowerCase();\n\t\tif (stripContentHeaders && (lower === \"content-encoding\" || lower === \"content-length\")) continue;\n\t\tconst values = Array.isArray(value) ? value : [value];\n\t\tfor (const v of values) try {\n\t\t\theaders.append(key, v);\n\t\t} catch {}\n\t}\n\tconst raw = res.statusCode ?? 502;\n\tconst status = raw >= 200 && raw <= 599 ? raw : 502;\n\tconst nullBody = status === 204 || status === 205 || status === 304;\n\tconst bytes = new Uint8Array(body.byteLength);\n\tbytes.set(body);\n\treturn new Response(nullBody ? null : bytes, {\n\t\tstatus,\n\t\tstatusText: res.statusMessage ?? \"\",\n\t\theaders\n\t});\n}\n/**\n* Content-decode a response body per its `Content-Encoding`. node:http returns\n* raw wire bytes (unlike global fetch), so gzip/deflate/br bodies are inflated\n* here to preserve the previous behavior. `maxOutputLength` bounds the inflated\n* size, turning a decompression bomb into a `SafeFetchError` rather than an OOM.\n* Returns the (possibly decoded) buffer, or a `SafeFetchError` on failure.\n*/\nfunction decodeBody(buf, encoding, zlib, cap, url, status) {\n\tif (!encoding) return {\n\t\tbody: buf,\n\t\tdecoded: false\n\t};\n\tif (buf.length === 0) return {\n\t\tbody: buf,\n\t\tdecoded: true\n\t};\n\tconst layers = encoding.split(\",\").map((e) => e.trim().toLowerCase()).filter(Boolean);\n\tconst opts = { maxOutputLength: cap };\n\tlet current = buf;\n\tlet decoded = false;\n\ttry {\n\t\tfor (let i = layers.length - 1; i >= 0; i--) {\n\t\t\tconst enc = layers[i];\n\t\t\tif (enc === \"identity\") continue;\n\t\t\tif (enc === \"gzip\" || enc === \"x-gzip\") current = zlib.gunzipSync(current, opts);\n\t\t\telse if (enc === \"br\") current = zlib.brotliDecompressSync(current, opts);\n\t\t\telse if (enc === \"deflate\") try {\n\t\t\t\tcurrent = zlib.inflateSync(current, opts);\n\t\t\t} catch (inflateErr) {\n\t\t\t\tif (errorCode(inflateErr) === \"ERR_BUFFER_TOO_LARGE\") throw inflateErr;\n\t\t\t\tcurrent = zlib.inflateRawSync(current, opts);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (decoded) return new SafeFetchError(`Cannot fully decode content-encoding \"${encoding}\"`, url, \"decode-failed\", status);\n\t\t\t\treturn {\n\t\t\t\t\tbody: buf,\n\t\t\t\t\tdecoded: false\n\t\t\t\t};\n\t\t\t}\n\t\t\tdecoded = true;\n\t\t}\n\t\treturn {\n\t\t\tbody: current,\n\t\t\tdecoded\n\t\t};\n\t} catch (err) {\n\t\tconst tooLarge = errorCode(err) === \"ERR_BUFFER_TOO_LARGE\";\n\t\treturn 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);\n\t}\n}\n/** The `.code` of a Node system error, if present. */\nfunction errorCode(err) {\n\tif (err != null && typeof err === \"object\" && \"code\" in err) {\n\t\tconst code = err.code;\n\t\treturn typeof code === \"string\" ? code : void 0;\n\t}\n}\nfunction isIpv4InCidr(intIp, cidr) {\n\tconst [addr, prefixRaw] = cidr.split(\"/\");\n\tconst intCidr = ipv4ToInt(addr);\n\tif (intCidr === null) return false;\n\tconst prefix = Number(prefixRaw);\n\tif (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false;\n\tconst mask = prefix === 0 ? 0 : -1 >>> 32 - prefix << 32 - prefix;\n\treturn (intIp & mask) >>> 0 === (intCidr & mask) >>> 0;\n}\nfunction isPublicIpv4(addr, allowLoopback) {\n\tconst intIp = ipv4ToInt(addr);\n\tif (intIp === null) return false;\n\tif (allowLoopback && addr === \"127.0.0.1\") return true;\n\tfor (const cidr of PRIVATE_IPV4_CIDRS) if (isIpv4InCidr(intIp, cidr)) return false;\n\treturn true;\n}\n/**\n* Extract the embedded IPv4 of an IPv4-mapped IPv6 address, or null. Handles\n* both the dotted form (`::ffff:1.2.3.4`) and the hex form (`::ffff:7f00:1`)\n* that `URL.hostname` normalizes the dotted literal to — the latter would\n* otherwise skip the IPv4 denylist and pin, e.g., loopback as public.\n*/\nfunction mappedIpv4(lower) {\n\tconst dotted = lower.match(/^::ffff:(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$/);\n\tif (dotted) return dotted[1];\n\tconst hex = lower.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n\tif (hex) {\n\t\tconst hi = parseInt(hex[1], 16);\n\t\tconst lo = parseInt(hex[2], 16);\n\t\treturn [\n\t\t\thi >> 8,\n\t\t\thi & 255,\n\t\t\tlo >> 8,\n\t\t\tlo & 255\n\t\t].join(\".\");\n\t}\n\treturn null;\n}\nfunction isPublicIpv6(addr, allowLoopback) {\n\tconst lower = addr.toLowerCase();\n\tif (allowLoopback && lower === \"::1\") return true;\n\tconst mapped = mappedIpv4(lower);\n\tif (mapped) return isPublicIpv4(mapped, allowLoopback);\n\tif (lower === \"::\" || lower === \"::1\") return false;\n\tconst firstHextet = lower.split(\":\")[0] || \"\";\n\tif (firstHextet.startsWith(\"fc\") || firstHextet.startsWith(\"fd\")) return false;\n\tif (firstHextet.startsWith(\"fe8\") || firstHextet.startsWith(\"fe9\")) return false;\n\tif (firstHextet.startsWith(\"fea\") || firstHextet.startsWith(\"feb\")) return false;\n\tif (firstHextet.startsWith(\"ff\")) return false;\n\treturn true;\n}\nexport { createPinnedLookup as a, SafeFetchError as i, DEFAULT_TIMEOUT_MS as n, safeFetch as o, ExternalUrlError as r, validateExternalUrl as s, DEFAULT_MAX_RESPONSE_BYTES as t };\n","import { t as NextlyError } from \"../nextly-error-C_MDZmJc.mjs\";\n// src/storage/read-errors.ts\n/**\n* The one way the storage layer says a read exceeded the caller's cap.\n*\n* `StorageReadOptions.maxBytes` is part of the adapter contract, so what happens\n* when it is exceeded belongs to the contract too. Without this each backend\n* refuses in its own vocabulary — the URL-addressed ones through a fetch error\n* carrying a `reason`, S3 through whatever its own code threw — and a caller\n* wanting to tell \"too large\" from \"could not read\" has to know which adapter it\n* is talking to. That is the thing an adapter contract exists to stop.\n*\n* Distinct from a generic internal failure because callers ACT on the\n* difference. The email attachment path answers an over-cap read with\n* `ATTACHMENT_SIZE_EXCEEDED`, which tells an author to attach something smaller;\n* a storage failure tells them nothing they can act on. Collapsing the two turns\n* a fixable refusal into an opaque error, which is the same conflation this\n* contract already draws between a missing key and an unreachable store.\n*\n* @module storage/read-errors\n*/\n/**\n* A read refused because the object is larger than the caller allowed.\n*\n* Carries the numbers rather than only a message, so a caller can say what the\n* limit was without parsing prose — and so the message itself stays free of the\n* key, which should not travel to whoever asked for the file.\n*/\nvar StorageReadTooLargeError = class extends NextlyError {\n\tpath;\n\tmaxBytes;\n\tsize;\n\tconstructor(path, maxBytes, size) {\n\t\tsuper({\n\t\t\tcode: \"STORAGE_READ_TOO_LARGE\",\n\t\t\tpublicMessage: \"The stored file is larger than the limit for this read.\",\n\t\t\tlogContext: {\n\t\t\t\tpath,\n\t\t\t\tmaxBytes,\n\t\t\t\t...size === void 0 ? {} : { size }\n\t\t\t}\n\t\t});\n\t\tthis.path = path;\n\t\tthis.maxBytes = maxBytes;\n\t\tthis.size = size;\n\t}\n};\n/**\n* Whether a thrown value is the over-cap refusal.\n*\n* A predicate rather than leaving every caller to write `instanceof`, because\n* this module can be loaded twice — a narrow entry point and a barrel are\n* different module instances, and `instanceof` across them is false for objects\n* that are otherwise identical. Callers that ask here cannot be caught by that.\n*/\nfunction isStorageReadTooLarge(error) {\n\treturn NextlyError.is(error) && error.code === \"STORAGE_READ_TOO_LARGE\";\n}\n/**\n* A read abandoned because the backend did not answer in time.\n*\n* Carried as the abort REASON rather than raised afterwards, which is what\n* makes it reach the caller at all: `AbortSignal.timeout` rejects with a\n* platform `DOMException`, and product code in this package answers in\n* `NextlyError` so a caller can classify what it caught without matching on a\n* name the runtime chose. `safeFetch` already aborts this way for the same\n* reason.\n*\n* Distinct from the over-cap refusal above by what each one KNOWS. The over-cap\n* refusal has measured the object and found it larger than the caller allowed.\n* This one knows only that the read did not finish in time: it may never have\n* opened the object, or may have taken some of it and been cut off part way, so\n* neither the object's size nor its existence follows from this error.\n*/\nvar StorageReadTimeoutError = class extends NextlyError {\n\tpath;\n\ttimeoutMs;\n\tconstructor(path, timeoutMs) {\n\t\tsuper({\n\t\t\tcode: \"STORAGE_READ_TIMEOUT\",\n\t\t\tpublicMessage: \"The stored file could not be read in time.\",\n\t\t\tlogContext: {\n\t\t\t\tpath,\n\t\t\t\ttimeoutMs\n\t\t\t}\n\t\t});\n\t\tthis.path = path;\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n};\n/**\n* Whether a thrown value is the deadline refusal.\n*\n* A predicate for the same reason as `isStorageReadTooLarge`: a narrow entry\n* point and a barrel are different module instances, and `instanceof` across\n* them is false for objects that are otherwise identical.\n*/\nfunction isStorageReadTimeout(error) {\n\treturn NextlyError.is(error) && error.code === \"STORAGE_READ_TIMEOUT\";\n}\nexport { StorageReadTimeoutError, StorageReadTooLargeError, isStorageReadTimeout, isStorageReadTooLarge };\n","import { t as NextlyError } from \"../nextly-error-C_MDZmJc.mjs\";\nimport { i as SafeFetchError, n as DEFAULT_TIMEOUT_MS, o as safeFetch, t as DEFAULT_MAX_RESPONSE_BYTES } from \"../validate-external-url-DF_HNT6F.mjs\";\nimport { StorageReadTimeoutError, StorageReadTooLargeError } from \"./read-errors.mjs\";\n// src/storage/fetch-stored-bytes.ts\n/**\n* Reading bytes back from a storage service that only exposes them over HTTP.\n*\n* The local adapter reads from disk and S3 reads through its own SDK, so\n* neither needs this. The services that address a file by URL — Vercel Blob,\n* UploadThing — all end up doing the same three things, and doing them the same\n* way matters more than it looks: each step below is a place where the obvious\n* shortcut reports the wrong thing to a caller who may act on it.\n*\n* Built on {@link safeFetch} rather than on a bare `fetch`, because \"read a\n* remote object into memory\" already has an implementation here that caps the\n* body, bounds the request and refuses an address that resolves somewhere\n* private. A second capped fetch beside it would be two answers to one\n* question, and the two would drift the first time either learned something.\n* Measured: it costs an adapter package about 80K, against the 1MB the whole\n* storage barrel costs.\n*\n* @module storage/fetch-stored-bytes\n*/\n/**\n* Fetch a stored object's bytes from the URL its service issued.\n*\n* Separates the two answers a read can have, which is the whole reason this is\n* a function rather than three lines inlined twice.\n*\n* `null` means the object is NOT THERE — an ordinary fact about the store. A\n* 404 is that answer even when the lookup just succeeded: these stores are\n* remote and concurrent, so an object can be deleted between resolving its\n* address and fetching it. Reporting that ordinary race as a server failure\n* would make a caller handle an error for something its own contract already\n* has a value for.\n*\n* Anything else THROWS. A dropped connection, a 5xx or a refused request says\n* nothing about whether the object exists, and reporting it as absence invites\n* a caller to treat a live file as deleted and write a replacement over it. The\n* two are easy to state apart and easy to lose when the fetch sits inside the\n* same `try` that catches the lookup.\n*\n* The URL is always one the SERVICE issued, never one assembled from a key.\n* These stores mint addresses carrying suffixes the adapter never chose, so a\n* derived URL is a guess at a string another system owns.\n*\n* @param url - The address the storage service reported for this object\n* @param context - What is being read, for the error message: usually the key\n* @param label - The service's name, so a failure says which store answered\n* @param options - Bounds for the read; see {@link StorageReadOptions}\n* @param signal - A deadline ALREADY RUNNING, covering an earlier phase too\n* @returns The object's bytes, or `null` when the store answers 404\n*/\nasync function fetchStoredBytes(url, context, label, options, signal) {\n\tlet response;\n\ttry {\n\t\tresponse = await safeFetch(url, {\n\t\t\t...options?.maxBytes === void 0 ? {} : { maxResponseBytes: options.maxBytes },\n\t\t\t...signal !== void 0 ? { signal } : options?.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }\n\t\t});\n\t} catch (error) {\n\t\tconst verdict = classifyFetchFailure(error);\n\t\tif (verdict === \"absent\") return null;\n\t\tif (verdict === \"oversized\") throw new StorageReadTooLargeError(context, resolveReadBounds(options).maxBytes);\n\t\tthrow error;\n\t}\n\tif (response.status === 404) return null;\n\tif (!response.ok) throw NextlyError.internal({ logContext: {\n\t\tservice: label,\n\t\tpath: context,\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText\n\t} });\n\treturn Buffer.from(await response.arrayBuffer());\n}\n/**\n* What a failed fetch actually says about the object.\n*\n* Its own function because the three answers are the whole point of this module\n* and they are easy to collapse into each other — each collapse having been a\n* real defect here rather than a hypothetical:\n*\n* - ABSENT. A 404 is absence whatever size its body was. `safeFetch` caps while\n* buffering, so a verbose CDN error page raises before a `Response` exists\n* and the status check further down is never reached; the object is still\n* gone, and must not become an error because the page explaining it was long.\n* - OVERSIZED. Only a SUCCESSFUL response that blew the cap. A failed response\n* can exceed it too, and translating on the reason alone reported a backend\n* outage as \"your file is too big\" — a cause the author would act on, wrongly.\n* - UNKNOWN. Everything else, including a too-large refusal carrying NO status:\n* that means the failure arrived before any status did, which says nothing\n* about whether the object was oversized.\n*/\nfunction classifyFetchFailure(error) {\n\tif (!(error instanceof SafeFetchError)) return \"unknown\";\n\tif (error.status === 404) return \"absent\";\n\tconst successful = error.status !== void 0 && error.status >= 200 && error.status < 300;\n\treturn error.reason === \"response-too-large\" && successful ? \"oversized\" : \"unknown\";\n}\n/** The deadline a stored read runs under when the caller names none. */\nconst DEFAULT_READ_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;\n/** The byte cap a stored read runs under when the caller names none. */\nconst DEFAULT_READ_MAX_BYTES = DEFAULT_MAX_RESPONSE_BYTES;\n/**\n* The bounds a read actually runs under, defaults filled in.\n*\n* ONE place, because every adapter needs the same answer and the ones that\n* derived it themselves diverged: the URL-backed pair inherited `safeFetch`'s\n* cap and deadline for free, while the local and S3 adapters — which never\n* touch `safeFetch` — applied NO bound at all when the caller named none.\n* `StorageReadOptions` promises the default either way, and a production caller\n* reading media without options got it from two of four backends.\n*\n* Filling the defaults here rather than per adapter is what makes the promise\n* true by construction rather than by four implementations agreeing.\n*/\nfunction resolveReadBounds(options) {\n\treturn {\n\t\tmaxBytes: options?.maxBytes ?? DEFAULT_READ_MAX_BYTES,\n\t\ttimeoutMs: options?.timeoutMs ?? DEFAULT_READ_TIMEOUT_MS\n\t};\n}\n/**\n* A deadline that aborts with a NextlyError rather than a platform exception.\n*\n* `AbortSignal.timeout` rejects with a `DOMException` named `TimeoutError`, and\n* product code in this package answers in `NextlyError` — so a caller can\n* classify what it caught rather than matching a name the runtime chose. Built\n* here rather than per adapter so every storage deadline says the same thing.\n*\n* The timer is unreferenced so a pending deadline is never a reason the process\n* stays alive, and the returned `cancel` clears it once the read settles — the\n* unref alone would leave one scheduled per read for the whole timeout.\n*\n* @param timeoutMs - How long the read may take\n* @param context - What is being read, carried into the refusal's log side\n*/\nfunction deadlineSignal(timeoutMs, context) {\n\tconst controller = new AbortController();\n\tconst timer = setTimeout(() => {\n\t\tcontroller.abort(new StorageReadTimeoutError(context, timeoutMs));\n\t}, timeoutMs);\n\ttimer.unref?.();\n\treturn {\n\t\tsignal: controller.signal,\n\t\tcancel: () => {\n\t\t\tclearTimeout(timer);\n\t\t}\n\t};\n}\n/**\n* Stop waiting on a promise once the deadline fires.\n*\n* For a lookup whose SDK cannot be cancelled. UploadThing 7.7.4's\n* `getFileUrls` reads only `keyType` and forwards no signal, so handing it one\n* bounds nothing — the option is accepted and ignored, which reads as covered\n* and behaves as absent.\n*\n* This RACES rather than cancels, and the difference is worth stating plainly:\n* the underlying request keeps running to completion in the background. What it\n* buys is that `read` returns within the deadline it advertised, instead of\n* holding its caller for as long as a stalled backend feels like. That is the\n* promise the contract actually makes; genuinely cancelling the work needs an\n* SDK that accepts cancellation, and this one does not.\n*/\nasync function withDeadline(work, signal) {\n\tif (signal === void 0) return await work;\n\treturn await Promise.race([work, new Promise((_, reject) => {\n\t\tif (signal.aborted) {\n\t\t\treject(signal.reason);\n\t\t\treturn;\n\t\t}\n\t\tsignal.addEventListener(\"abort\", () => reject(signal.reason), { once: true });\n\t})]);\n}\nexport { DEFAULT_READ_MAX_BYTES, DEFAULT_READ_TIMEOUT_MS, classifyFetchFailure, deadlineSignal, fetchStoredBytes, resolveReadBounds, withDeadline };\n","/**\n * S3 Storage Adapter\n *\n * Stores files on AWS S3 or S3-compatible services (Cloudflare R2, MinIO, DigitalOcean Spaces).\n * Uses AWS SDK v3 with automatic multipart upload for large files (>5MB).\n *\n * Features:\n * - Automatic multipart upload via @aws-sdk/lib-storage\n * - Pre-signed URL generation for client-side uploads\n * - Signed URL generation for private file access\n * - Cloudflare R2 support (S3-compatible API)\n * - Custom endpoint support (MinIO, DigitalOcean Spaces)\n * - CDN URL override support\n * - File metadata retrieval\n *\n * @example AWS S3\n * ```typescript\n * const adapter = new S3StorageAdapter({\n * bucket: 'my-media-bucket',\n * region: 'us-east-1',\n * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,\n * collections: { media: true }\n * });\n * ```\n *\n * @example Cloudflare R2\n * ```typescript\n * const adapter = new S3StorageAdapter({\n * bucket: 'my-media',\n * region: 'auto',\n * accessKeyId: process.env.R2_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,\n * endpoint: `https://${accountId}.r2.cloudflarestorage.com`,\n * publicUrl: 'https://pub-abc.r2.dev',\n * collections: { media: true }\n * });\n * ```\n *\n * @example MinIO (self-hosted)\n * ```typescript\n * const adapter = new S3StorageAdapter({\n * bucket: 'my-bucket',\n * region: 'us-east-1',\n * accessKeyId: process.env.MINIO_ACCESS_KEY!,\n * secretAccessKey: process.env.MINIO_SECRET_KEY!,\n * endpoint: 'http://localhost:9000',\n * forcePathStyle: true,\n * collections: { media: true }\n * });\n * ```\n */\n\nimport {\n S3Client,\n DeleteObjectCommand,\n DeleteObjectsCommand,\n ListObjectsV2Command,\n HeadObjectCommand,\n GetObjectCommand,\n PutObjectCommand,\n type PutObjectCommandInput,\n type GetObjectCommandOutput,\n} from \"@aws-sdk/client-s3\";\nimport { Upload } from \"@aws-sdk/lib-storage\";\nimport { getSignedUrl } from \"@aws-sdk/s3-request-presigner\";\nimport type {\n StorageReadOptions,\n IStorageAdapter,\n UploadOptions,\n UploadResult,\n StorageAdapterInfo,\n ClientUploadData,\n FileMetadata,\n BulkDeleteResult,\n StoredFileEntry,\n} from \"nextly/storage\";\nimport { resolveReadBounds } from \"nextly/storage/fetch-stored-bytes\";\nimport { StorageReadTooLargeError } from \"nextly/storage/read-errors\";\n\nimport type { S3StorageConfig, ResolvedS3Config } from \"./types\";\n\n// ============================================================\n// S3 Storage Adapter\n// ============================================================\n\n/**\n * S3 Storage Adapter\n *\n * Implements the IStorageAdapter interface for AWS S3 and S3-compatible services.\n * Provides full support for uploads, downloads, signed URLs, and client-side uploads.\n */\n/**\n * The SDK request options carrying the caller's deadline, or none.\n *\n * A free function rather than a branch inside `read`, because it is the only\n * part of that method with nothing to do with telling an absent key apart from\n * an unreachable bucket — which is the distinction a reader has to hold in\n * their head there.\n *\n * `AbortSignal.timeout` rather than a controller and a `setTimeout`: it needs no\n * clearing, so it cannot leak a timer when the read resolves first. The signal\n * covers the BODY as well as the request, because the SDK threads it through\n * the response stream — and a backend that answers headers promptly and then\n * stalls mid-transfer is exactly the case a request-only deadline misses.\n */\nfunction abortAfter(options?: StorageReadOptions): {\n abortSignal: AbortSignal;\n} {\n /*\n * ALWAYS a signal, defaulted through the shared resolver.\n * `StorageReadOptions` promises the deadline whether or not a caller names\n * one, and the URL-backed adapters keep that promise by inheriting\n * `safeFetch`'s. Returning nothing here left the no-options read — which is\n * what the media pipeline does — able to hang on a stalled bucket forever.\n */\n return {\n abortSignal: AbortSignal.timeout(resolveReadBounds(options).timeoutMs),\n };\n}\n\nexport class S3StorageAdapter implements IStorageAdapter {\n private client: S3Client | null = null;\n private resolvedConfig: ResolvedS3Config;\n private isR2: boolean;\n\n /**\n * Create a new S3 storage adapter.\n *\n * The bucket and region are deliberately NOT checked here, and the SDK\n * client is deliberately not built. This constructor runs while the host's\n * config file is evaluated, so a throw would stop every command —\n * including the schema-only ones that never touch storage. Both the checks\n * and the client construction move to the first storage operation\n * ({@link ensureClient} and {@link ensureConfigured}), which refuse with\n * the same messages a missing bucket or region has always produced.\n *\n * @param config - S3 storage configuration\n */\n constructor(private config: S3StorageConfig) {\n // Detect if this is Cloudflare R2\n this.isR2 = config.endpoint?.includes(\"r2.cloudflarestorage.com\") ?? false;\n\n // Resolve config with defaults\n this.resolvedConfig = {\n bucket: config.bucket,\n region: config.region,\n endpoint: config.endpoint,\n forcePathStyle: config.forcePathStyle ?? false,\n acl: config.acl ?? \"private\",\n publicUrl: config.publicUrl,\n cacheControl: config.cacheControl ?? \"public, max-age=31536000\",\n contentDisposition: config.contentDisposition,\n signedUrlExpiresIn: config.signedUrlExpiresIn ?? 3600,\n };\n }\n\n /**\n * Validate that bucket and region are present.\n *\n * @throws Error if bucket is not provided\n * @throws Error if region is not provided\n */\n private ensureConfigured(): void {\n if (!this.config.bucket) {\n throw new Error(\"@nextly/storage-s3: bucket is required\");\n }\n if (!this.config.region) {\n throw new Error(\"@nextly/storage-s3: region is required\");\n }\n }\n\n /**\n * Validate the stored configuration and build the SDK client, at the\n * first use that needs them.\n *\n * The refusals are the ones the constructor used to throw, in the same\n * order, so an operator with a genuinely misconfigured deployment sees\n * the message they have always seen — at the moment the value was\n * actually needed rather than at config load. The client is built once\n * and reused.\n *\n * @throws Error if bucket is not provided\n * @throws Error if region is not provided\n */\n private ensureClient(): S3Client {\n if (this.client) return this.client;\n\n this.ensureConfigured();\n\n // Build credentials\n const credentials = this.buildCredentials();\n\n this.client = new S3Client({\n region: this.config.region,\n endpoint: this.config.endpoint,\n credentials,\n forcePathStyle: this.resolvedConfig.forcePathStyle,\n ...this.config.config,\n });\n return this.client;\n }\n\n /**\n * Build AWS credentials from config.\n * Supports explicit credentials or falls back to SDK default chain.\n */\n private buildCredentials():\n | { accessKeyId: string; secretAccessKey: string }\n | undefined {\n if (this.config.accessKeyId && this.config.secretAccessKey) {\n return {\n accessKeyId: this.config.accessKeyId,\n secretAccessKey: this.config.secretAccessKey,\n };\n }\n\n // Check if credentials are in the config object\n if (this.config.config?.credentials) {\n return undefined; // Let SDK use the provided config.credentials\n }\n\n // Fall back to SDK default credential chain (env vars, IAM roles, etc.)\n return undefined;\n }\n\n // ============================================================\n // Core IStorageAdapter Methods\n // ============================================================\n\n /**\n * Upload file to S3.\n *\n * Uses AWS SDK v3's Upload class from @aws-sdk/lib-storage which:\n * - Automatically handles multipart upload for large files (>5MB)\n * - Provides progress tracking capability\n * - Includes retry logic\n * - Optimizes upload performance\n *\n * @param buffer - File content as Buffer\n * @param options - Upload options (filename, mimeType, folder, collection)\n * @returns Upload result with URL and storage path\n */\n async upload(buffer: Buffer, options: UploadOptions): Promise<UploadResult> {\n const client = this.ensureClient();\n const key = this.generateKey(options.filename, options.folder);\n\n // Build upload parameters\n const uploadParams: PutObjectCommandInput = {\n Bucket: this.resolvedConfig.bucket,\n Key: key,\n Body: buffer,\n ContentType: options.contentType || options.mimeType,\n CacheControl: this.resolvedConfig.cacheControl,\n };\n\n // Add ACL if not R2 (R2 ignores ACL settings)\n if (!this.isR2) {\n uploadParams.ACL = this.resolvedConfig.acl;\n }\n\n // Add Content-Disposition: per-file override takes priority, then global config\n const disposition =\n options.contentDisposition ?? this.resolvedConfig.contentDisposition;\n if (disposition) {\n const filename = this.sanitizeFilename(options.filename);\n uploadParams.ContentDisposition =\n disposition === \"attachment\"\n ? `attachment; filename=\"${filename}\"`\n : \"inline\";\n }\n\n // Store original filename in metadata for later retrieval\n uploadParams.Metadata = {\n \"original-filename\": options.filename,\n };\n\n // Use Upload for automatic multipart handling\n const upload = new Upload({\n client,\n params: uploadParams,\n });\n\n await upload.done();\n\n return {\n url: this.getPublicUrl(key),\n path: key,\n };\n }\n\n /**\n * Delete file from S3.\n *\n * @param filePath - Storage path/key to delete\n */\n async delete(filePath: string): Promise<void> {\n const client = this.ensureClient();\n const command = new DeleteObjectCommand({\n Bucket: this.resolvedConfig.bucket,\n Key: filePath,\n });\n\n await client.send(command);\n }\n\n /**\n * Bulk delete files from S3 using a single API call per 1000 keys.\n *\n * Uses AWS SDK v3's DeleteObjectsCommand which supports up to 1000 keys per\n * request. Automatically batches larger arrays and collects per-key results.\n *\n * @param filePaths - Storage paths/keys to delete\n * @returns Object with arrays of successful and failed deletions\n */\n async bulkDelete(filePaths: string[]): Promise<BulkDeleteResult> {\n const client = this.ensureClient();\n const successful: string[] = [];\n const failed: Array<{ filePath: string; error: string }> = [];\n const maxBatchSize = 1000; // AWS limit\n\n for (let i = 0; i < filePaths.length; i += maxBatchSize) {\n const batch = filePaths.slice(i, i + maxBatchSize);\n const command = new DeleteObjectsCommand({\n Bucket: this.resolvedConfig.bucket,\n Delete: {\n Objects: batch.map(key => ({ Key: key })),\n Quiet: false,\n },\n });\n\n const response = await client.send(command);\n\n if (response.Errors && response.Errors.length > 0) {\n for (const err of response.Errors) {\n if (err.Key) {\n failed.push({\n filePath: err.Key,\n error: err.Message ?? \"Unknown S3 delete error\",\n });\n }\n }\n }\n\n if (response.Deleted) {\n for (const del of response.Deleted) {\n if (del.Key) {\n successful.push(del.Key);\n }\n }\n }\n }\n\n return { successful, failed };\n }\n\n /**\n * Check if file exists in S3.\n *\n * Uses HeadObject command which is more efficient than GetObject\n * for existence checks (doesn't download the file).\n *\n * @param filePath - Storage path/key to check\n * @returns true if file exists, false otherwise\n */\n async exists(filePath: string): Promise<boolean> {\n const client = this.ensureClient();\n try {\n const command = new HeadObjectCommand({\n Bucket: this.resolvedConfig.bucket,\n Key: filePath,\n });\n\n await client.send(command);\n return true;\n } catch (error: unknown) {\n // HeadObject returns 404 if object doesn't exist\n if (this.isNotFoundError(error)) {\n return false;\n }\n // Re-throw other errors (permissions, network, etc.)\n throw error;\n }\n }\n\n /**\n * Get public URL for S3 file.\n *\n * Priority order:\n * 1. Custom publicUrl (CDN or custom domain) if configured\n * 2. Standard S3 URL based on region and bucket\n *\n * For R2: Requires publicUrl configuration (R2 has no default public URLs).\n *\n * @param filePath - Storage path/key\n * @returns Public URL to access the file\n * @throws Error if R2 is used without publicUrl configuration\n */\n /**\n * Every object in the bucket, by key, with when it was last written, a page\n * of up to 1,000 at a time.\n */\n async *list(): AsyncIterable<StoredFileEntry> {\n const client = this.ensureClient();\n let token: string | undefined;\n do {\n const page = await client.send(\n new ListObjectsV2Command({\n Bucket: this.resolvedConfig.bucket,\n ContinuationToken: token,\n })\n );\n for (const object of page.Contents ?? []) {\n if (object.Key) {\n yield { path: object.Key, lastModified: object.LastModified };\n }\n }\n token = page.IsTruncated ? page.NextContinuationToken : undefined;\n } while (token);\n }\n\n getPublicUrl(filePath: string): string {\n // A URL is derived from the bucket and region, so a missing one is\n // refused here exactly as an upload or read would refuse. A check-only\n // helper is used so forming a URL does not needlessly build the full\n // S3 client.\n this.ensureConfigured();\n\n // Use custom CDN/public URL if configured\n if (this.resolvedConfig.publicUrl) {\n const baseUrl = this.resolvedConfig.publicUrl.replace(/\\/$/, \"\");\n return `${baseUrl}/${filePath}`;\n }\n\n // R2 requires custom domain or public bucket URL\n if (this.isR2) {\n throw new Error(\n \"@nextly/storage-s3: Cloudflare R2 requires publicUrl configuration.\\n\\n\" +\n \"R2 does not have default public URLs like AWS S3. Configure one of:\\n\" +\n \"1. Public bucket URL: publicUrl: 'https://pub-xxx.r2.dev'\\n\" +\n \"2. Custom domain: publicUrl: 'https://cdn.example.com'\\n\\n\" +\n \"Set up public access in the Cloudflare R2 dashboard.\"\n );\n }\n\n // Standard S3 URL format\n // https://bucket.s3.region.amazonaws.com/key\n return `https://${this.resolvedConfig.bucket}.s3.${this.resolvedConfig.region}.amazonaws.com/${filePath}`;\n }\n\n /**\n * Get storage type identifier.\n *\n * Returns \"s3\" for all S3-compatible services (AWS S3, R2, MinIO, etc.)\n * as they all use the S3 API.\n */\n getType(): \"s3\" {\n return \"s3\";\n }\n\n // ============================================================\n // Optional IStorageAdapter Methods\n // ============================================================\n\n /**\n * Get adapter info including capabilities.\n *\n * @returns Adapter info with type, name, and capability flags\n */\n getInfo(): StorageAdapterInfo {\n return {\n type: \"s3\",\n name: \"S3StorageAdapter\",\n supportsSignedUrls: true,\n supportsClientUploads: true,\n };\n }\n\n /**\n * Get file metadata from S3.\n *\n * Retrieves file information including size, content type, and timestamps\n * using the HeadObject command.\n *\n * @param filePath - Storage path/key\n * @returns File metadata or null if file not found\n */\n async getMetadata(filePath: string): Promise<FileMetadata | null> {\n const client = this.ensureClient();\n try {\n const command = new HeadObjectCommand({\n Bucket: this.resolvedConfig.bucket,\n Key: filePath,\n });\n\n const response = await client.send(command);\n const filename = filePath.split(\"/\").pop() || filePath;\n\n return {\n id: filePath,\n filename,\n originalFilename: response.Metadata?.[\"original-filename\"] || filename,\n mimeType: response.ContentType || \"application/octet-stream\",\n size: response.ContentLength || 0,\n url: this.getPublicUrl(filePath),\n createdAt:\n response.LastModified?.toISOString() || new Date().toISOString(),\n };\n } catch (error: unknown) {\n if (this.isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Read a stored object back as bytes, or `null` when it is not there.\n *\n * The contract declares this OPTIONAL and, until now, no adapter supplied\n * it — so a caller reaching for `adapter.read` got `undefined` and fell\n * through whatever branch followed. An optional member nothing implements is\n * a contract that reads as a capability and behaves as an absence.\n *\n * BUFFERS rather than streams, because that is the declared return type and\n * widening it here would make this adapter answer a different question from\n * its siblings. That bounds what it should be used for: an asset the server\n * must serve from its own origin — a font file, a small document — rather\n * than arbitrarily large media, which belongs behind {@link getSignedUrl} or\n * a public URL. A streaming variant is a separate contract member, not a\n * quiet change to this one.\n *\n * `null` for a missing key rather than a throw, matching\n * {@link getMetadata}: absence is an ordinary answer about the bucket, while\n * a credential or network failure is not, so only the first is folded into\n * the return value.\n *\n * @param filePath - Storage path/key\n * @returns The object's bytes, or `null` when no such key exists\n */\n async read(\n filePath: string,\n options?: StorageReadOptions\n ): Promise<Buffer | null> {\n const client = this.ensureClient();\n try {\n const command = new GetObjectCommand({\n Bucket: this.resolvedConfig.bucket,\n Key: filePath,\n });\n\n /*\n * The caller's deadline reaches the SDK, or it is advertised and inert.\n * `StorageReadOptions` promises a bound, and the URL-backed adapters keep\n * it by handing `timeoutMs` to `safeFetch`; without this the same option\n * does nothing here, so a stalled bucket holds the read open past a\n * deadline the caller was told applied — the worst kind of option, one\n * that validates and then has no effect.\n *\n * Aborting covers the BODY as well as the request. `transformToByteArray`\n * pulls the stream after `send` resolves, and a backend that answers\n * headers promptly and then stalls mid-transfer is exactly the case a\n * request-only timeout misses.\n */\n const response = await client.send(command, abortAfter(options));\n /*\n * An empty body is not a missing object, and the two must not collapse.\n * `GetObject` on a zero-byte key succeeds with no stream to transform,\n * so returning `null` here would report a stored empty file as absent —\n * and a caller deleting \"missing\" keys would then delete a real one.\n */\n if (response.Body === undefined) return Buffer.alloc(0);\n\n /*\n * Refused on the LENGTH the store reports, before the body is pulled\n * down. `transformToByteArray` buffers the whole object, so a caller that\n * knows its own limit has to be able to stop an oversized read rather\n * than discover the size after paying for it — which is what an\n * attachment path does when it checks a size only after buffering.\n */\n const cap = resolveReadBounds(options).maxBytes;\n // Cheap refusal first, where the store told us the size up front.\n this.refuseOverCap(filePath, response.ContentLength, cap);\n return await this.readCapped(filePath, response.Body, cap);\n } catch (error: unknown) {\n /*\n * Only an OBJECT-level absence becomes `null`. `isNotFoundError` treats\n * any 404 as missing, and `NoSuchBucket` is a 404 — so a bucket that was\n * deleted, renamed or mistyped would report every key in it as absent,\n * which is the configuration failure this method's contract exists to\n * tell apart from an ordinary miss. Named explicitly rather than by\n * status, because the status cannot separate them.\n */\n if (error instanceof Error && error.name === \"NoSuchBucket\") throw error;\n if (this.isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Generate signed URL for temporary private file access.\n *\n * Creates a pre-signed GetObject URL that grants temporary read access\n * to private files. Useful for serving files from private buckets.\n *\n * @param filePath - Storage path/key\n * @param expiresIn - URL validity duration in seconds (default: 3600)\n * @returns Pre-signed URL for downloading the file\n */\n async getSignedUrl(filePath: string, expiresIn?: number): Promise<string> {\n const client = this.ensureClient();\n const command = new GetObjectCommand({\n Bucket: this.resolvedConfig.bucket,\n Key: filePath,\n });\n\n return getSignedUrl(client, command, {\n expiresIn: expiresIn ?? this.resolvedConfig.signedUrlExpiresIn,\n });\n }\n\n /**\n * Generate pre-signed URL for client-side uploads.\n *\n * Creates a pre-signed PutObject URL that allows direct uploads from\n * the browser to S3, bypassing server-side upload limits (e.g., Vercel's 4.5MB).\n *\n * The signature covers the `Content-Type` and, given `options.contentLength`,\n * the `Content-Length`: the bytes never pass Nextly's upload checks, so S3\n * itself refuses a body of another type or length. The browser sets the\n * length from the body; it is not a header the client sends.\n *\n * @param key - Storage path/key for the upload\n * @param mimeType - MIME type of the file being uploaded\n * @param expiresIn - URL validity in seconds, at most the configured\n * `signedUrlExpiresIn` (its default)\n * @param options - `contentLength`: the exact size the upload may have\n * @returns Client upload data with URL, method, and headers\n */\n async getPresignedUploadUrl(\n key: string,\n mimeType: string,\n expiresIn?: number,\n options?: { contentLength?: number }\n ): Promise<ClientUploadData> {\n const client = this.ensureClient();\n const longest = this.resolvedConfig.signedUrlExpiresIn;\n const expiration = Math.min(expiresIn ?? longest, longest);\n\n // Build PutObject command parameters\n const commandParams: PutObjectCommandInput = {\n Bucket: this.resolvedConfig.bucket,\n Key: key,\n ContentType: mimeType,\n CacheControl: this.resolvedConfig.cacheControl,\n ...(options?.contentLength !== undefined\n ? { ContentLength: options.contentLength }\n : {}),\n };\n\n // Add ACL if not R2\n if (!this.isR2) {\n commandParams.ACL = this.resolvedConfig.acl;\n }\n\n const command = new PutObjectCommand(commandParams);\n\n const uploadUrl = await getSignedUrl(client, command, {\n expiresIn: expiration,\n // Signed, so S3 refuses an upload whose type or length differs.\n signableHeaders: new Set([\"content-type\", \"content-length\"]),\n });\n\n return {\n uploadUrl,\n path: key,\n method: \"PUT\",\n headers: {\n \"Content-Type\": mimeType,\n },\n expiresAt: new Date(Date.now() + expiration * 1000),\n };\n }\n\n // ============================================================\n // Helper Methods\n // ============================================================\n\n /**\n * Generate a unique storage key with date-based prefix.\n *\n * Creates keys in format: {folder}/{year}/{month}/{uuid}-{sanitized-filename}\n *\n * @param filename - Original filename (will be sanitized)\n * @param folder - Optional folder/prefix for organizing uploads\n * @returns Generated storage key\n */\n private generateKey(filename: string, folder?: string): string {\n const sanitized = this.sanitizeFilename(filename);\n const uuid = crypto.randomUUID();\n const date = new Date();\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n\n const prefix = folder ? `${folder}/${year}/${month}` : `${year}/${month}`;\n\n return `${prefix}/${uuid}-${sanitized}`;\n }\n\n /**\n * Sanitize filename to prevent directory traversal and S3 key issues.\n *\n * @param filename - Original filename\n * @returns Sanitized filename safe for S3 keys\n */\n private sanitizeFilename(filename: string): string {\n const basename = filename.split(/[/\\\\]/).pop() || filename;\n return basename.replace(/[^a-zA-Z0-9._-]/g, \"-\");\n }\n\n /**\n * Check if an error is a \"not found\" error from S3.\n *\n * @param error - Error to check\n * @returns true if error indicates file not found\n */\n /**\n * The object's bytes, refusing once more than `cap` have actually arrived.\n *\n * `ContentLength` is OPTIONAL in the SDK's response type, and this adapter\n * explicitly supports MinIO, R2 and other compatible services — any of which\n * may omit it or report it wrongly. A preflight check against metadata is\n * therefore a courtesy that fails OPEN: trusting it alone leaves the cap\n * unenforced exactly where an unusual backend is involved, which is where a\n * caller most needs it.\n *\n * Counted while consuming, so an oversized body is abandoned partway rather\n * than after it has all been buffered — the cap exists to bound memory, and\n * one applied after `transformToByteArray` has already spent it.\n *\n * Falls back to buffering when the body is not async-iterable, which the SDK\n * types permit. Stated rather than hidden: on that path the cap bounds what a\n * caller RECEIVES rather than what the process allocates.\n */\n private async readCapped(\n filePath: string,\n body: NonNullable<GetObjectCommandOutput[\"Body\"]>,\n cap: number\n ): Promise<Buffer> {\n /*\n * Probed rather than assumed. The SDK types the body as a union whose Node\n * member is async-iterable and whose browser members are not, and this\n * package supports compatible services whose transport may differ — so the\n * capability is read off the value in hand instead of from the type.\n */\n const iterable = body as Partial<AsyncIterable<Uint8Array>>;\n if (typeof iterable[Symbol.asyncIterator] !== \"function\") {\n const whole = Buffer.from(await body.transformToByteArray());\n if (whole.byteLength > cap) {\n throw new StorageReadTooLargeError(filePath, cap, whole.byteLength);\n }\n return whole;\n }\n\n const chunks: Buffer[] = [];\n let received = 0;\n for await (const chunk of body as AsyncIterable<Uint8Array>) {\n received += chunk.byteLength;\n if (received > cap) {\n throw new StorageReadTooLargeError(filePath, cap, received);\n }\n chunks.push(Buffer.from(chunk));\n }\n return Buffer.concat(chunks);\n }\n\n /**\n * Refuse a read whose object is already known to exceed the caller's cap.\n *\n * Its own method rather than three conditions inside `read`, because the\n * decision has nothing to do with the surrounding error handling and reads\n * as noise there — and because `read`'s branching is the part a reviewer has\n * to hold in their head to check the absent-versus-unavailable distinction.\n *\n * Both `undefined` cases mean \"no opinion\" and pass: a caller that named no\n * cap has none, and a store that reported no length gives nothing to compare.\n * The second is deliberately permissive — refusing an unmeasured object would\n * reject valid reads whenever S3 omits the header.\n */\n private refuseOverCap(\n filePath: string,\n declared: number | undefined,\n cap: number | undefined\n ): void {\n if (cap === undefined || declared === undefined || declared <= cap) return;\n /*\n * The SHARED refusal rather than a generic internal error, because callers\n * act on the difference. The email attachment path answers an over-cap read\n * with a size error the author can do something about; anything else is\n * wrapped as an opaque storage failure, so throwing `internal` here would\n * turn a fixable refusal into one that tells them nothing.\n */\n throw new StorageReadTooLargeError(filePath, cap, declared);\n }\n\n private isNotFoundError(error: unknown): boolean {\n if (error && typeof error === \"object\") {\n const e = error as {\n name?: string;\n $metadata?: { httpStatusCode?: number };\n };\n return e.name === \"NotFound\" || e.$metadata?.httpStatusCode === 404;\n }\n return false;\n }\n\n // ============================================================\n // Public Accessors\n // ============================================================\n\n /**\n * Get the S3 client instance.\n * Useful for advanced operations not covered by the adapter interface.\n *\n * Handing out the client is itself a use of the adapter, so a caller\n * without the configuration a client needs is refused here like any\n * other operation.\n */\n getClient(): S3Client {\n return this.ensureClient();\n }\n\n /**\n * Get the bucket name.\n */\n getBucket(): string {\n return this.resolvedConfig.bucket;\n }\n\n /**\n * Get the AWS region.\n */\n getRegion(): string {\n return this.resolvedConfig.region;\n }\n\n /**\n * Check if this adapter is configured for Cloudflare R2.\n */\n isCloudflareR2(): boolean {\n return this.isR2;\n }\n}\n","/**\n * S3 Storage Plugin\n *\n * Factory function that creates a storage plugin for AWS S3 and S3-compatible services.\n * Returns a StoragePlugin that can be registered with MediaStorage.\n *\n * @example Basic usage with AWS S3\n * ```typescript\n * import { s3Storage } from '@nextly/storage-s3'\n * import { defineConfig } from 'nextly/config'\n *\n * export default defineConfig({\n * storage: [\n * s3Storage({\n * bucket: process.env.S3_BUCKET!,\n * region: process.env.AWS_REGION!,\n * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,\n * collections: {\n * media: true\n * }\n * })\n * ]\n * })\n * ```\n *\n * @example With Cloudflare R2\n * ```typescript\n * s3Storage({\n * bucket: process.env.R2_BUCKET!,\n * region: 'auto',\n * accessKeyId: process.env.R2_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,\n * endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,\n * publicUrl: process.env.R2_PUBLIC_URL,\n * collections: { media: true }\n * })\n * ```\n *\n * @example With collection-specific configuration\n * ```typescript\n * s3Storage({\n * bucket: 'my-bucket',\n * region: 'us-east-1',\n * collections: {\n * // Simple enable with defaults\n * media: true,\n *\n * // Full configuration for private documents\n * 'private-docs': {\n * prefix: 'private/',\n * clientUploads: true,\n * signedDownloads: true,\n * signedUrlExpiresIn: 3600\n * }\n * }\n * })\n * ```\n *\n * @packageDocumentation\n */\n\nimport type {\n ClientUploadData,\n ClientUploadOptions,\n StoragePlugin,\n} from \"nextly/storage\";\n\nimport { S3StorageAdapter } from \"./adapter\";\nimport type { S3StorageConfig } from \"./types\";\n\n// ============================================================\n// Plugin Factory Function\n// ============================================================\n\n/**\n * Create an S3 storage plugin for Nextly.\n *\n * This factory function creates a StoragePlugin that can be added to\n * the `storage` array in `nextly.config.ts`. It supports:\n *\n * - AWS S3 (standard)\n * - Cloudflare R2 (S3-compatible)\n * - MinIO (S3-compatible, self-hosted)\n * - DigitalOcean Spaces (S3-compatible)\n * - Any other S3-compatible service\n *\n * @param config - S3 storage configuration\n * @returns A StoragePlugin that MediaStorage can register\n *\n * Constructing the plugin never requires the bucket or region: a missing\n * one is refused when storage is first used, not while the config loads.\n */\nexport function s3Storage(config: S3StorageConfig): StoragePlugin {\n // Handle disabled plugin\n // When disabled, return a plugin with no collections and null adapter\n // MediaStorage.registerPlugin() checks for null adapter and skips registration\n if (config.enabled === false) {\n return {\n name: \"s3-storage\",\n type: \"s3\",\n collections: {},\n adapter: null as unknown as StoragePlugin[\"adapter\"],\n };\n }\n\n // Create the S3 adapter\n // Adapter constructor validates required config (bucket, region)\n const adapter = new S3StorageAdapter(config);\n\n // Build and return the plugin\n const plugin: StoragePlugin = {\n name: \"s3-storage\",\n type: \"s3\",\n collections: config.collections,\n adapter,\n\n /**\n * Generate a pre-signed URL for client-side uploads.\n *\n * This allows files to be uploaded directly from the browser to S3,\n * bypassing server-side upload limits (e.g., Vercel's 4.5MB limit).\n *\n * @param filename - Original filename from the client\n * @param mimeType - MIME type of the file\n * @param collection - Collection slug this upload belongs to\n * @param options - The file's exact size, and the URL's lifetime\n * @returns Client upload data with pre-signed URL\n */\n async getClientUploadUrl(\n filename: string,\n mimeType: string,\n collection: string,\n options?: ClientUploadOptions\n ): Promise<ClientUploadData> {\n // Get collection-specific configuration\n const collectionConfig = config.collections[collection];\n const prefix =\n typeof collectionConfig === \"object\"\n ? collectionConfig.prefix\n : undefined;\n\n // Generate storage key matching adapter's format\n // Format: {prefix}{year}/{month}/{uuid}-{sanitized-filename}\n const key = generateStorageKey(filename, prefix);\n\n // Get pre-signed upload URL from adapter\n // Bound to the exact size, so S3 refuses any other file.\n return adapter.getPresignedUploadUrl(key, mimeType, options?.expiresIn, {\n contentLength: options?.size,\n });\n },\n\n /**\n * Generate a signed URL for private file downloads.\n *\n * Creates a time-limited URL for accessing files in private buckets.\n * Only works when collection has `signedDownloads: true`.\n *\n * @param path - Storage path/key of the file\n * @param expiresIn - URL validity duration in seconds\n * @returns Signed URL for downloading the file\n */\n async getSignedDownloadUrl(\n path: string,\n expiresIn?: number\n ): Promise<string> {\n return adapter.getSignedUrl(\n path,\n expiresIn ?? config.signedUrlExpiresIn ?? 3600\n );\n },\n };\n\n return plugin;\n}\n\n// ============================================================\n// Helper Functions\n// ============================================================\n\n/**\n * Generate a unique storage key with date-based prefix.\n *\n * Creates keys in format: {prefix}{year}/{month}/{uuid}-{sanitized-filename}\n * This matches the format used by S3StorageAdapter for consistency.\n *\n * @param filename - Original filename (will be sanitized)\n * @param prefix - Optional folder/prefix for organizing uploads\n * @returns Generated storage key\n */\nfunction generateStorageKey(filename: string, prefix?: string): string {\n const sanitized = sanitizeFilename(filename);\n const uuid = crypto.randomUUID();\n const date = new Date();\n const year = date.getFullYear();\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n\n const keyPrefix = prefix ? `${prefix}${year}/${month}` : `${year}/${month}`;\n\n return `${keyPrefix}/${uuid}-${sanitized}`;\n}\n\n/**\n * Sanitize filename to prevent directory traversal and S3 key issues.\n *\n * Removes path separators and replaces unsafe characters with hyphens.\n * Keeps only: a-z, A-Z, 0-9, dot, underscore, hyphen\n *\n * @param filename - Original filename\n * @returns Sanitized filename safe for S3 keys\n */\nfunction sanitizeFilename(filename: string): string {\n // Extract basename (remove any path components)\n const basename = filename.split(/[/\\\\]/).pop() || filename;\n // Replace unsafe characters with hyphens\n return basename.replace(/[^a-zA-Z0-9._-]/g, \"-\");\n}\n","/**\n * @nextly/storage-s3\n *\n * AWS S3 storage adapter for Nextly CMS.\n * Also works with S3-compatible services like Cloudflare R2, MinIO, and DigitalOcean Spaces.\n *\n * @example Basic usage with AWS S3\n * ```typescript\n * import { s3Storage } from '@nextly/storage-s3'\n * import { defineConfig } from 'nextly/config'\n *\n * export default defineConfig({\n * storage: [\n * s3Storage({\n * bucket: process.env.S3_BUCKET!,\n * region: process.env.AWS_REGION!,\n * accessKeyId: process.env.AWS_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,\n * collections: {\n * media: true\n * }\n * })\n * ]\n * })\n * ```\n *\n * @example With Cloudflare R2\n * ```typescript\n * s3Storage({\n * bucket: process.env.R2_BUCKET!,\n * region: 'auto',\n * accessKeyId: process.env.R2_ACCESS_KEY_ID!,\n * secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,\n * endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,\n * publicUrl: process.env.R2_PUBLIC_URL,\n * collections: { media: true }\n * })\n * ```\n *\n * @example With MinIO\n * ```typescript\n * s3Storage({\n * bucket: 'my-bucket',\n * region: 'us-east-1',\n * accessKeyId: process.env.MINIO_ACCESS_KEY!,\n * secretAccessKey: process.env.MINIO_SECRET_KEY!,\n * endpoint: 'http://localhost:9000',\n * forcePathStyle: true,\n * collections: { media: true }\n * })\n * ```\n *\n * @packageDocumentation\n */\n\n// ============================================================\n// S3 Storage Plugin Export (Primary API)\n// ============================================================\n\nexport { s3Storage } from \"./plugin\";\n\n// ============================================================\n// S3 Storage Adapter Export\n// ============================================================\n\nexport { S3StorageAdapter } from \"./adapter\";\n\n// ============================================================\n// S3 Types Export\n// ============================================================\n\nexport type {\n S3StorageConfig,\n S3ObjectACL,\n S3CollectionConfig,\n S3CollectionStorageMap,\n ResolvedS3Config,\n} from \"./types\";\n\n// ============================================================\n// Package Metadata\n// ============================================================\n\nexport const PACKAGE_NAME = \"@nextly/storage-s3\";\nexport const PACKAGE_VERSION = \"0.1.0\";\n"],"mappings":";;;;;AAmCA,SAAS,UAAU,KAAK;CACvB,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO;CAC5C,MAAM,MAAM;CACZ,OAAO,IAAI,SAAS,aAAa,OAAO,IAAI,SAAS;AACtD;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,SAAS,WAAW,MAAM;CACzB,IAAI,SAAS,KAAK,GAAG,OAAO;CAC5B,OAAO,SAAS,8BAA8B,KAAK,YAAY,CAAC,CAAC,WAAW,aAAa;AAC1F;;;;;;;;;;AAUA,SAAS,eAAe,OAAO;CAC9B,IAAI,UAAU,KAAK,GAAG,OAAO,MAAM,SAAS;CAC5C,OAAO,WAAW,SAAS,KAAK,CAAC;AAClC;AAIA,SAAS,SAAS,OAAO;CACxB,IAAI,CAAC,SAAS,OAAO,U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