commerce-kit 0.67.0 → 0.67.1

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,"sources":["../node_modules/is-buffer/index.js","../node_modules/@vercel/oidc/dist/get-context.js","../node_modules/jose/dist/browser/runtime/webcrypto.js","../node_modules/jose/dist/browser/runtime/digest.js","../node_modules/jose/dist/browser/lib/buffer_utils.js","../node_modules/jose/dist/browser/runtime/base64url.js","../node_modules/jose/dist/browser/util/errors.js","../node_modules/jose/dist/browser/runtime/random.js","../node_modules/jose/dist/browser/lib/iv.js","../node_modules/jose/dist/browser/lib/check_iv_length.js","../node_modules/jose/dist/browser/runtime/check_cek_length.js","../node_modules/jose/dist/browser/runtime/timing_safe_equal.js","../node_modules/jose/dist/browser/lib/crypto_key.js","../node_modules/jose/dist/browser/lib/invalid_key_input.js","../node_modules/jose/dist/browser/runtime/is_key_like.js","../node_modules/jose/dist/browser/runtime/decrypt.js","../node_modules/jose/dist/browser/lib/is_disjoint.js","../node_modules/jose/dist/browser/lib/is_object.js","../node_modules/jose/dist/browser/runtime/bogus.js","../node_modules/jose/dist/browser/runtime/aeskw.js","../node_modules/jose/dist/browser/runtime/ecdhes.js","../node_modules/jose/dist/browser/lib/check_p2s.js","../node_modules/jose/dist/browser/runtime/pbes2kw.js","../node_modules/jose/dist/browser/runtime/subtle_rsaes.js","../node_modules/jose/dist/browser/runtime/check_key_length.js","../node_modules/jose/dist/browser/runtime/rsaes.js","../node_modules/jose/dist/browser/lib/is_jwk.js","../node_modules/jose/dist/browser/runtime/jwk_to_key.js","../node_modules/jose/dist/browser/runtime/normalize_key.js","../node_modules/jose/dist/browser/lib/cek.js","../node_modules/jose/dist/browser/lib/format_pem.js","../node_modules/jose/dist/browser/runtime/asn1.js","../node_modules/jose/dist/browser/key/import.js","../node_modules/jose/dist/browser/lib/check_key_type.js","../node_modules/jose/dist/browser/runtime/encrypt.js","../node_modules/jose/dist/browser/lib/aesgcmkw.js","../node_modules/jose/dist/browser/lib/decrypt_key_management.js","../node_modules/jose/dist/browser/lib/validate_crit.js","../node_modules/jose/dist/browser/lib/validate_algorithms.js","../node_modules/jose/dist/browser/jwe/flattened/decrypt.js","../node_modules/jose/dist/browser/jwe/compact/decrypt.js","../node_modules/jose/dist/browser/jwe/general/decrypt.js","../node_modules/jose/dist/browser/lib/private_symbols.js","../node_modules/jose/dist/browser/runtime/key_to_jwk.js","../node_modules/jose/dist/browser/key/export.js","../node_modules/jose/dist/browser/lib/encrypt_key_management.js","../node_modules/jose/dist/browser/jwe/flattened/encrypt.js","../node_modules/jose/dist/browser/jwe/general/encrypt.js","../node_modules/jose/dist/browser/runtime/subtle_dsa.js","../node_modules/jose/dist/browser/runtime/get_sign_verify_key.js","../node_modules/jose/dist/browser/runtime/verify.js","../node_modules/jose/dist/browser/jws/flattened/verify.js","../node_modules/jose/dist/browser/jws/compact/verify.js","../node_modules/jose/dist/browser/jws/general/verify.js","../node_modules/jose/dist/browser/lib/epoch.js","../node_modules/jose/dist/browser/lib/secs.js","../node_modules/jose/dist/browser/lib/jwt_claims_set.js","../node_modules/jose/dist/browser/jwt/verify.js","../node_modules/jose/dist/browser/jwt/decrypt.js","../node_modules/jose/dist/browser/jwe/compact/encrypt.js","../node_modules/jose/dist/browser/runtime/sign.js","../node_modules/jose/dist/browser/jws/flattened/sign.js","../node_modules/jose/dist/browser/jws/compact/sign.js","../node_modules/jose/dist/browser/jws/general/sign.js","../node_modules/jose/dist/browser/jwt/produce.js","../node_modules/jose/dist/browser/jwt/sign.js","../node_modules/jose/dist/browser/jwt/encrypt.js","../node_modules/jose/dist/browser/jwk/thumbprint.js","../node_modules/jose/dist/browser/jwk/embedded.js","../node_modules/jose/dist/browser/jwks/local.js","../node_modules/jose/dist/browser/runtime/fetch_jwks.js","../node_modules/jose/dist/browser/jwks/remote.js","../node_modules/jose/dist/browser/jwt/unsecured.js","../node_modules/jose/dist/browser/util/base64url.js","../node_modules/jose/dist/browser/util/decode_protected_header.js","../node_modules/jose/dist/browser/util/decode_jwt.js","../node_modules/jose/dist/browser/runtime/generate.js","../node_modules/jose/dist/browser/key/generate_key_pair.js","../node_modules/jose/dist/browser/key/generate_secret.js","../node_modules/jose/dist/browser/runtime/runtime.js","../node_modules/jose/dist/browser/util/runtime.js","../node_modules/jose/dist/browser/index.js","../node_modules/@vercel/oidc/dist/verify-vercel-oidc-token.js","../node_modules/@vercel/oidc/dist/auth-errors.js","../node_modules/@vercel/oidc/dist/index-browser.js","../node_modules/retry/lib/retry_operation.js","../node_modules/retry/lib/retry.js","../node_modules/retry/index.js","../node_modules/async-retry/lib/index.js","../node_modules/throttleit/index.js","../node_modules/is-node-process/src/index.ts","../node_modules/@vercel/blob/src/helpers.ts","../node_modules/@vercel/blob/src/multipart/helpers.ts","../node_modules/@vercel/blob/src/vercel-oidc-token.ts","../node_modules/@vercel/blob/src/bytes.ts","../node_modules/@vercel/blob/src/api.ts","../node_modules/@vercel/blob/src/debug.ts","../node_modules/@vercel/blob/src/dom-exception.ts","../node_modules/@vercel/blob/src/is-network-error.ts","../node_modules/@vercel/blob/src/fetch.ts","../node_modules/@vercel/blob/src/xhr.ts","../node_modules/@vercel/blob/src/request.ts","../node_modules/@vercel/blob/src/put-helpers.ts","../node_modules/@vercel/blob/src/multipart/complete.ts","../node_modules/@vercel/blob/src/multipart/create.ts","../node_modules/@vercel/blob/src/multipart/upload.ts","../node_modules/@vercel/blob/src/multipart/create-uploader.ts","../node_modules/@vercel/blob/src/put.ts","../node_modules/@vercel/blob/src/multipart/uncontrolled.ts","../node_modules/@vercel/blob/src/presign-query-params.ts","../node_modules/@vercel/blob/src/signed-token.ts","../node_modules/@vercel/blob/src/create-folder.ts","../node_modules/@vercel/blob/dist/stream-browser.js","../node_modules/@vercel/blob/dist/undici-browser.js","../node_modules/@vercel/blob/src/client.ts","../src/uploads.ts"],"sourcesContent":["/*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh <https://feross.org>\n * @license MIT\n */\n\nmodule.exports = function isBuffer (obj) {\n return obj != null && obj.constructor != null &&\n typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar get_context_exports = {};\n__export(get_context_exports, {\n SYMBOL_FOR_REQ_CONTEXT: () => SYMBOL_FOR_REQ_CONTEXT,\n getContext: () => getContext\n});\nmodule.exports = __toCommonJS(get_context_exports);\nconst SYMBOL_FOR_REQ_CONTEXT = Symbol.for(\"@vercel/request-context\");\nfunction getContext() {\n const fromSymbol = globalThis;\n return fromSymbol[SYMBOL_FOR_REQ_CONTEXT]?.get?.() ?? {};\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n SYMBOL_FOR_REQ_CONTEXT,\n getContext\n});\n","export default crypto;\nexport const isCryptoKey = (key) => key instanceof CryptoKey;\n","import crypto from './webcrypto.js';\nconst digest = async (algorithm, data) => {\n const subtleDigest = `SHA-${algorithm.slice(-3)}`;\n return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));\n};\nexport default digest;\n","import digest from '../runtime/digest.js';\nexport const encoder = new TextEncoder();\nexport const decoder = new TextDecoder();\nconst MAX_INT32 = 2 ** 32;\nexport function concat(...buffers) {\n const size = buffers.reduce((acc, { length }) => acc + length, 0);\n const buf = new Uint8Array(size);\n let i = 0;\n for (const buffer of buffers) {\n buf.set(buffer, i);\n i += buffer.length;\n }\n return buf;\n}\nexport function p2s(alg, p2sInput) {\n return concat(encoder.encode(alg), new Uint8Array([0]), p2sInput);\n}\nfunction writeUInt32BE(buf, value, offset) {\n if (value < 0 || value >= MAX_INT32) {\n throw new RangeError(`value must be >= 0 and <= ${MAX_INT32 - 1}. Received ${value}`);\n }\n buf.set([value >>> 24, value >>> 16, value >>> 8, value & 0xff], offset);\n}\nexport function uint64be(value) {\n const high = Math.floor(value / MAX_INT32);\n const low = value % MAX_INT32;\n const buf = new Uint8Array(8);\n writeUInt32BE(buf, high, 0);\n writeUInt32BE(buf, low, 4);\n return buf;\n}\nexport function uint32be(value) {\n const buf = new Uint8Array(4);\n writeUInt32BE(buf, value);\n return buf;\n}\nexport function lengthAndInput(input) {\n return concat(uint32be(input.length), input);\n}\nexport async function concatKdf(secret, bits, value) {\n const iterations = Math.ceil((bits >> 3) / 32);\n const res = new Uint8Array(iterations * 32);\n for (let iter = 0; iter < iterations; iter++) {\n const buf = new Uint8Array(4 + secret.length + value.length);\n buf.set(uint32be(iter + 1));\n buf.set(secret, 4);\n buf.set(value, 4 + secret.length);\n res.set(await digest('sha256', buf), iter * 32);\n }\n return res.slice(0, bits >> 3);\n}\n","import { encoder, decoder } from '../lib/buffer_utils.js';\nexport const encodeBase64 = (input) => {\n let unencoded = input;\n if (typeof unencoded === 'string') {\n unencoded = encoder.encode(unencoded);\n }\n const CHUNK_SIZE = 0x8000;\n const arr = [];\n for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) {\n arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE)));\n }\n return btoa(arr.join(''));\n};\nexport const encode = (input) => {\n return encodeBase64(input).replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n};\nexport const decodeBase64 = (encoded) => {\n const binary = atob(encoded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n};\nexport const decode = (input) => {\n let encoded = input;\n if (encoded instanceof Uint8Array) {\n encoded = decoder.decode(encoded);\n }\n encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\\s/g, '');\n try {\n return decodeBase64(encoded);\n }\n catch {\n throw new TypeError('The input to be decoded is not correctly encoded.');\n }\n};\n","export class JOSEError extends Error {\n constructor(message, options) {\n super(message, options);\n this.code = 'ERR_JOSE_GENERIC';\n this.name = this.constructor.name;\n Error.captureStackTrace?.(this, this.constructor);\n }\n}\nJOSEError.code = 'ERR_JOSE_GENERIC';\nexport class JWTClaimValidationFailed extends JOSEError {\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nJWTClaimValidationFailed.code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';\nexport class JWTExpired extends JOSEError {\n constructor(message, payload, claim = 'unspecified', reason = 'unspecified') {\n super(message, { cause: { claim, reason, payload } });\n this.code = 'ERR_JWT_EXPIRED';\n this.claim = claim;\n this.reason = reason;\n this.payload = payload;\n }\n}\nJWTExpired.code = 'ERR_JWT_EXPIRED';\nexport class JOSEAlgNotAllowed extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JOSE_ALG_NOT_ALLOWED';\n }\n}\nJOSEAlgNotAllowed.code = 'ERR_JOSE_ALG_NOT_ALLOWED';\nexport class JOSENotSupported extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JOSE_NOT_SUPPORTED';\n }\n}\nJOSENotSupported.code = 'ERR_JOSE_NOT_SUPPORTED';\nexport class JWEDecryptionFailed extends JOSEError {\n constructor(message = 'decryption operation failed', options) {\n super(message, options);\n this.code = 'ERR_JWE_DECRYPTION_FAILED';\n }\n}\nJWEDecryptionFailed.code = 'ERR_JWE_DECRYPTION_FAILED';\nexport class JWEInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWE_INVALID';\n }\n}\nJWEInvalid.code = 'ERR_JWE_INVALID';\nexport class JWSInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWS_INVALID';\n }\n}\nJWSInvalid.code = 'ERR_JWS_INVALID';\nexport class JWTInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWT_INVALID';\n }\n}\nJWTInvalid.code = 'ERR_JWT_INVALID';\nexport class JWKInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWK_INVALID';\n }\n}\nJWKInvalid.code = 'ERR_JWK_INVALID';\nexport class JWKSInvalid extends JOSEError {\n constructor() {\n super(...arguments);\n this.code = 'ERR_JWKS_INVALID';\n }\n}\nJWKSInvalid.code = 'ERR_JWKS_INVALID';\nexport class JWKSNoMatchingKey extends JOSEError {\n constructor(message = 'no applicable key found in the JSON Web Key Set', options) {\n super(message, options);\n this.code = 'ERR_JWKS_NO_MATCHING_KEY';\n }\n}\nJWKSNoMatchingKey.code = 'ERR_JWKS_NO_MATCHING_KEY';\nexport class JWKSMultipleMatchingKeys extends JOSEError {\n constructor(message = 'multiple matching keys found in the JSON Web Key Set', options) {\n super(message, options);\n this.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\n }\n}\nSymbol.asyncIterator;\nJWKSMultipleMatchingKeys.code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';\nexport class JWKSTimeout extends JOSEError {\n constructor(message = 'request timed out', options) {\n super(message, options);\n this.code = 'ERR_JWKS_TIMEOUT';\n }\n}\nJWKSTimeout.code = 'ERR_JWKS_TIMEOUT';\nexport class JWSSignatureVerificationFailed extends JOSEError {\n constructor(message = 'signature verification failed', options) {\n super(message, options);\n this.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n }\n}\nJWSSignatureVerificationFailed.code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';\n","import crypto from './webcrypto.js';\nexport default crypto.getRandomValues.bind(crypto);\n","import { JOSENotSupported } from '../util/errors.js';\nimport random from '../runtime/random.js';\nexport function bitLength(alg) {\n switch (alg) {\n case 'A128GCM':\n case 'A128GCMKW':\n case 'A192GCM':\n case 'A192GCMKW':\n case 'A256GCM':\n case 'A256GCMKW':\n return 96;\n case 'A128CBC-HS256':\n case 'A192CBC-HS384':\n case 'A256CBC-HS512':\n return 128;\n default:\n throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);\n }\n}\nexport default (alg) => random(new Uint8Array(bitLength(alg) >> 3));\n","import { JWEInvalid } from '../util/errors.js';\nimport { bitLength } from './iv.js';\nconst checkIvLength = (enc, iv) => {\n if (iv.length << 3 !== bitLength(enc)) {\n throw new JWEInvalid('Invalid Initialization Vector length');\n }\n};\nexport default checkIvLength;\n","import { JWEInvalid } from '../util/errors.js';\nconst checkCekLength = (cek, expected) => {\n const actual = cek.byteLength << 3;\n if (actual !== expected) {\n throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);\n }\n};\nexport default checkCekLength;\n","const timingSafeEqual = (a, b) => {\n if (!(a instanceof Uint8Array)) {\n throw new TypeError('First argument must be a buffer');\n }\n if (!(b instanceof Uint8Array)) {\n throw new TypeError('Second argument must be a buffer');\n }\n if (a.length !== b.length) {\n throw new TypeError('Input buffers must have the same length');\n }\n const len = a.length;\n let out = 0;\n let i = -1;\n while (++i < len) {\n out |= a[i] ^ b[i];\n }\n return out === 0;\n};\nexport default timingSafeEqual;\n","function unusable(name, prop = 'algorithm.name') {\n return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);\n}\nfunction isAlgorithm(algorithm, name) {\n return algorithm.name === name;\n}\nfunction getHashLength(hash) {\n return parseInt(hash.name.slice(4), 10);\n}\nfunction getNamedCurve(alg) {\n switch (alg) {\n case 'ES256':\n return 'P-256';\n case 'ES384':\n return 'P-384';\n case 'ES512':\n return 'P-521';\n default:\n throw new Error('unreachable');\n }\n}\nfunction checkUsage(key, usages) {\n if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {\n let msg = 'CryptoKey does not support this operation, its usages must include ';\n if (usages.length > 2) {\n const last = usages.pop();\n msg += `one of ${usages.join(', ')}, or ${last}.`;\n }\n else if (usages.length === 2) {\n msg += `one of ${usages[0]} or ${usages[1]}.`;\n }\n else {\n msg += `${usages[0]}.`;\n }\n throw new TypeError(msg);\n }\n}\nexport function checkSigCryptoKey(key, alg, ...usages) {\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512': {\n if (!isAlgorithm(key.algorithm, 'HMAC'))\n throw unusable('HMAC');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'RS256':\n case 'RS384':\n case 'RS512': {\n if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5'))\n throw unusable('RSASSA-PKCS1-v1_5');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'PS256':\n case 'PS384':\n case 'PS512': {\n if (!isAlgorithm(key.algorithm, 'RSA-PSS'))\n throw unusable('RSA-PSS');\n const expected = parseInt(alg.slice(2), 10);\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n case 'EdDSA': {\n if (key.algorithm.name !== 'Ed25519' && key.algorithm.name !== 'Ed448') {\n throw unusable('Ed25519 or Ed448');\n }\n break;\n }\n case 'Ed25519': {\n if (!isAlgorithm(key.algorithm, 'Ed25519'))\n throw unusable('Ed25519');\n break;\n }\n case 'ES256':\n case 'ES384':\n case 'ES512': {\n if (!isAlgorithm(key.algorithm, 'ECDSA'))\n throw unusable('ECDSA');\n const expected = getNamedCurve(alg);\n const actual = key.algorithm.namedCurve;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.namedCurve');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usages);\n}\nexport function checkEncCryptoKey(key, alg, ...usages) {\n switch (alg) {\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM': {\n if (!isAlgorithm(key.algorithm, 'AES-GCM'))\n throw unusable('AES-GCM');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n if (!isAlgorithm(key.algorithm, 'AES-KW'))\n throw unusable('AES-KW');\n const expected = parseInt(alg.slice(1, 4), 10);\n const actual = key.algorithm.length;\n if (actual !== expected)\n throw unusable(expected, 'algorithm.length');\n break;\n }\n case 'ECDH': {\n switch (key.algorithm.name) {\n case 'ECDH':\n case 'X25519':\n case 'X448':\n break;\n default:\n throw unusable('ECDH, X25519, or X448');\n }\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW':\n if (!isAlgorithm(key.algorithm, 'PBKDF2'))\n throw unusable('PBKDF2');\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n if (!isAlgorithm(key.algorithm, 'RSA-OAEP'))\n throw unusable('RSA-OAEP');\n const expected = parseInt(alg.slice(9), 10) || 1;\n const actual = getHashLength(key.algorithm.hash);\n if (actual !== expected)\n throw unusable(`SHA-${expected}`, 'algorithm.hash');\n break;\n }\n default:\n throw new TypeError('CryptoKey does not support this operation');\n }\n checkUsage(key, usages);\n}\n","function message(msg, actual, ...types) {\n types = types.filter(Boolean);\n if (types.length > 2) {\n const last = types.pop();\n msg += `one of type ${types.join(', ')}, or ${last}.`;\n }\n else if (types.length === 2) {\n msg += `one of type ${types[0]} or ${types[1]}.`;\n }\n else {\n msg += `of type ${types[0]}.`;\n }\n if (actual == null) {\n msg += ` Received ${actual}`;\n }\n else if (typeof actual === 'function' && actual.name) {\n msg += ` Received function ${actual.name}`;\n }\n else if (typeof actual === 'object' && actual != null) {\n if (actual.constructor?.name) {\n msg += ` Received an instance of ${actual.constructor.name}`;\n }\n }\n return msg;\n}\nexport default (actual, ...types) => {\n return message('Key must be ', actual, ...types);\n};\nexport function withAlg(alg, actual, ...types) {\n return message(`Key for the ${alg} algorithm must be `, actual, ...types);\n}\n","import { isCryptoKey } from './webcrypto.js';\nexport default (key) => {\n if (isCryptoKey(key)) {\n return true;\n }\n return key?.[Symbol.toStringTag] === 'KeyObject';\n};\nexport const types = ['CryptoKey'];\n","import { concat, uint64be } from '../lib/buffer_utils.js';\nimport checkIvLength from '../lib/check_iv_length.js';\nimport checkCekLength from './check_cek_length.js';\nimport timingSafeEqual from './timing_safe_equal.js';\nimport { JOSENotSupported, JWEDecryptionFailed, JWEInvalid } from '../util/errors.js';\nimport crypto, { isCryptoKey } from './webcrypto.js';\nimport { checkEncCryptoKey } from '../lib/crypto_key.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nasync function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {\n if (!(cek instanceof Uint8Array)) {\n throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));\n }\n const keySize = parseInt(enc.slice(1, 4), 10);\n const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['decrypt']);\n const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {\n hash: `SHA-${keySize << 1}`,\n name: 'HMAC',\n }, false, ['sign']);\n const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));\n const expectedTag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));\n let macCheckPassed;\n try {\n macCheckPassed = timingSafeEqual(tag, expectedTag);\n }\n catch {\n }\n if (!macCheckPassed) {\n throw new JWEDecryptionFailed();\n }\n let plaintext;\n try {\n plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv, name: 'AES-CBC' }, encKey, ciphertext));\n }\n catch {\n }\n if (!plaintext) {\n throw new JWEDecryptionFailed();\n }\n return plaintext;\n}\nasync function gcmDecrypt(enc, cek, ciphertext, iv, tag, aad) {\n let encKey;\n if (cek instanceof Uint8Array) {\n encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['decrypt']);\n }\n else {\n checkEncCryptoKey(cek, enc, 'decrypt');\n encKey = cek;\n }\n try {\n return new Uint8Array(await crypto.subtle.decrypt({\n additionalData: aad,\n iv,\n name: 'AES-GCM',\n tagLength: 128,\n }, encKey, concat(ciphertext, tag)));\n }\n catch {\n throw new JWEDecryptionFailed();\n }\n}\nconst decrypt = async (enc, cek, ciphertext, iv, tag, aad) => {\n if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {\n throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array'));\n }\n if (!iv) {\n throw new JWEInvalid('JWE Initialization Vector missing');\n }\n if (!tag) {\n throw new JWEInvalid('JWE Authentication Tag missing');\n }\n checkIvLength(enc, iv);\n switch (enc) {\n case 'A128CBC-HS256':\n case 'A192CBC-HS384':\n case 'A256CBC-HS512':\n if (cek instanceof Uint8Array)\n checkCekLength(cek, parseInt(enc.slice(-3), 10));\n return cbcDecrypt(enc, cek, ciphertext, iv, tag, aad);\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM':\n if (cek instanceof Uint8Array)\n checkCekLength(cek, parseInt(enc.slice(1, 4), 10));\n return gcmDecrypt(enc, cek, ciphertext, iv, tag, aad);\n default:\n throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');\n }\n};\nexport default decrypt;\n","const isDisjoint = (...headers) => {\n const sources = headers.filter(Boolean);\n if (sources.length === 0 || sources.length === 1) {\n return true;\n }\n let acc;\n for (const header of sources) {\n const parameters = Object.keys(header);\n if (!acc || acc.size === 0) {\n acc = new Set(parameters);\n continue;\n }\n for (const parameter of parameters) {\n if (acc.has(parameter)) {\n return false;\n }\n acc.add(parameter);\n }\n }\n return true;\n};\nexport default isDisjoint;\n","function isObjectLike(value) {\n return typeof value === 'object' && value !== null;\n}\nexport default function isObject(input) {\n if (!isObjectLike(input) || Object.prototype.toString.call(input) !== '[object Object]') {\n return false;\n }\n if (Object.getPrototypeOf(input) === null) {\n return true;\n }\n let proto = input;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(input) === proto;\n}\n","const bogusWebCrypto = [\n { hash: 'SHA-256', name: 'HMAC' },\n true,\n ['sign'],\n];\nexport default bogusWebCrypto;\n","import bogusWebCrypto from './bogus.js';\nimport crypto, { isCryptoKey } from './webcrypto.js';\nimport { checkEncCryptoKey } from '../lib/crypto_key.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nfunction checkKeySize(key, alg) {\n if (key.algorithm.length !== parseInt(alg.slice(1, 4), 10)) {\n throw new TypeError(`Invalid key size for alg: ${alg}`);\n }\n}\nfunction getCryptoKey(key, alg, usage) {\n if (isCryptoKey(key)) {\n checkEncCryptoKey(key, alg, usage);\n return key;\n }\n if (key instanceof Uint8Array) {\n return crypto.subtle.importKey('raw', key, 'AES-KW', true, [usage]);\n }\n throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));\n}\nexport const wrap = async (alg, key, cek) => {\n const cryptoKey = await getCryptoKey(key, alg, 'wrapKey');\n checkKeySize(cryptoKey, alg);\n const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto);\n return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, cryptoKey, 'AES-KW'));\n};\nexport const unwrap = async (alg, key, encryptedKey) => {\n const cryptoKey = await getCryptoKey(key, alg, 'unwrapKey');\n checkKeySize(cryptoKey, alg);\n const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, cryptoKey, 'AES-KW', ...bogusWebCrypto);\n return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));\n};\n","import { encoder, concat, uint32be, lengthAndInput, concatKdf } from '../lib/buffer_utils.js';\nimport crypto, { isCryptoKey } from './webcrypto.js';\nimport { checkEncCryptoKey } from '../lib/crypto_key.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nexport async function deriveKey(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(0), apv = new Uint8Array(0)) {\n if (!isCryptoKey(publicKey)) {\n throw new TypeError(invalidKeyInput(publicKey, ...types));\n }\n checkEncCryptoKey(publicKey, 'ECDH');\n if (!isCryptoKey(privateKey)) {\n throw new TypeError(invalidKeyInput(privateKey, ...types));\n }\n checkEncCryptoKey(privateKey, 'ECDH', 'deriveBits');\n const value = concat(lengthAndInput(encoder.encode(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength));\n let length;\n if (publicKey.algorithm.name === 'X25519') {\n length = 256;\n }\n else if (publicKey.algorithm.name === 'X448') {\n length = 448;\n }\n else {\n length =\n Math.ceil(parseInt(publicKey.algorithm.namedCurve.substr(-3), 10) / 8) <<\n 3;\n }\n const sharedSecret = new Uint8Array(await crypto.subtle.deriveBits({\n name: publicKey.algorithm.name,\n public: publicKey,\n }, privateKey, length));\n return concatKdf(sharedSecret, keyLength, value);\n}\nexport async function generateEpk(key) {\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n return crypto.subtle.generateKey(key.algorithm, true, ['deriveBits']);\n}\nexport function ecdhAllowed(key) {\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n return (['P-256', 'P-384', 'P-521'].includes(key.algorithm.namedCurve) ||\n key.algorithm.name === 'X25519' ||\n key.algorithm.name === 'X448');\n}\n","import { JWEInvalid } from '../util/errors.js';\nexport default function checkP2s(p2s) {\n if (!(p2s instanceof Uint8Array) || p2s.length < 8) {\n throw new JWEInvalid('PBES2 Salt Input must be 8 or more octets');\n }\n}\n","import random from './random.js';\nimport { p2s as concatSalt } from '../lib/buffer_utils.js';\nimport { encode as base64url } from './base64url.js';\nimport { wrap, unwrap } from './aeskw.js';\nimport checkP2s from '../lib/check_p2s.js';\nimport crypto, { isCryptoKey } from './webcrypto.js';\nimport { checkEncCryptoKey } from '../lib/crypto_key.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nfunction getCryptoKey(key, alg) {\n if (key instanceof Uint8Array) {\n return crypto.subtle.importKey('raw', key, 'PBKDF2', false, ['deriveBits']);\n }\n if (isCryptoKey(key)) {\n checkEncCryptoKey(key, alg, 'deriveBits', 'deriveKey');\n return key;\n }\n throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));\n}\nasync function deriveKey(p2s, alg, p2c, key) {\n checkP2s(p2s);\n const salt = concatSalt(alg, p2s);\n const keylen = parseInt(alg.slice(13, 16), 10);\n const subtleAlg = {\n hash: `SHA-${alg.slice(8, 11)}`,\n iterations: p2c,\n name: 'PBKDF2',\n salt,\n };\n const wrapAlg = {\n length: keylen,\n name: 'AES-KW',\n };\n const cryptoKey = await getCryptoKey(key, alg);\n if (cryptoKey.usages.includes('deriveBits')) {\n return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));\n }\n if (cryptoKey.usages.includes('deriveKey')) {\n return crypto.subtle.deriveKey(subtleAlg, cryptoKey, wrapAlg, false, ['wrapKey', 'unwrapKey']);\n }\n throw new TypeError('PBKDF2 key \"usages\" must include \"deriveBits\" or \"deriveKey\"');\n}\nexport const encrypt = async (alg, key, cek, p2c = 2048, p2s = random(new Uint8Array(16))) => {\n const derived = await deriveKey(p2s, alg, p2c, key);\n const encryptedKey = await wrap(alg.slice(-6), derived, cek);\n return { encryptedKey, p2c, p2s: base64url(p2s) };\n};\nexport const decrypt = async (alg, key, encryptedKey, p2c, p2s) => {\n const derived = await deriveKey(p2s, alg, p2c, key);\n return unwrap(alg.slice(-6), derived, encryptedKey);\n};\n","import { JOSENotSupported } from '../util/errors.js';\nexport default function subtleRsaEs(alg) {\n switch (alg) {\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n return 'RSA-OAEP';\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n}\n","export default (alg, key) => {\n if (alg.startsWith('RS') || alg.startsWith('PS')) {\n const { modulusLength } = key.algorithm;\n if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);\n }\n }\n};\n","import subtleAlgorithm from './subtle_rsaes.js';\nimport bogusWebCrypto from './bogus.js';\nimport crypto, { isCryptoKey } from './webcrypto.js';\nimport { checkEncCryptoKey } from '../lib/crypto_key.js';\nimport checkKeyLength from './check_key_length.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nexport const encrypt = async (alg, key, cek) => {\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n checkEncCryptoKey(key, alg, 'encrypt', 'wrapKey');\n checkKeyLength(alg, key);\n if (key.usages.includes('encrypt')) {\n return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm(alg), key, cek));\n }\n if (key.usages.includes('wrapKey')) {\n const cryptoKeyCek = await crypto.subtle.importKey('raw', cek, ...bogusWebCrypto);\n return new Uint8Array(await crypto.subtle.wrapKey('raw', cryptoKeyCek, key, subtleAlgorithm(alg)));\n }\n throw new TypeError('RSA-OAEP key \"usages\" must include \"encrypt\" or \"wrapKey\" for this operation');\n};\nexport const decrypt = async (alg, key, encryptedKey) => {\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n checkEncCryptoKey(key, alg, 'decrypt', 'unwrapKey');\n checkKeyLength(alg, key);\n if (key.usages.includes('decrypt')) {\n return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm(alg), key, encryptedKey));\n }\n if (key.usages.includes('unwrapKey')) {\n const cryptoKeyCek = await crypto.subtle.unwrapKey('raw', encryptedKey, key, subtleAlgorithm(alg), ...bogusWebCrypto);\n return new Uint8Array(await crypto.subtle.exportKey('raw', cryptoKeyCek));\n }\n throw new TypeError('RSA-OAEP key \"usages\" must include \"decrypt\" or \"unwrapKey\" for this operation');\n};\n","import isObject from './is_object.js';\nexport function isJWK(key) {\n return isObject(key) && typeof key.kty === 'string';\n}\nexport function isPrivateJWK(key) {\n return key.kty !== 'oct' && typeof key.d === 'string';\n}\nexport function isPublicJWK(key) {\n return key.kty !== 'oct' && typeof key.d === 'undefined';\n}\nexport function isSecretJWK(key) {\n return isJWK(key) && key.kty === 'oct' && typeof key.k === 'string';\n}\n","import crypto from './webcrypto.js';\nimport { JOSENotSupported } from '../util/errors.js';\nfunction subtleMapping(jwk) {\n let algorithm;\n let keyUsages;\n switch (jwk.kty) {\n case 'RSA': {\n switch (jwk.alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${jwk.alg.slice(-3)}` };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`,\n };\n keyUsages = jwk.d ? ['decrypt', 'unwrapKey'] : ['encrypt', 'wrapKey'];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n case 'EC': {\n switch (jwk.alg) {\n case 'ES256':\n algorithm = { name: 'ECDSA', namedCurve: 'P-256' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ES384':\n algorithm = { name: 'ECDSA', namedCurve: 'P-384' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ES512':\n algorithm = { name: 'ECDSA', namedCurve: 'P-521' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: 'ECDH', namedCurve: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n case 'OKP': {\n switch (jwk.alg) {\n case 'Ed25519':\n algorithm = { name: 'Ed25519' };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'EdDSA':\n algorithm = { name: jwk.crv };\n keyUsages = jwk.d ? ['sign'] : ['verify'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW':\n algorithm = { name: jwk.crv };\n keyUsages = jwk.d ? ['deriveBits'] : [];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n break;\n }\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"kty\" (Key Type) Parameter value');\n }\n return { algorithm, keyUsages };\n}\nconst parse = async (jwk) => {\n if (!jwk.alg) {\n throw new TypeError('\"alg\" argument is required when \"jwk.alg\" is not present');\n }\n const { algorithm, keyUsages } = subtleMapping(jwk);\n const rest = [\n algorithm,\n jwk.ext ?? false,\n jwk.key_ops ?? keyUsages,\n ];\n const keyData = { ...jwk };\n delete keyData.alg;\n delete keyData.use;\n return crypto.subtle.importKey('jwk', keyData, ...rest);\n};\nexport default parse;\n","import { isJWK } from '../lib/is_jwk.js';\nimport { decode } from './base64url.js';\nimport importJWK from './jwk_to_key.js';\nconst exportKeyValue = (k) => decode(k);\nlet privCache;\nlet pubCache;\nconst isKeyObject = (key) => {\n return key?.[Symbol.toStringTag] === 'KeyObject';\n};\nconst importAndCache = async (cache, key, jwk, alg, freeze = false) => {\n let cached = cache.get(key);\n if (cached?.[alg]) {\n return cached[alg];\n }\n const cryptoKey = await importJWK({ ...jwk, alg });\n if (freeze)\n Object.freeze(key);\n if (!cached) {\n cache.set(key, { [alg]: cryptoKey });\n }\n else {\n cached[alg] = cryptoKey;\n }\n return cryptoKey;\n};\nconst normalizePublicKey = (key, alg) => {\n if (isKeyObject(key)) {\n let jwk = key.export({ format: 'jwk' });\n delete jwk.d;\n delete jwk.dp;\n delete jwk.dq;\n delete jwk.p;\n delete jwk.q;\n delete jwk.qi;\n if (jwk.k) {\n return exportKeyValue(jwk.k);\n }\n pubCache || (pubCache = new WeakMap());\n return importAndCache(pubCache, key, jwk, alg);\n }\n if (isJWK(key)) {\n if (key.k)\n return decode(key.k);\n pubCache || (pubCache = new WeakMap());\n const cryptoKey = importAndCache(pubCache, key, key, alg, true);\n return cryptoKey;\n }\n return key;\n};\nconst normalizePrivateKey = (key, alg) => {\n if (isKeyObject(key)) {\n let jwk = key.export({ format: 'jwk' });\n if (jwk.k) {\n return exportKeyValue(jwk.k);\n }\n privCache || (privCache = new WeakMap());\n return importAndCache(privCache, key, jwk, alg);\n }\n if (isJWK(key)) {\n if (key.k)\n return decode(key.k);\n privCache || (privCache = new WeakMap());\n const cryptoKey = importAndCache(privCache, key, key, alg, true);\n return cryptoKey;\n }\n return key;\n};\nexport default { normalizePublicKey, normalizePrivateKey };\n","import { JOSENotSupported } from '../util/errors.js';\nimport random from '../runtime/random.js';\nexport function bitLength(alg) {\n switch (alg) {\n case 'A128GCM':\n return 128;\n case 'A192GCM':\n return 192;\n case 'A256GCM':\n case 'A128CBC-HS256':\n return 256;\n case 'A192CBC-HS384':\n return 384;\n case 'A256CBC-HS512':\n return 512;\n default:\n throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`);\n }\n}\nexport default (alg) => random(new Uint8Array(bitLength(alg) >> 3));\n","export default (b64, descriptor) => {\n const newlined = (b64.match(/.{1,64}/g) || []).join('\\n');\n return `-----BEGIN ${descriptor}-----\\n${newlined}\\n-----END ${descriptor}-----`;\n};\n","import crypto, { isCryptoKey } from './webcrypto.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { encodeBase64, decodeBase64 } from './base64url.js';\nimport formatPEM from '../lib/format_pem.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { types } from './is_key_like.js';\nconst genericExport = async (keyType, keyFormat, key) => {\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n if (!key.extractable) {\n throw new TypeError('CryptoKey is not extractable');\n }\n if (key.type !== keyType) {\n throw new TypeError(`key is not a ${keyType} key`);\n }\n return formatPEM(encodeBase64(new Uint8Array(await crypto.subtle.exportKey(keyFormat, key))), `${keyType.toUpperCase()} KEY`);\n};\nexport const toSPKI = (key) => {\n return genericExport('public', 'spki', key);\n};\nexport const toPKCS8 = (key) => {\n return genericExport('private', 'pkcs8', key);\n};\nconst findOid = (keyData, oid, from = 0) => {\n if (from === 0) {\n oid.unshift(oid.length);\n oid.unshift(0x06);\n }\n const i = keyData.indexOf(oid[0], from);\n if (i === -1)\n return false;\n const sub = keyData.subarray(i, i + oid.length);\n if (sub.length !== oid.length)\n return false;\n return sub.every((value, index) => value === oid[index]) || findOid(keyData, oid, i + 1);\n};\nconst getNamedCurve = (keyData) => {\n switch (true) {\n case findOid(keyData, [0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07]):\n return 'P-256';\n case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x22]):\n return 'P-384';\n case findOid(keyData, [0x2b, 0x81, 0x04, 0x00, 0x23]):\n return 'P-521';\n case findOid(keyData, [0x2b, 0x65, 0x6e]):\n return 'X25519';\n case findOid(keyData, [0x2b, 0x65, 0x6f]):\n return 'X448';\n case findOid(keyData, [0x2b, 0x65, 0x70]):\n return 'Ed25519';\n case findOid(keyData, [0x2b, 0x65, 0x71]):\n return 'Ed448';\n default:\n throw new JOSENotSupported('Invalid or unsupported EC Key Curve or OKP Key Sub Type');\n }\n};\nconst genericImport = async (replace, keyFormat, pem, alg, options) => {\n let algorithm;\n let keyUsages;\n const keyData = new Uint8Array(atob(pem.replace(replace, ''))\n .split('')\n .map((c) => c.charCodeAt(0)));\n const isPublic = keyFormat === 'spki';\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = { name: 'RSA-PSS', hash: `SHA-${alg.slice(-3)}` };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = { name: 'RSASSA-PKCS1-v1_5', hash: `SHA-${alg.slice(-3)}` };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,\n };\n keyUsages = isPublic ? ['encrypt', 'wrapKey'] : ['decrypt', 'unwrapKey'];\n break;\n case 'ES256':\n algorithm = { name: 'ECDSA', namedCurve: 'P-256' };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'ES384':\n algorithm = { name: 'ECDSA', namedCurve: 'P-384' };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'ES512':\n algorithm = { name: 'ECDSA', namedCurve: 'P-521' };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n const namedCurve = getNamedCurve(keyData);\n algorithm = namedCurve.startsWith('P-') ? { name: 'ECDH', namedCurve } : { name: namedCurve };\n keyUsages = isPublic ? [] : ['deriveBits'];\n break;\n }\n case 'Ed25519':\n algorithm = { name: 'Ed25519' };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n case 'EdDSA':\n algorithm = { name: getNamedCurve(keyData) };\n keyUsages = isPublic ? ['verify'] : ['sign'];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported \"alg\" (Algorithm) value');\n }\n return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? false, keyUsages);\n};\nexport const fromPKCS8 = (pem, alg, options) => {\n return genericImport(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\\s)/g, 'pkcs8', pem, alg, options);\n};\nexport const fromSPKI = (pem, alg, options) => {\n return genericImport(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\\s)/g, 'spki', pem, alg, options);\n};\nfunction getElement(seq) {\n const result = [];\n let next = 0;\n while (next < seq.length) {\n const nextPart = parseElement(seq.subarray(next));\n result.push(nextPart);\n next += nextPart.byteLength;\n }\n return result;\n}\nfunction parseElement(bytes) {\n let position = 0;\n let tag = bytes[0] & 0x1f;\n position++;\n if (tag === 0x1f) {\n tag = 0;\n while (bytes[position] >= 0x80) {\n tag = tag * 128 + bytes[position] - 0x80;\n position++;\n }\n tag = tag * 128 + bytes[position] - 0x80;\n position++;\n }\n let length = 0;\n if (bytes[position] < 0x80) {\n length = bytes[position];\n position++;\n }\n else if (length === 0x80) {\n length = 0;\n while (bytes[position + length] !== 0 || bytes[position + length + 1] !== 0) {\n if (length > bytes.byteLength) {\n throw new TypeError('invalid indefinite form length');\n }\n length++;\n }\n const byteLength = position + length + 2;\n return {\n byteLength,\n contents: bytes.subarray(position, position + length),\n raw: bytes.subarray(0, byteLength),\n };\n }\n else {\n const numberOfDigits = bytes[position] & 0x7f;\n position++;\n length = 0;\n for (let i = 0; i < numberOfDigits; i++) {\n length = length * 256 + bytes[position];\n position++;\n }\n }\n const byteLength = position + length;\n return {\n byteLength,\n contents: bytes.subarray(position, byteLength),\n raw: bytes.subarray(0, byteLength),\n };\n}\nfunction spkiFromX509(buf) {\n const tbsCertificate = getElement(getElement(parseElement(buf).contents)[0].contents);\n return encodeBase64(tbsCertificate[tbsCertificate[0].raw[0] === 0xa0 ? 6 : 5].raw);\n}\nfunction getSPKI(x509) {\n const pem = x509.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\\s)/g, '');\n const raw = decodeBase64(pem);\n return formatPEM(spkiFromX509(raw), 'PUBLIC KEY');\n}\nexport const fromX509 = (pem, alg, options) => {\n let spki;\n try {\n spki = getSPKI(pem);\n }\n catch (cause) {\n throw new TypeError('Failed to parse the X.509 certificate', { cause });\n }\n return fromSPKI(spki, alg, options);\n};\n","import { decode as decodeBase64URL } from '../runtime/base64url.js';\nimport { fromSPKI, fromPKCS8, fromX509 } from '../runtime/asn1.js';\nimport asKeyObject from '../runtime/jwk_to_key.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport isObject from '../lib/is_object.js';\nexport async function importSPKI(spki, alg, options) {\n if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {\n throw new TypeError('\"spki\" must be SPKI formatted string');\n }\n return fromSPKI(spki, alg, options);\n}\nexport async function importX509(x509, alg, options) {\n if (typeof x509 !== 'string' || x509.indexOf('-----BEGIN CERTIFICATE-----') !== 0) {\n throw new TypeError('\"x509\" must be X.509 formatted string');\n }\n return fromX509(x509, alg, options);\n}\nexport async function importPKCS8(pkcs8, alg, options) {\n if (typeof pkcs8 !== 'string' || pkcs8.indexOf('-----BEGIN PRIVATE KEY-----') !== 0) {\n throw new TypeError('\"pkcs8\" must be PKCS#8 formatted string');\n }\n return fromPKCS8(pkcs8, alg, options);\n}\nexport async function importJWK(jwk, alg) {\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n alg || (alg = jwk.alg);\n switch (jwk.kty) {\n case 'oct':\n if (typeof jwk.k !== 'string' || !jwk.k) {\n throw new TypeError('missing \"k\" (Key Value) Parameter value');\n }\n return decodeBase64URL(jwk.k);\n case 'RSA':\n if ('oth' in jwk && jwk.oth !== undefined) {\n throw new JOSENotSupported('RSA JWK \"oth\" (Other Primes Info) Parameter value is not supported');\n }\n case 'EC':\n case 'OKP':\n return asKeyObject({ ...jwk, alg });\n default:\n throw new JOSENotSupported('Unsupported \"kty\" (Key Type) Parameter value');\n }\n}\n","import { withAlg as invalidKeyInput } from './invalid_key_input.js';\nimport isKeyLike, { types } from '../runtime/is_key_like.js';\nimport * as jwk from './is_jwk.js';\nconst tag = (key) => key?.[Symbol.toStringTag];\nconst jwkMatchesOp = (alg, key, usage) => {\n if (key.use !== undefined && key.use !== 'sig') {\n throw new TypeError('Invalid key for this operation, when present its use must be sig');\n }\n if (key.key_ops !== undefined && key.key_ops.includes?.(usage) !== true) {\n throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`);\n }\n if (key.alg !== undefined && key.alg !== alg) {\n throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`);\n }\n return true;\n};\nconst symmetricTypeCheck = (alg, key, usage, allowJwk) => {\n if (key instanceof Uint8Array)\n return;\n if (allowJwk && jwk.isJWK(key)) {\n if (jwk.isSecretJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK \"kty\" (Key Type) equal to \"oct\" and the JWK \"k\" (Key Value) present`);\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, ...types, 'Uint8Array', allowJwk ? 'JSON Web Key' : null));\n }\n if (key.type !== 'secret') {\n throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type \"secret\"`);\n }\n};\nconst asymmetricTypeCheck = (alg, key, usage, allowJwk) => {\n if (allowJwk && jwk.isJWK(key)) {\n switch (usage) {\n case 'sign':\n if (jwk.isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation be a private JWK`);\n case 'verify':\n if (jwk.isPublicJWK(key) && jwkMatchesOp(alg, key, usage))\n return;\n throw new TypeError(`JSON Web Key for this operation be a public JWK`);\n }\n }\n if (!isKeyLike(key)) {\n throw new TypeError(invalidKeyInput(alg, key, ...types, allowJwk ? 'JSON Web Key' : null));\n }\n if (key.type === 'secret') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type \"secret\"`);\n }\n if (usage === 'sign' && key.type === 'public') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type \"private\"`);\n }\n if (usage === 'decrypt' && key.type === 'public') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type \"private\"`);\n }\n if (key.algorithm && usage === 'verify' && key.type === 'private') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type \"public\"`);\n }\n if (key.algorithm && usage === 'encrypt' && key.type === 'private') {\n throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type \"public\"`);\n }\n};\nfunction checkKeyType(allowJwk, alg, key, usage) {\n const symmetric = alg.startsWith('HS') ||\n alg === 'dir' ||\n alg.startsWith('PBES2') ||\n /^A\\d{3}(?:GCM)?KW$/.test(alg);\n if (symmetric) {\n symmetricTypeCheck(alg, key, usage, allowJwk);\n }\n else {\n asymmetricTypeCheck(alg, key, usage, allowJwk);\n }\n}\nexport default checkKeyType.bind(undefined, false);\nexport const checkKeyTypeWithJwk = checkKeyType.bind(undefined, true);\n","import { concat, uint64be } from '../lib/buffer_utils.js';\nimport checkIvLength from '../lib/check_iv_length.js';\nimport checkCekLength from './check_cek_length.js';\nimport crypto, { isCryptoKey } from './webcrypto.js';\nimport { checkEncCryptoKey } from '../lib/crypto_key.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport generateIv from '../lib/iv.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { types } from './is_key_like.js';\nasync function cbcEncrypt(enc, plaintext, cek, iv, aad) {\n if (!(cek instanceof Uint8Array)) {\n throw new TypeError(invalidKeyInput(cek, 'Uint8Array'));\n }\n const keySize = parseInt(enc.slice(1, 4), 10);\n const encKey = await crypto.subtle.importKey('raw', cek.subarray(keySize >> 3), 'AES-CBC', false, ['encrypt']);\n const macKey = await crypto.subtle.importKey('raw', cek.subarray(0, keySize >> 3), {\n hash: `SHA-${keySize << 1}`,\n name: 'HMAC',\n }, false, ['sign']);\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({\n iv,\n name: 'AES-CBC',\n }, encKey, plaintext));\n const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));\n const tag = new Uint8Array((await crypto.subtle.sign('HMAC', macKey, macData)).slice(0, keySize >> 3));\n return { ciphertext, tag, iv };\n}\nasync function gcmEncrypt(enc, plaintext, cek, iv, aad) {\n let encKey;\n if (cek instanceof Uint8Array) {\n encKey = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);\n }\n else {\n checkEncCryptoKey(cek, enc, 'encrypt');\n encKey = cek;\n }\n const encrypted = new Uint8Array(await crypto.subtle.encrypt({\n additionalData: aad,\n iv,\n name: 'AES-GCM',\n tagLength: 128,\n }, encKey, plaintext));\n const tag = encrypted.slice(-16);\n const ciphertext = encrypted.slice(0, -16);\n return { ciphertext, tag, iv };\n}\nconst encrypt = async (enc, plaintext, cek, iv, aad) => {\n if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) {\n throw new TypeError(invalidKeyInput(cek, ...types, 'Uint8Array'));\n }\n if (iv) {\n checkIvLength(enc, iv);\n }\n else {\n iv = generateIv(enc);\n }\n switch (enc) {\n case 'A128CBC-HS256':\n case 'A192CBC-HS384':\n case 'A256CBC-HS512':\n if (cek instanceof Uint8Array) {\n checkCekLength(cek, parseInt(enc.slice(-3), 10));\n }\n return cbcEncrypt(enc, plaintext, cek, iv, aad);\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM':\n if (cek instanceof Uint8Array) {\n checkCekLength(cek, parseInt(enc.slice(1, 4), 10));\n }\n return gcmEncrypt(enc, plaintext, cek, iv, aad);\n default:\n throw new JOSENotSupported('Unsupported JWE Content Encryption Algorithm');\n }\n};\nexport default encrypt;\n","import encrypt from '../runtime/encrypt.js';\nimport decrypt from '../runtime/decrypt.js';\nimport { encode as base64url } from '../runtime/base64url.js';\nexport async function wrap(alg, key, cek, iv) {\n const jweAlgorithm = alg.slice(0, 7);\n const wrapped = await encrypt(jweAlgorithm, cek, key, iv, new Uint8Array(0));\n return {\n encryptedKey: wrapped.ciphertext,\n iv: base64url(wrapped.iv),\n tag: base64url(wrapped.tag),\n };\n}\nexport async function unwrap(alg, key, encryptedKey, iv, tag) {\n const jweAlgorithm = alg.slice(0, 7);\n return decrypt(jweAlgorithm, key, encryptedKey, iv, tag, new Uint8Array(0));\n}\n","import { unwrap as aesKw } from '../runtime/aeskw.js';\nimport * as ECDH from '../runtime/ecdhes.js';\nimport { decrypt as pbes2Kw } from '../runtime/pbes2kw.js';\nimport { decrypt as rsaEs } from '../runtime/rsaes.js';\nimport { decode as base64url } from '../runtime/base64url.js';\nimport normalize from '../runtime/normalize_key.js';\nimport { JOSENotSupported, JWEInvalid } from '../util/errors.js';\nimport { bitLength as cekLength } from '../lib/cek.js';\nimport { importJWK } from '../key/import.js';\nimport checkKeyType from './check_key_type.js';\nimport isObject from './is_object.js';\nimport { unwrap as aesGcmKw } from './aesgcmkw.js';\nasync function decryptKeyManagement(alg, key, encryptedKey, joseHeader, options) {\n checkKeyType(alg, key, 'decrypt');\n key = (await normalize.normalizePrivateKey?.(key, alg)) || key;\n switch (alg) {\n case 'dir': {\n if (encryptedKey !== undefined)\n throw new JWEInvalid('Encountered unexpected JWE Encrypted Key');\n return key;\n }\n case 'ECDH-ES':\n if (encryptedKey !== undefined)\n throw new JWEInvalid('Encountered unexpected JWE Encrypted Key');\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n if (!isObject(joseHeader.epk))\n throw new JWEInvalid(`JOSE Header \"epk\" (Ephemeral Public Key) missing or invalid`);\n if (!ECDH.ecdhAllowed(key))\n throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');\n const epk = await importJWK(joseHeader.epk, alg);\n let partyUInfo;\n let partyVInfo;\n if (joseHeader.apu !== undefined) {\n if (typeof joseHeader.apu !== 'string')\n throw new JWEInvalid(`JOSE Header \"apu\" (Agreement PartyUInfo) invalid`);\n try {\n partyUInfo = base64url(joseHeader.apu);\n }\n catch {\n throw new JWEInvalid('Failed to base64url decode the apu');\n }\n }\n if (joseHeader.apv !== undefined) {\n if (typeof joseHeader.apv !== 'string')\n throw new JWEInvalid(`JOSE Header \"apv\" (Agreement PartyVInfo) invalid`);\n try {\n partyVInfo = base64url(joseHeader.apv);\n }\n catch {\n throw new JWEInvalid('Failed to base64url decode the apv');\n }\n }\n const sharedSecret = await ECDH.deriveKey(epk, key, alg === 'ECDH-ES' ? joseHeader.enc : alg, alg === 'ECDH-ES' ? cekLength(joseHeader.enc) : parseInt(alg.slice(-5, -2), 10), partyUInfo, partyVInfo);\n if (alg === 'ECDH-ES')\n return sharedSecret;\n if (encryptedKey === undefined)\n throw new JWEInvalid('JWE Encrypted Key missing');\n return aesKw(alg.slice(-6), sharedSecret, encryptedKey);\n }\n case 'RSA1_5':\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n if (encryptedKey === undefined)\n throw new JWEInvalid('JWE Encrypted Key missing');\n return rsaEs(alg, key, encryptedKey);\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW': {\n if (encryptedKey === undefined)\n throw new JWEInvalid('JWE Encrypted Key missing');\n if (typeof joseHeader.p2c !== 'number')\n throw new JWEInvalid(`JOSE Header \"p2c\" (PBES2 Count) missing or invalid`);\n const p2cLimit = options?.maxPBES2Count || 10000;\n if (joseHeader.p2c > p2cLimit)\n throw new JWEInvalid(`JOSE Header \"p2c\" (PBES2 Count) out is of acceptable bounds`);\n if (typeof joseHeader.p2s !== 'string')\n throw new JWEInvalid(`JOSE Header \"p2s\" (PBES2 Salt) missing or invalid`);\n let p2s;\n try {\n p2s = base64url(joseHeader.p2s);\n }\n catch {\n throw new JWEInvalid('Failed to base64url decode the p2s');\n }\n return pbes2Kw(alg, key, encryptedKey, joseHeader.p2c, p2s);\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n if (encryptedKey === undefined)\n throw new JWEInvalid('JWE Encrypted Key missing');\n return aesKw(alg, key, encryptedKey);\n }\n case 'A128GCMKW':\n case 'A192GCMKW':\n case 'A256GCMKW': {\n if (encryptedKey === undefined)\n throw new JWEInvalid('JWE Encrypted Key missing');\n if (typeof joseHeader.iv !== 'string')\n throw new JWEInvalid(`JOSE Header \"iv\" (Initialization Vector) missing or invalid`);\n if (typeof joseHeader.tag !== 'string')\n throw new JWEInvalid(`JOSE Header \"tag\" (Authentication Tag) missing or invalid`);\n let iv;\n try {\n iv = base64url(joseHeader.iv);\n }\n catch {\n throw new JWEInvalid('Failed to base64url decode the iv');\n }\n let tag;\n try {\n tag = base64url(joseHeader.tag);\n }\n catch {\n throw new JWEInvalid('Failed to base64url decode the tag');\n }\n return aesGcmKw(alg, key, encryptedKey, iv, tag);\n }\n default: {\n throw new JOSENotSupported('Invalid or unsupported \"alg\" (JWE Algorithm) header value');\n }\n }\n}\nexport default decryptKeyManagement;\n","import { JOSENotSupported } from '../util/errors.js';\nfunction validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {\n if (joseHeader.crit !== undefined && protectedHeader?.crit === undefined) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be integrity protected');\n }\n if (!protectedHeader || protectedHeader.crit === undefined) {\n return new Set();\n }\n if (!Array.isArray(protectedHeader.crit) ||\n protectedHeader.crit.length === 0 ||\n protectedHeader.crit.some((input) => typeof input !== 'string' || input.length === 0)) {\n throw new Err('\"crit\" (Critical) Header Parameter MUST be an array of non-empty strings when present');\n }\n let recognized;\n if (recognizedOption !== undefined) {\n recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);\n }\n else {\n recognized = recognizedDefault;\n }\n for (const parameter of protectedHeader.crit) {\n if (!recognized.has(parameter)) {\n throw new JOSENotSupported(`Extension Header Parameter \"${parameter}\" is not recognized`);\n }\n if (joseHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" is missing`);\n }\n if (recognized.get(parameter) && protectedHeader[parameter] === undefined) {\n throw new Err(`Extension Header Parameter \"${parameter}\" MUST be integrity protected`);\n }\n }\n return new Set(protectedHeader.crit);\n}\nexport default validateCrit;\n","const validateAlgorithms = (option, algorithms) => {\n if (algorithms !== undefined &&\n (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== 'string'))) {\n throw new TypeError(`\"${option}\" option must be an array of strings`);\n }\n if (!algorithms) {\n return undefined;\n }\n return new Set(algorithms);\n};\nexport default validateAlgorithms;\n","import { decode as base64url } from '../../runtime/base64url.js';\nimport decrypt from '../../runtime/decrypt.js';\nimport { JOSEAlgNotAllowed, JOSENotSupported, JWEInvalid } from '../../util/errors.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport isObject from '../../lib/is_object.js';\nimport decryptKeyManagement from '../../lib/decrypt_key_management.js';\nimport { encoder, decoder, concat } from '../../lib/buffer_utils.js';\nimport generateCek from '../../lib/cek.js';\nimport validateCrit from '../../lib/validate_crit.js';\nimport validateAlgorithms from '../../lib/validate_algorithms.js';\nexport async function flattenedDecrypt(jwe, key, options) {\n if (!isObject(jwe)) {\n throw new JWEInvalid('Flattened JWE must be an object');\n }\n if (jwe.protected === undefined && jwe.header === undefined && jwe.unprotected === undefined) {\n throw new JWEInvalid('JOSE Header missing');\n }\n if (jwe.iv !== undefined && typeof jwe.iv !== 'string') {\n throw new JWEInvalid('JWE Initialization Vector incorrect type');\n }\n if (typeof jwe.ciphertext !== 'string') {\n throw new JWEInvalid('JWE Ciphertext missing or incorrect type');\n }\n if (jwe.tag !== undefined && typeof jwe.tag !== 'string') {\n throw new JWEInvalid('JWE Authentication Tag incorrect type');\n }\n if (jwe.protected !== undefined && typeof jwe.protected !== 'string') {\n throw new JWEInvalid('JWE Protected Header incorrect type');\n }\n if (jwe.encrypted_key !== undefined && typeof jwe.encrypted_key !== 'string') {\n throw new JWEInvalid('JWE Encrypted Key incorrect type');\n }\n if (jwe.aad !== undefined && typeof jwe.aad !== 'string') {\n throw new JWEInvalid('JWE AAD incorrect type');\n }\n if (jwe.header !== undefined && !isObject(jwe.header)) {\n throw new JWEInvalid('JWE Shared Unprotected Header incorrect type');\n }\n if (jwe.unprotected !== undefined && !isObject(jwe.unprotected)) {\n throw new JWEInvalid('JWE Per-Recipient Unprotected Header incorrect type');\n }\n let parsedProt;\n if (jwe.protected) {\n try {\n const protectedHeader = base64url(jwe.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch {\n throw new JWEInvalid('JWE Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) {\n throw new JWEInvalid('JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jwe.header,\n ...jwe.unprotected,\n };\n validateCrit(JWEInvalid, new Map(), options?.crit, parsedProt, joseHeader);\n if (joseHeader.zip !== undefined) {\n throw new JOSENotSupported('JWE \"zip\" (Compression Algorithm) Header Parameter is not supported.');\n }\n const { alg, enc } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWEInvalid('missing JWE Algorithm (alg) in JWE Header');\n }\n if (typeof enc !== 'string' || !enc) {\n throw new JWEInvalid('missing JWE Encryption Algorithm (enc) in JWE Header');\n }\n const keyManagementAlgorithms = options && validateAlgorithms('keyManagementAlgorithms', options.keyManagementAlgorithms);\n const contentEncryptionAlgorithms = options &&\n validateAlgorithms('contentEncryptionAlgorithms', options.contentEncryptionAlgorithms);\n if ((keyManagementAlgorithms && !keyManagementAlgorithms.has(alg)) ||\n (!keyManagementAlgorithms && alg.startsWith('PBES2'))) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n }\n if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc)) {\n throw new JOSEAlgNotAllowed('\"enc\" (Encryption Algorithm) Header Parameter value not allowed');\n }\n let encryptedKey;\n if (jwe.encrypted_key !== undefined) {\n try {\n encryptedKey = base64url(jwe.encrypted_key);\n }\n catch {\n throw new JWEInvalid('Failed to base64url decode the encrypted_key');\n }\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jwe);\n resolvedKey = true;\n }\n let cek;\n try {\n cek = await decryptKeyManagement(alg, key, encryptedKey, joseHeader, options);\n }\n catch (err) {\n if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) {\n throw err;\n }\n cek = generateCek(enc);\n }\n let iv;\n let tag;\n if (jwe.iv !== undefined) {\n try {\n iv = base64url(jwe.iv);\n }\n catch {\n throw new JWEInvalid('Failed to base64url decode the iv');\n }\n }\n if (jwe.tag !== undefined) {\n try {\n tag = base64url(jwe.tag);\n }\n catch {\n throw new JWEInvalid('Failed to base64url decode the tag');\n }\n }\n const protectedHeader = encoder.encode(jwe.protected ?? '');\n let additionalData;\n if (jwe.aad !== undefined) {\n additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(jwe.aad));\n }\n else {\n additionalData = protectedHeader;\n }\n let ciphertext;\n try {\n ciphertext = base64url(jwe.ciphertext);\n }\n catch {\n throw new JWEInvalid('Failed to base64url decode the ciphertext');\n }\n const plaintext = await decrypt(enc, cek, ciphertext, iv, tag, additionalData);\n const result = { plaintext };\n if (jwe.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jwe.aad !== undefined) {\n try {\n result.additionalAuthenticatedData = base64url(jwe.aad);\n }\n catch {\n throw new JWEInvalid('Failed to base64url decode the aad');\n }\n }\n if (jwe.unprotected !== undefined) {\n result.sharedUnprotectedHeader = jwe.unprotected;\n }\n if (jwe.header !== undefined) {\n result.unprotectedHeader = jwe.header;\n }\n if (resolvedKey) {\n return { ...result, key };\n }\n return result;\n}\n","import { flattenedDecrypt } from '../flattened/decrypt.js';\nimport { JWEInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactDecrypt(jwe, key, options) {\n if (jwe instanceof Uint8Array) {\n jwe = decoder.decode(jwe);\n }\n if (typeof jwe !== 'string') {\n throw new JWEInvalid('Compact JWE must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length, } = jwe.split('.');\n if (length !== 5) {\n throw new JWEInvalid('Invalid Compact JWE');\n }\n const decrypted = await flattenedDecrypt({\n ciphertext,\n iv: iv || undefined,\n protected: protectedHeader,\n tag: tag || undefined,\n encrypted_key: encryptedKey || undefined,\n }, key, options);\n const result = { plaintext: decrypted.plaintext, protectedHeader: decrypted.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: decrypted.key };\n }\n return result;\n}\n","import { flattenedDecrypt } from '../flattened/decrypt.js';\nimport { JWEDecryptionFailed, JWEInvalid } from '../../util/errors.js';\nimport isObject from '../../lib/is_object.js';\nexport async function generalDecrypt(jwe, key, options) {\n if (!isObject(jwe)) {\n throw new JWEInvalid('General JWE must be an object');\n }\n if (!Array.isArray(jwe.recipients) || !jwe.recipients.every(isObject)) {\n throw new JWEInvalid('JWE Recipients missing or incorrect type');\n }\n if (!jwe.recipients.length) {\n throw new JWEInvalid('JWE Recipients has no members');\n }\n for (const recipient of jwe.recipients) {\n try {\n return await flattenedDecrypt({\n aad: jwe.aad,\n ciphertext: jwe.ciphertext,\n encrypted_key: recipient.encrypted_key,\n header: recipient.header,\n iv: jwe.iv,\n protected: jwe.protected,\n tag: jwe.tag,\n unprotected: jwe.unprotected,\n }, key, options);\n }\n catch {\n }\n }\n throw new JWEDecryptionFailed();\n}\n","export const unprotected = Symbol();\n","import crypto, { isCryptoKey } from './webcrypto.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { encode as base64url } from './base64url.js';\nimport { types } from './is_key_like.js';\nconst keyToJWK = async (key) => {\n if (key instanceof Uint8Array) {\n return {\n kty: 'oct',\n k: base64url(key),\n };\n }\n if (!isCryptoKey(key)) {\n throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array'));\n }\n if (!key.extractable) {\n throw new TypeError('non-extractable CryptoKey cannot be exported as a JWK');\n }\n const { ext, key_ops, alg, use, ...jwk } = await crypto.subtle.exportKey('jwk', key);\n return jwk;\n};\nexport default keyToJWK;\n","import { toSPKI as exportPublic } from '../runtime/asn1.js';\nimport { toPKCS8 as exportPrivate } from '../runtime/asn1.js';\nimport keyToJWK from '../runtime/key_to_jwk.js';\nexport async function exportSPKI(key) {\n return exportPublic(key);\n}\nexport async function exportPKCS8(key) {\n return exportPrivate(key);\n}\nexport async function exportJWK(key) {\n return keyToJWK(key);\n}\n","import { wrap as aesKw } from '../runtime/aeskw.js';\nimport * as ECDH from '../runtime/ecdhes.js';\nimport { encrypt as pbes2Kw } from '../runtime/pbes2kw.js';\nimport { encrypt as rsaEs } from '../runtime/rsaes.js';\nimport { encode as base64url } from '../runtime/base64url.js';\nimport normalize from '../runtime/normalize_key.js';\nimport generateCek, { bitLength as cekLength } from '../lib/cek.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport { exportJWK } from '../key/export.js';\nimport checkKeyType from './check_key_type.js';\nimport { wrap as aesGcmKw } from './aesgcmkw.js';\nasync function encryptKeyManagement(alg, enc, key, providedCek, providedParameters = {}) {\n let encryptedKey;\n let parameters;\n let cek;\n checkKeyType(alg, key, 'encrypt');\n key = (await normalize.normalizePublicKey?.(key, alg)) || key;\n switch (alg) {\n case 'dir': {\n cek = key;\n break;\n }\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n if (!ECDH.ecdhAllowed(key)) {\n throw new JOSENotSupported('ECDH with the provided key is not allowed or not supported by your javascript runtime');\n }\n const { apu, apv } = providedParameters;\n let { epk: ephemeralKey } = providedParameters;\n ephemeralKey || (ephemeralKey = (await ECDH.generateEpk(key)).privateKey);\n const { x, y, crv, kty } = await exportJWK(ephemeralKey);\n const sharedSecret = await ECDH.deriveKey(key, ephemeralKey, alg === 'ECDH-ES' ? enc : alg, alg === 'ECDH-ES' ? cekLength(enc) : parseInt(alg.slice(-5, -2), 10), apu, apv);\n parameters = { epk: { x, crv, kty } };\n if (kty === 'EC')\n parameters.epk.y = y;\n if (apu)\n parameters.apu = base64url(apu);\n if (apv)\n parameters.apv = base64url(apv);\n if (alg === 'ECDH-ES') {\n cek = sharedSecret;\n break;\n }\n cek = providedCek || generateCek(enc);\n const kwAlg = alg.slice(-6);\n encryptedKey = await aesKw(kwAlg, sharedSecret, cek);\n break;\n }\n case 'RSA1_5':\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512': {\n cek = providedCek || generateCek(enc);\n encryptedKey = await rsaEs(alg, key, cek);\n break;\n }\n case 'PBES2-HS256+A128KW':\n case 'PBES2-HS384+A192KW':\n case 'PBES2-HS512+A256KW': {\n cek = providedCek || generateCek(enc);\n const { p2c, p2s } = providedParameters;\n ({ encryptedKey, ...parameters } = await pbes2Kw(alg, key, cek, p2c, p2s));\n break;\n }\n case 'A128KW':\n case 'A192KW':\n case 'A256KW': {\n cek = providedCek || generateCek(enc);\n encryptedKey = await aesKw(alg, key, cek);\n break;\n }\n case 'A128GCMKW':\n case 'A192GCMKW':\n case 'A256GCMKW': {\n cek = providedCek || generateCek(enc);\n const { iv } = providedParameters;\n ({ encryptedKey, ...parameters } = await aesGcmKw(alg, key, cek, iv));\n break;\n }\n default: {\n throw new JOSENotSupported('Invalid or unsupported \"alg\" (JWE Algorithm) header value');\n }\n }\n return { cek, encryptedKey, parameters };\n}\nexport default encryptKeyManagement;\n","import { encode as base64url } from '../../runtime/base64url.js';\nimport { unprotected } from '../../lib/private_symbols.js';\nimport encrypt from '../../runtime/encrypt.js';\nimport encryptKeyManagement from '../../lib/encrypt_key_management.js';\nimport { JOSENotSupported, JWEInvalid } from '../../util/errors.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport { encoder, decoder, concat } from '../../lib/buffer_utils.js';\nimport validateCrit from '../../lib/validate_crit.js';\nexport class FlattenedEncrypt {\n constructor(plaintext) {\n if (!(plaintext instanceof Uint8Array)) {\n throw new TypeError('plaintext must be an instance of Uint8Array');\n }\n this._plaintext = plaintext;\n }\n setKeyManagementParameters(parameters) {\n if (this._keyManagementParameters) {\n throw new TypeError('setKeyManagementParameters can only be called once');\n }\n this._keyManagementParameters = parameters;\n return this;\n }\n setProtectedHeader(protectedHeader) {\n if (this._protectedHeader) {\n throw new TypeError('setProtectedHeader can only be called once');\n }\n this._protectedHeader = protectedHeader;\n return this;\n }\n setSharedUnprotectedHeader(sharedUnprotectedHeader) {\n if (this._sharedUnprotectedHeader) {\n throw new TypeError('setSharedUnprotectedHeader can only be called once');\n }\n this._sharedUnprotectedHeader = sharedUnprotectedHeader;\n return this;\n }\n setUnprotectedHeader(unprotectedHeader) {\n if (this._unprotectedHeader) {\n throw new TypeError('setUnprotectedHeader can only be called once');\n }\n this._unprotectedHeader = unprotectedHeader;\n return this;\n }\n setAdditionalAuthenticatedData(aad) {\n this._aad = aad;\n return this;\n }\n setContentEncryptionKey(cek) {\n if (this._cek) {\n throw new TypeError('setContentEncryptionKey can only be called once');\n }\n this._cek = cek;\n return this;\n }\n setInitializationVector(iv) {\n if (this._iv) {\n throw new TypeError('setInitializationVector can only be called once');\n }\n this._iv = iv;\n return this;\n }\n async encrypt(key, options) {\n if (!this._protectedHeader && !this._unprotectedHeader && !this._sharedUnprotectedHeader) {\n throw new JWEInvalid('either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()');\n }\n if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, this._sharedUnprotectedHeader)) {\n throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...this._protectedHeader,\n ...this._unprotectedHeader,\n ...this._sharedUnprotectedHeader,\n };\n validateCrit(JWEInvalid, new Map(), options?.crit, this._protectedHeader, joseHeader);\n if (joseHeader.zip !== undefined) {\n throw new JOSENotSupported('JWE \"zip\" (Compression Algorithm) Header Parameter is not supported.');\n }\n const { alg, enc } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWEInvalid('JWE \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n if (typeof enc !== 'string' || !enc) {\n throw new JWEInvalid('JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid');\n }\n let encryptedKey;\n if (this._cek && (alg === 'dir' || alg === 'ECDH-ES')) {\n throw new TypeError(`setContentEncryptionKey cannot be called with JWE \"alg\" (Algorithm) Header ${alg}`);\n }\n let cek;\n {\n let parameters;\n ({ cek, encryptedKey, parameters } = await encryptKeyManagement(alg, enc, key, this._cek, this._keyManagementParameters));\n if (parameters) {\n if (options && unprotected in options) {\n if (!this._unprotectedHeader) {\n this.setUnprotectedHeader(parameters);\n }\n else {\n this._unprotectedHeader = { ...this._unprotectedHeader, ...parameters };\n }\n }\n else if (!this._protectedHeader) {\n this.setProtectedHeader(parameters);\n }\n else {\n this._protectedHeader = { ...this._protectedHeader, ...parameters };\n }\n }\n }\n let additionalData;\n let protectedHeader;\n let aadMember;\n if (this._protectedHeader) {\n protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));\n }\n else {\n protectedHeader = encoder.encode('');\n }\n if (this._aad) {\n aadMember = base64url(this._aad);\n additionalData = concat(protectedHeader, encoder.encode('.'), encoder.encode(aadMember));\n }\n else {\n additionalData = protectedHeader;\n }\n const { ciphertext, tag, iv } = await encrypt(enc, this._plaintext, cek, this._iv, additionalData);\n const jwe = {\n ciphertext: base64url(ciphertext),\n };\n if (iv) {\n jwe.iv = base64url(iv);\n }\n if (tag) {\n jwe.tag = base64url(tag);\n }\n if (encryptedKey) {\n jwe.encrypted_key = base64url(encryptedKey);\n }\n if (aadMember) {\n jwe.aad = aadMember;\n }\n if (this._protectedHeader) {\n jwe.protected = decoder.decode(protectedHeader);\n }\n if (this._sharedUnprotectedHeader) {\n jwe.unprotected = this._sharedUnprotectedHeader;\n }\n if (this._unprotectedHeader) {\n jwe.header = this._unprotectedHeader;\n }\n return jwe;\n }\n}\n","import { FlattenedEncrypt } from '../flattened/encrypt.js';\nimport { unprotected } from '../../lib/private_symbols.js';\nimport { JOSENotSupported, JWEInvalid } from '../../util/errors.js';\nimport generateCek from '../../lib/cek.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport encryptKeyManagement from '../../lib/encrypt_key_management.js';\nimport { encode as base64url } from '../../runtime/base64url.js';\nimport validateCrit from '../../lib/validate_crit.js';\nclass IndividualRecipient {\n constructor(enc, key, options) {\n this.parent = enc;\n this.key = key;\n this.options = options;\n }\n setUnprotectedHeader(unprotectedHeader) {\n if (this.unprotectedHeader) {\n throw new TypeError('setUnprotectedHeader can only be called once');\n }\n this.unprotectedHeader = unprotectedHeader;\n return this;\n }\n addRecipient(...args) {\n return this.parent.addRecipient(...args);\n }\n encrypt(...args) {\n return this.parent.encrypt(...args);\n }\n done() {\n return this.parent;\n }\n}\nexport class GeneralEncrypt {\n constructor(plaintext) {\n this._recipients = [];\n this._plaintext = plaintext;\n }\n addRecipient(key, options) {\n const recipient = new IndividualRecipient(this, key, { crit: options?.crit });\n this._recipients.push(recipient);\n return recipient;\n }\n setProtectedHeader(protectedHeader) {\n if (this._protectedHeader) {\n throw new TypeError('setProtectedHeader can only be called once');\n }\n this._protectedHeader = protectedHeader;\n return this;\n }\n setSharedUnprotectedHeader(sharedUnprotectedHeader) {\n if (this._unprotectedHeader) {\n throw new TypeError('setSharedUnprotectedHeader can only be called once');\n }\n this._unprotectedHeader = sharedUnprotectedHeader;\n return this;\n }\n setAdditionalAuthenticatedData(aad) {\n this._aad = aad;\n return this;\n }\n async encrypt() {\n if (!this._recipients.length) {\n throw new JWEInvalid('at least one recipient must be added');\n }\n if (this._recipients.length === 1) {\n const [recipient] = this._recipients;\n const flattened = await new FlattenedEncrypt(this._plaintext)\n .setAdditionalAuthenticatedData(this._aad)\n .setProtectedHeader(this._protectedHeader)\n .setSharedUnprotectedHeader(this._unprotectedHeader)\n .setUnprotectedHeader(recipient.unprotectedHeader)\n .encrypt(recipient.key, { ...recipient.options });\n const jwe = {\n ciphertext: flattened.ciphertext,\n iv: flattened.iv,\n recipients: [{}],\n tag: flattened.tag,\n };\n if (flattened.aad)\n jwe.aad = flattened.aad;\n if (flattened.protected)\n jwe.protected = flattened.protected;\n if (flattened.unprotected)\n jwe.unprotected = flattened.unprotected;\n if (flattened.encrypted_key)\n jwe.recipients[0].encrypted_key = flattened.encrypted_key;\n if (flattened.header)\n jwe.recipients[0].header = flattened.header;\n return jwe;\n }\n let enc;\n for (let i = 0; i < this._recipients.length; i++) {\n const recipient = this._recipients[i];\n if (!isDisjoint(this._protectedHeader, this._unprotectedHeader, recipient.unprotectedHeader)) {\n throw new JWEInvalid('JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...this._protectedHeader,\n ...this._unprotectedHeader,\n ...recipient.unprotectedHeader,\n };\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWEInvalid('JWE \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n if (alg === 'dir' || alg === 'ECDH-ES') {\n throw new JWEInvalid('\"dir\" and \"ECDH-ES\" alg may only be used with a single recipient');\n }\n if (typeof joseHeader.enc !== 'string' || !joseHeader.enc) {\n throw new JWEInvalid('JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid');\n }\n if (!enc) {\n enc = joseHeader.enc;\n }\n else if (enc !== joseHeader.enc) {\n throw new JWEInvalid('JWE \"enc\" (Encryption Algorithm) Header Parameter must be the same for all recipients');\n }\n validateCrit(JWEInvalid, new Map(), recipient.options.crit, this._protectedHeader, joseHeader);\n if (joseHeader.zip !== undefined) {\n throw new JOSENotSupported('JWE \"zip\" (Compression Algorithm) Header Parameter is not supported.');\n }\n }\n const cek = generateCek(enc);\n const jwe = {\n ciphertext: '',\n iv: '',\n recipients: [],\n tag: '',\n };\n for (let i = 0; i < this._recipients.length; i++) {\n const recipient = this._recipients[i];\n const target = {};\n jwe.recipients.push(target);\n const joseHeader = {\n ...this._protectedHeader,\n ...this._unprotectedHeader,\n ...recipient.unprotectedHeader,\n };\n const p2c = joseHeader.alg.startsWith('PBES2') ? 2048 + i : undefined;\n if (i === 0) {\n const flattened = await new FlattenedEncrypt(this._plaintext)\n .setAdditionalAuthenticatedData(this._aad)\n .setContentEncryptionKey(cek)\n .setProtectedHeader(this._protectedHeader)\n .setSharedUnprotectedHeader(this._unprotectedHeader)\n .setUnprotectedHeader(recipient.unprotectedHeader)\n .setKeyManagementParameters({ p2c })\n .encrypt(recipient.key, {\n ...recipient.options,\n [unprotected]: true,\n });\n jwe.ciphertext = flattened.ciphertext;\n jwe.iv = flattened.iv;\n jwe.tag = flattened.tag;\n if (flattened.aad)\n jwe.aad = flattened.aad;\n if (flattened.protected)\n jwe.protected = flattened.protected;\n if (flattened.unprotected)\n jwe.unprotected = flattened.unprotected;\n target.encrypted_key = flattened.encrypted_key;\n if (flattened.header)\n target.header = flattened.header;\n continue;\n }\n const { encryptedKey, parameters } = await encryptKeyManagement(recipient.unprotectedHeader?.alg ||\n this._protectedHeader?.alg ||\n this._unprotectedHeader?.alg, enc, recipient.key, cek, { p2c });\n target.encrypted_key = base64url(encryptedKey);\n if (recipient.unprotectedHeader || parameters)\n target.header = { ...recipient.unprotectedHeader, ...parameters };\n }\n return jwe;\n }\n}\n","import { JOSENotSupported } from '../util/errors.js';\nexport default function subtleDsa(alg, algorithm) {\n const hash = `SHA-${alg.slice(-3)}`;\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n return { hash, name: 'HMAC' };\n case 'PS256':\n case 'PS384':\n case 'PS512':\n return { hash, name: 'RSA-PSS', saltLength: alg.slice(-3) >> 3 };\n case 'RS256':\n case 'RS384':\n case 'RS512':\n return { hash, name: 'RSASSA-PKCS1-v1_5' };\n case 'ES256':\n case 'ES384':\n case 'ES512':\n return { hash, name: 'ECDSA', namedCurve: algorithm.namedCurve };\n case 'Ed25519':\n return { name: 'Ed25519' };\n case 'EdDSA':\n return { name: algorithm.name };\n default:\n throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);\n }\n}\n","import crypto, { isCryptoKey } from './webcrypto.js';\nimport { checkSigCryptoKey } from '../lib/crypto_key.js';\nimport invalidKeyInput from '../lib/invalid_key_input.js';\nimport { types } from './is_key_like.js';\nimport normalize from './normalize_key.js';\nexport default async function getCryptoKey(alg, key, usage) {\n if (usage === 'sign') {\n key = await normalize.normalizePrivateKey(key, alg);\n }\n if (usage === 'verify') {\n key = await normalize.normalizePublicKey(key, alg);\n }\n if (isCryptoKey(key)) {\n checkSigCryptoKey(key, alg, usage);\n return key;\n }\n if (key instanceof Uint8Array) {\n if (!alg.startsWith('HS')) {\n throw new TypeError(invalidKeyInput(key, ...types));\n }\n return crypto.subtle.importKey('raw', key, { hash: `SHA-${alg.slice(-3)}`, name: 'HMAC' }, false, [usage]);\n }\n throw new TypeError(invalidKeyInput(key, ...types, 'Uint8Array', 'JSON Web Key'));\n}\n","import subtleAlgorithm from './subtle_dsa.js';\nimport crypto from './webcrypto.js';\nimport checkKeyLength from './check_key_length.js';\nimport getVerifyKey from './get_sign_verify_key.js';\nconst verify = async (alg, key, signature, data) => {\n const cryptoKey = await getVerifyKey(alg, key, 'verify');\n checkKeyLength(alg, cryptoKey);\n const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);\n try {\n return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);\n }\n catch {\n return false;\n }\n};\nexport default verify;\n","import { decode as base64url } from '../../runtime/base64url.js';\nimport verify from '../../runtime/verify.js';\nimport { JOSEAlgNotAllowed, JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport { concat, encoder, decoder } from '../../lib/buffer_utils.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport isObject from '../../lib/is_object.js';\nimport { checkKeyTypeWithJwk } from '../../lib/check_key_type.js';\nimport validateCrit from '../../lib/validate_crit.js';\nimport validateAlgorithms from '../../lib/validate_algorithms.js';\nimport { isJWK } from '../../lib/is_jwk.js';\nimport { importJWK } from '../../key/import.js';\nexport async function flattenedVerify(jws, key, options) {\n if (!isObject(jws)) {\n throw new JWSInvalid('Flattened JWS must be an object');\n }\n if (jws.protected === undefined && jws.header === undefined) {\n throw new JWSInvalid('Flattened JWS must have either of the \"protected\" or \"header\" members');\n }\n if (jws.protected !== undefined && typeof jws.protected !== 'string') {\n throw new JWSInvalid('JWS Protected Header incorrect type');\n }\n if (jws.payload === undefined) {\n throw new JWSInvalid('JWS Payload missing');\n }\n if (typeof jws.signature !== 'string') {\n throw new JWSInvalid('JWS Signature missing or incorrect type');\n }\n if (jws.header !== undefined && !isObject(jws.header)) {\n throw new JWSInvalid('JWS Unprotected Header incorrect type');\n }\n let parsedProt = {};\n if (jws.protected) {\n try {\n const protectedHeader = base64url(jws.protected);\n parsedProt = JSON.parse(decoder.decode(protectedHeader));\n }\n catch {\n throw new JWSInvalid('JWS Protected Header is invalid');\n }\n }\n if (!isDisjoint(parsedProt, jws.header)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...parsedProt,\n ...jws.header,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, parsedProt, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = parsedProt.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n const algorithms = options && validateAlgorithms('algorithms', options.algorithms);\n if (algorithms && !algorithms.has(alg)) {\n throw new JOSEAlgNotAllowed('\"alg\" (Algorithm) Header Parameter value not allowed');\n }\n if (b64) {\n if (typeof jws.payload !== 'string') {\n throw new JWSInvalid('JWS Payload must be a string');\n }\n }\n else if (typeof jws.payload !== 'string' && !(jws.payload instanceof Uint8Array)) {\n throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');\n }\n let resolvedKey = false;\n if (typeof key === 'function') {\n key = await key(parsedProt, jws);\n resolvedKey = true;\n checkKeyTypeWithJwk(alg, key, 'verify');\n if (isJWK(key)) {\n key = await importJWK(key, alg);\n }\n }\n else {\n checkKeyTypeWithJwk(alg, key, 'verify');\n }\n const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), typeof jws.payload === 'string' ? encoder.encode(jws.payload) : jws.payload);\n let signature;\n try {\n signature = base64url(jws.signature);\n }\n catch {\n throw new JWSInvalid('Failed to base64url decode the signature');\n }\n const verified = await verify(alg, key, signature, data);\n if (!verified) {\n throw new JWSSignatureVerificationFailed();\n }\n let payload;\n if (b64) {\n try {\n payload = base64url(jws.payload);\n }\n catch {\n throw new JWSInvalid('Failed to base64url decode the payload');\n }\n }\n else if (typeof jws.payload === 'string') {\n payload = encoder.encode(jws.payload);\n }\n else {\n payload = jws.payload;\n }\n const result = { payload };\n if (jws.protected !== undefined) {\n result.protectedHeader = parsedProt;\n }\n if (jws.header !== undefined) {\n result.unprotectedHeader = jws.header;\n }\n if (resolvedKey) {\n return { ...result, key };\n }\n return result;\n}\n","import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { decoder } from '../../lib/buffer_utils.js';\nexport async function compactVerify(jws, key, options) {\n if (jws instanceof Uint8Array) {\n jws = decoder.decode(jws);\n }\n if (typeof jws !== 'string') {\n throw new JWSInvalid('Compact JWS must be a string or Uint8Array');\n }\n const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');\n if (length !== 3) {\n throw new JWSInvalid('Invalid Compact JWS');\n }\n const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);\n const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n","import { flattenedVerify } from '../flattened/verify.js';\nimport { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';\nimport isObject from '../../lib/is_object.js';\nexport async function generalVerify(jws, key, options) {\n if (!isObject(jws)) {\n throw new JWSInvalid('General JWS must be an object');\n }\n if (!Array.isArray(jws.signatures) || !jws.signatures.every(isObject)) {\n throw new JWSInvalid('JWS Signatures missing or incorrect type');\n }\n for (const signature of jws.signatures) {\n try {\n return await flattenedVerify({\n header: signature.header,\n payload: jws.payload,\n protected: signature.protected,\n signature: signature.signature,\n }, key, options);\n }\n catch {\n }\n }\n throw new JWSSignatureVerificationFailed();\n}\n","export default (date) => Math.floor(date.getTime() / 1000);\n","const minute = 60;\nconst hour = minute * 60;\nconst day = hour * 24;\nconst week = day * 7;\nconst year = day * 365.25;\nconst REGEX = /^(\\+|\\-)? ?(\\d+|\\d+\\.\\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;\nexport default (str) => {\n const matched = REGEX.exec(str);\n if (!matched || (matched[4] && matched[1])) {\n throw new TypeError('Invalid time period format');\n }\n const value = parseFloat(matched[2]);\n const unit = matched[3].toLowerCase();\n let numericDate;\n switch (unit) {\n case 'sec':\n case 'secs':\n case 'second':\n case 'seconds':\n case 's':\n numericDate = Math.round(value);\n break;\n case 'minute':\n case 'minutes':\n case 'min':\n case 'mins':\n case 'm':\n numericDate = Math.round(value * minute);\n break;\n case 'hour':\n case 'hours':\n case 'hr':\n case 'hrs':\n case 'h':\n numericDate = Math.round(value * hour);\n break;\n case 'day':\n case 'days':\n case 'd':\n numericDate = Math.round(value * day);\n break;\n case 'week':\n case 'weeks':\n case 'w':\n numericDate = Math.round(value * week);\n break;\n default:\n numericDate = Math.round(value * year);\n break;\n }\n if (matched[1] === '-' || matched[4] === 'ago') {\n return -numericDate;\n }\n return numericDate;\n};\n","import { JWTClaimValidationFailed, JWTExpired, JWTInvalid } from '../util/errors.js';\nimport { decoder } from './buffer_utils.js';\nimport epoch from './epoch.js';\nimport secs from './secs.js';\nimport isObject from './is_object.js';\nconst normalizeTyp = (value) => value.toLowerCase().replace(/^application\\//, '');\nconst checkAudiencePresence = (audPayload, audOption) => {\n if (typeof audPayload === 'string') {\n return audOption.includes(audPayload);\n }\n if (Array.isArray(audPayload)) {\n return audOption.some(Set.prototype.has.bind(new Set(audPayload)));\n }\n return false;\n};\nexport default (protectedHeader, encodedPayload, options = {}) => {\n let payload;\n try {\n payload = JSON.parse(decoder.decode(encodedPayload));\n }\n catch {\n }\n if (!isObject(payload)) {\n throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');\n }\n const { typ } = options;\n if (typ &&\n (typeof protectedHeader.typ !== 'string' ||\n normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {\n throw new JWTClaimValidationFailed('unexpected \"typ\" JWT header value', payload, 'typ', 'check_failed');\n }\n const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;\n const presenceCheck = [...requiredClaims];\n if (maxTokenAge !== undefined)\n presenceCheck.push('iat');\n if (audience !== undefined)\n presenceCheck.push('aud');\n if (subject !== undefined)\n presenceCheck.push('sub');\n if (issuer !== undefined)\n presenceCheck.push('iss');\n for (const claim of new Set(presenceCheck.reverse())) {\n if (!(claim in payload)) {\n throw new JWTClaimValidationFailed(`missing required \"${claim}\" claim`, payload, claim, 'missing');\n }\n }\n if (issuer &&\n !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {\n throw new JWTClaimValidationFailed('unexpected \"iss\" claim value', payload, 'iss', 'check_failed');\n }\n if (subject && payload.sub !== subject) {\n throw new JWTClaimValidationFailed('unexpected \"sub\" claim value', payload, 'sub', 'check_failed');\n }\n if (audience &&\n !checkAudiencePresence(payload.aud, typeof audience === 'string' ? [audience] : audience)) {\n throw new JWTClaimValidationFailed('unexpected \"aud\" claim value', payload, 'aud', 'check_failed');\n }\n let tolerance;\n switch (typeof options.clockTolerance) {\n case 'string':\n tolerance = secs(options.clockTolerance);\n break;\n case 'number':\n tolerance = options.clockTolerance;\n break;\n case 'undefined':\n tolerance = 0;\n break;\n default:\n throw new TypeError('Invalid clockTolerance option type');\n }\n const { currentDate } = options;\n const now = epoch(currentDate || new Date());\n if ((payload.iat !== undefined || maxTokenAge) && typeof payload.iat !== 'number') {\n throw new JWTClaimValidationFailed('\"iat\" claim must be a number', payload, 'iat', 'invalid');\n }\n if (payload.nbf !== undefined) {\n if (typeof payload.nbf !== 'number') {\n throw new JWTClaimValidationFailed('\"nbf\" claim must be a number', payload, 'nbf', 'invalid');\n }\n if (payload.nbf > now + tolerance) {\n throw new JWTClaimValidationFailed('\"nbf\" claim timestamp check failed', payload, 'nbf', 'check_failed');\n }\n }\n if (payload.exp !== undefined) {\n if (typeof payload.exp !== 'number') {\n throw new JWTClaimValidationFailed('\"exp\" claim must be a number', payload, 'exp', 'invalid');\n }\n if (payload.exp <= now - tolerance) {\n throw new JWTExpired('\"exp\" claim timestamp check failed', payload, 'exp', 'check_failed');\n }\n }\n if (maxTokenAge) {\n const age = now - payload.iat;\n const max = typeof maxTokenAge === 'number' ? maxTokenAge : secs(maxTokenAge);\n if (age - tolerance > max) {\n throw new JWTExpired('\"iat\" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');\n }\n if (age < 0 - tolerance) {\n throw new JWTClaimValidationFailed('\"iat\" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');\n }\n }\n return payload;\n};\n","import { compactVerify } from '../jws/compact/verify.js';\nimport jwtPayload from '../lib/jwt_claims_set.js';\nimport { JWTInvalid } from '../util/errors.js';\nexport async function jwtVerify(jwt, key, options) {\n const verified = await compactVerify(jwt, key, options);\n if (verified.protectedHeader.crit?.includes('b64') && verified.protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n const payload = jwtPayload(verified.protectedHeader, verified.payload, options);\n const result = { payload, protectedHeader: verified.protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: verified.key };\n }\n return result;\n}\n","import { compactDecrypt } from '../jwe/compact/decrypt.js';\nimport jwtPayload from '../lib/jwt_claims_set.js';\nimport { JWTClaimValidationFailed } from '../util/errors.js';\nexport async function jwtDecrypt(jwt, key, options) {\n const decrypted = await compactDecrypt(jwt, key, options);\n const payload = jwtPayload(decrypted.protectedHeader, decrypted.plaintext, options);\n const { protectedHeader } = decrypted;\n if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) {\n throw new JWTClaimValidationFailed('replicated \"iss\" claim header parameter mismatch', payload, 'iss', 'mismatch');\n }\n if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {\n throw new JWTClaimValidationFailed('replicated \"sub\" claim header parameter mismatch', payload, 'sub', 'mismatch');\n }\n if (protectedHeader.aud !== undefined &&\n JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {\n throw new JWTClaimValidationFailed('replicated \"aud\" claim header parameter mismatch', payload, 'aud', 'mismatch');\n }\n const result = { payload, protectedHeader };\n if (typeof key === 'function') {\n return { ...result, key: decrypted.key };\n }\n return result;\n}\n","import { FlattenedEncrypt } from '../flattened/encrypt.js';\nexport class CompactEncrypt {\n constructor(plaintext) {\n this._flattened = new FlattenedEncrypt(plaintext);\n }\n setContentEncryptionKey(cek) {\n this._flattened.setContentEncryptionKey(cek);\n return this;\n }\n setInitializationVector(iv) {\n this._flattened.setInitializationVector(iv);\n return this;\n }\n setProtectedHeader(protectedHeader) {\n this._flattened.setProtectedHeader(protectedHeader);\n return this;\n }\n setKeyManagementParameters(parameters) {\n this._flattened.setKeyManagementParameters(parameters);\n return this;\n }\n async encrypt(key, options) {\n const jwe = await this._flattened.encrypt(key, options);\n return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.');\n }\n}\n","import subtleAlgorithm from './subtle_dsa.js';\nimport crypto from './webcrypto.js';\nimport checkKeyLength from './check_key_length.js';\nimport getSignKey from './get_sign_verify_key.js';\nconst sign = async (alg, key, data) => {\n const cryptoKey = await getSignKey(alg, key, 'sign');\n checkKeyLength(alg, cryptoKey);\n const signature = await crypto.subtle.sign(subtleAlgorithm(alg, cryptoKey.algorithm), cryptoKey, data);\n return new Uint8Array(signature);\n};\nexport default sign;\n","import { encode as base64url } from '../../runtime/base64url.js';\nimport sign from '../../runtime/sign.js';\nimport isDisjoint from '../../lib/is_disjoint.js';\nimport { JWSInvalid } from '../../util/errors.js';\nimport { encoder, decoder, concat } from '../../lib/buffer_utils.js';\nimport { checkKeyTypeWithJwk } from '../../lib/check_key_type.js';\nimport validateCrit from '../../lib/validate_crit.js';\nexport class FlattenedSign {\n constructor(payload) {\n if (!(payload instanceof Uint8Array)) {\n throw new TypeError('payload must be an instance of Uint8Array');\n }\n this._payload = payload;\n }\n setProtectedHeader(protectedHeader) {\n if (this._protectedHeader) {\n throw new TypeError('setProtectedHeader can only be called once');\n }\n this._protectedHeader = protectedHeader;\n return this;\n }\n setUnprotectedHeader(unprotectedHeader) {\n if (this._unprotectedHeader) {\n throw new TypeError('setUnprotectedHeader can only be called once');\n }\n this._unprotectedHeader = unprotectedHeader;\n return this;\n }\n async sign(key, options) {\n if (!this._protectedHeader && !this._unprotectedHeader) {\n throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');\n }\n if (!isDisjoint(this._protectedHeader, this._unprotectedHeader)) {\n throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');\n }\n const joseHeader = {\n ...this._protectedHeader,\n ...this._unprotectedHeader,\n };\n const extensions = validateCrit(JWSInvalid, new Map([['b64', true]]), options?.crit, this._protectedHeader, joseHeader);\n let b64 = true;\n if (extensions.has('b64')) {\n b64 = this._protectedHeader.b64;\n if (typeof b64 !== 'boolean') {\n throw new JWSInvalid('The \"b64\" (base64url-encode payload) Header Parameter must be a boolean');\n }\n }\n const { alg } = joseHeader;\n if (typeof alg !== 'string' || !alg) {\n throw new JWSInvalid('JWS \"alg\" (Algorithm) Header Parameter missing or invalid');\n }\n checkKeyTypeWithJwk(alg, key, 'sign');\n let payload = this._payload;\n if (b64) {\n payload = encoder.encode(base64url(payload));\n }\n let protectedHeader;\n if (this._protectedHeader) {\n protectedHeader = encoder.encode(base64url(JSON.stringify(this._protectedHeader)));\n }\n else {\n protectedHeader = encoder.encode('');\n }\n const data = concat(protectedHeader, encoder.encode('.'), payload);\n const signature = await sign(alg, key, data);\n const jws = {\n signature: base64url(signature),\n payload: '',\n };\n if (b64) {\n jws.payload = decoder.decode(payload);\n }\n if (this._unprotectedHeader) {\n jws.header = this._unprotectedHeader;\n }\n if (this._protectedHeader) {\n jws.protected = decoder.decode(protectedHeader);\n }\n return jws;\n }\n}\n","import { FlattenedSign } from '../flattened/sign.js';\nexport class CompactSign {\n constructor(payload) {\n this._flattened = new FlattenedSign(payload);\n }\n setProtectedHeader(protectedHeader) {\n this._flattened.setProtectedHeader(protectedHeader);\n return this;\n }\n async sign(key, options) {\n const jws = await this._flattened.sign(key, options);\n if (jws.payload === undefined) {\n throw new TypeError('use the flattened module for creating JWS with b64: false');\n }\n return `${jws.protected}.${jws.payload}.${jws.signature}`;\n }\n}\n","import { FlattenedSign } from '../flattened/sign.js';\nimport { JWSInvalid } from '../../util/errors.js';\nclass IndividualSignature {\n constructor(sig, key, options) {\n this.parent = sig;\n this.key = key;\n this.options = options;\n }\n setProtectedHeader(protectedHeader) {\n if (this.protectedHeader) {\n throw new TypeError('setProtectedHeader can only be called once');\n }\n this.protectedHeader = protectedHeader;\n return this;\n }\n setUnprotectedHeader(unprotectedHeader) {\n if (this.unprotectedHeader) {\n throw new TypeError('setUnprotectedHeader can only be called once');\n }\n this.unprotectedHeader = unprotectedHeader;\n return this;\n }\n addSignature(...args) {\n return this.parent.addSignature(...args);\n }\n sign(...args) {\n return this.parent.sign(...args);\n }\n done() {\n return this.parent;\n }\n}\nexport class GeneralSign {\n constructor(payload) {\n this._signatures = [];\n this._payload = payload;\n }\n addSignature(key, options) {\n const signature = new IndividualSignature(this, key, options);\n this._signatures.push(signature);\n return signature;\n }\n async sign() {\n if (!this._signatures.length) {\n throw new JWSInvalid('at least one signature must be added');\n }\n const jws = {\n signatures: [],\n payload: '',\n };\n for (let i = 0; i < this._signatures.length; i++) {\n const signature = this._signatures[i];\n const flattened = new FlattenedSign(this._payload);\n flattened.setProtectedHeader(signature.protectedHeader);\n flattened.setUnprotectedHeader(signature.unprotectedHeader);\n const { payload, ...rest } = await flattened.sign(signature.key, signature.options);\n if (i === 0) {\n jws.payload = payload;\n }\n else if (jws.payload !== payload) {\n throw new JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)');\n }\n jws.signatures.push(rest);\n }\n return jws;\n }\n}\n","import epoch from '../lib/epoch.js';\nimport isObject from '../lib/is_object.js';\nimport secs from '../lib/secs.js';\nfunction validateInput(label, input) {\n if (!Number.isFinite(input)) {\n throw new TypeError(`Invalid ${label} input`);\n }\n return input;\n}\nexport class ProduceJWT {\n constructor(payload = {}) {\n if (!isObject(payload)) {\n throw new TypeError('JWT Claims Set MUST be an object');\n }\n this._payload = payload;\n }\n setIssuer(issuer) {\n this._payload = { ...this._payload, iss: issuer };\n return this;\n }\n setSubject(subject) {\n this._payload = { ...this._payload, sub: subject };\n return this;\n }\n setAudience(audience) {\n this._payload = { ...this._payload, aud: audience };\n return this;\n }\n setJti(jwtId) {\n this._payload = { ...this._payload, jti: jwtId };\n return this;\n }\n setNotBefore(input) {\n if (typeof input === 'number') {\n this._payload = { ...this._payload, nbf: validateInput('setNotBefore', input) };\n }\n else if (input instanceof Date) {\n this._payload = { ...this._payload, nbf: validateInput('setNotBefore', epoch(input)) };\n }\n else {\n this._payload = { ...this._payload, nbf: epoch(new Date()) + secs(input) };\n }\n return this;\n }\n setExpirationTime(input) {\n if (typeof input === 'number') {\n this._payload = { ...this._payload, exp: validateInput('setExpirationTime', input) };\n }\n else if (input instanceof Date) {\n this._payload = { ...this._payload, exp: validateInput('setExpirationTime', epoch(input)) };\n }\n else {\n this._payload = { ...this._payload, exp: epoch(new Date()) + secs(input) };\n }\n return this;\n }\n setIssuedAt(input) {\n if (typeof input === 'undefined') {\n this._payload = { ...this._payload, iat: epoch(new Date()) };\n }\n else if (input instanceof Date) {\n this._payload = { ...this._payload, iat: validateInput('setIssuedAt', epoch(input)) };\n }\n else if (typeof input === 'string') {\n this._payload = {\n ...this._payload,\n iat: validateInput('setIssuedAt', epoch(new Date()) + secs(input)),\n };\n }\n else {\n this._payload = { ...this._payload, iat: validateInput('setIssuedAt', input) };\n }\n return this;\n }\n}\n","import { CompactSign } from '../jws/compact/sign.js';\nimport { JWTInvalid } from '../util/errors.js';\nimport { encoder } from '../lib/buffer_utils.js';\nimport { ProduceJWT } from './produce.js';\nexport class SignJWT extends ProduceJWT {\n setProtectedHeader(protectedHeader) {\n this._protectedHeader = protectedHeader;\n return this;\n }\n async sign(key, options) {\n const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));\n sig.setProtectedHeader(this._protectedHeader);\n if (Array.isArray(this._protectedHeader?.crit) &&\n this._protectedHeader.crit.includes('b64') &&\n this._protectedHeader.b64 === false) {\n throw new JWTInvalid('JWTs MUST NOT use unencoded payload');\n }\n return sig.sign(key, options);\n }\n}\n","import { CompactEncrypt } from '../jwe/compact/encrypt.js';\nimport { encoder } from '../lib/buffer_utils.js';\nimport { ProduceJWT } from './produce.js';\nexport class EncryptJWT extends ProduceJWT {\n setProtectedHeader(protectedHeader) {\n if (this._protectedHeader) {\n throw new TypeError('setProtectedHeader can only be called once');\n }\n this._protectedHeader = protectedHeader;\n return this;\n }\n setKeyManagementParameters(parameters) {\n if (this._keyManagementParameters) {\n throw new TypeError('setKeyManagementParameters can only be called once');\n }\n this._keyManagementParameters = parameters;\n return this;\n }\n setContentEncryptionKey(cek) {\n if (this._cek) {\n throw new TypeError('setContentEncryptionKey can only be called once');\n }\n this._cek = cek;\n return this;\n }\n setInitializationVector(iv) {\n if (this._iv) {\n throw new TypeError('setInitializationVector can only be called once');\n }\n this._iv = iv;\n return this;\n }\n replicateIssuerAsHeader() {\n this._replicateIssuerAsHeader = true;\n return this;\n }\n replicateSubjectAsHeader() {\n this._replicateSubjectAsHeader = true;\n return this;\n }\n replicateAudienceAsHeader() {\n this._replicateAudienceAsHeader = true;\n return this;\n }\n async encrypt(key, options) {\n const enc = new CompactEncrypt(encoder.encode(JSON.stringify(this._payload)));\n if (this._replicateIssuerAsHeader) {\n this._protectedHeader = { ...this._protectedHeader, iss: this._payload.iss };\n }\n if (this._replicateSubjectAsHeader) {\n this._protectedHeader = { ...this._protectedHeader, sub: this._payload.sub };\n }\n if (this._replicateAudienceAsHeader) {\n this._protectedHeader = { ...this._protectedHeader, aud: this._payload.aud };\n }\n enc.setProtectedHeader(this._protectedHeader);\n if (this._iv) {\n enc.setInitializationVector(this._iv);\n }\n if (this._cek) {\n enc.setContentEncryptionKey(this._cek);\n }\n if (this._keyManagementParameters) {\n enc.setKeyManagementParameters(this._keyManagementParameters);\n }\n return enc.encrypt(key, options);\n }\n}\n","import digest from '../runtime/digest.js';\nimport { encode as base64url } from '../runtime/base64url.js';\nimport { JOSENotSupported, JWKInvalid } from '../util/errors.js';\nimport { encoder } from '../lib/buffer_utils.js';\nimport isObject from '../lib/is_object.js';\nconst check = (value, description) => {\n if (typeof value !== 'string' || !value) {\n throw new JWKInvalid(`${description} missing or invalid`);\n }\n};\nexport async function calculateJwkThumbprint(jwk, digestAlgorithm) {\n if (!isObject(jwk)) {\n throw new TypeError('JWK must be an object');\n }\n digestAlgorithm ?? (digestAlgorithm = 'sha256');\n if (digestAlgorithm !== 'sha256' &&\n digestAlgorithm !== 'sha384' &&\n digestAlgorithm !== 'sha512') {\n throw new TypeError('digestAlgorithm must one of \"sha256\", \"sha384\", or \"sha512\"');\n }\n let components;\n switch (jwk.kty) {\n case 'EC':\n check(jwk.crv, '\"crv\" (Curve) Parameter');\n check(jwk.x, '\"x\" (X Coordinate) Parameter');\n check(jwk.y, '\"y\" (Y Coordinate) Parameter');\n components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };\n break;\n case 'OKP':\n check(jwk.crv, '\"crv\" (Subtype of Key Pair) Parameter');\n check(jwk.x, '\"x\" (Public Key) Parameter');\n components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };\n break;\n case 'RSA':\n check(jwk.e, '\"e\" (Exponent) Parameter');\n check(jwk.n, '\"n\" (Modulus) Parameter');\n components = { e: jwk.e, kty: jwk.kty, n: jwk.n };\n break;\n case 'oct':\n check(jwk.k, '\"k\" (Key Value) Parameter');\n components = { k: jwk.k, kty: jwk.kty };\n break;\n default:\n throw new JOSENotSupported('\"kty\" (Key Type) Parameter missing or unsupported');\n }\n const data = encoder.encode(JSON.stringify(components));\n return base64url(await digest(digestAlgorithm, data));\n}\nexport async function calculateJwkThumbprintUri(jwk, digestAlgorithm) {\n digestAlgorithm ?? (digestAlgorithm = 'sha256');\n const thumbprint = await calculateJwkThumbprint(jwk, digestAlgorithm);\n return `urn:ietf:params:oauth:jwk-thumbprint:sha-${digestAlgorithm.slice(-3)}:${thumbprint}`;\n}\n","import { importJWK } from '../key/import.js';\nimport isObject from '../lib/is_object.js';\nimport { JWSInvalid } from '../util/errors.js';\nexport async function EmbeddedJWK(protectedHeader, token) {\n const joseHeader = {\n ...protectedHeader,\n ...token?.header,\n };\n if (!isObject(joseHeader.jwk)) {\n throw new JWSInvalid('\"jwk\" (JSON Web Key) Header Parameter must be a JSON object');\n }\n const key = await importJWK({ ...joseHeader.jwk, ext: true }, joseHeader.alg);\n if (key instanceof Uint8Array || key.type !== 'public') {\n throw new JWSInvalid('\"jwk\" (JSON Web Key) Header Parameter must be a public key');\n }\n return key;\n}\n","import { importJWK } from '../key/import.js';\nimport { JWKSInvalid, JOSENotSupported, JWKSNoMatchingKey, JWKSMultipleMatchingKeys, } from '../util/errors.js';\nimport isObject from '../lib/is_object.js';\nfunction getKtyFromAlg(alg) {\n switch (typeof alg === 'string' && alg.slice(0, 2)) {\n case 'RS':\n case 'PS':\n return 'RSA';\n case 'ES':\n return 'EC';\n case 'Ed':\n return 'OKP';\n default:\n throw new JOSENotSupported('Unsupported \"alg\" value for a JSON Web Key Set');\n }\n}\nfunction isJWKSLike(jwks) {\n return (jwks &&\n typeof jwks === 'object' &&\n Array.isArray(jwks.keys) &&\n jwks.keys.every(isJWKLike));\n}\nfunction isJWKLike(key) {\n return isObject(key);\n}\nfunction clone(obj) {\n if (typeof structuredClone === 'function') {\n return structuredClone(obj);\n }\n return JSON.parse(JSON.stringify(obj));\n}\nclass LocalJWKSet {\n constructor(jwks) {\n this._cached = new WeakMap();\n if (!isJWKSLike(jwks)) {\n throw new JWKSInvalid('JSON Web Key Set malformed');\n }\n this._jwks = clone(jwks);\n }\n async getKey(protectedHeader, token) {\n const { alg, kid } = { ...protectedHeader, ...token?.header };\n const kty = getKtyFromAlg(alg);\n const candidates = this._jwks.keys.filter((jwk) => {\n let candidate = kty === jwk.kty;\n if (candidate && typeof kid === 'string') {\n candidate = kid === jwk.kid;\n }\n if (candidate && typeof jwk.alg === 'string') {\n candidate = alg === jwk.alg;\n }\n if (candidate && typeof jwk.use === 'string') {\n candidate = jwk.use === 'sig';\n }\n if (candidate && Array.isArray(jwk.key_ops)) {\n candidate = jwk.key_ops.includes('verify');\n }\n if (candidate) {\n switch (alg) {\n case 'ES256':\n candidate = jwk.crv === 'P-256';\n break;\n case 'ES256K':\n candidate = jwk.crv === 'secp256k1';\n break;\n case 'ES384':\n candidate = jwk.crv === 'P-384';\n break;\n case 'ES512':\n candidate = jwk.crv === 'P-521';\n break;\n case 'Ed25519':\n candidate = jwk.crv === 'Ed25519';\n break;\n case 'EdDSA':\n candidate = jwk.crv === 'Ed25519' || jwk.crv === 'Ed448';\n break;\n }\n }\n return candidate;\n });\n const { 0: jwk, length } = candidates;\n if (length === 0) {\n throw new JWKSNoMatchingKey();\n }\n if (length !== 1) {\n const error = new JWKSMultipleMatchingKeys();\n const { _cached } = this;\n error[Symbol.asyncIterator] = async function* () {\n for (const jwk of candidates) {\n try {\n yield await importWithAlgCache(_cached, jwk, alg);\n }\n catch { }\n }\n };\n throw error;\n }\n return importWithAlgCache(this._cached, jwk, alg);\n }\n}\nasync function importWithAlgCache(cache, jwk, alg) {\n const cached = cache.get(jwk) || cache.set(jwk, {}).get(jwk);\n if (cached[alg] === undefined) {\n const key = await importJWK({ ...jwk, ext: true }, alg);\n if (key instanceof Uint8Array || key.type !== 'public') {\n throw new JWKSInvalid('JSON Web Key Set members must be public keys');\n }\n cached[alg] = key;\n }\n return cached[alg];\n}\nexport function createLocalJWKSet(jwks) {\n const set = new LocalJWKSet(jwks);\n const localJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(localJWKSet, {\n jwks: {\n value: () => clone(set._jwks),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n });\n return localJWKSet;\n}\n","import { JOSEError, JWKSTimeout } from '../util/errors.js';\nconst fetchJwks = async (url, timeout, options) => {\n let controller;\n let id;\n let timedOut = false;\n if (typeof AbortController === 'function') {\n controller = new AbortController();\n id = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeout);\n }\n const response = await fetch(url.href, {\n signal: controller ? controller.signal : undefined,\n redirect: 'manual',\n headers: options.headers,\n }).catch((err) => {\n if (timedOut)\n throw new JWKSTimeout();\n throw err;\n });\n if (id !== undefined)\n clearTimeout(id);\n if (response.status !== 200) {\n throw new JOSEError('Expected 200 OK from the JSON Web Key Set HTTP response');\n }\n try {\n return await response.json();\n }\n catch {\n throw new JOSEError('Failed to parse the JSON Web Key Set HTTP response as JSON');\n }\n};\nexport default fetchJwks;\n","import fetchJwks from '../runtime/fetch_jwks.js';\nimport { JWKSNoMatchingKey } from '../util/errors.js';\nimport { createLocalJWKSet } from './local.js';\nimport isObject from '../lib/is_object.js';\nfunction isCloudflareWorkers() {\n return (typeof WebSocketPair !== 'undefined' ||\n (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') ||\n (typeof EdgeRuntime !== 'undefined' && EdgeRuntime === 'vercel'));\n}\nlet USER_AGENT;\nif (typeof navigator === 'undefined' || !navigator.userAgent?.startsWith?.('Mozilla/5.0 ')) {\n const NAME = 'jose';\n const VERSION = 'v5.10.0';\n USER_AGENT = `${NAME}/${VERSION}`;\n}\nexport const jwksCache = Symbol();\nfunction isFreshJwksCache(input, cacheMaxAge) {\n if (typeof input !== 'object' || input === null) {\n return false;\n }\n if (!('uat' in input) || typeof input.uat !== 'number' || Date.now() - input.uat >= cacheMaxAge) {\n return false;\n }\n if (!('jwks' in input) ||\n !isObject(input.jwks) ||\n !Array.isArray(input.jwks.keys) ||\n !Array.prototype.every.call(input.jwks.keys, isObject)) {\n return false;\n }\n return true;\n}\nclass RemoteJWKSet {\n constructor(url, options) {\n if (!(url instanceof URL)) {\n throw new TypeError('url must be an instance of URL');\n }\n this._url = new URL(url.href);\n this._options = { agent: options?.agent, headers: options?.headers };\n this._timeoutDuration =\n typeof options?.timeoutDuration === 'number' ? options?.timeoutDuration : 5000;\n this._cooldownDuration =\n typeof options?.cooldownDuration === 'number' ? options?.cooldownDuration : 30000;\n this._cacheMaxAge = typeof options?.cacheMaxAge === 'number' ? options?.cacheMaxAge : 600000;\n if (options?.[jwksCache] !== undefined) {\n this._cache = options?.[jwksCache];\n if (isFreshJwksCache(options?.[jwksCache], this._cacheMaxAge)) {\n this._jwksTimestamp = this._cache.uat;\n this._local = createLocalJWKSet(this._cache.jwks);\n }\n }\n }\n coolingDown() {\n return typeof this._jwksTimestamp === 'number'\n ? Date.now() < this._jwksTimestamp + this._cooldownDuration\n : false;\n }\n fresh() {\n return typeof this._jwksTimestamp === 'number'\n ? Date.now() < this._jwksTimestamp + this._cacheMaxAge\n : false;\n }\n async getKey(protectedHeader, token) {\n if (!this._local || !this.fresh()) {\n await this.reload();\n }\n try {\n return await this._local(protectedHeader, token);\n }\n catch (err) {\n if (err instanceof JWKSNoMatchingKey) {\n if (this.coolingDown() === false) {\n await this.reload();\n return this._local(protectedHeader, token);\n }\n }\n throw err;\n }\n }\n async reload() {\n if (this._pendingFetch && isCloudflareWorkers()) {\n this._pendingFetch = undefined;\n }\n const headers = new Headers(this._options.headers);\n if (USER_AGENT && !headers.has('User-Agent')) {\n headers.set('User-Agent', USER_AGENT);\n this._options.headers = Object.fromEntries(headers.entries());\n }\n this._pendingFetch || (this._pendingFetch = fetchJwks(this._url, this._timeoutDuration, this._options)\n .then((json) => {\n this._local = createLocalJWKSet(json);\n if (this._cache) {\n this._cache.uat = Date.now();\n this._cache.jwks = json;\n }\n this._jwksTimestamp = Date.now();\n this._pendingFetch = undefined;\n })\n .catch((err) => {\n this._pendingFetch = undefined;\n throw err;\n }));\n await this._pendingFetch;\n }\n}\nexport function createRemoteJWKSet(url, options) {\n const set = new RemoteJWKSet(url, options);\n const remoteJWKSet = async (protectedHeader, token) => set.getKey(protectedHeader, token);\n Object.defineProperties(remoteJWKSet, {\n coolingDown: {\n get: () => set.coolingDown(),\n enumerable: true,\n configurable: false,\n },\n fresh: {\n get: () => set.fresh(),\n enumerable: true,\n configurable: false,\n },\n reload: {\n value: () => set.reload(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n reloading: {\n get: () => !!set._pendingFetch,\n enumerable: true,\n configurable: false,\n },\n jwks: {\n value: () => set._local?.jwks(),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n });\n return remoteJWKSet;\n}\nexport const experimental_jwksCache = jwksCache;\n","import * as base64url from '../runtime/base64url.js';\nimport { decoder } from '../lib/buffer_utils.js';\nimport { JWTInvalid } from '../util/errors.js';\nimport jwtPayload from '../lib/jwt_claims_set.js';\nimport { ProduceJWT } from './produce.js';\nexport class UnsecuredJWT extends ProduceJWT {\n encode() {\n const header = base64url.encode(JSON.stringify({ alg: 'none' }));\n const payload = base64url.encode(JSON.stringify(this._payload));\n return `${header}.${payload}.`;\n }\n static decode(jwt, options) {\n if (typeof jwt !== 'string') {\n throw new JWTInvalid('Unsecured JWT must be a string');\n }\n const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.');\n if (length !== 3 || signature !== '') {\n throw new JWTInvalid('Invalid Unsecured JWT');\n }\n let header;\n try {\n header = JSON.parse(decoder.decode(base64url.decode(encodedHeader)));\n if (header.alg !== 'none')\n throw new Error();\n }\n catch {\n throw new JWTInvalid('Invalid Unsecured JWT');\n }\n const payload = jwtPayload(header, base64url.decode(encodedPayload), options);\n return { payload, header };\n }\n}\n","import * as base64url from '../runtime/base64url.js';\nexport const encode = base64url.encode;\nexport const decode = base64url.decode;\n","import { decode as base64url } from './base64url.js';\nimport { decoder } from '../lib/buffer_utils.js';\nimport isObject from '../lib/is_object.js';\nexport function decodeProtectedHeader(token) {\n let protectedB64u;\n if (typeof token === 'string') {\n const parts = token.split('.');\n if (parts.length === 3 || parts.length === 5) {\n ;\n [protectedB64u] = parts;\n }\n }\n else if (typeof token === 'object' && token) {\n if ('protected' in token) {\n protectedB64u = token.protected;\n }\n else {\n throw new TypeError('Token does not contain a Protected Header');\n }\n }\n try {\n if (typeof protectedB64u !== 'string' || !protectedB64u) {\n throw new Error();\n }\n const result = JSON.parse(decoder.decode(base64url(protectedB64u)));\n if (!isObject(result)) {\n throw new Error();\n }\n return result;\n }\n catch {\n throw new TypeError('Invalid Token or Protected Header formatting');\n }\n}\n","import { decode as base64url } from './base64url.js';\nimport { decoder } from '../lib/buffer_utils.js';\nimport isObject from '../lib/is_object.js';\nimport { JWTInvalid } from './errors.js';\nexport function decodeJwt(jwt) {\n if (typeof jwt !== 'string')\n throw new JWTInvalid('JWTs must use Compact JWS serialization, JWT must be a string');\n const { 1: payload, length } = jwt.split('.');\n if (length === 5)\n throw new JWTInvalid('Only JWTs using Compact JWS serialization can be decoded');\n if (length !== 3)\n throw new JWTInvalid('Invalid JWT');\n if (!payload)\n throw new JWTInvalid('JWTs must contain a payload');\n let decoded;\n try {\n decoded = base64url(payload);\n }\n catch {\n throw new JWTInvalid('Failed to base64url decode the payload');\n }\n let result;\n try {\n result = JSON.parse(decoder.decode(decoded));\n }\n catch {\n throw new JWTInvalid('Failed to parse the decoded payload as JSON');\n }\n if (!isObject(result))\n throw new JWTInvalid('Invalid JWT Claims Set');\n return result;\n}\n","import crypto from './webcrypto.js';\nimport { JOSENotSupported } from '../util/errors.js';\nimport random from './random.js';\nexport async function generateSecret(alg, options) {\n let length;\n let algorithm;\n let keyUsages;\n switch (alg) {\n case 'HS256':\n case 'HS384':\n case 'HS512':\n length = parseInt(alg.slice(-3), 10);\n algorithm = { name: 'HMAC', hash: `SHA-${length}`, length };\n keyUsages = ['sign', 'verify'];\n break;\n case 'A128CBC-HS256':\n case 'A192CBC-HS384':\n case 'A256CBC-HS512':\n length = parseInt(alg.slice(-3), 10);\n return random(new Uint8Array(length >> 3));\n case 'A128KW':\n case 'A192KW':\n case 'A256KW':\n length = parseInt(alg.slice(1, 4), 10);\n algorithm = { name: 'AES-KW', length };\n keyUsages = ['wrapKey', 'unwrapKey'];\n break;\n case 'A128GCMKW':\n case 'A192GCMKW':\n case 'A256GCMKW':\n case 'A128GCM':\n case 'A192GCM':\n case 'A256GCM':\n length = parseInt(alg.slice(1, 4), 10);\n algorithm = { name: 'AES-GCM', length };\n keyUsages = ['encrypt', 'decrypt'];\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);\n}\nfunction getModulusLengthOption(options) {\n const modulusLength = options?.modulusLength ?? 2048;\n if (typeof modulusLength !== 'number' || modulusLength < 2048) {\n throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');\n }\n return modulusLength;\n}\nexport async function generateKeyPair(alg, options) {\n let algorithm;\n let keyUsages;\n switch (alg) {\n case 'PS256':\n case 'PS384':\n case 'PS512':\n algorithm = {\n name: 'RSA-PSS',\n hash: `SHA-${alg.slice(-3)}`,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n modulusLength: getModulusLengthOption(options),\n };\n keyUsages = ['sign', 'verify'];\n break;\n case 'RS256':\n case 'RS384':\n case 'RS512':\n algorithm = {\n name: 'RSASSA-PKCS1-v1_5',\n hash: `SHA-${alg.slice(-3)}`,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n modulusLength: getModulusLengthOption(options),\n };\n keyUsages = ['sign', 'verify'];\n break;\n case 'RSA-OAEP':\n case 'RSA-OAEP-256':\n case 'RSA-OAEP-384':\n case 'RSA-OAEP-512':\n algorithm = {\n name: 'RSA-OAEP',\n hash: `SHA-${parseInt(alg.slice(-3), 10) || 1}`,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n modulusLength: getModulusLengthOption(options),\n };\n keyUsages = ['decrypt', 'unwrapKey', 'encrypt', 'wrapKey'];\n break;\n case 'ES256':\n algorithm = { name: 'ECDSA', namedCurve: 'P-256' };\n keyUsages = ['sign', 'verify'];\n break;\n case 'ES384':\n algorithm = { name: 'ECDSA', namedCurve: 'P-384' };\n keyUsages = ['sign', 'verify'];\n break;\n case 'ES512':\n algorithm = { name: 'ECDSA', namedCurve: 'P-521' };\n keyUsages = ['sign', 'verify'];\n break;\n case 'Ed25519':\n algorithm = { name: 'Ed25519' };\n keyUsages = ['sign', 'verify'];\n break;\n case 'EdDSA': {\n keyUsages = ['sign', 'verify'];\n const crv = options?.crv ?? 'Ed25519';\n switch (crv) {\n case 'Ed25519':\n case 'Ed448':\n algorithm = { name: crv };\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported crv option provided');\n }\n break;\n }\n case 'ECDH-ES':\n case 'ECDH-ES+A128KW':\n case 'ECDH-ES+A192KW':\n case 'ECDH-ES+A256KW': {\n keyUsages = ['deriveKey', 'deriveBits'];\n const crv = options?.crv ?? 'P-256';\n switch (crv) {\n case 'P-256':\n case 'P-384':\n case 'P-521': {\n algorithm = { name: 'ECDH', namedCurve: crv };\n break;\n }\n case 'X25519':\n case 'X448':\n algorithm = { name: crv };\n break;\n default:\n throw new JOSENotSupported('Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448');\n }\n break;\n }\n default:\n throw new JOSENotSupported('Invalid or unsupported JWK \"alg\" (Algorithm) Parameter value');\n }\n return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);\n}\n","import { generateKeyPair as generate } from '../runtime/generate.js';\nexport async function generateKeyPair(alg, options) {\n return generate(alg, options);\n}\n","import { generateSecret as generate } from '../runtime/generate.js';\nexport async function generateSecret(alg, options) {\n return generate(alg, options);\n}\n","export default 'WebCryptoAPI';\n","import value from '../runtime/runtime.js';\nexport default value;\n","export { compactDecrypt } from './jwe/compact/decrypt.js';\nexport { flattenedDecrypt } from './jwe/flattened/decrypt.js';\nexport { generalDecrypt } from './jwe/general/decrypt.js';\nexport { GeneralEncrypt } from './jwe/general/encrypt.js';\nexport { compactVerify } from './jws/compact/verify.js';\nexport { flattenedVerify } from './jws/flattened/verify.js';\nexport { generalVerify } from './jws/general/verify.js';\nexport { jwtVerify } from './jwt/verify.js';\nexport { jwtDecrypt } from './jwt/decrypt.js';\nexport { CompactEncrypt } from './jwe/compact/encrypt.js';\nexport { FlattenedEncrypt } from './jwe/flattened/encrypt.js';\nexport { CompactSign } from './jws/compact/sign.js';\nexport { FlattenedSign } from './jws/flattened/sign.js';\nexport { GeneralSign } from './jws/general/sign.js';\nexport { SignJWT } from './jwt/sign.js';\nexport { EncryptJWT } from './jwt/encrypt.js';\nexport { calculateJwkThumbprint, calculateJwkThumbprintUri } from './jwk/thumbprint.js';\nexport { EmbeddedJWK } from './jwk/embedded.js';\nexport { createLocalJWKSet } from './jwks/local.js';\nexport { createRemoteJWKSet, jwksCache, experimental_jwksCache } from './jwks/remote.js';\nexport { UnsecuredJWT } from './jwt/unsecured.js';\nexport { exportPKCS8, exportSPKI, exportJWK } from './key/export.js';\nexport { importSPKI, importPKCS8, importX509, importJWK } from './key/import.js';\nexport { decodeProtectedHeader } from './util/decode_protected_header.js';\nexport { decodeJwt } from './util/decode_jwt.js';\nexport * as errors from './util/errors.js';\nexport { generateKeyPair } from './key/generate_key_pair.js';\nexport { generateSecret } from './key/generate_secret.js';\nexport * as base64url from './util/base64url.js';\nexport { default as cryptoRuntime } from './util/runtime.js';\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar verify_vercel_oidc_token_exports = {};\n__export(verify_vercel_oidc_token_exports, {\n verifyVercelOidcToken: () => verifyVercelOidcToken\n});\nmodule.exports = __toCommonJS(verify_vercel_oidc_token_exports);\nvar import_jose = require(\"jose\");\nconst VERCEL_OIDC_ISSUER = \"https://oidc.vercel.com\";\nconst VERCEL_OIDC_JWKS_URL = new URL(\n \"https://oidc.vercel.com/.well-known/jwks\"\n);\nconst DEFAULT_ALGORITHMS = [\"RS256\"];\nconst VERCEL_OIDC_JWKS = (0, import_jose.createRemoteJWKSet)(VERCEL_OIDC_JWKS_URL);\nasync function verifyVercelOidcToken(token, options) {\n const {\n algorithms,\n projectId = process.env.VERCEL_PROJECT_ID,\n environment = process.env.VERCEL_TARGET_ENV || process.env.VERCEL_ENV,\n ownerId,\n ...verifyOptions\n } = options ?? {};\n if (projectId === \"*\" && ownerId === void 0 && !hasAudienceVerification(verifyOptions.audience)) {\n throw new TypeError(\n \"Expected ownerId or audience to be provided when projectId is '*'.\"\n );\n }\n const result = await (0, import_jose.jwtVerify)(token, VERCEL_OIDC_JWKS, {\n ...verifyOptions,\n algorithms: algorithms ?? DEFAULT_ALGORITHMS\n });\n validateIssuer(result.payload.iss);\n validateClaim({\n actual: result.payload.project_id,\n claim: \"project_id\",\n env: \"VERCEL_PROJECT_ID\",\n expected: projectId,\n option: \"projectId\"\n });\n validateClaim({\n actual: result.payload.environment,\n claim: \"environment\",\n env: \"VERCEL_TARGET_ENV or VERCEL_ENV\",\n expected: environment,\n option: \"environment\"\n });\n validateOptionalClaim({\n actual: result.payload.owner_id,\n claim: \"owner_id\",\n expected: ownerId\n });\n return result;\n}\nfunction hasAudienceVerification(audience) {\n return Array.isArray(audience) ? audience.length > 0 : audience !== void 0;\n}\nfunction validateIssuer(actual) {\n if (actual !== VERCEL_OIDC_ISSUER && (typeof actual !== \"string\" || !actual.startsWith(`${VERCEL_OIDC_ISSUER}/`))) {\n throw new TypeError(\n `Expected Vercel OIDC token iss claim to be \"${VERCEL_OIDC_ISSUER}\" or to start with \"${VERCEL_OIDC_ISSUER}/\".`\n );\n }\n}\nfunction validateClaim({\n actual,\n claim,\n env,\n expected,\n option\n}) {\n if (expected === \"*\") {\n return;\n }\n if (expected === void 0 || expected.length === 0) {\n throw new TypeError(\n `Expected ${env} to be set or ${option} to be provided. Pass ${option}: '*' to allow any ${claim} claim.`\n );\n }\n if (Array.isArray(expected) && typeof actual === \"string\" && expected.includes(actual)) {\n return;\n }\n if (actual !== expected) {\n throw new TypeError(\n Array.isArray(expected) ? `Expected Vercel OIDC token ${claim} claim to be one of: ${expected.map((value) => `\"${value}\"`).join(\", \")}.` : `Expected Vercel OIDC token ${claim} claim to be \"${expected}\".`\n );\n }\n}\nfunction validateOptionalClaim({\n actual,\n claim,\n expected\n}) {\n if (expected === void 0) {\n return;\n }\n if (actual !== expected) {\n throw new TypeError(\n `Expected Vercel OIDC token ${claim} claim to be \"${expected}\".`\n );\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n verifyVercelOidcToken\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar auth_errors_exports = {};\n__export(auth_errors_exports, {\n AccessTokenMissingError: () => AccessTokenMissingError,\n RefreshAccessTokenFailedError: () => RefreshAccessTokenFailedError\n});\nmodule.exports = __toCommonJS(auth_errors_exports);\nclass AccessTokenMissingError extends Error {\n constructor() {\n super(\n \"No authentication found. Please log in with the Vercel CLI (vercel login).\"\n );\n this.name = \"AccessTokenMissingError\";\n }\n}\nclass RefreshAccessTokenFailedError extends Error {\n constructor(cause) {\n super(\"Failed to refresh authentication token.\");\n this.name = \"RefreshAccessTokenFailedError\";\n if (cause !== void 0) {\n this.cause = cause;\n }\n }\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n AccessTokenMissingError,\n RefreshAccessTokenFailedError\n});\n","\"use strict\";\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toCommonJS = (mod) => __copyProps(__defProp({}, \"__esModule\", { value: true }), mod);\nvar index_browser_exports = {};\n__export(index_browser_exports, {\n AccessTokenMissingError: () => import_auth_errors.AccessTokenMissingError,\n RefreshAccessTokenFailedError: () => import_auth_errors.RefreshAccessTokenFailedError,\n getContext: () => import_get_context.getContext,\n getVercelOidcToken: () => getVercelOidcToken,\n getVercelOidcTokenSync: () => getVercelOidcTokenSync,\n getVercelToken: () => getVercelToken,\n verifyVercelOidcToken: () => import_verify_vercel_oidc_token.verifyVercelOidcToken\n});\nmodule.exports = __toCommonJS(index_browser_exports);\nvar import_get_context = require(\"./get-context\");\nvar import_verify_vercel_oidc_token = require(\"./verify-vercel-oidc-token\");\nvar import_auth_errors = require(\"./auth-errors\");\nasync function getVercelOidcToken() {\n return \"\";\n}\nfunction getVercelOidcTokenSync() {\n return \"\";\n}\nasync function getVercelToken() {\n throw new Error(\"getVercelToken is not supported in browser environments\");\n}\n// Annotate the CommonJS export names for ESM import in node:\n0 && (module.exports = {\n AccessTokenMissingError,\n RefreshAccessTokenFailedError,\n getContext,\n getVercelOidcToken,\n getVercelOidcTokenSync,\n getVercelToken,\n verifyVercelOidcToken\n});\n","function RetryOperation(timeouts, options) {\n // Compatibility for the old (timeouts, retryForever) signature\n if (typeof options === 'boolean') {\n options = { forever: options };\n }\n\n this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));\n this._timeouts = timeouts;\n this._options = options || {};\n this._maxRetryTime = options && options.maxRetryTime || Infinity;\n this._fn = null;\n this._errors = [];\n this._attempts = 1;\n this._operationTimeout = null;\n this._operationTimeoutCb = null;\n this._timeout = null;\n this._operationStart = null;\n this._timer = null;\n\n if (this._options.forever) {\n this._cachedTimeouts = this._timeouts.slice(0);\n }\n}\nmodule.exports = RetryOperation;\n\nRetryOperation.prototype.reset = function() {\n this._attempts = 1;\n this._timeouts = this._originalTimeouts.slice(0);\n}\n\nRetryOperation.prototype.stop = function() {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n if (this._timer) {\n clearTimeout(this._timer);\n }\n\n this._timeouts = [];\n this._cachedTimeouts = null;\n};\n\nRetryOperation.prototype.retry = function(err) {\n if (this._timeout) {\n clearTimeout(this._timeout);\n }\n\n if (!err) {\n return false;\n }\n var currentTime = new Date().getTime();\n if (err && currentTime - this._operationStart >= this._maxRetryTime) {\n this._errors.push(err);\n this._errors.unshift(new Error('RetryOperation timeout occurred'));\n return false;\n }\n\n this._errors.push(err);\n\n var timeout = this._timeouts.shift();\n if (timeout === undefined) {\n if (this._cachedTimeouts) {\n // retry forever, only keep last error\n this._errors.splice(0, this._errors.length - 1);\n timeout = this._cachedTimeouts.slice(-1);\n } else {\n return false;\n }\n }\n\n var self = this;\n this._timer = setTimeout(function() {\n self._attempts++;\n\n if (self._operationTimeoutCb) {\n self._timeout = setTimeout(function() {\n self._operationTimeoutCb(self._attempts);\n }, self._operationTimeout);\n\n if (self._options.unref) {\n self._timeout.unref();\n }\n }\n\n self._fn(self._attempts);\n }, timeout);\n\n if (this._options.unref) {\n this._timer.unref();\n }\n\n return true;\n};\n\nRetryOperation.prototype.attempt = function(fn, timeoutOps) {\n this._fn = fn;\n\n if (timeoutOps) {\n if (timeoutOps.timeout) {\n this._operationTimeout = timeoutOps.timeout;\n }\n if (timeoutOps.cb) {\n this._operationTimeoutCb = timeoutOps.cb;\n }\n }\n\n var self = this;\n if (this._operationTimeoutCb) {\n this._timeout = setTimeout(function() {\n self._operationTimeoutCb();\n }, self._operationTimeout);\n }\n\n this._operationStart = new Date().getTime();\n\n this._fn(this._attempts);\n};\n\nRetryOperation.prototype.try = function(fn) {\n console.log('Using RetryOperation.try() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = function(fn) {\n console.log('Using RetryOperation.start() is deprecated');\n this.attempt(fn);\n};\n\nRetryOperation.prototype.start = RetryOperation.prototype.try;\n\nRetryOperation.prototype.errors = function() {\n return this._errors;\n};\n\nRetryOperation.prototype.attempts = function() {\n return this._attempts;\n};\n\nRetryOperation.prototype.mainError = function() {\n if (this._errors.length === 0) {\n return null;\n }\n\n var counts = {};\n var mainError = null;\n var mainErrorCount = 0;\n\n for (var i = 0; i < this._errors.length; i++) {\n var error = this._errors[i];\n var message = error.message;\n var count = (counts[message] || 0) + 1;\n\n counts[message] = count;\n\n if (count >= mainErrorCount) {\n mainError = error;\n mainErrorCount = count;\n }\n }\n\n return mainError;\n};\n","var RetryOperation = require('./retry_operation');\n\nexports.operation = function(options) {\n var timeouts = exports.timeouts(options);\n return new RetryOperation(timeouts, {\n forever: options && (options.forever || options.retries === Infinity),\n unref: options && options.unref,\n maxRetryTime: options && options.maxRetryTime\n });\n};\n\nexports.timeouts = function(options) {\n if (options instanceof Array) {\n return [].concat(options);\n }\n\n var opts = {\n retries: 10,\n factor: 2,\n minTimeout: 1 * 1000,\n maxTimeout: Infinity,\n randomize: false\n };\n for (var key in options) {\n opts[key] = options[key];\n }\n\n if (opts.minTimeout > opts.maxTimeout) {\n throw new Error('minTimeout is greater than maxTimeout');\n }\n\n var timeouts = [];\n for (var i = 0; i < opts.retries; i++) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n if (options && options.forever && !timeouts.length) {\n timeouts.push(this.createTimeout(i, opts));\n }\n\n // sort the array numerically ascending\n timeouts.sort(function(a,b) {\n return a - b;\n });\n\n return timeouts;\n};\n\nexports.createTimeout = function(attempt, opts) {\n var random = (opts.randomize)\n ? (Math.random() + 1)\n : 1;\n\n var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));\n timeout = Math.min(timeout, opts.maxTimeout);\n\n return timeout;\n};\n\nexports.wrap = function(obj, options, methods) {\n if (options instanceof Array) {\n methods = options;\n options = null;\n }\n\n if (!methods) {\n methods = [];\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n methods.push(key);\n }\n }\n }\n\n for (var i = 0; i < methods.length; i++) {\n var method = methods[i];\n var original = obj[method];\n\n obj[method] = function retryWrapper(original) {\n var op = exports.operation(options);\n var args = Array.prototype.slice.call(arguments, 1);\n var callback = args.pop();\n\n args.push(function(err) {\n if (op.retry(err)) {\n return;\n }\n if (err) {\n arguments[0] = op.mainError();\n }\n callback.apply(this, arguments);\n });\n\n op.attempt(function() {\n original.apply(obj, args);\n });\n }.bind(obj, original);\n obj[method].options = options;\n }\n};\n","module.exports = require('./lib/retry');","// Packages\nvar retrier = require('retry');\n\nfunction retry(fn, opts) {\n function run(resolve, reject) {\n var options = opts || {};\n var op;\n\n // Default `randomize` to true\n if (!('randomize' in options)) {\n options.randomize = true;\n }\n\n op = retrier.operation(options);\n\n // We allow the user to abort retrying\n // this makes sense in the cases where\n // knowledge is obtained that retrying\n // would be futile (e.g.: auth errors)\n\n function bail(err) {\n reject(err || new Error('Aborted'));\n }\n\n function onError(err, num) {\n if (err.bail) {\n bail(err);\n return;\n }\n\n if (!op.retry(err)) {\n reject(op.mainError());\n } else if (options.onRetry) {\n options.onRetry(err, num);\n }\n }\n\n function runAttempt(num) {\n var val;\n\n try {\n val = fn(bail, num);\n } catch (err) {\n onError(err, num);\n return;\n }\n\n Promise.resolve(val)\n .then(resolve)\n .catch(function catchIt(err) {\n onError(err, num);\n });\n }\n\n op.attempt(runAttempt);\n }\n\n return new Promise(run);\n}\n\nmodule.exports = retry;\n","function throttle(function_, wait) {\n\tif (typeof function_ !== 'function') {\n\t\tthrow new TypeError(`Expected the first argument to be a \\`function\\`, got \\`${typeof function_}\\`.`);\n\t}\n\n\t// TODO: Add `wait` validation too in the next major version.\n\n\tlet timeoutId;\n\tlet lastCallTime = 0;\n\n\treturn function throttled(...arguments_) { // eslint-disable-line func-names\n\t\tclearTimeout(timeoutId);\n\n\t\tconst now = Date.now();\n\t\tconst timeSinceLastCall = now - lastCallTime;\n\t\tconst delayForNextCall = wait - timeSinceLastCall;\n\n\t\tif (delayForNextCall <= 0) {\n\t\t\tlastCallTime = now;\n\t\t\tfunction_.apply(this, arguments_);\n\t\t} else {\n\t\t\ttimeoutId = setTimeout(() => {\n\t\t\t\tlastCallTime = Date.now();\n\t\t\t\tfunction_.apply(this, arguments_);\n\t\t\t}, delayForNextCall);\n\t\t}\n\t};\n}\n\nmodule.exports = throttle;\n","/**\n * Determines if the current process is a Node.js process.\n */\nexport function isNodeProcess(): boolean {\n if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {\n return true\n }\n\n if (typeof process !== 'undefined') {\n // Electron (https://www.electronjs.org/docs/latest/api/process#processtype-readonly)\n const type = (process as any).type\n if (type === 'renderer' || type === 'worker') {\n return false\n }\n\n\n return !!(\n process.versions &&\n process.versions.node\n )\n }\n\n return false\n}\n","// common util interface for blob raw commands, not meant to be used directly\n// this is why it's not exported from index/client\n\nimport type { Readable } from 'node:stream';\nimport { isNodeProcess } from 'is-node-process';\nimport type { RequestInit, Response } from 'undici';\nimport { isNodeJsReadableStream } from './multipart/helpers';\nimport type { PutBody } from './put-helpers';\nimport { getVercelOidcToken } from './vercel-oidc-token';\n\nexport { bytes } from './bytes';\n\nconst defaultVercelBlobApiUrl = 'https://vercel.com/api/blob';\n\nexport interface BlobCommandOptions {\n /**\n * Define your blob API token.\n * When supplied, this takes priority over process.env.VERCEL_OIDC_TOKEN and process.env.BLOB_READ_WRITE_TOKEN.\n * @defaultvalue process.env.BLOB_READ_WRITE_TOKEN\n */\n token?: string;\n /**\n * Define your Vercel OIDC token for store-scoped blob operations.\n * Use this together with `storeId` (or `BLOB_STORE_ID`) when you want to pass OIDC credentials explicitly.\n * @defaultvalue process.env.VERCEL_OIDC_TOKEN\n */\n oidcToken?: string;\n /**\n * Blob store id. Used to override process.env.BLOB_STORE_ID when Vercel OIDC token is available.\n * @defaultvalue process.env.BLOB_STORE_ID\n */\n storeId?: string;\n /**\n * `AbortSignal` to cancel the running request. See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\n */\n abortSignal?: AbortSignal;\n}\n\nexport interface PresignedUrlPayload {\n delegationToken: string;\n signature: string;\n params: Record<string, string>;\n}\n\n/**\n * Presigned control-plane URL for writes (`put`, `copy`, multipart) and other\n * methods built on {@link CommonCreateBlobOptions}. When set, it is used as the\n * fetch target instead of composing `getApiUrl` with a bearer token.\n */\nexport interface BlobPresignedCommandOptions extends BlobCommandOptions {\n /**\n * Takes precedence over `token` and store credentials for supported calls.\n */\n presignedUrlPayload?: PresignedUrlPayload;\n}\n\n/**\n * The access level of a blob.\n * - 'public': The blob is publicly accessible via its URL.\n * - 'private': The blob requires authentication to access.\n */\nexport type BlobAccessType = 'public' | 'private';\n\n// shared interface for put, copy and multipart upload\nexport interface CommonCreateBlobOptions extends BlobCommandOptions {\n /**\n * Whether the blob should be publicly accessible.\n * - 'public': The blob will be publicly accessible via its URL.\n * - 'private': The blob will require authentication to access.\n */\n access: BlobAccessType;\n /**\n * Adds a random suffix to the filename.\n * @defaultvalue false\n */\n addRandomSuffix?: boolean;\n /**\n * Allow overwriting an existing blob. By default this is set to false and will throw an error if the blob already exists.\n * @defaultvalue false\n */\n allowOverwrite?: boolean;\n /**\n * Defines the content type of the blob. By default, this value is inferred from the pathname. Sent as the 'content-type' header when downloading a blob.\n */\n contentType?: string;\n /**\n * Number in seconds to configure the edge and browser cache. The minimum is 1 minute. There's no maximum but keep in mind that browser and edge caches will do a best effort to respect this value.\n * Detailed documentation can be found here: https://vercel.com/docs/storage/vercel-blob#caching\n * @defaultvalue 30 * 24 * 60 * 60 (1 Month)\n */\n cacheControlMaxAge?: number;\n /**\n * Only perform the operation if the blob's current ETag matches this value.\n * Use this for optimistic concurrency control to prevent overwriting changes made by others.\n * If the ETag doesn't match, a `BlobPreconditionFailedError` will be thrown.\n */\n ifMatch?: string;\n /**\n * Maximum size in bytes allowed for this upload. Currently only enforced\n * client-side for multipart uploads (`put(..., { multipart: true })`).\n * For bodies with a known size (Blob, File, Buffer, etc.) the check is\n * performed before the upload starts. Streams cannot be checked upfront.\n * The maximum allowed value is 5TB.\n */\n maximumSizeInBytes?: number;\n}\n\n/**\n * Event object passed to the onUploadProgress callback.\n */\nexport interface UploadProgressEvent {\n /**\n * The number of bytes uploaded.\n */\n loaded: number;\n\n /**\n * The total number of bytes to upload.\n */\n total: number;\n\n /**\n * The percentage of the upload that has been completed.\n */\n percentage: number;\n}\n\n/**\n * Callback type for tracking upload progress.\n */\nexport type OnUploadProgressCallback = (\n progressEvent: UploadProgressEvent,\n) => void;\n\nexport type InternalOnUploadProgressCallback = (loaded: number) => void;\n\nexport type BlobRequestInit = Omit<RequestInit, 'body'> & { body?: PutBody };\n\nexport type BlobRequest = ({\n input,\n init,\n onUploadProgress,\n}: {\n input: string | URL;\n init: BlobRequestInit;\n onUploadProgress?: InternalOnUploadProgressCallback;\n}) => Promise<Response>;\n\n/**\n * Interface for including upload progress tracking capabilities.\n */\nexport interface WithUploadProgress {\n /**\n * Callback to track the upload progress. You will receive an object with the following properties:\n * - `loaded`: The number of bytes uploaded\n * - `total`: The total number of bytes to upload\n * - `percentage`: The percentage of the upload that has been completed\n */\n onUploadProgress?: OnUploadProgressCallback;\n}\n\nfunction readEnv(name: string): string | undefined {\n try {\n const value = process.env[name];\n return typeof value === 'string' && value.trim() !== ''\n ? value.trim()\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport type ResolvedBlobAuth =\n | { kind: 'readWrite' | 'oidc'; token: string; storeId: string }\n | { kind: 'presigned'; storeId: string };\n\nexport function parseStoreIdFromReadWriteToken(token: string): string {\n const [, , , storeId = ''] = token.split('_');\n return storeId;\n}\n\nfunction base64UrlDecodeDelegationSegment(segment: string): string {\n let base64 = segment.replace(/-/g, '+').replace(/_/g, '/');\n const padding = 4 - (base64.length % 4);\n if (padding !== 4) {\n base64 += '='.repeat(padding);\n }\n if (typeof atob === 'function') {\n return atob(base64);\n }\n if (typeof Buffer !== 'undefined') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(base64, 'base64').toString('utf8');\n }\n throw new BlobError('Cannot decode base64: no atob or Buffer available.');\n}\n\n/**\n * Reads `storeId` from the delegation JWT embedded in a presigned blob URL’s\n * `vercel-blob-delegation` query parameter (same payload shape as `issueSignedToken` delegations).\n */\n/**\n * Reads `storeId` from a delegation JWT’s payload segment (same format as\n * embedded in a presigned URL’s `vercel-blob-delegation` query parameter).\n */\nexport function parseStoreIdFromDelegationToken(\n delegationToken: string,\n): string {\n const dot = delegationToken.indexOf('.');\n if (dot < 0) {\n throw new BlobError('Invalid delegation token format.');\n }\n\n const payloadSeg = delegationToken.slice(0, dot);\n let parsed: { storeId?: unknown };\n try {\n parsed = JSON.parse(base64UrlDecodeDelegationSegment(payloadSeg)) as {\n storeId?: unknown;\n };\n } catch {\n throw new BlobError('Invalid delegation token payload.');\n }\n\n if (!parsed.storeId || typeof parsed.storeId !== 'string') {\n throw new BlobError('Delegation token payload is missing `storeId`.');\n }\n\n return normalizeStoreId(parsed.storeId);\n}\n\nexport function parseStoreIdFromPresignedUrl(\n presignedUrlPayload: PresignedUrlPayload,\n): string {\n const delegation = presignedUrlPayload.delegationToken;\n return parseStoreIdFromDelegationToken(delegation);\n}\n\n/**\n * Strips the optional `store_` prefix from a store id. `BLOB_STORE_ID` (what\n * `vercel env pull` writes) and the `storeId` option are accepted in either\n * `store_<id>` or `<id>` form; downstream consumers (CDN host subdomain,\n * `x-vercel-blob-store-id` header) want the bare form. Case is preserved\n * because the API is case-sensitive on this value.\n */\nexport function normalizeStoreId(storeId: string): string {\n return storeId.startsWith('store_')\n ? storeId.slice('store_'.length)\n : storeId;\n}\n\n/**\n * Resolves credentials in the following priority order:\n * 1. An explicit read-write `token` passed via options.\n * 2. An explicit `oidcToken` (or `VERCEL_OIDC_TOKEN`) paired with `storeId` option (or `BLOB_STORE_ID`).\n * 3. `BLOB_READ_WRITE_TOKEN` from the environment.\n */\nexport async function resolveBlobAuth(\n options?: BlobCommandOptions & BlobPresignedCommandOptions,\n): Promise<ResolvedBlobAuth> {\n if (options?.presignedUrlPayload) {\n const storeId = parseStoreIdFromDelegationToken(\n options.presignedUrlPayload.delegationToken,\n );\n return { kind: 'presigned', storeId };\n }\n // An explicitly supplied token always wins over OIDC and env-based tokens.\n if (options?.token) {\n const storeId = parseStoreIdFromReadWriteToken(options.token);\n return { kind: 'readWrite', token: options.token, storeId };\n }\n\n const manualOidcToken = options?.oidcToken?.trim();\n const oidcToken = manualOidcToken || (await getVercelOidcToken());\n if (oidcToken) {\n // Try to get storeId from the supplied options\n const manualStoreId = options?.storeId?.trim();\n if (manualStoreId) {\n return {\n kind: 'oidc',\n token: oidcToken,\n storeId: normalizeStoreId(manualStoreId),\n };\n }\n\n // If not supplied manually, try to get storeId from the environment variable\n const blobStoreId = readEnv('BLOB_STORE_ID');\n if (blobStoreId) {\n return {\n kind: 'oidc',\n token: oidcToken,\n storeId: normalizeStoreId(blobStoreId),\n };\n }\n\n // User passed an OIDC token explicitly, but we couldn't resolve the storeId\n // So throw an error. If the oidcToken is from the environment, fall back to rw token\n if (manualOidcToken) {\n throw new BlobError(\n 'oidcToken was passed, but no storeId was found. Pass a `storeId` option or set `BLOB_STORE_ID` to use OIDC auth',\n );\n }\n }\n\n const readWrite = readEnv('BLOB_READ_WRITE_TOKEN');\n if (readWrite) {\n const storeId = parseStoreIdFromReadWriteToken(readWrite);\n return { kind: 'readWrite', token: readWrite, storeId };\n }\n\n throw new BlobError(\n 'No blob credentials found. Pass a `token` option, set `BLOB_READ_WRITE_TOKEN`, or use `oidcToken` (or `VERCEL_OIDC_TOKEN`) with `storeId` or `BLOB_STORE_ID`.',\n );\n}\n\n/**\n * Returns the read-write token for signing and callback verification.\n * OIDC-only configuration is not sufficient; pass `token` or set `BLOB_READ_WRITE_TOKEN`.\n */\nexport function getReadWriteBlobTokenFromOptionsOrEnv(\n options?: Pick<BlobCommandOptions, 'token'>,\n): string {\n if (options?.token) {\n return options.token;\n }\n\n const readWrite = readEnv('BLOB_READ_WRITE_TOKEN');\n if (readWrite) {\n return readWrite;\n }\n\n throw new BlobError(\n 'No read-write token found. Either configure the `BLOB_READ_WRITE_TOKEN` environment variable, or pass a `token` option to your calls.',\n );\n}\n\nexport class BlobError extends Error {\n constructor(message: string) {\n super(`Vercel Blob: ${message}`);\n }\n}\n\n/**\n * Generates a download URL for a blob.\n * The download URL includes a ?download=1 parameter which causes browsers to download\n * the file instead of displaying it inline.\n *\n * @param blobUrl - The URL of the blob to generate a download URL for\n * @returns A string containing the download URL with the download parameter appended\n */\nexport function getDownloadUrl(blobUrl: string): string {\n const url = new URL(blobUrl);\n\n url.searchParams.set('download', '1');\n\n return url.toString();\n}\n\n// Extracted from https://github.com/sindresorhus/is-plain-obj/blob/main/index.js\n// It's just nearly impossible to use ESM modules with our current setup\nexport function isPlainObject(value: unknown): boolean {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n return (\n (prototype === null ||\n prototype === Object.prototype ||\n Object.getPrototypeOf(prototype) === null) &&\n !(Symbol.toStringTag in value) &&\n !(Symbol.iterator in value)\n );\n}\n\nexport const disallowedPathnameCharacters = ['//'];\n\n// Chrome: implemented https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requests\n// Microsoft Edge: implemented (Chromium)\n// Firefox: not implemented, BOO!! https://bugzilla.mozilla.org/show_bug.cgi?id=1469359\n// Safari: not implemented, BOO!! https://github.com/WebKit/standards-positions/issues/24\nexport const supportsRequestStreams = (() => {\n // The next line is mostly for Node.js 16 to avoid trying to do new Request() as it's not supported\n // TODO: Can be removed when Node.js 16 is no more required internally\n if (isNodeProcess()) {\n return true;\n }\n\n const apiUrl = getApiUrl();\n\n // Localhost generally doesn't work with HTTP 2 so we can stop here\n if (apiUrl.startsWith('http://localhost')) {\n return false;\n }\n\n let duplexAccessed = false;\n\n const hasContentType = new Request(getApiUrl(), {\n body: new ReadableStream(),\n method: 'POST',\n // @ts-expect-error -- TypeScript doesn't yet have duplex but it's in the spec: https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1729\n get duplex() {\n duplexAccessed = true;\n return 'half';\n },\n }).headers.has('Content-Type');\n\n return duplexAccessed && !hasContentType;\n})();\n\nexport function getApiUrl(pathname = ''): string {\n let baseUrl = null;\n try {\n // wrapping this code in a try/catch as this function is used in the browser and Vite doesn't define the process.env.\n // As this varaible is NOT used in production, it will always default to production endpoint\n baseUrl =\n process.env.VERCEL_BLOB_API_URL ||\n process.env.NEXT_PUBLIC_VERCEL_BLOB_API_URL;\n } catch {\n // noop\n }\n\n return `${baseUrl || defaultVercelBlobApiUrl}${pathname}`;\n}\n\nconst TEXT_ENCODER =\n typeof TextEncoder === 'function' ? new TextEncoder() : null;\n\nexport function computeBodyLength(body: PutBody): number {\n if (!body) {\n return 0;\n }\n\n if (typeof body === 'string') {\n if (TEXT_ENCODER) {\n return TEXT_ENCODER.encode(body).byteLength;\n }\n\n // React Native doesn't have TextEncoder\n return new Blob([body]).size;\n }\n\n if ('byteLength' in body && typeof body.byteLength === 'number') {\n // handles Uint8Array, ArrayBuffer, Buffer, and ArrayBufferView\n return body.byteLength;\n }\n\n if ('size' in body && typeof body.size === 'number') {\n // handles Blob and File\n return body.size;\n }\n\n return 0;\n}\n\nexport const createChunkTransformStream = (\n chunkSize: number,\n onProgress?: (bytes: number) => void,\n): TransformStream<ArrayBuffer | Uint8Array> => {\n let buffer = new Uint8Array(0);\n\n return new TransformStream<ArrayBuffer, Uint8Array>({\n transform(chunk, controller) {\n // Combine the new chunk with any leftover data\n const newBuffer = new Uint8Array(buffer.length + chunk.byteLength);\n newBuffer.set(buffer);\n newBuffer.set(new Uint8Array(chunk), buffer.length);\n buffer = newBuffer;\n\n // Output complete chunks\n while (buffer.length >= chunkSize) {\n const newChunk = buffer.slice(0, chunkSize);\n controller.enqueue(newChunk);\n onProgress?.(newChunk.byteLength);\n buffer = buffer.slice(chunkSize);\n }\n },\n\n flush(controller) {\n // Send any remaining data\n if (buffer.length > 0) {\n controller.enqueue(buffer);\n onProgress?.(buffer.byteLength);\n }\n },\n });\n};\n\nexport function isReadableStream(value: PutBody): value is ReadableStream {\n return (\n globalThis.ReadableStream && // TODO: Can be removed once Node.js 16 is no more required internally\n value instanceof ReadableStream\n );\n}\n\nexport function isStream(value: PutBody): value is ReadableStream | Readable {\n if (isReadableStream(value)) {\n return true;\n }\n\n if (isNodeJsReadableStream(value)) {\n return true;\n }\n\n return false;\n}\n\nexport const addPresignedParams = (\n url: string,\n presignedUrlPayload: PresignedUrlPayload,\n): string => {\n const urlObj = new URL(url);\n for (const [key, value] of Object.entries(presignedUrlPayload.params)) {\n urlObj.searchParams.set(key, value);\n }\n urlObj.searchParams.set(\n 'vercel-blob-delegation',\n presignedUrlPayload.delegationToken,\n );\n urlObj.searchParams.set(\n 'vercel-blob-signature',\n presignedUrlPayload.signature,\n );\n return urlObj.toString();\n};\n\n/**\n * Checks if the input is a URL (starts with http:// or https://).\n */\nexport function isUrl(urlOrPathname: string): boolean {\n return (\n urlOrPathname.startsWith('http://') || urlOrPathname.startsWith('https://')\n );\n}\n\n/**\n * Constructs the blob URL from storeId and pathname.\n */\nexport function constructBlobUrl(\n storeId: string,\n pathname: string,\n access: BlobAccessType,\n): string {\n return `https://${storeId}.${access}.blob.vercel-storage.com/${pathname}`;\n}\n","import type { Buffer } from 'buffer';\nimport isBuffer from 'is-buffer';\nimport { Readable } from 'stream';\nimport type { PutBody } from '../put-helpers';\n\n/**\n * Input format for a multipart upload part.\n * Used internally for processing multipart uploads.\n */\nexport interface PartInput {\n /**\n * The part number (1-based index).\n */\n partNumber: number;\n\n /**\n * The content of the part.\n */\n blob: PutBody;\n}\n\n/**\n * Represents a single part of a multipart upload.\n * This structure is used when completing a multipart upload to specify the\n * uploaded parts and their order.\n */\nexport interface Part {\n /**\n * The ETag value returned when the part was uploaded.\n * This value is used to verify the integrity of the uploaded part.\n */\n etag: string;\n\n /**\n * The part number of this part (1-based).\n * This number is used to order the parts when completing the multipart upload.\n */\n partNumber: number;\n}\n\nconst supportsNewBlobFromArrayBuffer = new Promise<boolean>((resolve) => {\n // React Native doesn't support creating a Blob from an ArrayBuffer, so we feature detect it\n try {\n const helloAsArrayBuffer = new Uint8Array([104, 101, 108, 108, 111]);\n const blob = new Blob([helloAsArrayBuffer]);\n blob\n .text()\n .then((text) => {\n resolve(text === 'hello');\n })\n .catch(() => {\n resolve(false);\n });\n } catch {\n resolve(false);\n }\n});\n\nexport async function toReadableStream(\n value: PutBody,\n): Promise<ReadableStream<ArrayBuffer | Uint8Array>> {\n // Already a ReadableStream, nothing to do\n if (value instanceof ReadableStream) {\n return value as ReadableStream<ArrayBuffer>;\n }\n\n // In the case of a Blob or File (which inherits from Blob), we could use .slice() to create pointers\n // to the original data instead of loading data in memory gradually.\n // Here's an explanation on this subject: https://stackoverflow.com/a/24834417\n if (value instanceof Blob) {\n return value.stream();\n }\n\n if (isNodeJsReadableStream(value)) {\n return Readable.toWeb(value) as ReadableStream<ArrayBuffer>;\n }\n\n let streamValue: Uint8Array;\n\n // While ArrayBuffer is valid as a fetch body, when used in a ReadableStream it will fail in Node.js with\n // The \"chunk\" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of ArrayBuffer\n if (value instanceof ArrayBuffer) {\n streamValue = new Uint8Array(value);\n } else if (isNodeJsBuffer(value)) {\n streamValue = value;\n } else {\n // value is a string, we need to convert it to a Uint8Array to get create a stream from it\n streamValue = stringToUint8Array(value as string);\n }\n\n // This line ensures that even when we get a buffer of 70MB, we'll create a stream out of it so we can have\n // better progress indication during uploads\n if (await supportsNewBlobFromArrayBuffer) {\n // @ts-expect-error Uint8Array is compatible with BlobPart at runtime\n return new Blob([streamValue]).stream();\n }\n\n // from https://github.com/sindresorhus/to-readable-stream/blob/main/index.js\n return new ReadableStream<ArrayBuffer | Uint8Array>({\n start(controller) {\n controller.enqueue(streamValue);\n controller.close();\n },\n });\n}\n\n// From https://github.com/sindresorhus/is-stream/\nexport function isNodeJsReadableStream(value: PutBody): value is Readable {\n return (\n typeof value === 'object' &&\n typeof (value as Readable).pipe === 'function' &&\n (value as Readable).readable &&\n typeof (value as Readable)._read === 'function' &&\n // @ts-expect-error _readableState does exists on Readable\n typeof value._readableState === 'object'\n );\n}\n\nfunction stringToUint8Array(s: string): Uint8Array {\n const enc = new TextEncoder();\n return enc.encode(s);\n}\n\nfunction isNodeJsBuffer(value: PutBody): value is Buffer {\n return isBuffer(value);\n}\n","import { getVercelOidcToken as getVercelOidcTokenWithRefresh } from '@vercel/oidc';\n\n/**\n * Gets the current OIDC token from the request context header or the\n * `VERCEL_OIDC_TOKEN` env var, or `undefined` when none is set.\n *\n * Delegates to `@vercel/oidc`'s `getVercelOidcToken`, which reads the\n * `x-vercel-oidc-token` request-context header (falling back to\n * `VERCEL_OIDC_TOKEN`) and throws when neither is present. Unlike the sync\n * variant, it also refreshes an expired token in a development environment. We\n * convert any throw to `undefined` so callers (see `resolveBlobAuth`) can fall\n * through to a `BLOB_READ_WRITE_TOKEN`, and treat a blank token as absent.\n *\n * Do not cache this value, as it is subject to change in production!\n */\nexport async function getVercelOidcToken(): Promise<string | undefined> {\n try {\n const token = (await getVercelOidcTokenWithRefresh()).trim();\n return token === '' ? undefined : token;\n } catch {\n return undefined;\n }\n}\n","/*!\n * bytes\n * Copyright(c) 2012-2014 TJ Holowaychuk\n * Copyright(c) 2015 Jed Watson\n * MIT Licensed\n */\n\n// from https://github.com/visionmedia/bytes.js/blob/master/index.js\n// had too many issues with bundling: https://github.com/vercel/storage/issues/818\ntype ByteUnit = 'b' | 'kb' | 'mb' | 'gb' | 'tb' | 'pb';\n\ntype ByteUnitMap = {\n readonly [_K in ByteUnit]: number;\n};\n\nconst parseRegExp = /^((-|\\+)?(\\d+(?:\\.\\d+)?)) *(kb|mb|gb|tb|pb)$/i;\n\nconst map: ByteUnitMap = {\n b: 1,\n\n kb: 1 << 10,\n\n mb: 1 << 20,\n\n gb: 1 << 30,\n tb: 1024 ** 4,\n pb: 1024 ** 5,\n};\n\nexport function bytes(val: string | number): number | null {\n if (typeof val === 'number' && !Number.isNaN(val)) {\n return val;\n }\n if (typeof val !== 'string') {\n return null;\n }\n\n const results = parseRegExp.exec(val);\n let floatValue: number;\n let unit: ByteUnit = 'b';\n\n if (!results) {\n floatValue = parseInt(val, 10);\n } else {\n const [, res, , , unitMatch] = results;\n if (!res) {\n return null;\n }\n floatValue = parseFloat(res);\n if (unitMatch) {\n unit = unitMatch.toLowerCase() as ByteUnit;\n }\n }\n\n if (Number.isNaN(floatValue)) {\n return null;\n }\n\n return Math.floor(map[unit] * floatValue);\n}\n","import retry from 'async-retry';\nimport type { Response } from 'undici';\nimport { debug } from './debug';\nimport { DOMException } from './dom-exception';\nimport type {\n BlobPresignedCommandOptions,\n BlobRequestInit,\n WithUploadProgress,\n} from './helpers';\nimport {\n addPresignedParams,\n BlobError,\n computeBodyLength,\n getApiUrl,\n resolveBlobAuth,\n} from './helpers';\nimport isNetworkError from './is-network-error';\nimport { blobRequest } from './request';\n\n// maximum pathname length is:\n// 1024 (provider limit) - 26 chars (vercel internal suffixes) - 31 chars (blob `-randomId` suffix) = 967\n// we round it to 950 to make it more human friendly, and we apply the limit whatever the value of\n// addRandomSuffix is, to make it consistent\nexport const MAXIMUM_PATHNAME_LENGTH = 950;\n\nexport class BlobAccessError extends BlobError {\n constructor() {\n super('Access denied, please provide a valid token for this resource.');\n }\n}\n\nexport class BlobOidcEnvironmentNotAllowedError extends BlobError {\n constructor(message?: string) {\n super(\n message ??\n \"OIDC is enabled for this project, but not for this token's environment.\",\n );\n }\n}\n\nexport class BlobContentTypeNotAllowedError extends BlobError {\n constructor(message: string) {\n super(`Content type mismatch, ${message}.`);\n }\n}\n\nexport class BlobPathnameMismatchError extends BlobError {\n constructor(message: string) {\n super(\n `Pathname mismatch, ${message}. Check the pathname used in upload() or put() matches the one from the client token.`,\n );\n }\n}\n\nexport class BlobClientTokenExpiredError extends BlobError {\n constructor() {\n super('Client token has expired.');\n }\n}\n\nexport class BlobFileTooLargeError extends BlobError {\n constructor(message: string) {\n super(`File is too large, ${message}.`);\n }\n}\n\nexport class BlobStoreNotFoundError extends BlobError {\n constructor() {\n super('This store does not exist.');\n }\n}\n\nexport class BlobStoreSuspendedError extends BlobError {\n constructor() {\n super('This store has been suspended.');\n }\n}\n\nexport class BlobUnknownError extends BlobError {\n constructor() {\n super('Unknown error, please visit https://vercel.com/help.');\n }\n}\n\nexport class BlobNotFoundError extends BlobError {\n constructor() {\n super('The requested blob does not exist');\n }\n}\n\nexport class BlobServiceNotAvailable extends BlobError {\n constructor() {\n super('The blob service is currently not available. Please try again.');\n }\n}\n\nexport class BlobServiceRateLimited extends BlobError {\n public readonly retryAfter: number;\n\n constructor(seconds?: number) {\n super(\n `Too many requests please lower the number of concurrent requests ${\n seconds ? ` - try again in ${seconds} seconds` : ''\n }.`,\n );\n\n this.retryAfter = seconds ?? 0;\n }\n}\n\nexport class BlobRequestAbortedError extends BlobError {\n constructor() {\n super('The request was aborted.');\n }\n}\n\nexport class BlobPreconditionFailedError extends BlobError {\n constructor() {\n super('Precondition failed: ETag mismatch.');\n }\n}\n\ntype BlobApiErrorCodes =\n | 'store_suspended'\n | 'forbidden'\n | 'oidc_environment_not_allowed'\n | 'not_found'\n | 'unknown_error'\n | 'bad_request'\n | 'store_not_found'\n | 'not_allowed'\n | 'client_token_not_allowed'\n | 'service_unavailable'\n | 'rate_limited'\n | 'content_type_not_allowed'\n | 'client_token_pathname_mismatch'\n | 'client_token_expired'\n | 'file_too_large'\n | 'precondition_failed';\n\nexport interface BlobApiError {\n error?: { code?: BlobApiErrorCodes; message?: string };\n}\n\n// This version is used to ensure that the client and server are compatible\n// The server (Vercel Blob API) uses this information to change its behavior like the\n// response format\nconst BLOB_API_VERSION = 12;\n\nfunction getApiVersion(): string {\n let versionOverride = null;\n try {\n // wrapping this code in a try/catch as this function is used in the browser and Vite doesn't define the process.env.\n // As this varaible is NOT used in production, it will always default to the BLOB_API_VERSION\n versionOverride =\n process.env.VERCEL_BLOB_API_VERSION_OVERRIDE ||\n process.env.NEXT_PUBLIC_VERCEL_BLOB_API_VERSION_OVERRIDE;\n } catch {\n // noop\n }\n\n return `${versionOverride ?? BLOB_API_VERSION}`;\n}\n\nfunction getRetries(): number {\n try {\n const retries = process.env.VERCEL_BLOB_RETRIES || '10';\n\n return parseInt(retries, 10);\n } catch {\n return 10;\n }\n}\n\nfunction createBlobServiceRateLimited(\n response: Response,\n): BlobServiceRateLimited {\n const retryAfter = response.headers.get('retry-after');\n\n return new BlobServiceRateLimited(\n retryAfter ? parseInt(retryAfter, 10) : undefined,\n );\n}\n\n// reads the body of a error response\nexport async function getBlobError(\n response: Response,\n): Promise<{ code: string; error: BlobError }> {\n let code: BlobApiErrorCodes;\n let message: string | undefined;\n\n try {\n const data = (await response.json()) as BlobApiError;\n code = data.error?.code ?? 'unknown_error';\n message = data.error?.message;\n } catch {\n code = 'unknown_error';\n }\n\n // Now that we have multiple API clients out in the wild handling errors, we can't just send a different\n // error code for this type of error. We need to add a new field in the API response to handle this correctly,\n // but for now, we can just check the message.\n if (message?.includes('contentType') && message.includes('is not allowed')) {\n code = 'content_type_not_allowed';\n }\n\n if (\n message?.includes('\"pathname\"') &&\n message.includes('does not match the token payload')\n ) {\n code = 'client_token_pathname_mismatch';\n }\n\n if (message === 'Token expired') {\n code = 'client_token_expired';\n }\n\n if (message?.includes('the file length cannot be greater than')) {\n code = 'file_too_large';\n }\n\n if (\n message?.startsWith('OIDC is enabled for this project, but not for the') &&\n message.includes('environment.')\n ) {\n code = 'oidc_environment_not_allowed';\n }\n\n let error: BlobError;\n switch (code) {\n case 'store_suspended':\n error = new BlobStoreSuspendedError();\n break;\n case 'forbidden':\n error = new BlobAccessError();\n break;\n case 'oidc_environment_not_allowed':\n error = new BlobOidcEnvironmentNotAllowedError(message);\n break;\n case 'content_type_not_allowed':\n error = new BlobContentTypeNotAllowedError(message!);\n break;\n case 'client_token_pathname_mismatch':\n error = new BlobPathnameMismatchError(message!);\n break;\n case 'client_token_expired':\n error = new BlobClientTokenExpiredError();\n break;\n case 'file_too_large':\n error = new BlobFileTooLargeError(message!);\n break;\n case 'not_found':\n error = new BlobNotFoundError();\n break;\n case 'client_token_not_allowed':\n error = new BlobError(\n message ??\n 'This operation is not available when using a client token. Use a read–write or OIDC token on the server.',\n );\n break;\n case 'store_not_found':\n error = new BlobStoreNotFoundError();\n break;\n case 'bad_request':\n error = new BlobError(message ?? 'Bad request');\n break;\n case 'service_unavailable':\n error = new BlobServiceNotAvailable();\n break;\n case 'rate_limited':\n error = createBlobServiceRateLimited(response);\n break;\n case 'precondition_failed':\n error = new BlobPreconditionFailedError();\n break;\n case 'unknown_error':\n case 'not_allowed':\n default:\n error = new BlobUnknownError();\n break;\n }\n\n return { code, error };\n}\n\nexport async function requestApi<TResponse>(\n pathname: string,\n init: BlobRequestInit,\n commandOptions:\n | (BlobPresignedCommandOptions & WithUploadProgress)\n | undefined,\n): Promise<TResponse> {\n const apiVersion = getApiVersion();\n const auth = await resolveBlobAuth(commandOptions);\n const bearerToken = auth.kind === 'presigned' ? undefined : auth.token;\n const extraHeaders = getProxyThroughAlternativeApiHeaderFromEnv();\n\n let requestInput = getApiUrl(pathname);\n if (commandOptions?.presignedUrlPayload) {\n requestInput = addPresignedParams(\n requestInput,\n commandOptions.presignedUrlPayload,\n );\n }\n\n const requestId = `${auth.storeId}:${Date.now()}:${Math.random().toString(16).slice(2)}`;\n let retryCount = 0;\n let bodyLength = 0;\n let totalLoaded = 0;\n const sendBodyLength =\n commandOptions?.onUploadProgress || shouldUseXContentLength();\n\n if (\n init.body &&\n // 1. For upload progress we always need to know the total size of the body\n // 2. In development we need the header for put() to work correctly when passing a stream\n sendBodyLength\n ) {\n bodyLength = computeBodyLength(init.body);\n }\n\n if (commandOptions?.onUploadProgress) {\n commandOptions.onUploadProgress({\n loaded: 0,\n total: bodyLength,\n percentage: 0,\n });\n }\n\n const apiResponse = await retry(\n async (bail) => {\n let res: Response;\n\n // try/catch here to treat certain errors as not-retryable\n try {\n res = await blobRequest({\n input: requestInput,\n init: {\n ...init,\n headers: {\n 'x-api-blob-request-id': requestId,\n // Store ID is not encoded in OIDC token, so pass it separately as a header\n 'x-vercel-blob-store-id': auth.storeId,\n 'x-api-blob-request-attempt': String(retryCount),\n 'x-api-version': apiVersion,\n ...(sendBodyLength\n ? { 'x-content-length': String(bodyLength) }\n : {}),\n ...(bearerToken !== undefined\n ? { authorization: `Bearer ${bearerToken}` }\n : {}),\n ...extraHeaders,\n ...init.headers,\n },\n },\n onUploadProgress: commandOptions?.onUploadProgress\n ? (loaded) => {\n const total = bodyLength !== 0 ? bodyLength : loaded;\n totalLoaded = loaded;\n const percentage =\n bodyLength > 0\n ? Number(((loaded / total) * 100).toFixed(2))\n : 0;\n\n // Leave percentage 100 for the end of request\n if (percentage === 100 && bodyLength > 0) {\n return;\n }\n\n commandOptions.onUploadProgress?.({\n loaded,\n // When passing a stream to put(), we have no way to know the total size of the body.\n // Instead of defining total as total?: number we decided to set the total to the currently\n // loaded number. This is not inaccurate and way more practical for DX.\n // Passing down a stream to put() is very rare\n total,\n percentage,\n });\n }\n : undefined,\n });\n } catch (error) {\n // if the request was aborted, don't retry\n if (error instanceof DOMException && error.name === 'AbortError') {\n bail(new BlobRequestAbortedError());\n return;\n }\n\n // We specifically target network errors because fetch network errors are regular TypeErrors\n // We want to retry for network errors, but not for other TypeErrors\n if (isNetworkError(error)) {\n throw error;\n }\n\n // If we messed up the request part, don't even retry\n if (error instanceof TypeError) {\n bail(error);\n return;\n }\n\n // retry for any other erros thrown by fetch\n throw error;\n }\n\n if (res.ok) {\n return res;\n }\n\n const { code, error } = await getBlobError(res);\n\n // only retry for certain errors\n if (\n code === 'unknown_error' ||\n code === 'service_unavailable' ||\n code === 'internal_server_error'\n ) {\n throw error;\n }\n\n // don't retry for e.g. suspended stores\n bail(error);\n },\n {\n retries: getRetries(),\n onRetry: (error) => {\n if (error instanceof Error) {\n debug(`retrying API request to ${pathname}`, error.message);\n }\n\n retryCount = retryCount + 1;\n },\n },\n );\n\n if (!apiResponse) {\n throw new BlobUnknownError();\n }\n\n // Calling onUploadProgress here has two benefits:\n // 1. It ensures 100% is only reached at the end of the request. While otherwise you can reach 100%\n // before the request is fully done, as we only really measure what gets sent over the wire, not what\n // has been processed by the server.\n // 2. It makes the uploadProgress \"work\" even in rare cases where fetch/xhr onprogress is not working\n // And in the case of multipart uploads it actually provides a simple progress indication (per part)\n if (commandOptions?.onUploadProgress) {\n commandOptions.onUploadProgress({\n loaded: totalLoaded,\n total: totalLoaded,\n percentage: 100,\n });\n }\n\n return (await apiResponse.json()) as TResponse;\n}\n\nfunction getProxyThroughAlternativeApiHeaderFromEnv(): {\n 'x-proxy-through-alternative-api'?: string;\n} {\n const extraHeaders: Record<string, string> = {};\n\n try {\n if (\n 'VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API' in process.env &&\n process.env.VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API !== undefined\n ) {\n extraHeaders['x-proxy-through-alternative-api'] =\n process.env.VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API;\n } else if (\n 'NEXT_PUBLIC_VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API' in process.env &&\n process.env.NEXT_PUBLIC_VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API !==\n undefined\n ) {\n extraHeaders['x-proxy-through-alternative-api'] =\n process.env.NEXT_PUBLIC_VERCEL_BLOB_PROXY_THROUGH_ALTERNATIVE_API;\n }\n } catch {\n // noop\n }\n\n return extraHeaders;\n}\n\nfunction shouldUseXContentLength(): boolean {\n try {\n return process.env.VERCEL_BLOB_USE_X_CONTENT_LENGTH === '1';\n } catch {\n return false;\n }\n}\n","let debugIsActive = false;\n\n// wrapping this code in a try/catch in case some env doesn't support process.env (vite by default)\ntry {\n if (\n process.env.DEBUG?.includes('blob') ||\n process.env.NEXT_PUBLIC_DEBUG?.includes('blob')\n ) {\n debugIsActive = true;\n }\n} catch {\n // noop\n}\n\n// Set process.env.DEBUG = 'blob' to enable debug logging\nexport function debug(message: string, ...args: unknown[]): void {\n if (debugIsActive) {\n console.debug(`vercel-blob: ${message}`, ...args);\n }\n}\n","// TODO: Once Node 16 is no more needed internally, we can remove this file and use the native DOMException type.\nexport const DOMException =\n globalThis.DOMException ??\n (() => {\n // DOMException was only made a global in Node v17.0.0,\n // but fetch supports >= v16.8.\n try {\n atob('~');\n } catch (err) {\n return Object.getPrototypeOf(err).constructor;\n }\n })();\n","// @ts-nocheck -- This file is copy pasted\n\n// Source: https://github.com/sindresorhus/is-network-error/blob/main/index.js\n// Why: Jest + ES6 modules = harder than maintaining a nuclear plant\n\n/**\n * MIT License\n\nCopyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\nconst objectToString = Object.prototype.toString;\n\nconst isError = (value) => objectToString.call(value) === '[object Error]';\n\nconst errorMessages = new Set([\n 'network error', // Chrome\n 'Failed to fetch', // Chrome\n 'NetworkError when attempting to fetch resource.', // Firefox\n 'The Internet connection appears to be offline.', // Safari 16\n 'Load failed', // Safari 17+\n 'Network request failed', // `cross-fetch`\n 'fetch failed', // Undici (Node.js)\n 'terminated', // Undici (Node.js)\n]);\n\nexport default function isNetworkError(error) {\n const isValid =\n error &&\n isError(error) &&\n error.name === 'TypeError' &&\n typeof error.message === 'string';\n\n if (!isValid) {\n return false;\n }\n\n // We do an extra check for Safari 17+ as it has a very generic error message.\n // Network errors in Safari have no stack.\n if (error.message === 'Load failed') {\n return error.stack === undefined;\n }\n\n return errorMessages.has(error.message);\n}\n","import type { BodyInit } from 'undici';\nimport { fetch } from 'undici';\nimport { debug } from './debug';\nimport type { BlobRequest } from './helpers';\nimport {\n createChunkTransformStream,\n isStream,\n supportsRequestStreams,\n} from './helpers';\nimport { toReadableStream } from './multipart/helpers';\nimport type { PutBody } from './put-helpers';\n\nexport const hasFetch = typeof fetch === 'function';\n\nexport const hasFetchWithUploadProgress = hasFetch && supportsRequestStreams;\n\nconst CHUNK_SIZE = 64 * 1024;\n\nexport const blobFetch: BlobRequest = async ({\n input,\n init,\n onUploadProgress,\n}) => {\n debug('using fetch');\n let body: BodyInit | undefined;\n\n if (init.body) {\n if (onUploadProgress) {\n // We transform the body to a stream here instead of at the call site\n // So that on retries we can reuse the original body, otherwise we would not be able to reuse it\n const stream = await toReadableStream(init.body);\n\n let loaded = 0;\n\n const chunkTransformStream = createChunkTransformStream(\n CHUNK_SIZE,\n (newLoaded: number) => {\n loaded += newLoaded;\n onUploadProgress(loaded);\n },\n );\n\n body = stream.pipeThrough(chunkTransformStream);\n } else {\n body = init.body as BodyInit;\n }\n }\n\n // Only set duplex option when supported and dealing with a stream body\n const duplex =\n supportsRequestStreams && body && isStream(body as PutBody)\n ? 'half'\n : undefined;\n\n return fetch(\n input,\n // @ts-expect-error -- Blob and Nodejs Blob are triggering type errors, fine with it\n {\n ...init,\n ...(init.body ? { body } : {}),\n duplex,\n },\n );\n};\n","import type { Response as UndiciResponse } from 'undici';\nimport { debug } from './debug';\nimport { type BlobRequest, isReadableStream } from './helpers';\n\nexport const hasXhr = typeof XMLHttpRequest !== 'undefined';\n\nexport const blobXhr: BlobRequest = async ({\n input,\n init,\n onUploadProgress,\n}) => {\n debug('using xhr');\n let body: XMLHttpRequestBodyInit | null = null;\n\n // xhr.send only support XMLHttpRequestBodyInit types, excluding ReadableStream (web)\n // and Readable (node)\n // We do have to support ReadableStream being sent to xhr as our library allows\n // for Safari to use put(path, ReadableStream, { onUploadProgress }) which would\n // end up here.\n // We do not have to support Readable being sent to xhr as using Node.js you would\n // endup in the fetch implementation by default.\n if (init.body) {\n if (isReadableStream(init.body)) {\n body = await new Response(init.body).blob();\n } else {\n // We \"type lie\" here, what we should do instead:\n // Exclude ReadableStream:\n // body = init.body as Exclude<PutBody, ReadableStream | Readable>;\n // We can't do this because init.body (PutBody) relies on Blob (node:buffer)\n // while XMLHttpRequestBodyInit relies on native Blob type.\n // If we get rid of undici we can remove this trick.\n body = init.body as XMLHttpRequestBodyInit;\n }\n }\n\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(init.method || 'GET', input.toString(), true);\n\n // Handle upload progress\n if (onUploadProgress) {\n xhr.upload.addEventListener('progress', (event) => {\n if (event.lengthComputable) {\n onUploadProgress(event.loaded);\n }\n });\n }\n\n // Handle response\n xhr.onload = () => {\n if (init.signal?.aborted) {\n reject(new DOMException('The user aborted the request.', 'AbortError'));\n return;\n }\n\n const headers = new Headers();\n const rawHeaders = xhr\n .getAllResponseHeaders()\n .trim()\n .split(/[\\r\\n]+/);\n\n // Parse headers\n rawHeaders.forEach((line) => {\n const parts = line.split(': ');\n const key = parts.shift();\n const value = parts.join(': ');\n if (key) headers.set(key.toLowerCase(), value);\n });\n\n // Create response object, api-blob sends back text and api.ts will turn it into json if necessary\n const response = new Response(xhr.response as string, {\n status: xhr.status,\n statusText: xhr.statusText,\n headers,\n }) as unknown as UndiciResponse;\n\n resolve(response);\n };\n\n // Handle network errors\n xhr.onerror = () => {\n reject(new TypeError('Network request failed'));\n };\n\n // Handle timeouts\n xhr.ontimeout = () => {\n reject(new TypeError('Network request timed out'));\n };\n\n // Handle aborts\n xhr.onabort = () => {\n reject(new DOMException('The user aborted a request.', 'AbortError'));\n };\n\n // Set headers\n if (init.headers) {\n const headers = new Headers(init.headers as HeadersInit);\n headers.forEach((value, key) => {\n xhr.setRequestHeader(key, value);\n });\n }\n\n // Handle abort signal\n if (init.signal) {\n init.signal.addEventListener('abort', () => {\n xhr.abort();\n });\n\n // If already aborted, abort xhr immediately\n if (init.signal.aborted) {\n xhr.abort();\n return;\n }\n }\n\n // We're cheating and saying that nobody is gonna use put() with a stream in an environment not supporting\n // fetch with streams. If this ever happens please open an issue and we'll figure it out.\n xhr.send(body);\n });\n};\n","import type { Response } from 'undici';\nimport { blobFetch, hasFetch, hasFetchWithUploadProgress } from './fetch';\nimport type { BlobRequest } from './helpers';\nimport { blobXhr, hasXhr } from './xhr';\n\nexport const blobRequest: BlobRequest = async ({\n input,\n init,\n onUploadProgress,\n}): Promise<Response> => {\n if (onUploadProgress) {\n if (hasFetchWithUploadProgress) {\n return blobFetch({ input, init, onUploadProgress });\n }\n\n if (hasXhr) {\n return blobXhr({ input, init, onUploadProgress });\n }\n }\n\n if (hasFetch) {\n return blobFetch({ input, init });\n }\n\n if (hasXhr) {\n return blobXhr({ input, init });\n }\n\n throw new Error('No request implementation available');\n};\n","import type { Readable } from 'stream';\n// We use the undici types to ensure TS doesn't complain about native types (like ReadableStream) vs\n// undici types fetch expects (like Blob is from node:buffer..)\n// import type { Blob } from 'node:buffer';\nimport type { File } from 'undici';\nimport { MAXIMUM_PATHNAME_LENGTH } from './api';\nimport type { ClientCommonCreateBlobOptions } from './client';\nimport type { CommonCreateBlobOptions, PresignedUrlPayload } from './helpers';\nimport { BlobError, disallowedPathnameCharacters } from './helpers';\n\n/**\n * Options to optimize an image through Vercel Image Optimization before\n * storing it. Requires OIDC authentication.\n */\nexport interface OptimizeImageOptions {\n /**\n * The desired width of the optimized image in pixels (1-8192).\n */\n width: number;\n /**\n * The desired quality of the optimized image (1-100).\n * @defaultvalue 75\n */\n quality?: number;\n /**\n * The desired output format. The original format is preserved when omitted.\n */\n format?: 'jpeg' | 'png' | 'webp' | 'avif';\n}\n\nconst optimizeImageFormatToMimeType = {\n jpeg: 'image/jpeg',\n png: 'image/png',\n webp: 'image/webp',\n avif: 'image/avif',\n} as const;\n\n// Mirrors the server-side limits so invalid values fail fast, before paying\n// for an upload (and a billable transformation) the API would reject.\nexport function validateOptimizeImageOptions(\n optimizeImage: OptimizeImageOptions,\n): void {\n if (typeof optimizeImage !== 'object' || optimizeImage === null) {\n throw new BlobError('optimizeImage must be an object, see usage');\n }\n\n const { width, quality, format } = optimizeImage;\n\n if (!Number.isInteger(width) || width < 1 || width > 8192) {\n throw new BlobError(\n 'optimizeImage.width must be an integer between 1 and 8192',\n );\n }\n\n if (\n quality !== undefined &&\n (!Number.isInteger(quality) || quality < 1 || quality > 100)\n ) {\n throw new BlobError(\n 'optimizeImage.quality must be an integer between 1 and 100',\n );\n }\n\n if (format !== undefined && !(format in optimizeImageFormatToMimeType)) {\n throw new BlobError(\n `optimizeImage.format must be one of: ${Object.keys(\n optimizeImageFormatToMimeType,\n ).join(', ')}`,\n );\n }\n}\n\n/**\n * Fail fast when the source is clearly not an image; unknown/absent content\n * types are left to the server, which detects the actual format from the bytes.\n */\nexport function validateOptimizeImageSourceContentType(\n contentType: string | undefined,\n): void {\n if (\n contentType &&\n contentType !== 'application/octet-stream' &&\n !contentType.startsWith('image/')\n ) {\n throw new BlobError(\n `optimizeImage requires an image body, but the content type is \"${contentType}\"`,\n );\n }\n}\n\n// Query params for the put-optimized/put-from-url endpoints. Values are\n// validated here first; the API owns the authoritative validation.\nexport function addOptimizeImageParams(\n params: URLSearchParams,\n optimizeImage: OptimizeImageOptions,\n): void {\n validateOptimizeImageOptions(optimizeImage);\n params.set('width', String(optimizeImage.width));\n params.set('quality', String(optimizeImage.quality ?? 75));\n if (optimizeImage.format) {\n params.set('format', optimizeImageFormatToMimeType[optimizeImage.format]);\n }\n}\n\nexport const putOptionHeaderMap = {\n cacheControlMaxAge: 'x-cache-control-max-age',\n addRandomSuffix: 'x-add-random-suffix',\n allowOverwrite: 'x-allow-overwrite',\n contentType: 'x-content-type',\n access: 'x-vercel-blob-access',\n ifMatch: 'x-if-match',\n};\n\n/**\n * Result of a successful put or copy operation.\n */\nexport interface PutBlobResult {\n /**\n * The URL of the blob.\n */\n url: string;\n /**\n * A URL that will cause browsers to download the file instead of displaying it inline.\n */\n downloadUrl: string;\n /**\n * The pathname of the blob within the store.\n */\n pathname: string;\n /**\n * The content-type of the blob.\n */\n contentType: string;\n /**\n * The content disposition header value.\n */\n contentDisposition: string;\n /**\n * The ETag of the blob. Can be used with `ifMatch` for conditional writes.\n */\n etag: string;\n}\n\nexport type PutBlobApiResponse = PutBlobResult;\n\n/**\n * Represents the body content for a put operation.\n * Can be one of several supported types.\n */\nexport type PutBody =\n | string\n | Readable // Node.js streams\n | Buffer // Node.js buffers\n | Blob\n | ArrayBuffer\n | ReadableStream // Streams API (= Web streams in Node.js)\n | File;\n\nexport type CommonPutCommandOptions = CommonCreateBlobOptions &\n ClientCommonCreateBlobOptions;\n\nexport interface CreatePutMethodOptions<TOptions> {\n allowedOptions: (keyof typeof putOptionHeaderMap)[];\n getToken?: (pathname: string, options: TOptions) => Promise<string>;\n getPresignedUrlPayload?: (\n pathname: string,\n options: TOptions,\n ) => Promise<PresignedUrlPayload>;\n extraChecks?: (options: TOptions) => void;\n}\n\nexport function createPutHeaders<TOptions extends CommonPutCommandOptions>(\n allowedOptions: CreatePutMethodOptions<TOptions>['allowedOptions'],\n options: TOptions,\n): Record<string, string> {\n const headers: Record<string, string> = {};\n\n // access is always required, so always add it to headers\n headers[putOptionHeaderMap.access] = options.access;\n\n if (allowedOptions.includes('contentType') && options.contentType) {\n headers[putOptionHeaderMap.contentType] = options.contentType;\n }\n\n if (\n allowedOptions.includes('addRandomSuffix') &&\n options.addRandomSuffix !== undefined\n ) {\n headers[putOptionHeaderMap.addRandomSuffix] = options.addRandomSuffix\n ? '1'\n : '0';\n }\n\n // ifMatch implies allowOverwrite — updating a blob by ETag inherently requires\n // overwriting. Throw if the user explicitly contradicts this.\n if (allowedOptions.includes('ifMatch') && options.ifMatch) {\n if (options.allowOverwrite === false) {\n throw new BlobError(\n 'ifMatch and allowOverwrite: false are contradictory. ifMatch is used for conditional overwrites, which requires allowOverwrite to be true.',\n );\n }\n\n headers[putOptionHeaderMap.ifMatch] = options.ifMatch;\n // Implicitly enable allowOverwrite when ifMatch is set and allowOverwrite\n // was not explicitly provided, to prevent the server from sending\n // conflicting If-Match + If-None-Match headers to S3.\n if (\n allowedOptions.includes('allowOverwrite') &&\n options.allowOverwrite === undefined\n ) {\n headers[putOptionHeaderMap.allowOverwrite] = '1';\n }\n }\n\n if (\n allowedOptions.includes('allowOverwrite') &&\n options.allowOverwrite !== undefined\n ) {\n headers[putOptionHeaderMap.allowOverwrite] = options.allowOverwrite\n ? '1'\n : '0';\n }\n\n if (\n allowedOptions.includes('cacheControlMaxAge') &&\n options.cacheControlMaxAge !== undefined\n ) {\n headers[putOptionHeaderMap.cacheControlMaxAge] =\n options.cacheControlMaxAge.toString();\n }\n\n return headers;\n}\n\nexport async function createPutOptions<\n TOptions extends CommonPutCommandOptions,\n>({\n pathname,\n options,\n extraChecks,\n getToken,\n}: {\n pathname: string;\n options?: TOptions;\n extraChecks?: CreatePutMethodOptions<TOptions>['extraChecks'];\n getToken?: CreatePutMethodOptions<TOptions>['getToken'];\n}): Promise<TOptions> {\n if (!pathname) {\n throw new BlobError('pathname is required');\n }\n\n if (pathname.length > MAXIMUM_PATHNAME_LENGTH) {\n throw new BlobError(\n `pathname is too long, maximum length is ${MAXIMUM_PATHNAME_LENGTH}`,\n );\n }\n\n for (const invalidCharacter of disallowedPathnameCharacters) {\n if (pathname.includes(invalidCharacter)) {\n throw new BlobError(\n `pathname cannot contain \"${invalidCharacter}\", please encode it if needed`,\n );\n }\n }\n\n if (!options) {\n throw new BlobError('missing options, see usage');\n }\n\n if (options.access !== 'public' && options.access !== 'private') {\n throw new BlobError(\n 'access must be \"private\" or \"public\", see https://vercel.com/docs/vercel-blob',\n );\n }\n\n if (extraChecks) {\n extraChecks(options);\n }\n\n if (getToken) {\n options.token = await getToken(pathname, options);\n }\n\n return options;\n}\n","import { BlobServiceNotAvailable, requestApi } from '../api';\nimport { debug } from '../debug';\nimport type { CommonCreateBlobOptions } from '../helpers';\nimport type {\n CreatePutMethodOptions,\n PutBlobApiResponse,\n PutBlobResult,\n} from '../put-helpers';\nimport { createPutHeaders, createPutOptions } from '../put-helpers';\nimport type { Part } from './helpers';\n\n/**\n * Options for completing a multipart upload.\n * Used with the completeMultipartUpload method.\n */\nexport interface CommonCompleteMultipartUploadOptions {\n /**\n * Unique upload identifier for the multipart upload, received from createMultipartUpload.\n * This ID is used to identify which multipart upload is being completed.\n */\n uploadId: string;\n\n /**\n * Unique key identifying the blob object, received from createMultipartUpload.\n * This key is used to identify which blob object the parts belong to.\n */\n key: string;\n}\n\nexport type CompleteMultipartUploadCommandOptions =\n CommonCompleteMultipartUploadOptions & CommonCreateBlobOptions;\n\nexport function createCompleteMultipartUploadMethod<\n TOptions extends CompleteMultipartUploadCommandOptions,\n>({ allowedOptions, getToken, extraChecks }: CreatePutMethodOptions<TOptions>) {\n return async (pathname: string, parts: Part[], optionsInput: TOptions) => {\n const options = await createPutOptions({\n pathname,\n options: optionsInput,\n extraChecks,\n getToken,\n });\n\n const headers = createPutHeaders(allowedOptions, options);\n\n return completeMultipartUpload({\n uploadId: options.uploadId,\n key: options.key,\n pathname,\n headers,\n options,\n parts,\n });\n };\n}\n\nexport async function completeMultipartUpload({\n uploadId,\n key,\n pathname,\n parts,\n headers,\n options,\n}: {\n uploadId: string;\n key: string;\n pathname: string;\n parts: Part[];\n headers: Record<string, string>;\n options: CommonCreateBlobOptions;\n}): Promise<PutBlobResult> {\n const params = new URLSearchParams({ pathname });\n\n try {\n const response = await requestApi<PutBlobApiResponse>(\n `/mpu?${params.toString()}`,\n {\n method: 'POST',\n headers: {\n ...headers,\n 'content-type': 'application/json',\n 'x-mpu-action': 'complete',\n 'x-mpu-upload-id': uploadId,\n // key can be any utf8 character so we need to encode it as HTTP headers can only be us-ascii\n // https://www.rfc-editor.org/rfc/rfc7230#swection-3.2.4\n 'x-mpu-key': encodeURIComponent(key),\n },\n body: JSON.stringify(parts),\n signal: options.abortSignal,\n },\n options,\n );\n\n debug('mpu: complete', response);\n\n return response;\n } catch (error: unknown) {\n if (\n error instanceof TypeError &&\n (error.message === 'Failed to fetch' || error.message === 'fetch failed')\n ) {\n throw new BlobServiceNotAvailable();\n } else {\n throw error;\n }\n }\n}\n","import { BlobServiceNotAvailable, requestApi } from '../api';\nimport { debug } from '../debug';\nimport type { CommonCreateBlobOptions } from '../helpers';\nimport type { CreatePutMethodOptions } from '../put-helpers';\nimport { createPutHeaders, createPutOptions } from '../put-helpers';\n\nexport function createCreateMultipartUploadMethod<\n TOptions extends CommonCreateBlobOptions,\n>({ allowedOptions, getToken, extraChecks }: CreatePutMethodOptions<TOptions>) {\n return async (pathname: string, optionsInput: TOptions) => {\n const options = await createPutOptions({\n pathname,\n options: optionsInput,\n extraChecks,\n getToken,\n });\n\n const headers = createPutHeaders(allowedOptions, options);\n\n const createMultipartUploadResponse = await createMultipartUpload(\n pathname,\n headers,\n options,\n );\n\n return {\n key: createMultipartUploadResponse.key,\n uploadId: createMultipartUploadResponse.uploadId,\n };\n };\n}\n\ninterface CreateMultipartUploadApiResponse {\n uploadId: string;\n key: string;\n}\n\nexport async function createMultipartUpload(\n pathname: string,\n headers: Record<string, string>,\n options: CommonCreateBlobOptions,\n): Promise<CreateMultipartUploadApiResponse> {\n debug('mpu: create', 'pathname:', pathname);\n\n const params = new URLSearchParams({ pathname });\n\n try {\n const response = await requestApi<CreateMultipartUploadApiResponse>(\n `/mpu?${params.toString()}`,\n {\n method: 'POST',\n headers: {\n ...headers,\n 'x-mpu-action': 'create',\n },\n signal: options.abortSignal,\n },\n options,\n );\n\n debug('mpu: create', response);\n\n return response;\n } catch (error: unknown) {\n if (\n error instanceof TypeError &&\n (error.message === 'Failed to fetch' || error.message === 'fetch failed')\n ) {\n throw new BlobServiceNotAvailable();\n }\n\n throw error;\n }\n}\n","import throttle from 'throttleit';\nimport { BlobServiceNotAvailable, requestApi } from '../api';\nimport { debug } from '../debug';\nimport type { CommonCreateBlobOptions, WithUploadProgress } from '../helpers';\nimport { BlobError, bytes, isPlainObject } from '../helpers';\nimport type { CreatePutMethodOptions, PutBody } from '../put-helpers';\nimport { createPutHeaders, createPutOptions } from '../put-helpers';\nimport type { Part, PartInput } from './helpers';\n\n/**\n * Options for uploading a part in a multipart upload process.\n * Used with the uploadPart method.\n */\nexport interface CommonMultipartUploadOptions {\n /**\n * Unique upload identifier for the multipart upload, received from createMultipartUpload.\n * This ID is used to associate all uploaded parts with the same multipart upload.\n */\n uploadId: string;\n\n /**\n * Unique key identifying the blob object, received from createMultipartUpload.\n * This key is used to identify which blob object the parts belong to.\n */\n key: string;\n\n /**\n * A number identifying which part is being uploaded (1-based).\n * This number is used to order the parts when completing the multipart upload.\n * Parts must be uploaded with consecutive part numbers starting from 1.\n */\n partNumber: number;\n}\n\nexport type UploadPartCommandOptions = CommonMultipartUploadOptions &\n CommonCreateBlobOptions;\n\nexport function createUploadPartMethod<\n TOptions extends UploadPartCommandOptions,\n>({ allowedOptions, getToken, extraChecks }: CreatePutMethodOptions<TOptions>) {\n return async (\n pathname: string,\n body: PutBody,\n optionsInput: TOptions,\n ): Promise<Part> => {\n const options = await createPutOptions({\n pathname,\n options: optionsInput,\n extraChecks,\n getToken,\n });\n\n const headers = createPutHeaders(allowedOptions, options);\n\n if (isPlainObject(body)) {\n throw new BlobError(\n \"Body must be a string, buffer or stream. You sent a plain JavaScript object, double check what you're trying to upload.\",\n );\n }\n\n const result = await uploadPart({\n uploadId: options.uploadId,\n key: options.key,\n pathname,\n part: { blob: body, partNumber: options.partNumber },\n headers,\n options,\n });\n\n return {\n etag: result.etag,\n partNumber: options.partNumber,\n };\n };\n}\n\nexport async function uploadPart({\n uploadId,\n key,\n pathname,\n headers,\n options,\n internalAbortController = new AbortController(),\n part,\n}: {\n uploadId: string;\n key: string;\n pathname: string;\n headers: Record<string, string>;\n options: CommonCreateBlobOptions & WithUploadProgress;\n internalAbortController?: AbortController;\n part: PartInput;\n}): Promise<UploadPartApiResponse> {\n const params = new URLSearchParams({ pathname });\n\n const responsePromise = requestApi<UploadPartApiResponse>(\n `/mpu?${params.toString()}`,\n {\n signal: internalAbortController.signal,\n method: 'POST',\n headers: {\n ...headers,\n 'x-mpu-action': 'upload',\n 'x-mpu-key': encodeURIComponent(key),\n 'x-mpu-upload-id': uploadId,\n 'x-mpu-part-number': part.partNumber.toString(),\n },\n // weird things between undici types and native fetch types\n body: part.blob,\n },\n options,\n );\n\n function handleAbort(): void {\n internalAbortController.abort();\n }\n\n if (options.abortSignal?.aborted) {\n // abort if the signal is already aborted\n handleAbort();\n } else {\n // we connect the internal abort controller to the external abortSignal to allow the user to cancel the upload\n options.abortSignal?.addEventListener('abort', handleAbort);\n }\n\n const response = await responsePromise;\n\n options.abortSignal?.removeEventListener('abort', handleAbort);\n\n return response;\n}\n\n// Most browsers will cap requests at 6 concurrent uploads per domain (Vercel Blob API domain)\n// In other environments, we can afford to be more aggressive\nconst maxConcurrentUploads = typeof window !== 'undefined' ? 6 : 8;\n\n// 5MB is the minimum part size accepted by Vercel Blob, but we set our default part size to 8mb like the aws cli\nconst partSizeInBytes = 8 * 1024 * 1024;\n\nconst maxBytesInMemory = maxConcurrentUploads * partSizeInBytes * 2;\n\ninterface UploadPartApiResponse {\n etag: string;\n}\n\nexport interface BlobUploadPart {\n partNumber: number;\n blob: Blob;\n}\n\n// Can we rewrite this function without new Promise?\nexport function uploadAllParts({\n uploadId,\n key,\n pathname,\n stream,\n headers,\n options,\n totalToLoad,\n}: {\n uploadId: string;\n key: string;\n pathname: string;\n stream: ReadableStream<ArrayBuffer>;\n headers: Record<string, string>;\n options: CommonCreateBlobOptions & WithUploadProgress;\n totalToLoad: number;\n}): Promise<Part[]> {\n debug('mpu: upload init', 'key:', key);\n const internalAbortController = new AbortController();\n\n return new Promise((resolve, reject) => {\n const partsToUpload: BlobUploadPart[] = [];\n const completedParts: Part[] = [];\n const reader = stream.getReader();\n let activeUploads = 0;\n let reading = false;\n let currentPartNumber = 1;\n // this next variable is used to escape the read loop when an error occurs\n let rejected = false;\n let currentBytesInMemory = 0;\n let doneReading = false;\n let bytesSent = 0;\n\n // This must be outside the read loop, in case we reach the maxBytesInMemory and\n // we exit the loop but some bytes are still to be sent on the next read invocation.\n let arrayBuffers: ArrayBuffer[] = [];\n let currentPartBytesRead = 0;\n\n let onUploadProgress: (() => void) | undefined;\n const totalLoadedPerPartNumber: Record<string, number> = {};\n\n if (options.onUploadProgress) {\n onUploadProgress = throttle(() => {\n const loaded = Object.values(totalLoadedPerPartNumber).reduce(\n (acc, cur) => {\n return acc + cur;\n },\n 0,\n );\n const total = totalToLoad || loaded;\n const percentage =\n totalToLoad > 0\n ? Number(((loaded / totalToLoad || loaded) * 100).toFixed(2))\n : 0;\n\n // we call the user's onUploadProgress callback\n options.onUploadProgress?.({ loaded, total, percentage });\n }, 150);\n }\n\n read().catch(cancel);\n\n async function read(): Promise<void> {\n debug(\n 'mpu: upload read start',\n 'activeUploads:',\n activeUploads,\n 'currentBytesInMemory:',\n `${bytes(currentBytesInMemory)}/${bytes(maxBytesInMemory)}`,\n 'bytesSent:',\n bytes(bytesSent),\n );\n\n reading = true;\n\n while (currentBytesInMemory < maxBytesInMemory && !rejected) {\n try {\n const { value, done } = await reader.read();\n\n if (done) {\n doneReading = true;\n debug('mpu: upload read consumed the whole stream');\n // done is sent when the stream is fully consumed. That's why we're not using the value here.\n if (arrayBuffers.length > 0) {\n partsToUpload.push({\n partNumber: currentPartNumber++,\n blob: new Blob(arrayBuffers, {\n type: 'application/octet-stream',\n }),\n });\n\n sendParts();\n } else if (activeUploads === 0) {\n // Stream was empty or ended exactly on a part boundary with no\n // in-flight uploads. Nothing will call resolve() later, so do it here.\n reader.releaseLock();\n resolve(completedParts);\n }\n reading = false;\n return;\n }\n\n currentBytesInMemory += value.byteLength;\n\n // This code ensures that each part will be exactly of `partSizeInBytes` size\n // Otherwise R2 will refuse it. AWS S3 is fine with parts of different sizes.\n let valueOffset = 0;\n while (valueOffset < value.byteLength) {\n const remainingPartSize = partSizeInBytes - currentPartBytesRead;\n const endOffset = Math.min(\n valueOffset + remainingPartSize,\n value.byteLength,\n );\n\n const chunk = value.slice(valueOffset, endOffset);\n\n arrayBuffers.push(chunk);\n currentPartBytesRead += chunk.byteLength;\n valueOffset = endOffset;\n\n if (currentPartBytesRead === partSizeInBytes) {\n partsToUpload.push({\n partNumber: currentPartNumber++,\n blob: new Blob(arrayBuffers, {\n type: 'application/octet-stream',\n }),\n });\n\n arrayBuffers = [];\n currentPartBytesRead = 0;\n sendParts();\n }\n }\n } catch (error) {\n cancel(error);\n }\n }\n\n debug(\n 'mpu: upload read end',\n 'activeUploads:',\n activeUploads,\n 'currentBytesInMemory:',\n `${bytes(currentBytesInMemory)}/${bytes(maxBytesInMemory)}`,\n 'bytesSent:',\n bytes(bytesSent),\n );\n\n reading = false;\n }\n\n async function sendPart(part: BlobUploadPart): Promise<void> {\n activeUploads++;\n\n debug(\n 'mpu: upload send part start',\n 'partNumber:',\n part.partNumber,\n 'size:',\n part.blob.size,\n 'activeUploads:',\n activeUploads,\n 'currentBytesInMemory:',\n `${bytes(currentBytesInMemory)}/${bytes(maxBytesInMemory)}`,\n 'bytesSent:',\n bytes(bytesSent),\n );\n\n try {\n const uploadProgressForPart: WithUploadProgress['onUploadProgress'] =\n options.onUploadProgress\n ? (event) => {\n totalLoadedPerPartNumber[part.partNumber] = event.loaded;\n if (onUploadProgress) {\n onUploadProgress();\n }\n }\n : undefined;\n\n const completedPart = await uploadPart({\n uploadId,\n key,\n pathname,\n headers,\n options: {\n ...options,\n onUploadProgress: uploadProgressForPart,\n },\n internalAbortController,\n part,\n });\n\n debug(\n 'mpu: upload send part end',\n 'partNumber:',\n part.partNumber,\n 'activeUploads',\n activeUploads,\n 'currentBytesInMemory:',\n `${bytes(currentBytesInMemory)}/${bytes(maxBytesInMemory)}`,\n 'bytesSent:',\n bytes(bytesSent),\n );\n\n if (rejected) {\n return;\n }\n\n completedParts.push({\n partNumber: part.partNumber,\n etag: completedPart.etag,\n });\n\n currentBytesInMemory -= part.blob.size;\n activeUploads--;\n bytesSent += part.blob.size;\n\n if (partsToUpload.length > 0) {\n sendParts();\n }\n\n if (doneReading) {\n if (activeUploads === 0) {\n reader.releaseLock();\n resolve(completedParts);\n }\n return;\n }\n\n if (!reading) {\n read().catch(cancel);\n }\n } catch (error) {\n // cancel if fetch throws an error\n cancel(error);\n }\n }\n\n function sendParts(): void {\n if (rejected) {\n return;\n }\n\n debug(\n 'send parts',\n 'activeUploads',\n activeUploads,\n 'partsToUpload',\n partsToUpload.length,\n );\n\n while (activeUploads < maxConcurrentUploads && partsToUpload.length > 0) {\n const partToSend = partsToUpload.shift();\n if (partToSend) {\n void sendPart(partToSend);\n }\n }\n }\n\n function cancel(error: unknown): void {\n // a previous call already rejected the whole call, ignore\n if (rejected) {\n return;\n }\n rejected = true;\n internalAbortController.abort();\n reader.releaseLock();\n if (\n error instanceof TypeError &&\n (error.message === 'Failed to fetch' ||\n error.message === 'fetch failed')\n ) {\n reject(new BlobServiceNotAvailable());\n } else {\n reject(error as Error);\n }\n }\n });\n}\n","import {\n BlobError,\n type CommonCreateBlobOptions,\n isPlainObject,\n} from '../helpers';\nimport type { CreatePutMethodOptions, PutBody } from '../put-helpers';\nimport { createPutHeaders, createPutOptions } from '../put-helpers';\nimport { completeMultipartUpload } from './complete';\nimport { createMultipartUpload } from './create';\nimport type { Part } from './helpers';\nimport { uploadPart as rawUploadPart } from './upload';\n\nexport function createCreateMultipartUploaderMethod<\n TOptions extends CommonCreateBlobOptions,\n>({ allowedOptions, getToken, extraChecks }: CreatePutMethodOptions<TOptions>) {\n return async (pathname: string, optionsInput: TOptions) => {\n const options = await createPutOptions({\n pathname,\n options: optionsInput,\n extraChecks,\n getToken,\n });\n\n const headers = createPutHeaders(allowedOptions, options);\n\n const createMultipartUploadResponse = await createMultipartUpload(\n pathname,\n headers,\n options,\n );\n\n return {\n key: createMultipartUploadResponse.key,\n uploadId: createMultipartUploadResponse.uploadId,\n\n async uploadPart(partNumber: number, body: PutBody) {\n if (isPlainObject(body)) {\n throw new BlobError(\n \"Body must be a string, buffer or stream. You sent a plain JavaScript object, double check what you're trying to upload.\",\n );\n }\n\n const result = await rawUploadPart({\n uploadId: createMultipartUploadResponse.uploadId,\n key: createMultipartUploadResponse.key,\n pathname,\n part: { partNumber, blob: body },\n headers,\n options,\n });\n\n return {\n etag: result.etag,\n partNumber,\n };\n },\n\n async complete(parts: Part[]) {\n return completeMultipartUpload({\n uploadId: createMultipartUploadResponse.uploadId,\n key: createMultipartUploadResponse.key,\n pathname,\n parts,\n headers,\n options,\n });\n },\n };\n };\n}\n","import throttle from 'throttleit';\nimport { requestApi } from './api';\nimport type { CommonCreateBlobOptions, WithUploadProgress } from './helpers';\nimport { BlobError, isPlainObject } from './helpers';\nimport { uncontrolledMultipartUpload } from './multipart/uncontrolled';\nimport type {\n CreatePutMethodOptions,\n OptimizeImageOptions,\n PutBlobApiResponse,\n PutBlobResult,\n PutBody,\n} from './put-helpers';\nimport {\n addOptimizeImageParams,\n createPutHeaders,\n createPutOptions,\n validateOptimizeImageSourceContentType,\n} from './put-helpers';\n\nexport interface PutCommandOptions\n extends CommonCreateBlobOptions,\n WithUploadProgress {\n /**\n * Whether to use multipart upload. Use this when uploading large files. It will split the file into multiple parts, upload them in parallel and retry failed parts.\n * @defaultvalue false\n */\n multipart?: boolean;\n /**\n * Optimize the image through Vercel Image Optimization before storing it.\n * Only the optimized output is stored. Requires OIDC authentication and is\n * billed as an image transformation plus a regular blob put.\n * @deprecated Use `putImage` instead.\n */\n optimizeImage?: OptimizeImageOptions;\n}\n\nexport function createPutMethod<TOptions extends PutCommandOptions>({\n allowedOptions,\n getToken,\n getPresignedUrlPayload,\n extraChecks,\n}: CreatePutMethodOptions<TOptions>) {\n return async function put(\n pathname: string,\n body: PutBody,\n optionsInput: TOptions,\n ): Promise<PutBlobResult> {\n if (!body) {\n throw new BlobError('body is required');\n }\n\n if (isPlainObject(body)) {\n throw new BlobError(\n \"Body must be a string, buffer or stream. You sent a plain JavaScript object, double check what you're trying to upload.\",\n );\n }\n\n const options = await createPutOptions({\n pathname,\n options: optionsInput,\n extraChecks,\n getToken,\n });\n\n const presignedUrlPayload = await getPresignedUrlPayload?.(\n pathname,\n options,\n );\n\n const optionsWithPresignedUrlPayload = {\n ...options,\n presignedUrlPayload,\n };\n\n const headers = createPutHeaders(allowedOptions, options);\n\n if (options.optimizeImage) {\n if (options.multipart === true) {\n throw new BlobError(\n 'optimizeImage cannot be combined with multipart uploads',\n );\n }\n\n // The `contentType` option or a Blob/File `type` reveals a non-image\n // source without reading the body; File extends Blob.\n validateOptimizeImageSourceContentType(\n options.contentType ??\n (typeof Blob !== 'undefined' && body instanceof Blob\n ? body.type\n : undefined),\n );\n\n const params = new URLSearchParams({ pathname });\n addOptimizeImageParams(params, options.optimizeImage);\n\n const response = await requestApi<PutBlobApiResponse>(\n `/put-optimized?${params.toString()}`,\n {\n method: 'POST',\n body,\n headers,\n signal: options.abortSignal,\n },\n optionsWithPresignedUrlPayload,\n );\n\n return {\n url: response.url,\n downloadUrl: response.downloadUrl,\n pathname: response.pathname,\n contentType: response.contentType,\n contentDisposition: response.contentDisposition,\n etag: response.etag,\n };\n }\n\n if (options.multipart === true) {\n return uncontrolledMultipartUpload(\n pathname,\n body,\n headers,\n optionsWithPresignedUrlPayload,\n );\n }\n\n const onUploadProgress = options.onUploadProgress\n ? throttle(options.onUploadProgress, 100)\n : undefined;\n\n const params = new URLSearchParams({ pathname });\n\n const response = await requestApi<PutBlobApiResponse>(\n `/?${params.toString()}`,\n {\n method: 'PUT',\n body,\n headers,\n signal: options.abortSignal,\n },\n {\n ...optionsWithPresignedUrlPayload,\n onUploadProgress,\n },\n );\n\n return {\n url: response.url,\n downloadUrl: response.downloadUrl,\n pathname: response.pathname,\n contentType: response.contentType,\n contentDisposition: response.contentDisposition,\n etag: response.etag,\n };\n };\n}\n","import { debug } from '../debug';\nimport type { CommonCreateBlobOptions, WithUploadProgress } from '../helpers';\nimport { BlobError, computeBodyLength, isStream } from '../helpers';\nimport type { PutBlobResult, PutBody } from '../put-helpers';\nimport { completeMultipartUpload } from './complete';\nimport { createMultipartUpload } from './create';\nimport { toReadableStream } from './helpers';\nimport { uploadAllParts } from './upload';\n\n// this automatically slices the body into parts and uploads all of them as multiple parts\nexport async function uncontrolledMultipartUpload(\n pathname: string,\n body: PutBody,\n headers: Record<string, string>,\n options: CommonCreateBlobOptions & WithUploadProgress,\n): Promise<PutBlobResult> {\n debug('mpu: init', 'pathname:', pathname, 'headers:', headers);\n\n const optionsWithoutOnUploadProgress = {\n ...options,\n onUploadProgress: undefined,\n };\n\n // For bodies with a known size (Blob, File, Buffer, etc.) enforce\n // maximumSizeInBytes client-side before starting the upload. This avoids\n // creating a multipart upload that will ultimately fail.\n // Streams are skipped because their size is unknown upfront.\n if (\n options.maximumSizeInBytes !== undefined &&\n !isStream(body) &&\n computeBodyLength(body) > options.maximumSizeInBytes\n ) {\n throw new BlobError(\n `Body size of ${computeBodyLength(body)} bytes exceeds the maximum allowed size of ${options.maximumSizeInBytes} bytes`,\n );\n }\n\n // Step 1: Start multipart upload\n const createMultipartUploadResponse = await createMultipartUpload(\n pathname,\n headers,\n optionsWithoutOnUploadProgress,\n );\n\n const totalToLoad = computeBodyLength(body);\n const stream = await toReadableStream(body);\n\n // Step 2: Upload parts one by one\n const parts = await uploadAllParts({\n uploadId: createMultipartUploadResponse.uploadId,\n key: createMultipartUploadResponse.key,\n pathname,\n // @ts-expect-error ReadableStream<ArrayBuffer | Uint8Array> is compatible at runtime\n stream,\n headers,\n options,\n totalToLoad,\n });\n\n // Step 3: Complete multipart upload\n const blob = await completeMultipartUpload({\n uploadId: createMultipartUploadResponse.uploadId,\n key: createMultipartUploadResponse.key,\n pathname,\n parts,\n headers,\n options: optionsWithoutOnUploadProgress,\n });\n\n // changes:\n // stream => set percentage to 0% even if loaded/total is valid\n // stream => send onUploadProgress 100% at the end of the request here\n\n return blob;\n}\n","/**\n * Per-query presign constraints on signed blob URLs. Must stay aligned with\n * api-blob and proxy (`signed_url.go`).\n *\n * Each listed param participates in the HMAC canonical string as `key=value`\n * (decoded query value), sorted with `operation` and `pathname`.\n *\n * Callback completion uses two params (no nested JSON in the query string):\n * `vercel-blob-callback-url` and optional `vercel-blob-callback-token-payload`.\n */\n\nexport const BLOB_PRESIGN_QUERY_VALID_UNTIL =\n 'vercel-blob-valid-until' as const;\nexport const BLOB_PRESIGN_QUERY_MAXIMUM_SIZE =\n 'vercel-blob-maximum-size-in-bytes' as const;\nexport const BLOB_PRESIGN_QUERY_ALLOWED_CONTENT_TYPES =\n 'vercel-blob-allowed-content-types' as const;\nexport const BLOB_PRESIGN_QUERY_ADD_RANDOM_SUFFIX =\n 'vercel-blob-add-random-suffix' as const;\nexport const BLOB_PRESIGN_QUERY_ALLOW_OVERWRITE =\n 'vercel-blob-allow-overwrite' as const;\nexport const BLOB_PRESIGN_QUERY_CACHE_CONTROL_MAX_AGE =\n 'vercel-blob-cache-control-max-age' as const;\nexport const BLOB_PRESIGN_QUERY_IF_MATCH = 'vercel-blob-if-match' as const;\nexport const BLOB_PRESIGN_QUERY_CALLBACK_URL =\n 'vercel-blob-callback-url' as const;\nexport const BLOB_PRESIGN_QUERY_CALLBACK_TOKEN_PAYLOAD =\n 'vercel-blob-callback-token-payload' as const;\n\n/**\n * Presign constraint query names\n */\nexport const PRESIGN_QUERY = {\n validUntil: BLOB_PRESIGN_QUERY_VALID_UNTIL,\n maximumSizeInBytes: BLOB_PRESIGN_QUERY_MAXIMUM_SIZE,\n allowedContentTypes: BLOB_PRESIGN_QUERY_ALLOWED_CONTENT_TYPES,\n addRandomSuffix: BLOB_PRESIGN_QUERY_ADD_RANDOM_SUFFIX,\n allowOverwrite: BLOB_PRESIGN_QUERY_ALLOW_OVERWRITE,\n cacheControlMaxAge: BLOB_PRESIGN_QUERY_CACHE_CONTROL_MAX_AGE,\n ifMatch: BLOB_PRESIGN_QUERY_IF_MATCH,\n callbackUrl: BLOB_PRESIGN_QUERY_CALLBACK_URL,\n callbackTokenPayload: BLOB_PRESIGN_QUERY_CALLBACK_TOKEN_PAYLOAD,\n} as const;\n\n/** Sorted UTF-8 (lexicographic over param names). */\nexport const PRESIGN_CANONICAL_QUERY_KEYS = [\n BLOB_PRESIGN_QUERY_ADD_RANDOM_SUFFIX,\n BLOB_PRESIGN_QUERY_ALLOW_OVERWRITE,\n BLOB_PRESIGN_QUERY_ALLOWED_CONTENT_TYPES,\n BLOB_PRESIGN_QUERY_CACHE_CONTROL_MAX_AGE,\n BLOB_PRESIGN_QUERY_CALLBACK_TOKEN_PAYLOAD,\n BLOB_PRESIGN_QUERY_CALLBACK_URL,\n BLOB_PRESIGN_QUERY_IF_MATCH,\n BLOB_PRESIGN_QUERY_MAXIMUM_SIZE,\n BLOB_PRESIGN_QUERY_VALID_UNTIL,\n] as const;\n\nexport type PresignCanonicalQueryKey =\n (typeof PRESIGN_CANONICAL_QUERY_KEYS)[number];\n\nexport const MAX_PRESIGN_CALLBACK_URL_CHARS = 4096;\nexport const MAX_PRESIGN_CALLBACK_TOKEN_PAYLOAD_CHARS = 8192;\n\nexport type PresignOptionsOnUploadCompletedWire = {\n callbackUrl: string;\n tokenPayload?: string | null;\n};\n\nexport type DelegationScopeForPresign = {\n validUntil: number;\n maximumSizeInBytes?: number;\n allowedContentTypes?: string[];\n};\n\nfunction contentTypeAllowedByList(\n contentType: string,\n allowed: readonly string[],\n): boolean {\n const [type] = contentType.split('/');\n const wildcard = `${type}/*`;\n return (\n allowed.includes(contentType) || (type ? allowed.includes(wildcard) : false)\n );\n}\n\nfunction assertAllowedContentTypesSubset(\n optionsTypes: string[] | undefined,\n delegationTypes: string[] | undefined,\n label: string,\n): void {\n if (!optionsTypes?.length) {\n return;\n }\n if (!delegationTypes?.length) {\n return;\n }\n for (const ct of optionsTypes) {\n if (!contentTypeAllowedByList(ct, delegationTypes)) {\n throw new Error(\n `${label}: allowedContentTypes entry \"${ct}\" is not permitted by the delegation token.`,\n );\n }\n }\n}\n\nfunction assertNumberSubset(\n name: string,\n optionVal: number | undefined,\n delegationVal: number | undefined,\n label: string,\n mode: 'lte' | 'eqIfDelegation',\n): void {\n if (optionVal === undefined) {\n return;\n }\n if (delegationVal === undefined) {\n return;\n }\n if (mode === 'lte' && optionVal > delegationVal) {\n throw new Error(\n `${label}: ${name} must be ≤ delegation (${String(delegationVal)}).`,\n );\n }\n}\n\nfunction isPlausibleAbsoluteUrl(s: string): boolean {\n if (typeof URL !== 'undefined' && typeof URL.canParse === 'function') {\n return URL.canParse(s);\n }\n try {\n // eslint-disable-next-line no-new\n new URL(s);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Callback is URL-only; delegation never embeds `onUploadCompleted`. */\nfunction validatePresignUrlOnUploadCompletedWire(\n opt: PresignOptionsOnUploadCompletedWire | undefined,\n label: string,\n): void {\n if (!opt) {\n return;\n }\n if (typeof opt.callbackUrl !== 'string' || opt.callbackUrl.length === 0) {\n throw new Error(\n `${label}: onUploadCompleted.callbackUrl must be a non-empty string.`,\n );\n }\n if (opt.callbackUrl.length > MAX_PRESIGN_CALLBACK_URL_CHARS) {\n throw new Error(`${label}: onUploadCompleted.callbackUrl is too long.`);\n }\n if (!isPlausibleAbsoluteUrl(opt.callbackUrl)) {\n throw new Error(\n `${label}: onUploadCompleted.callbackUrl must be a valid URL.`,\n );\n }\n if (opt.tokenPayload !== undefined && opt.tokenPayload !== null) {\n if (typeof opt.tokenPayload !== 'string') {\n throw new Error(\n `${label}: onUploadCompleted.tokenPayload must be a string.`,\n );\n }\n if (opt.tokenPayload.length > MAX_PRESIGN_CALLBACK_TOKEN_PAYLOAD_CHARS) {\n throw new Error(`${label}: onUploadCompleted.tokenPayload is too long.`);\n }\n }\n}\n\nexport const MAX_PRESIGN_CACHE_CONTROL_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;\nconst MAX_PRESIGN_IF_MATCH_LENGTH = 256;\n\n// biome-ignore lint/suspicious/noControlCharactersInRegex: intentionally blocking them\nconst IF_MATCH_CONTROL_CHARS_RE = /[\\x00-\\x1f\\x7f]/;\n\ntype PresignUrlConstraintOptions = {\n validUntil?: number;\n allowedContentTypes?: string[];\n maximumSizeInBytes?: number;\n addRandomSuffix?: boolean;\n allowOverwrite?: boolean;\n cacheControlMaxAge?: number;\n ifMatch?: string;\n onUploadCompleted?: PresignOptionsOnUploadCompletedWire;\n};\n\n/** `addRandomSuffix` / `allowOverwrite` are wire-only; validate numeric / string fields. */\nfunction validateUrlOnlyPresignUploadOptions(\n urlOptions: PresignUrlConstraintOptions,\n label: string,\n): void {\n if (urlOptions.cacheControlMaxAge !== undefined) {\n const n = urlOptions.cacheControlMaxAge;\n if (\n !Number.isInteger(n) ||\n n < 0 ||\n n > MAX_PRESIGN_CACHE_CONTROL_MAX_AGE_SECONDS\n ) {\n throw new Error(\n `${label}: cacheControlMaxAge must be an integer between 0 and ${MAX_PRESIGN_CACHE_CONTROL_MAX_AGE_SECONDS}.`,\n );\n }\n }\n if (urlOptions.ifMatch !== undefined) {\n const im = urlOptions.ifMatch;\n if (typeof im !== 'string' || im.length === 0) {\n throw new Error(`${label}: ifMatch must be a non-empty string.`);\n }\n if (im.length > MAX_PRESIGN_IF_MATCH_LENGTH) {\n throw new Error(`${label}: ifMatch is too long.`);\n }\n if (IF_MATCH_CONTROL_CHARS_RE.test(im)) {\n throw new Error(\n `${label}: ifMatch contains disallowed control characters.`,\n );\n }\n }\n}\n\nfunction sortedContentTypesCsv(types: readonly string[]): string {\n return [...types].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)).join(',');\n}\n\n/**\n * Clears presign constraint params (not delegation/signature) from a URL.\n */\nexport function deletePresignCanonicalParams(url: URL): void {\n for (const k of PRESIGN_CANONICAL_QUERY_KEYS) {\n url.searchParams.delete(k);\n }\n}\n\n/**\n * Computes resolved URL expiry (ms). When omitted from the wire, callers treat\n * it as the delegation ceiling.\n */\nexport function resolvePresignUrlValidUntilMs(args: {\n delegationValidUntil: number;\n urlOptions?: { validUntil?: number };\n nowMs: number;\n}): number {\n const { delegationValidUntil, urlOptions, nowMs } = args;\n let t: number;\n if (urlOptions?.validUntil !== undefined) {\n if (\n typeof urlOptions.validUntil !== 'number' ||\n !Number.isFinite(urlOptions.validUntil)\n ) {\n throw new Error('presignUrl: validUntil must be a finite number (ms).');\n }\n t = Math.trunc(urlOptions.validUntil);\n } else {\n t = Math.trunc(delegationValidUntil);\n }\n if (Number.isFinite(delegationValidUntil)) {\n t = Math.min(t, Math.trunc(delegationValidUntil));\n }\n if (t <= nowMs) {\n throw new Error(\n 'presignUrl: resolved URL expiry is not after the current time; issue a new delegation token or pass a later validUntil.',\n );\n }\n return t;\n}\n\n/**\n * Returns entries to set on the URL before signing. Omits\n * `vercel-blob-valid-until` when it equals the delegation ceiling (server\n * defaults to delegation expiry).\n */\nexport function buildPresignCanonicalQueryEntries(args: {\n operation: 'get' | 'head' | 'put' | 'delete';\n delegation: DelegationScopeForPresign;\n urlOptions?: {\n validUntil?: number;\n allowedContentTypes?: string[];\n maximumSizeInBytes?: number;\n addRandomSuffix?: boolean;\n allowOverwrite?: boolean;\n cacheControlMaxAge?: number;\n ifMatch?: string;\n onUploadCompleted?: PresignOptionsOnUploadCompletedWire;\n };\n nowMs: number;\n}): [string, string][] {\n const { operation, delegation, urlOptions, nowMs } = args;\n const label = 'presignUrl';\n const resolvedUntil = resolvePresignUrlValidUntilMs({\n delegationValidUntil: delegation.validUntil,\n urlOptions,\n nowMs,\n });\n const delegUntil = Math.trunc(delegation.validUntil);\n const entries: [string, string][] = [];\n\n if (resolvedUntil < delegUntil) {\n entries.push([BLOB_PRESIGN_QUERY_VALID_UNTIL, String(resolvedUntil)]);\n }\n\n if (operation === 'delete') {\n if (urlOptions?.ifMatch !== undefined) {\n entries.push([BLOB_PRESIGN_QUERY_IF_MATCH, urlOptions.ifMatch]);\n }\n return entries;\n }\n\n if (operation !== 'put' || !urlOptions) {\n return entries;\n }\n\n assertAllowedContentTypesSubset(\n urlOptions.allowedContentTypes,\n delegation.allowedContentTypes,\n label,\n );\n assertNumberSubset(\n 'maximumSizeInBytes',\n urlOptions.maximumSizeInBytes,\n delegation.maximumSizeInBytes,\n label,\n 'lte',\n );\n validateUrlOnlyPresignUploadOptions(urlOptions, label);\n validatePresignUrlOnUploadCompletedWire(urlOptions.onUploadCompleted, label);\n\n if (urlOptions.allowedContentTypes !== undefined) {\n const csv = sortedContentTypesCsv(urlOptions.allowedContentTypes);\n if (csv.length > 16_384) {\n throw new Error(`${label}: allowedContentTypes query value is too long.`);\n }\n entries.push([BLOB_PRESIGN_QUERY_ALLOWED_CONTENT_TYPES, csv]);\n }\n if (urlOptions.maximumSizeInBytes !== undefined) {\n entries.push([\n BLOB_PRESIGN_QUERY_MAXIMUM_SIZE,\n String(Math.trunc(urlOptions.maximumSizeInBytes)),\n ]);\n }\n if (urlOptions.addRandomSuffix !== undefined) {\n entries.push([\n BLOB_PRESIGN_QUERY_ADD_RANDOM_SUFFIX,\n urlOptions.addRandomSuffix ? 'true' : 'false',\n ]);\n }\n if (urlOptions.allowOverwrite !== undefined) {\n entries.push([\n BLOB_PRESIGN_QUERY_ALLOW_OVERWRITE,\n urlOptions.allowOverwrite ? 'true' : 'false',\n ]);\n }\n if (urlOptions.cacheControlMaxAge !== undefined) {\n entries.push([\n BLOB_PRESIGN_QUERY_CACHE_CONTROL_MAX_AGE,\n String(Math.trunc(urlOptions.cacheControlMaxAge)),\n ]);\n }\n if (urlOptions.ifMatch !== undefined) {\n entries.push([BLOB_PRESIGN_QUERY_IF_MATCH, urlOptions.ifMatch]);\n }\n if (urlOptions.onUploadCompleted !== undefined) {\n const { callbackUrl, tokenPayload } = urlOptions.onUploadCompleted;\n if (callbackUrl.length > MAX_PRESIGN_CALLBACK_URL_CHARS) {\n throw new Error(`${label}: onUploadCompleted.callbackUrl is too long.`);\n }\n entries.push([BLOB_PRESIGN_QUERY_CALLBACK_URL, callbackUrl]);\n if (\n tokenPayload !== undefined &&\n tokenPayload !== null &&\n tokenPayload !== ''\n ) {\n if (tokenPayload.length > MAX_PRESIGN_CALLBACK_TOKEN_PAYLOAD_CHARS) {\n throw new Error(\n `${label}: onUploadCompleted.tokenPayload is too long.`,\n );\n }\n entries.push([BLOB_PRESIGN_QUERY_CALLBACK_TOKEN_PAYLOAD, tokenPayload]);\n }\n }\n\n return entries;\n}\n","import { requestApi } from './api';\nimport {\n addPresignedParams,\n type BlobCommandOptions,\n BlobError,\n constructBlobUrl,\n getApiUrl,\n isUrl,\n type PresignedUrlPayload,\n parseStoreIdFromDelegationToken,\n} from './helpers';\nimport {\n buildPresignCanonicalQueryEntries,\n PRESIGN_CANONICAL_QUERY_KEYS,\n} from './presign-query-params';\n\n/**\n * Operations that may be encoded in a delegation token (e.g. read: `get` /\n * `head` for blob object reads, write: `put` for presigned control-plane writes\n * — both single-object `PUT`, destructive: `delete` for presigned control-plane\n * `DELETE /?pathname=…`). `head` shares the GET URL shape (blob object host)\n * and is distinguished only by the HTTP method and `operation=head` in the\n * canonical signing string.\n */\nexport type DelegationOperation = 'get' | 'head' | 'put' | 'delete';\n\n/**\n * Result of `issueSignedToken` — the same values returned from `POST /signed-token` on\n * the Blob API. Use with {@link presignUrl} to obtain `{ presignedUrl }` for GET/HEAD,\n * presigned `PUT`, presigned multipart `POST`\n * without a bearer token when verified by the CDN.\n */\nexport interface IssuedSignedToken {\n /**\n * Encodes delegation scope (pathname, allowed operations, expiry) and a store-level\n * HMAC, as issued by the API.\n */\n delegationToken: string;\n /**\n * Per-issuance HMAC key: `HMAC-SHA256(blobSigningSecret, delegationToken)` in base64url\n * form. The SDK uses this as the HMAC key when signing a concrete blob URL\n * (the CDN re-derives the same value from the delegation token and store secret).\n */\n clientSigningToken: string;\n /** Time after which the delegation (and any presigned URLs) must be rejected, in ms since epoch. */\n validUntil: number;\n}\n\n/**\n * Options for {@link issueSignedToken}.\n */\nexport type IssueSignedTokenOptions = BlobCommandOptions & {\n /**\n * Blob object pathname to scope the token to, e.g. `media/photo.png`.\n * Use `\"*\"` to allow any pathname in the store. When omitted, the API defaults\n * to a whole-store `\"*\"` wildcard.\n */\n pathname?: string;\n /**\n * Allowed operations (e.g. `get` / `head` for reads to `*.blob.vercel-storage.com`,\n * `put` for presigned control-plane `PUT` and multipart `POST /mpu`,\n * When omitted, the API defaults to read (`get`) only.\n */\n operations?: DelegationOperation[];\n /**\n * Absolute delegation expiry (ms since epoch). Must be after `now`. When omitted, the API uses `now + 1 hour`.\n */\n validUntil?: number;\n\n allowedContentTypes?: string[];\n\n maximumSizeInBytes?: number;\n};\n\ninterface IssuedSignedTokenResponse {\n delegationToken: string;\n clientSigningToken: string;\n validUntil: number;\n}\n\nfunction assertIssueSignedTokenValidUntilOption(validUntil: number): void {\n const now = Date.now();\n if (\n typeof validUntil !== 'number' ||\n !Number.isInteger(validUntil) ||\n !Number.isFinite(validUntil)\n ) {\n throw new BlobError(\n '`issueSignedToken`: validUntil must be an integer milliseconds timestamp.',\n );\n }\n if (validUntil <= now) {\n throw new BlobError(\n '`issueSignedToken`: validUntil must be in the future.',\n );\n }\n}\n\n/**\n * Requests short-lived signed-token material from the Blob control API\n * (`POST /signed-token`). Use OIDC (`VERCEL_OIDC_TOKEN` + `storeId` / `BLOB_STORE_ID`)\n * or a read–write token like other SDK control-plane calls. Client (browser) tokens\n * are not allowed by the server for this operation.\n */\nexport async function issueSignedToken(\n options: IssueSignedTokenOptions,\n): Promise<IssuedSignedToken> {\n if (!options) {\n throw new BlobError('`issueSignedToken` requires an options object');\n }\n\n const body: Record<string, unknown> = {};\n if (options.pathname !== undefined) {\n body.pathname = options.pathname;\n }\n if (options.operations !== undefined) {\n if (options.operations.length === 0) {\n throw new BlobError('`operations` must be a non-empty array if provided');\n }\n body.operations = dedupeOps(options.operations);\n }\n if (options.validUntil !== undefined) {\n assertIssueSignedTokenValidUntilOption(options.validUntil);\n body.validUntil = options.validUntil;\n }\n if (options.maximumSizeInBytes !== undefined) {\n body.maximumSizeInBytes = options.maximumSizeInBytes;\n }\n if (options.allowedContentTypes !== undefined) {\n body.allowedContentTypes = options.allowedContentTypes;\n }\n\n return requestApi<IssuedSignedTokenResponse>(\n '/signed-token',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n signal: options.abortSignal,\n },\n options,\n );\n}\n\nfunction dedupeOps(\n operations: readonly DelegationOperation[],\n): DelegationOperation[] {\n return Array.from(new Set(operations));\n}\n\ninterface DecodedDelegationPayload {\n storeId: string;\n ownerId: string;\n pathname: string;\n operations: string[];\n validUntil: number;\n iat: number;\n maximumSizeInBytes?: number;\n allowedContentTypes?: string[];\n}\n\nfunction base64UrlDecodeToString(segment: string): string {\n let base64 = segment.replace(/-/g, '+').replace(/_/g, '/');\n const padding = 4 - (base64.length % 4);\n if (padding !== 4) {\n base64 += '='.repeat(padding);\n }\n if (typeof atob === 'function') {\n return atob(base64);\n }\n if (typeof Buffer !== 'undefined') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(base64, 'base64').toString('utf8');\n }\n throw new BlobError('Cannot decode base64: no atob or Buffer available.');\n}\n\nfunction tryDecodePayload(\n delegationToken: string,\n): DecodedDelegationPayload | null {\n const dot = delegationToken.indexOf('.');\n if (dot < 0) {\n return null;\n }\n const payloadSeg = delegationToken.slice(0, dot);\n try {\n return JSON.parse(\n base64UrlDecodeToString(payloadSeg),\n ) as DecodedDelegationPayload;\n } catch {\n return null;\n }\n}\n\n/**\n * @internal\n */\nfunction uint8ToBase64(bytes: Uint8Array): string {\n if (typeof Buffer !== 'undefined') {\n // eslint-disable-next-line no-restricted-globals\n return Buffer.from(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n ).toString('base64');\n }\n let s = '';\n for (let i = 0; i < bytes.length; i++) {\n s += String.fromCharCode(bytes[i]!);\n }\n return btoa(s);\n}\n\n/**\n * HMAC-SHA256 with the `clientSigningToken` string as the UTF-8 key; signature\n * digest is base64url (no padding), i.e. `vercel-blob-signature`.\n * Uses the Web Crypto API (Node 20+, browsers, Edge).\n */\nasync function hmacSha256Base64Url(key: string, data: string): Promise<string> {\n if (!globalThis.crypto?.subtle) {\n throw new BlobError(\n 'HMAC is not available: expected globalThis.crypto.subtle (Node 20+ or a modern browser).',\n );\n }\n const enc = new TextEncoder();\n const cryptoKey = await globalThis.crypto.subtle.importKey(\n 'raw',\n enc.encode(key),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n );\n const buf = await globalThis.crypto.subtle.sign(\n 'HMAC',\n cryptoKey,\n enc.encode(data),\n );\n return toBase64Url(uint8ToBase64(new Uint8Array(buf)));\n}\n\n/**\n * @internal\n */\nfunction toBase64Url(base64: string): string {\n return base64.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\nfunction normalizeStoreId(storeId: string): string {\n const lowercase = storeId.toLowerCase();\n return lowercase.startsWith('store_')\n ? lowercase.slice('store_'.length)\n : lowercase;\n}\n\n/**\n * Presign URL options for {@link presignUrl} when `operation` is `get`.\n * Only `validUntil` is honored for these operations; upload-only fields are rejected at the type level.\n */\nexport type PresignGetUrlOptions = {\n operation: 'get';\n\n pathname: string;\n /**\n * Absolute URL expiry (ms since epoch), capped to the delegation `validUntil`.\n * Omitted on the wire when equal to the delegation ceiling (server defaults to delegation).\n */\n validUntil?: number;\n /**\n * Whether the presigned URL may be served from CDN cache. When false, a\n * `cache=0` query param is appended so fetches read the latest content\n * directly from origin storage. The CDN only supports the bypass for\n * private blobs, so it's ignored for public ones. The param is not part\n * of the signed payload: whoever holds the URL can add or remove it.\n * @defaultValue true\n */\n useCache?: boolean;\n};\n\n/**\n * Presign URL options for {@link presignUrl} when `operation` is `head`.\n * Mirrors {@link PresignGetUrlOptions}; the CDN URL is identical, the HTTP\n * method differentiates, and the canonical signing string carries\n * `operation=head` so a GET-signed URL cannot be replayed for HEAD.\n */\nexport type PresignHeadUrlOptions = {\n operation: 'head';\n\n pathname: string;\n\n validUntil?: number;\n};\n\n/**\n * Presign URL options for {@link presignUrl} when `operation` is `put` (single `PUT` or multipart `POST`).\n * Serialized as individual `vercel-blob-*` query params (see {@link PRESIGN_CANONICAL_QUERY_KEYS}).\n */\nexport type PresignPutUrlOptions = {\n operation: 'put';\n\n pathname: string;\n\n validUntil?: number;\n\n allowedContentTypes?: string[];\n\n maximumSizeInBytes?: number;\n\n onUploadCompleted?: {\n callbackUrl: string;\n tokenPayload?: string;\n };\n\n allowOverwrite?: boolean;\n\n addRandomSuffix?: boolean;\n\n cacheControlMaxAge?: number;\n\n ifMatch?: string;\n};\n\n/**\n * Presign URL options for {@link presignUrl} when `operation` is `delete`.\n * Targets the control-plane `DELETE /?pathname=…` route — mirrors the PUT\n * presign URL shape, signed with `operation=delete` so the HTTP method\n * differentiates without changing the URL path. Only `validUntil` and\n * `ifMatch` are honored; upload-only fields are rejected at the type level.\n */\nexport type PresignDeleteUrlOptions = {\n operation: 'delete';\n\n pathname: string;\n\n validUntil?: number;\n\n ifMatch?: string;\n};\n\nexport type PresignUrlOptions =\n | PresignGetUrlOptions\n | PresignHeadUrlOptions\n | PresignPutUrlOptions\n | PresignDeleteUrlOptions;\n\n/**\n * Builds the payload for a presigned URL\n */\nexport async function presign(\n signedToken: Pick<\n IssuedSignedToken,\n 'clientSigningToken' | 'delegationToken'\n >,\n options: PresignUrlOptions,\n): Promise<PresignedUrlPayload> {\n if (!signedToken?.clientSigningToken || !signedToken?.delegationToken) {\n throw new BlobError(\n '`clientSigningToken` and `delegationToken` from `issueSignedToken` are required.',\n );\n }\n\n const scope = tryDecodePayload(signedToken.delegationToken);\n if (!scope) {\n throw new BlobError('Invalid or unreadable `delegationToken` payload.');\n }\n\n const p = scope.pathname;\n if (p && p !== '*') {\n if (options.pathname !== p) {\n throw new BlobError(\n `Blob path does not match the signed token scope; expected \\`${p}\\`, got \\`${options.pathname}\\`.`,\n );\n }\n }\n if (Number.isFinite(scope.validUntil) && Date.now() > scope.validUntil) {\n throw new BlobError(\n 'The signed delegation has expired; issue a new token first.',\n );\n }\n\n if (options.operation === 'get' && !scope.operations?.includes('get')) {\n throw new BlobError(\n 'The delegation token is not valid for `GET` requests. Include `\"get\"` in `operations` when calling `issueSignedToken`.',\n );\n }\n if (options.operation === 'head' && !scope.operations?.includes('head')) {\n throw new BlobError(\n 'The delegation token is not valid for `HEAD` requests. Include `\"head\"` in `operations` when calling `issueSignedToken`.',\n );\n }\n if (options.operation === 'put' && !scope.operations?.includes('put')) {\n throw new BlobError(\n 'The delegation token is not valid for presigned write requests. Include `\"put\"` in `operations` when calling `issueSignedToken`.',\n );\n }\n if (options.operation === 'delete' && !scope.operations?.includes('delete')) {\n throw new BlobError(\n 'The delegation token is not valid for presigned delete requests. Include `\"delete\"` in `operations` when calling `issueSignedToken`.',\n );\n }\n\n const delegationForOptions = {\n validUntil: scope.validUntil,\n maximumSizeInBytes: scope.maximumSizeInBytes,\n allowedContentTypes: scope.allowedContentTypes,\n };\n\n let presignEntries: [string, string][];\n try {\n presignEntries = buildPresignCanonicalQueryEntries({\n operation: options.operation,\n delegation: delegationForOptions,\n urlOptions: options,\n nowMs: Date.now(),\n });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n throw new BlobError(msg);\n }\n\n const canonical = canonicalString(\n options.pathname,\n presignEntries,\n options.operation,\n );\n const signature = await hmacSha256Base64Url(\n signedToken.clientSigningToken,\n canonical,\n );\n\n return {\n delegationToken: signedToken.delegationToken,\n signature,\n params: Object.fromEntries(presignEntries),\n };\n}\n\nfunction buildPresignedGetUrl(\n pathnameOrUrl: string,\n presignedUrlPayload: PresignedUrlPayload,\n options: {\n access: 'public' | 'private';\n useCache?: boolean;\n },\n): string {\n const storeId = parseStoreIdFromDelegationToken(\n presignedUrlPayload.delegationToken,\n );\n let blobUrl = isUrl(pathnameOrUrl)\n ? pathnameOrUrl\n : constructBlobUrl(storeId, pathnameOrUrl, options.access);\n\n // Same gating as get(): the CDN only supports the cache bypass for private\n // blobs. The param is deliberately outside the signed payload, so adding it\n // here doesn't affect signature verification.\n if (options.useCache === false && options.access === 'private') {\n const url = new URL(blobUrl);\n url.searchParams.set('cache', '0');\n blobUrl = url.toString();\n }\n\n return addPresignedParams(blobUrl, presignedUrlPayload);\n}\n\nfunction buildPresignedPutUrl(\n pathname: string,\n presignedUrlPayload: PresignedUrlPayload,\n): string {\n const params = new URLSearchParams({ pathname });\n const apiUrl = getApiUrl(`/?${params.toString()}`);\n return addPresignedParams(apiUrl, presignedUrlPayload);\n}\n\nfunction buildPresignedDeleteUrl(\n pathname: string,\n presignedUrlPayload: PresignedUrlPayload,\n): string {\n const params = new URLSearchParams({ pathname });\n const apiUrl = getApiUrl(`/?${params.toString()}`);\n return addPresignedParams(apiUrl, presignedUrlPayload);\n}\n\n/** Result of {@link presignUrl}: a ready-to-fetch blob object URL or control-plane upload URL. */\nexport type PresignUrlResult = {\n presignedUrl: string;\n};\n\n/**\n * Builds a presigned URL for `GET` / `HEAD` (blob object host), `PUT` / multipart (control API),\n * or `DELETE` (`DELETE /?pathname=…` on the control API — mirrors the PUT URL shape; the\n * HTTP method discriminates, and the canonical signing string includes `operation=delete`).\n * `HEAD` reuses the GET URL shape against the blob object host; `operation=head` in the\n * canonical string prevents a GET-signed URL from being replayed as a HEAD.\n */\nexport async function presignUrl(\n signedToken: Pick<\n IssuedSignedToken,\n 'clientSigningToken' | 'delegationToken'\n >,\n options: PresignUrlOptions & { access: 'public' | 'private' },\n): Promise<PresignUrlResult> {\n const payload = await presign(signedToken, options);\n\n if (options.operation === 'get' || options.operation === 'head') {\n return {\n presignedUrl: buildPresignedGetUrl(options.pathname, payload, options),\n };\n }\n if (options.operation === 'put') {\n return {\n presignedUrl: buildPresignedPutUrl(options.pathname, payload),\n };\n }\n if (options.operation === 'delete') {\n return {\n presignedUrl: buildPresignedDeleteUrl(options.pathname, payload),\n };\n }\n\n throw new BlobError(`Unknown operation`);\n}\n\n/** @internal Exported for presign URL contract tests (must match proxy / api-blob). */\nexport function canonicalString(\n pathname: string,\n presignEntries: [string, string][],\n operation: DelegationOperation,\n): string {\n const lines: string[] = [`operation=${operation}`, `pathname=${pathname}`];\n for (const k of PRESIGN_CANONICAL_QUERY_KEYS) {\n const v = presignEntries.find(([key]) => key === k)?.[1];\n if (v) {\n lines.push(`${k}=${v}`);\n }\n }\n lines.sort((a, b) => compareUtf8(a, b));\n return lines.join('\\n');\n}\n\nconst utf8Encoder = new TextEncoder();\n\n/**\n * Lexicographic order of UTF-8 bytewise (matches Go `string` comparison and\n * `url.Values` key / pair ordering in practice).\n * @internal\n */\nfunction compareUtf8(a: string, b: string): number {\n const ab = utf8Encoder.encode(a);\n const bb = utf8Encoder.encode(b);\n const n = Math.min(ab.length, bb.length);\n for (let i = 0; i < n; i++) {\n const d = (ab[i]! - bb[i]!) as number;\n if (d !== 0) {\n return d;\n }\n }\n return ab.length - bb.length;\n}\n","import { requestApi } from './api';\nimport type { BlobAccessType, CommonCreateBlobOptions } from './helpers';\nimport { BlobError } from './helpers';\nimport { type PutBlobApiResponse, putOptionHeaderMap } from './put-helpers';\n\nexport type CreateFolderCommandOptions = Pick<\n CommonCreateBlobOptions,\n 'token' | 'abortSignal'\n> & {\n /** @defaultValue 'public' — kept for backward compatibility */\n access?: BlobAccessType;\n};\n\nexport interface CreateFolderResult {\n pathname: string;\n url: string;\n}\n\n/**\n * Creates a folder in your store. Vercel Blob has no real concept of folders, our file browser on Vercel.com displays folders based on the presence of trailing slashes in the pathname. Unless you are building a file browser system, you probably don't need to use this method.\n *\n * Use the resulting `url` to delete the folder, just like you would delete a blob.\n * @param pathname - Can be user1/ or user1/avatars/\n * @param options - Additional options including required `access` ('public' or 'private') and optional `token`\n */\n// access defaults to 'public' for backward compatibility with callers\n// that don't pass options (pre-private-storage API)\nexport async function createFolder(\n pathname: string,\n options: CreateFolderCommandOptions = { access: 'public' },\n): Promise<CreateFolderResult> {\n const access = options.access ?? 'public';\n\n const folderPathname = pathname.endsWith('/') ? pathname : `${pathname}/`;\n\n const headers: Record<string, string> = {};\n\n headers[putOptionHeaderMap.access] = access;\n headers[putOptionHeaderMap.addRandomSuffix] = '0';\n\n const params = new URLSearchParams({ pathname: folderPathname });\n const response = await requestApi<PutBlobApiResponse>(\n `/?${params.toString()}`,\n {\n method: 'PUT',\n headers,\n signal: options.abortSignal,\n },\n options,\n );\n\n return {\n url: response.url,\n pathname: response.pathname,\n };\n}\n","// This file is here because Edge Functions have no support for Node.js streams by default\n// It's unlikely someone would try to read/use a Node.js stream in an Edge function but we still put\n// a message in case this happens\n\nexport const Readable = {\n toWeb() {\n throw new Error(\n 'Vercel Blob: Sorry, we cannot get a Readable stream in this environment. If you see this message please open an issue here: https://github.com/vercel/storage/ with details on your environment.',\n );\n },\n};\n","// this file gets copied to the dist folder\n// it makes undici work in the browser by reusing the global fetch\n// it's the simplest way I've found to make http requests work in Node.js, Serverles Functions, Edge Functions, and the browser\n// this should work as long as this module is used via Next.js/Webpack\n// moving forward we will have to solve this problem in a more robust way\n// reusing https://github.com/inrupt/universal-fetch\n// or seeing how/if cross-fetch solves https://github.com/lquixada/cross-fetch/issues/69\nexport const fetch = globalThis.fetch.bind(globalThis);\n","import type { IncomingMessage } from 'node:http';\nimport * as crypto from 'crypto';\n// When bundled via a bundler supporting the `browser` field, then\n// the `undici` module will be replaced with https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n// for browser contexts. See ./undici-browser.js and ./package.json\nimport { fetch } from 'undici';\nimport type { BlobClientTokenConstraintOptions } from './client-token-constraints';\nimport type {\n BlobAccessType,\n BlobCommandOptions,\n PresignedUrlPayload,\n WithUploadProgress,\n} from './helpers';\nimport {\n BlobError,\n getReadWriteBlobTokenFromOptionsOrEnv,\n parseStoreIdFromReadWriteToken,\n} from './helpers';\nimport type { CommonCompleteMultipartUploadOptions } from './multipart/complete';\nimport { createCompleteMultipartUploadMethod } from './multipart/complete';\nimport { createCreateMultipartUploadMethod } from './multipart/create';\nimport { createCreateMultipartUploaderMethod } from './multipart/create-uploader';\nimport type { CommonMultipartUploadOptions } from './multipart/upload';\nimport { createUploadPartMethod } from './multipart/upload';\nimport { createPutMethod } from './put';\nimport type { PutBlobResult } from './put-helpers';\nimport {\n type IssuedSignedToken,\n type IssueSignedTokenOptions,\n type PresignPutUrlOptions,\n presign,\n} from './signed-token';\n\n/**\n * Interface for put, upload and multipart upload operations.\n * This type omits all options that are encoded in the client token.\n */\nexport interface ClientCommonCreateBlobOptions {\n /**\n * Whether the blob should be publicly accessible.\n * - 'public': The blob will be publicly accessible via its URL.\n * - 'private': The blob will require authentication to access.\n */\n access: BlobAccessType;\n /**\n * Defines the content type of the blob. By default, this value is inferred from the pathname.\n * Sent as the 'content-type' header when downloading a blob.\n */\n contentType?: string;\n /**\n * `AbortSignal` to cancel the running request. See https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * Shared interface for put and multipart operations that use client tokens.\n */\nexport interface ClientTokenOptions {\n /**\n * A client token that was generated by your server using the `generateClientToken` method.\n */\n token: string;\n}\n\n/**\n * Shared interface for put and upload operations.\n * @internal This is an internal interface not intended for direct use by consumers.\n */\ninterface ClientCommonPutOptions\n extends ClientCommonCreateBlobOptions,\n WithUploadProgress {\n /**\n * Whether to use multipart upload. Use this when uploading large files.\n * It will split the file into multiple parts, upload them in parallel and retry failed parts.\n */\n multipart?: boolean;\n}\n\n/**\n * @internal Internal function to validate client token options.\n */\nfunction createPutExtraChecks<\n TOptions extends ClientTokenOptions & ClientCommonCreateBlobOptions,\n>(methodName: string) {\n return function extraChecks(options: TOptions) {\n if (!options.token.startsWith('vercel_blob_client_')) {\n throw new BlobError(`${methodName} must be called with a client token`);\n }\n\n if (\n // @ts-expect-error -- Runtime check for DX.\n options.addRandomSuffix !== undefined ||\n // @ts-expect-error -- Runtime check for DX.\n options.allowOverwrite !== undefined ||\n // @ts-expect-error -- Runtime check for DX.\n options.cacheControlMaxAge !== undefined\n ) {\n throw new BlobError(\n `${methodName} doesn't allow \\`addRandomSuffix\\`, \\`cacheControlMaxAge\\` or \\`allowOverwrite\\`. Configure these options at the server side when generating client tokens.`,\n );\n }\n };\n}\n\n/**\n * Options for the client-side put operation.\n */\nexport type ClientPutCommandOptions = ClientCommonPutOptions &\n ClientTokenOptions;\n\n/**\n * Uploads a file to the blob store using a client token.\n *\n * @param pathname - The pathname to upload the blob to, including the extension. This will influence the URL of your blob.\n * @param body - The content of your blob. Can be a string, File, Blob, Buffer or ReadableStream.\n * @param options - Configuration options including:\n * - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.\n * - token - (Required) A client token generated by your server using the generateClientTokenFromReadWriteToken method.\n * - contentType - (Optional) The media type for the blob. By default, it's derived from the pathname.\n * - multipart - (Optional) Whether to use multipart upload for large files. It will split the file into multiple parts, upload them in parallel and retry failed parts.\n * - abortSignal - (Optional) AbortSignal to cancel the operation.\n * - onUploadProgress - (Optional) Callback to track upload progress: onUploadProgress(\\{loaded: number, total: number, percentage: number\\})\n * @returns A promise that resolves to the blob information, including pathname, contentType, contentDisposition, url, and downloadUrl.\n */\nexport const put = createPutMethod<ClientPutCommandOptions>({\n allowedOptions: ['contentType'],\n extraChecks: createPutExtraChecks('client/`put`'),\n});\n\n/**\n * Options for creating a multipart upload from the client side.\n */\nexport type ClientCreateMultipartUploadCommandOptions =\n ClientCommonCreateBlobOptions & ClientTokenOptions;\n\n/**\n * Creates a multipart upload. This is the first step in the manual multipart upload process.\n *\n * @param pathname - A string specifying the path inside the blob store. This will be the base value of the return URL and includes the filename and extension.\n * @param options - Configuration options including:\n * - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.\n * - token - (Required) A client token generated by your server using the generateClientTokenFromReadWriteToken method.\n * - contentType - (Optional) The media type for the file. If not specified, it's derived from the file extension.\n * - abortSignal - (Optional) AbortSignal to cancel the operation.\n * @returns A promise that resolves to an object containing:\n * - key: A string that identifies the blob object.\n * - uploadId: A string that identifies the multipart upload. Both are needed for subsequent uploadPart calls.\n */\nexport const createMultipartUpload =\n createCreateMultipartUploadMethod<ClientCreateMultipartUploadCommandOptions>({\n allowedOptions: ['contentType'],\n extraChecks: createPutExtraChecks('client/`createMultipartUpload`'),\n });\n\n/**\n * Creates a multipart uploader that simplifies the multipart upload process.\n * This is a wrapper around the manual multipart upload process that provides a more convenient API.\n *\n * @param pathname - A string specifying the path inside the blob store. This will be the base value of the return URL and includes the filename and extension.\n * @param options - Configuration options including:\n * - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.\n * - token - (Required) A client token generated by your server using the generateClientTokenFromReadWriteToken method.\n * - contentType - (Optional) The media type for the file. If not specified, it's derived from the file extension.\n * - abortSignal - (Optional) AbortSignal to cancel the operation.\n * @returns A promise that resolves to an uploader object with the following properties and methods:\n * - key: A string that identifies the blob object.\n * - uploadId: A string that identifies the multipart upload.\n * - uploadPart: A method to upload a part of the file.\n * - complete: A method to complete the multipart upload process.\n */\nexport const createMultipartUploader =\n createCreateMultipartUploaderMethod<ClientCreateMultipartUploadCommandOptions>(\n {\n allowedOptions: ['contentType'],\n extraChecks: createPutExtraChecks('client/`createMultipartUpload`'),\n },\n );\n\n/**\n * @internal Internal type for multipart upload options.\n */\ntype ClientMultipartUploadCommandOptions = ClientCommonCreateBlobOptions &\n ClientTokenOptions &\n CommonMultipartUploadOptions &\n WithUploadProgress;\n\n/**\n * Uploads a part of a multipart upload.\n * Used as part of the manual multipart upload process.\n *\n * @param pathname - Same value as the pathname parameter passed to createMultipartUpload. This will influence the final URL of your blob.\n * @param body - A blob object as ReadableStream, String, ArrayBuffer or Blob based on these supported body types. Each part must be a minimum of 5MB, except the last one which can be smaller.\n * @param options - Configuration options including:\n * - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.\n * - token - (Required) A client token generated by your server using the generateClientTokenFromReadWriteToken method.\n * - uploadId - (Required) A string returned from createMultipartUpload which identifies the multipart upload.\n * - key - (Required) A string returned from createMultipartUpload which identifies the blob object.\n * - partNumber - (Required) A number identifying which part is uploaded (1-based index).\n * - contentType - (Optional) The media type for the blob. By default, it's derived from the pathname.\n * - abortSignal - (Optional) AbortSignal to cancel the running request.\n * - onUploadProgress - (Optional) Callback to track upload progress: onUploadProgress(\\{loaded: number, total: number, percentage: number\\})\n * @returns A promise that resolves to the uploaded part information containing etag and partNumber, which will be needed for the completeMultipartUpload call.\n */\nexport const uploadPart =\n createUploadPartMethod<ClientMultipartUploadCommandOptions>({\n allowedOptions: ['contentType'],\n extraChecks: createPutExtraChecks('client/`multipartUpload`'),\n });\n\n/**\n * @internal Internal type for completing multipart uploads.\n */\ntype ClientCompleteMultipartUploadCommandOptions =\n ClientCommonCreateBlobOptions &\n ClientTokenOptions &\n CommonCompleteMultipartUploadOptions;\n\n/**\n * Completes a multipart upload by combining all uploaded parts.\n * This is the final step in the manual multipart upload process.\n *\n * @param pathname - Same value as the pathname parameter passed to createMultipartUpload.\n * @param parts - An array containing all the uploaded parts information from previous uploadPart calls. Each part must have properties etag and partNumber.\n * @param options - Configuration options including:\n * - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.\n * - token - (Required) A client token generated by your server using the generateClientTokenFromReadWriteToken method.\n * - uploadId - (Required) A string returned from createMultipartUpload which identifies the multipart upload.\n * - key - (Required) A string returned from createMultipartUpload which identifies the blob object.\n * - contentType - (Optional) The media type for the file. If not specified, it's derived from the file extension.\n * - abortSignal - (Optional) AbortSignal to cancel the operation.\n * @returns A promise that resolves to the finalized blob information, including pathname, contentType, contentDisposition, url, and downloadUrl.\n */\nexport const completeMultipartUpload =\n createCompleteMultipartUploadMethod<ClientCompleteMultipartUploadCommandOptions>(\n {\n allowedOptions: ['contentType'],\n extraChecks: createPutExtraChecks('client/`completeMultipartUpload`'),\n },\n );\n\n/**\n * Options for client-side upload operations.\n */\nexport interface CommonUploadOptions {\n /**\n * A route that implements the `handleUpload` function for generating a client token.\n */\n handleUploadUrl: string;\n /**\n * Additional data which will be sent to your `handleUpload` route.\n */\n clientPayload?: string;\n /**\n * Additional headers to be sent when making the request to your `handleUpload` route.\n * This is useful for sending authorization headers or any other custom headers.\n */\n headers?: Record<string, string>;\n}\n\n/**\n * Options for the upload method, which handles client-side uploads.\n */\nexport type UploadOptions = ClientCommonPutOptions & CommonUploadOptions;\n\n/**\n * Uploads a blob into your store from the client.\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#client-uploads\n *\n * If you want to upload from your server instead, check out the documentation for the put operation: https://vercel.com/docs/vercel-blob/using-blob-sdk#upload-a-blob\n *\n * Unlike the put method, this method does not require a client token as it will fetch one from your server.\n *\n * @param pathname - The pathname to upload the blob to. This includes the filename and extension.\n * @param body - The contents of your blob. This has to be a supported fetch body type (string, Blob, File, ArrayBuffer, etc).\n * @param options - Configuration options including:\n * - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.\n * - handleUploadUrl - (Required) A string specifying the route to call for generating client tokens for client uploads.\n * - clientPayload - (Optional) A string to be sent to your handleUpload server code. Example use-case: attaching the post id an image relates to.\n * - headers - (Optional) An object containing custom headers to be sent with the request to your handleUpload route. Example use-case: sending Authorization headers.\n * - contentType - (Optional) A string indicating the media type. By default, it's extracted from the pathname's extension.\n * - multipart - (Optional) Whether to use multipart upload for large files. It will split the file into multiple parts, upload them in parallel and retry failed parts.\n * - abortSignal - (Optional) AbortSignal to cancel the operation.\n * - onUploadProgress - (Optional) Callback to track upload progress: onUploadProgress(\\{loaded: number, total: number, percentage: number\\})\n * @returns A promise that resolves to the blob information, including pathname, contentType, contentDisposition, url, and downloadUrl.\n */\nexport const upload = createPutMethod<UploadOptions>({\n allowedOptions: ['contentType'],\n extraChecks(options) {\n if (options.handleUploadUrl === undefined) {\n throw new BlobError(\n \"client/`upload` requires the 'handleUploadUrl' parameter\",\n );\n }\n\n if (\n // @ts-expect-error -- Runtime check for DX.\n options.addRandomSuffix !== undefined ||\n // @ts-expect-error -- Runtime check for DX.\n options.allowOverwrite !== undefined ||\n // @ts-expect-error -- Runtime check for DX.\n options.cacheControlMaxAge !== undefined ||\n // @ts-expect-error -- Runtime check for DX.\n options.ifMatch !== undefined\n ) {\n throw new BlobError(\n \"client/`upload` doesn't allow `addRandomSuffix`, `cacheControlMaxAge`, `allowOverwrite` or `ifMatch`. Configure these options at the server side when generating client tokens.\",\n );\n }\n },\n async getToken(pathname, options) {\n return retrieveClientToken({\n handleUploadUrl: options.handleUploadUrl,\n pathname,\n clientPayload: options.clientPayload ?? null,\n multipart: options.multipart ?? false,\n headers: options.headers,\n });\n },\n});\n\n/**\n * Uploads a blob into your store from the client using a presigned URL.\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#client-uploads\n *\n * If you want to upload from your server instead, check out the documentation for the put operation: https://vercel.com/docs/vercel-blob/using-blob-sdk#upload-a-blob\n *\n * @param pathname - The pathname to upload the blob to. This includes the filename and extension.\n * @param body - The contents of your blob. This has to be a supported fetch body type (string, Blob, File, ArrayBuffer, etc).\n * @param options - Configuration options including:\n * - access - (Required) Must be 'public' or 'private'. Public blobs are accessible via URL, private blobs require authentication.\n * - handleUploadUrl - (Required) A string specifying the route to call for generating client tokens for client uploads.\n * - clientPayload - (Optional) A string to be sent to your handleUpload server code. Example use-case: attaching the post id an image relates to.\n * - headers - (Optional) An object containing custom headers to be sent with the request to your handleUpload route. Example use-case: sending Authorization headers.\n * - contentType - (Optional) A string indicating the media type. By default, it's extracted from the pathname's extension.\n * - multipart - (Optional) Whether to use multipart upload for large files. When true, your `handleUploadPresigned` route must return a presigned `POST` URL for `/mpu`.\n * - abortSignal - (Optional) AbortSignal to cancel the operation.\n * - onUploadProgress - (Optional) Callback to track upload progress: onUploadProgress(\\{loaded: number, total: number, percentage: number\\})\n * @returns A promise that resolves to the blob information, including pathname, contentType, contentDisposition, url, and downloadUrl.\n */\nexport const uploadPresigned = createPutMethod<UploadOptions>({\n allowedOptions: ['contentType'],\n extraChecks(options) {\n if (options.handleUploadUrl === undefined) {\n throw new BlobError(\n \"client/`upload` requires the 'handleUploadUrl' parameter\",\n );\n }\n\n if (\n // @ts-expect-error -- Runtime check for DX.\n options.addRandomSuffix !== undefined ||\n // @ts-expect-error -- Runtime check for DX.\n options.allowOverwrite !== undefined ||\n // @ts-expect-error -- Runtime check for DX.\n options.cacheControlMaxAge !== undefined ||\n // @ts-expect-error -- Runtime check for DX.\n options.ifMatch !== undefined\n ) {\n throw new BlobError(\n \"client/`uploadPresigned` doesn't allow `addRandomSuffix`, `cacheControlMaxAge`, `allowOverwrite` or `ifMatch`. Configure these options at the server side when generating presigned URLs.\",\n );\n }\n },\n async getPresignedUrlPayload(pathname, options) {\n return retrievePresignedUrlPayload({\n pathname,\n handleUploadUrl: options.handleUploadUrl,\n clientPayload: options.clientPayload ?? null,\n multipart: options.multipart ?? false,\n headers: options.headers,\n });\n },\n});\n\n/**\n * @internal Internal function to import a crypto key.\n */\nasync function importKey(token: string): Promise<CryptoKey> {\n return globalThis.crypto.subtle.importKey(\n 'raw',\n new TextEncoder().encode(token),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign', 'verify'],\n );\n}\n\n/**\n * @internal Internal function to sign a payload.\n */\nasync function signPayload(\n payload: string,\n token: string,\n): Promise<string | undefined> {\n if (!globalThis.crypto) {\n return crypto.createHmac('sha256', token).update(payload).digest('hex');\n }\n\n const signature = await globalThis.crypto.subtle.sign(\n 'HMAC',\n await importKey(token),\n new TextEncoder().encode(payload),\n );\n return Buffer.from(new Uint8Array(signature)).toString('hex');\n}\n\n/**\n * Decodes PEM `-----BEGIN PUBLIC KEY----- …` (SPKI) to DER bytes.\n */\nfunction publicKeyDerFromPem(pem: string): Buffer | undefined {\n const match = pem\n .trim()\n .match(/-----BEGIN PUBLIC KEY-----([^-]*)-----END PUBLIC KEY-----/s);\n const b64 = match?.[1]?.replace(/\\s+/g, '');\n if (!b64) {\n return undefined;\n }\n try {\n return Buffer.from(b64, 'base64');\n } catch {\n return undefined;\n }\n}\n\n/**\n * @internal Internal function to verify a callback signature for presigned uploads.\n */\nasync function verifyCallbackSignaturePresigned({\n webhookPublicKey,\n signature,\n body,\n}: {\n webhookPublicKey: string;\n signature: string;\n body: string;\n}): Promise<boolean> {\n if (\n typeof signature !== 'string' ||\n !/^[0-9a-fA-F]+$/.test(signature) ||\n signature.length !== 128\n ) {\n return false;\n }\n\n const signatureBuf = Buffer.from(signature, 'hex');\n\n const bodyBuf = Buffer.from(body, 'utf8');\n\n const der = publicKeyDerFromPem(webhookPublicKey);\n\n // Prefer Web Crypto when available so browser bundles (which replace `crypto`\n // with a small shim) never take the Node `createPublicKey` branch.\n if (globalThis.crypto?.subtle && der) {\n try {\n const derCopy = Uint8Array.from(der);\n const verifyKey = await globalThis.crypto.subtle.importKey(\n 'spki',\n derCopy,\n { name: 'Ed25519' },\n false,\n ['verify'],\n );\n const sigBytes = new Uint8Array(64);\n sigBytes.set(signatureBuf.subarray(0, 64), 0);\n const ok = await globalThis.crypto.subtle.verify(\n 'Ed25519',\n verifyKey,\n sigBytes,\n new TextEncoder().encode(body),\n );\n return ok;\n } catch {\n return false;\n }\n }\n\n if (typeof crypto.createPublicKey === 'function') {\n try {\n const key = crypto.createPublicKey(webhookPublicKey.trim());\n return crypto.verify(null, bodyBuf, key, signatureBuf);\n } catch {\n return false;\n }\n }\n\n return false;\n}\n\n/**\n * @internal Internal function to verify a callback signature.\n */\nasync function verifyCallbackSignature({\n token,\n signature,\n body,\n}: {\n token: string;\n signature: string;\n body: string;\n}): Promise<boolean> {\n // callback signature is signed using the server token\n const secret = token;\n // Browsers, Edge runtime and Node >=20 implement the Web Crypto API\n\n if (!globalThis.crypto) {\n // Node <20 falls back to the Node.js crypto module\n const digest = crypto\n .createHmac('sha256', secret)\n .update(body)\n .digest('hex');\n const digestBuffer = Buffer.from(digest);\n const signatureBuffer = Buffer.from(signature);\n\n return (\n digestBuffer.length === signatureBuffer.length &&\n crypto.timingSafeEqual(digestBuffer, signatureBuffer)\n );\n }\n\n const verified = await globalThis.crypto.subtle.verify(\n 'HMAC',\n await importKey(token),\n // @ts-expect-error Buffer is compatible with BufferSource at runtime\n hexToArrayByte(signature),\n new TextEncoder().encode(body),\n );\n return verified;\n}\n\n/**\n * @internal Internal utility function to convert hex to array byte.\n */\nfunction hexToArrayByte(input: string): Buffer {\n if (input.length % 2 !== 0) {\n throw new RangeError('Expected string to be an even number of characters');\n }\n const view = new Uint8Array(input.length / 2);\n\n for (let i = 0; i < input.length; i += 2) {\n view[i / 2] = Number.parseInt(input.substring(i, i + 2), 16);\n }\n\n return Buffer.from(view);\n}\n\n/**\n * Decoded payload from a client token.\n */\nexport type DecodedClientTokenPayload = Omit<\n GenerateClientTokenOptions,\n 'token'\n> & {\n /**\n * Timestamp in milliseconds when the token will expire.\n */\n validUntil: number;\n};\n\n/**\n * Extracts and decodes the payload from a client token.\n *\n * @param clientToken - The client token string to decode\n * @returns The decoded payload containing token options\n */\nexport function getPayloadFromClientToken(\n clientToken: string,\n): DecodedClientTokenPayload {\n const [, , , , encodedToken] = clientToken.split('_');\n const encodedPayload = Buffer.from(encodedToken ?? '', 'base64')\n .toString()\n .split('.')[1];\n const decodedPayload = Buffer.from(encodedPayload ?? '', 'base64').toString();\n return JSON.parse(decodedPayload) as DecodedClientTokenPayload;\n}\n\n/**\n * @internal Event type constants for internal use.\n */\nconst EventTypes = {\n generateClientToken: 'blob.generate-client-token',\n generatePresignedUrl: 'blob.generate-presigned-url',\n uploadCompleted: 'blob.upload-completed',\n} as const;\n\n/**\n * Event for generating a client token for blob uploads.\n * @internal This is an internal interface used by the SDK.\n */\ninterface GenerateClientTokenEvent {\n /**\n * Type identifier for the generate client token event.\n */\n type: (typeof EventTypes)['generateClientToken'];\n\n /**\n * Payload containing information needed to generate a client token.\n */\n payload: {\n /**\n * The destination path for the blob.\n */\n pathname: string;\n\n /**\n * Whether the upload will use multipart uploading.\n */\n multipart: boolean;\n\n /**\n * Additional data from the client which will be available in onBeforeGenerateToken.\n */\n clientPayload: string | null;\n };\n}\n\nexport interface GeneratePresignedUrlEvent {\n /**\n * Type identifier for the generate presigned url event.\n */\n type: (typeof EventTypes)['generatePresignedUrl'];\n\n /**\n * Payload containing information needed to generate a presigned url.\n */\n payload: {\n /**\n * The destination path for the blob.\n */\n pathname: string;\n\n /**\n * Whether the upload will use multipart uploading.\n */\n multipart: boolean;\n\n /**\n * Additional data from the client which will be available in onBeforeGenerateToken.\n */\n clientPayload: string | null;\n };\n}\n\n/**\n * Event that occurs when a client upload has completed.\n * @internal This is an internal interface used by the SDK.\n */\ninterface UploadCompletedEvent {\n /**\n * Type identifier for the upload completed event.\n */\n type: (typeof EventTypes)['uploadCompleted'];\n\n /**\n * Payload containing information about the uploaded blob.\n */\n payload: {\n /**\n * Details about the blob that was uploaded.\n */\n blob: PutBlobResult;\n\n /**\n * Optional payload that was defined during token generation.\n */\n tokenPayload?: string | null;\n };\n}\n\n/**\n * Union type representing either a request to generate a client token or a notification that an upload completed.\n */\nexport type HandleUploadBody = GenerateClientTokenEvent | UploadCompletedEvent;\n\n/**\n * Request body for {@link handleUploadPresigned}: presigned `PUT` URL issuance or upload completion callback.\n */\nexport type HandleUploadPresignedBody =\n | GeneratePresignedUrlEvent\n | UploadCompletedEvent;\n\n/**\n * Type representing either a Node.js IncomingMessage or a web standard Request object.\n * @internal This is an internal type used by the SDK.\n */\ntype RequestType = IncomingMessage | Request;\n\n/**\n * Options for the handleUpload function.\n */\nexport interface HandleUploadOptions {\n /**\n * The request body containing upload information.\n */\n body: HandleUploadBody;\n\n /**\n * Function called before generating the client token for uploads.\n *\n * @param pathname - The destination path for the blob\n * @param clientPayload - A string payload specified on the client when calling upload()\n * @param multipart - A boolean specifying whether the file is a multipart upload\n *\n * @returns An object with configuration options for the client token including the optional callbackUrl\n */\n onBeforeGenerateToken: (\n pathname: string,\n clientPayload: string | null,\n multipart: boolean,\n ) => Promise<\n Pick<\n GenerateClientTokenOptions,\n | 'allowedContentTypes'\n | 'maximumSizeInBytes'\n | 'validUntil'\n | 'addRandomSuffix'\n | 'allowOverwrite'\n | 'cacheControlMaxAge'\n | 'ifMatch'\n > & { tokenPayload?: string | null; callbackUrl?: string }\n >;\n\n /**\n * Function called by Vercel Blob when the client upload finishes.\n * This is useful to update your database with the blob URL that was uploaded.\n *\n * @param body - Contains information about the completed upload including the blob details\n */\n onUploadCompleted?: (body: UploadCompletedEvent['payload']) => Promise<void>;\n\n /**\n * A string specifying the read-write token to use when making requests.\n * It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\n */\n token?: string;\n\n /**\n * An IncomingMessage or Request object to be used to determine the action to take.\n */\n request: RequestType;\n}\n\n/**\n * A server-side route helper to manage client uploads. It has two responsibilities:\n * 1. Generate tokens for client uploads\n * 2. Listen for completed client uploads, so you can update your database with the URL of the uploaded file\n *\n * @param options - Configuration options for handling uploads\n * - request - (Required) An IncomingMessage or Request object to be used to determine the action to take.\n * - body - (Required) The request body containing upload information.\n * - onBeforeGenerateToken - (Required) Function called before generating the client token for uploads.\n * - onUploadCompleted - (Optional) Function called by Vercel Blob when the client upload finishes.\n * - token - (Optional) A string specifying the read-write token to use when making requests. Defaults to process.env.BLOB_READ_WRITE_TOKEN.\n * @returns A promise that resolves to either a client token generation result or an upload completion result\n */\nexport async function handleUpload({\n token,\n request,\n body,\n onBeforeGenerateToken,\n onUploadCompleted,\n}: HandleUploadOptions): Promise<\n | { type: 'blob.generate-client-token'; clientToken: string }\n | { type: 'blob.upload-completed'; response: 'ok' }\n> {\n const resolvedToken = getReadWriteBlobTokenFromOptionsOrEnv({ token });\n\n const type = body.type;\n switch (type) {\n case 'blob.generate-client-token': {\n const { pathname, clientPayload, multipart } = body.payload;\n const payload = await onBeforeGenerateToken(\n pathname,\n clientPayload,\n multipart,\n );\n const tokenPayload = payload.tokenPayload ?? clientPayload;\n const { callbackUrl: providedCallbackUrl, ...tokenOptions } = payload;\n let callbackUrl = providedCallbackUrl;\n\n // If onUploadCompleted is provided but no callbackUrl was provided, try to infer it from environment\n if (onUploadCompleted && !callbackUrl) {\n callbackUrl = getCallbackUrl(request);\n }\n\n // If no onUploadCompleted but callbackUrl was provided, warn about it\n if (!onUploadCompleted && callbackUrl) {\n console.warn(\n 'callbackUrl was provided but onUploadCompleted is not defined. The callback will not be handled.',\n );\n }\n\n // one hour\n const oneHourInSeconds = 60 * 60;\n const now = new Date();\n const validUntil =\n payload.validUntil ??\n now.setSeconds(now.getSeconds() + oneHourInSeconds);\n\n return {\n type,\n clientToken: await generateClientTokenFromReadWriteToken({\n ...tokenOptions,\n token: resolvedToken,\n pathname,\n onUploadCompleted: callbackUrl\n ? {\n callbackUrl,\n tokenPayload,\n }\n : undefined,\n validUntil,\n }),\n };\n }\n case 'blob.upload-completed': {\n const signatureHeader = 'x-vercel-signature';\n const signature = (\n 'credentials' in request\n ? (request.headers.get(signatureHeader) ?? '')\n : (request.headers[signatureHeader] ?? '')\n ) as string;\n\n if (!signature) {\n throw new BlobError('Missing callback signature');\n }\n\n const isVerified = await verifyCallbackSignature({\n token: resolvedToken,\n signature,\n body: JSON.stringify(body),\n });\n\n if (!isVerified) {\n throw new BlobError('Invalid callback signature');\n }\n\n if (onUploadCompleted) {\n await onUploadCompleted(body.payload);\n }\n return { type, response: 'ok' };\n }\n default:\n throw new BlobError('Invalid event type');\n }\n}\n\n/**\n * Delegation fields accepted by {@link issueSignedToken}, i.e.\n * JSON embedded in `vercel-blob-delegation`. Upload-behavior options belong in\n * {@link PresignUrlOptions} for `put` (`urlOptions` from {@link HandleUploadPresignedOptions.getSignedToken}),\n * not in the delegation body.\n */\nexport type HandleUploadPresignedSignedTokenPayload = Pick<\n IssueSignedTokenOptions,\n | 'allowedContentTypes'\n | 'maximumSizeInBytes'\n | 'operations'\n | 'pathname'\n | 'validUntil'\n>;\n\n/**\n * @deprecated Callback wiring for presigned uploads is merged into {@link PresignUrlOptions}\n * by {@link handleUploadPresigned} after `getSignedToken` returns; you no longer receive this\n * object as a separate argument.\n */\nexport interface HandleUploadPresignedIssuanceContext {\n onUploadCompleted?: {\n callbackUrl: string;\n tokenPayload?: string | null;\n };\n}\n\n/**\n * Options for {@link handleUploadPresigned} — same upload-completion flow as {@link handleUpload},\n * but `blob.generate-presigned-url` returns a presigned control-plane URL: `PUT` to `/?pathname=…`\n * for single upload, or `POST` to `/mpu?pathname=…` when the client requested multipart.\n */\nexport interface HandleUploadPresignedOptions {\n body: HandleUploadPresignedBody;\n /**\n * Produce signed token (e.g. via `issueSignedToken`) for {@link presign}.\n * This must be a token with 'put' priveleges and access to the pathname\n */\n getSignedToken: (\n pathname: string,\n clientPayload: string | null,\n multipart: boolean,\n ) => Promise<{\n token: IssuedSignedToken;\n urlOptions?: Omit<\n PresignPutUrlOptions,\n 'operation' | 'pathname' | 'onUploadCompleted'\n > & {\n callbackUrl?: string;\n tokenPayload?: string | null;\n };\n }>;\n\n /**\n * Public key for verifying webhook signatures.\n * This is used to verify the signature of the webhook request.\n *\n * @default process.env.BLOB_WEBHOOK_PUBLIC_KEY\n */\n webhookPublicKey?: string;\n\n /**\n * Function called by Vercel Blob when the client upload finishes.\n * This is useful to update your database with the blob URL that was uploaded.\n *\n * @param body - Contains information about the completed upload including the blob details\n */\n onUploadCompleted?: HandleUploadOptions['onUploadCompleted'];\n\n /**\n * An IncomingMessage or Request object to be used to determine the action to take.\n */\n request: RequestType;\n}\n\n/**\n * Server route helper for **presigned** client uploads: returns a presigned control-plane\n * `PUT` URL for single-object uploads, or a presigned `POST` URL for `/mpu` when multipart.\n * Verifies upload-completed callbacks with Ed25519 (`BLOB_WEBHOOK_PUBLIC_KEY`) over `x-vercel-signature`,\n * matching outbound `webhook_keypair` signing from api-storage when sending the callback.\n *\n * If `onUploadCompleted` is set, the callback target URL is resolved like {@link handleUpload}\n * (same `VERCEL_BLOB_CALLBACK_URL` / Vercel URL rules) and merged into the options passed to\n * {@link presignUrl} after `getSignedToken` returns.\n */\nexport async function handleUploadPresigned({\n body,\n request,\n webhookPublicKey,\n getSignedToken,\n onUploadCompleted,\n}: HandleUploadPresignedOptions): Promise<\n | {\n type: 'blob.generate-presigned-url';\n presignedUrlPayload: PresignedUrlPayload;\n }\n | { type: 'blob.upload-completed'; response: 'ok' }\n> {\n const resolvedWebhookPublicKey =\n webhookPublicKey ?? process.env.BLOB_WEBHOOK_PUBLIC_KEY;\n\n if (!resolvedWebhookPublicKey) {\n throw new BlobError('Missing webhook public key');\n }\n\n const type = body.type;\n switch (type) {\n case 'blob.generate-presigned-url': {\n const { pathname, clientPayload, multipart } = body.payload;\n\n const { token, urlOptions = {} } = await getSignedToken(\n pathname,\n clientPayload,\n multipart,\n );\n\n const tokenPayload =\n urlOptions?.tokenPayload ?? clientPayload ?? undefined;\n const { callbackUrl: providedCallbackUrl } = urlOptions;\n let callbackUrl = providedCallbackUrl;\n\n if (onUploadCompleted && !callbackUrl) {\n callbackUrl = getCallbackUrl(request);\n }\n\n // If no onUploadCompleted but callbackUrl was provided, warn about it\n if (!onUploadCompleted && callbackUrl) {\n console.warn(\n 'callbackUrl was provided but onUploadCompleted is not defined. The callback will not be handled.',\n );\n }\n\n const urlOptionsWithCallback = {\n ...urlOptions,\n onUploadCompleted: callbackUrl\n ? {\n callbackUrl,\n tokenPayload,\n }\n : undefined,\n };\n\n const presignedUrlPayload = await presign(token, {\n ...urlOptionsWithCallback,\n operation: 'put',\n pathname,\n });\n return { type, presignedUrlPayload };\n }\n case 'blob.upload-completed': {\n const signatureHeader = 'x-vercel-signature';\n const signature = (\n 'credentials' in request\n ? (request.headers.get(signatureHeader) ?? '')\n : (request.headers[signatureHeader] ?? '')\n ) as string;\n\n if (!signature) {\n throw new BlobError('Missing callback signature');\n }\n\n const isVerified = await verifyCallbackSignaturePresigned({\n webhookPublicKey: resolvedWebhookPublicKey,\n signature,\n body: JSON.stringify(body),\n });\n\n if (!isVerified) {\n throw new BlobError('Invalid callback signature');\n }\n\n if (onUploadCompleted) {\n await onUploadCompleted(body.payload);\n }\n return { type, response: 'ok' };\n }\n default:\n throw new BlobError('Invalid event type');\n }\n}\n\n/**\n * @internal Internal function to retrieve a client token from server.\n */\nasync function retrieveClientToken(options: {\n pathname: string;\n handleUploadUrl: string;\n clientPayload: string | null;\n multipart: boolean;\n abortSignal?: AbortSignal;\n headers?: Record<string, string>;\n}): Promise<string> {\n const { handleUploadUrl, pathname } = options;\n const url = isAbsoluteUrl(handleUploadUrl)\n ? handleUploadUrl\n : toAbsoluteUrl(handleUploadUrl);\n\n const event: GenerateClientTokenEvent = {\n type: EventTypes.generateClientToken,\n payload: {\n pathname,\n clientPayload: options.clientPayload,\n multipart: options.multipart,\n },\n };\n\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(event),\n headers: {\n 'content-type': 'application/json',\n ...options.headers,\n },\n signal: options.abortSignal,\n });\n\n if (!res.ok) {\n throw new BlobError('Failed to retrieve the client token');\n }\n\n try {\n const { clientToken } = (await res.json()) as { clientToken: string };\n return clientToken;\n } catch {\n throw new BlobError('Failed to retrieve the client token');\n }\n}\n\n/**\n * @internal Internal function to retrieve a presigned URL from server.\n */\nasync function retrievePresignedUrlPayload(options: {\n pathname: string;\n handleUploadUrl: string;\n clientPayload: string | null;\n multipart: boolean;\n abortSignal?: AbortSignal;\n headers?: Record<string, string>;\n}): Promise<PresignedUrlPayload> {\n const { handleUploadUrl, pathname } = options;\n const url = isAbsoluteUrl(handleUploadUrl)\n ? handleUploadUrl\n : toAbsoluteUrl(handleUploadUrl);\n\n const event: GeneratePresignedUrlEvent = {\n type: EventTypes.generatePresignedUrl,\n payload: {\n pathname,\n clientPayload: options.clientPayload,\n multipart: options.multipart,\n },\n };\n\n const res = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(event),\n headers: {\n 'content-type': 'application/json',\n ...options.headers,\n },\n signal: options.abortSignal,\n });\n\n if (!res.ok) {\n throw new BlobError('Failed to retrieve the presigned URL');\n }\n\n try {\n const { presignedUrlPayload } = (await res.json()) as {\n presignedUrlPayload: PresignedUrlPayload;\n };\n if (presignedUrlPayload) {\n return presignedUrlPayload;\n }\n throw new BlobError('Missing presignedUrlPayload');\n } catch (error) {\n if (error instanceof BlobError) {\n throw error;\n }\n throw new BlobError('Failed to retrieve the presigned URL');\n }\n}\n\n/**\n * @internal Internal utility to convert a relative URL to absolute URL.\n */\nfunction toAbsoluteUrl(url: string): string {\n // location is available in web workers too: https://developer.mozilla.org/en-US/docs/Web/API/Window/location\n return new URL(url, location.href).href;\n}\n\n/**\n * @internal Internal utility to check if a URL is absolute.\n */\nfunction isAbsoluteUrl(url: string): boolean {\n try {\n return Boolean(new URL(url));\n } catch {\n return false;\n }\n}\n\n/**\n * Generates a client token from a read-write token. This function must be called from a server environment.\n * The client token contains permissions and constraints that limit what the client can do.\n *\n * @param options - Options for generating the client token\n * - pathname - (Required) The destination path for the blob.\n * - token - (Optional) A string specifying the read-write token to use. Defaults to process.env.BLOB_READ_WRITE_TOKEN.\n * - onUploadCompleted - (Optional) Configuration for upload completion callback.\n * - maximumSizeInBytes - (Optional) A number specifying the maximum size in bytes that can be uploaded (max 5TB).\n * - allowedContentTypes - (Optional) An array of media types that are allowed to be uploaded. Wildcards are supported (text/*).\n * - validUntil - (Optional) A timestamp in ms when the token will expire. Defaults to one hour from generation.\n * - addRandomSuffix - (Optional) Whether to add a random suffix to the filename. Defaults to false.\n * - allowOverwrite - (Optional) Whether to allow overwriting existing blobs. Defaults to false.\n * - cacheControlMaxAge - (Optional) Number of seconds to configure cache duration. Defaults to one month.\n * - ifMatch - (Optional) Only write if the ETag matches (optimistic concurrency control).\n * @returns A promise that resolves to the generated client token string which can be used in client-side upload operations.\n */\nexport async function generateClientTokenFromReadWriteToken({\n token,\n ...argsWithoutToken\n}: GenerateClientTokenOptions): Promise<string> {\n if (typeof window !== 'undefined') {\n throw new BlobError(\n '\"generateClientTokenFromReadWriteToken\" must be called from a server environment',\n );\n }\n\n // ifMatch implies allowOverwrite — updating a blob by ETag inherently requires\n // overwriting. Throw if the user explicitly contradicts this.\n if (argsWithoutToken.ifMatch && argsWithoutToken.allowOverwrite === false) {\n throw new BlobError(\n 'ifMatch and allowOverwrite: false are contradictory. ifMatch is used for conditional overwrites, which requires allowOverwrite to be true.',\n );\n }\n\n // Implicitly enable allowOverwrite when ifMatch is set and allowOverwrite\n // was not explicitly provided, to prevent the server from sending\n // conflicting If-Match + If-None-Match headers to S3.\n if (\n argsWithoutToken.ifMatch &&\n argsWithoutToken.allowOverwrite === undefined\n ) {\n argsWithoutToken.allowOverwrite = true;\n }\n\n const timestamp = new Date();\n timestamp.setSeconds(timestamp.getSeconds() + 30);\n const readWriteToken = getReadWriteBlobTokenFromOptionsOrEnv({ token });\n\n const storeId = parseStoreIdFromReadWriteToken(readWriteToken) || null;\n\n if (!storeId) {\n throw new BlobError(\n token ? 'Invalid `token` parameter' : 'Invalid `BLOB_READ_WRITE_TOKEN`',\n );\n }\n\n const payload = Buffer.from(\n JSON.stringify({\n ...argsWithoutToken,\n validUntil: argsWithoutToken.validUntil ?? timestamp.getTime(),\n }),\n ).toString('base64');\n\n const securedKey = await signPayload(payload, readWriteToken);\n\n if (!securedKey) {\n throw new BlobError('Unable to sign client token');\n }\n return `vercel_blob_client_${storeId}_${Buffer.from(\n `${securedKey}.${payload}`,\n ).toString('base64')}`;\n}\n\n/**\n * Options for generating a client token.\n */\nexport interface GenerateClientTokenOptions\n extends BlobCommandOptions,\n BlobClientTokenConstraintOptions {\n /**\n * The destination path for the blob\n */\n pathname: string;\n}\n\n/**\n * @internal Helper function to determine the callback URL for client uploads\n * when onUploadCompleted is provided but no callbackUrl was specified\n */\nfunction getCallbackUrl(request: RequestType): string | undefined {\n const reqPath = getPathFromRequestUrl(request.url!);\n\n if (!reqPath) {\n console.warn(\n 'onUploadCompleted provided but no callbackUrl could be determined. Please provide a callbackUrl in onBeforeGenerateToken or set the VERCEL_BLOB_CALLBACK_URL environment variable.',\n );\n return undefined;\n }\n\n // Check if we have VERCEL_BLOB_CALLBACK_URL env var (works on or off Vercel)\n if (process.env.VERCEL_BLOB_CALLBACK_URL) {\n return `${process.env.VERCEL_BLOB_CALLBACK_URL}${reqPath}`;\n }\n\n // Not hosted on Vercel and no VERCEL_BLOB_CALLBACK_URL\n if (process.env.VERCEL !== '1') {\n console.warn(\n 'onUploadCompleted provided but no callbackUrl could be determined. Please provide a callbackUrl in onBeforeGenerateToken or set the VERCEL_BLOB_CALLBACK_URL environment variable.',\n );\n return undefined;\n }\n\n // If hosted on Vercel, generate default callbackUrl\n\n if (process.env.VERCEL_ENV === 'preview') {\n if (process.env.VERCEL_BRANCH_URL) {\n return `https://${process.env.VERCEL_BRANCH_URL}${reqPath}`;\n }\n if (process.env.VERCEL_URL) {\n return `https://${process.env.VERCEL_URL}${reqPath}`;\n }\n }\n\n if (\n process.env.VERCEL_ENV === 'production' &&\n process.env.VERCEL_PROJECT_PRODUCTION_URL\n ) {\n return `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}${reqPath}`;\n }\n\n return undefined;\n}\n\n/**\n * @internal Helper function to safely extract pathname and query string from request URL\n * Handles both full URLs (http://localhost:3000/api/upload?test=1) and relative paths (/api/upload?test=1)\n */\nfunction getPathFromRequestUrl(url: string): string | null {\n try {\n // Using dummy.com as base URL to handle relative paths\n const parsedUrl = new URL(url, 'https://dummy.com');\n return parsedUrl.pathname + parsedUrl.search;\n } catch {\n return null;\n }\n}\n\nexport { createFolder } from './create-folder';\n","import { put } from \"@vercel/blob/client\";\n\n/**\n * Shopper file uploads for personalised products (a photo for a portrait, a print-ready PDF).\n *\n * Browser-only. The storefront calls `uploadLineItemFile(file, { variantId })` from its product\n * page; the platform hands out a short-lived token for exactly one file (its `/checkout/api/**`\n * endpoint is already forwarded by every tenant's proxy, so the storefront needs no route of its\n * own and no API key in the browser), and the file goes straight into the store's private storage.\n * The returned `uploadId` is what a cart line's file property carries:\n *\n * ```ts\n * const { uploadId } = await uploadLineItemFile(file, { variantId });\n * await cartUpsert({ variantId, quantity: 1, properties: [lineItemFileProperty({ key: \"photo\", label: \"Photo\", uploadId })] });\n * ```\n *\n * Requires the store's Customer Uploads module. Images (JPEG, PNG, WebP, GIF, HEIC/HEIF, AVIF,\n * TIFF) and PDF, up to 20 MB.\n */\n\nexport const LINE_ITEM_UPLOAD_ENDPOINT = \"/checkout/api/line-item-uploads\";\nexport const MAX_LINE_ITEM_UPLOAD_BYTES = 20 * 1024 * 1024;\n\n/** Some browsers report HEIC/HEIF (and the occasional other image) with an empty type. */\nconst TYPE_BY_EXTENSION: Record<string, string> = {\n\tjpg: \"image/jpeg\",\n\tjpeg: \"image/jpeg\",\n\tpng: \"image/png\",\n\twebp: \"image/webp\",\n\tgif: \"image/gif\",\n\theic: \"image/heic\",\n\theif: \"image/heif\",\n\tavif: \"image/avif\",\n\ttif: \"image/tiff\",\n\ttiff: \"image/tiff\",\n\tpdf: \"application/pdf\",\n};\n\nexport const ACCEPTED_LINE_ITEM_UPLOAD_TYPES = [...new Set(Object.values(TYPE_BY_EXTENSION))].join(\",\");\n\nexport class LineItemUploadError extends Error {\n\treadonly status: number;\n\tconstructor(message: string, status: number) {\n\t\tsuper(message);\n\t\tthis.name = \"LineItemUploadError\";\n\t\tthis.status = status;\n\t}\n}\n\nconst contentTypeOf = (file: File): string =>\n\tfile.type || TYPE_BY_EXTENSION[file.name.split(\".\").pop()?.toLowerCase() ?? \"\"] || \"\";\n\nconst isTokenResponse = (\n\tvalue: unknown,\n): value is { uploadId: string; pathname: string; clientToken: string } =>\n\ttypeof value === \"object\" &&\n\tvalue !== null &&\n\t\"uploadId\" in value &&\n\ttypeof value.uploadId === \"string\" &&\n\t\"pathname\" in value &&\n\ttypeof value.pathname === \"string\" &&\n\t\"clientToken\" in value &&\n\ttypeof value.clientToken === \"string\";\n\nconst errorMessageOf = (value: unknown): string | null =>\n\ttypeof value === \"object\" && value !== null && \"error\" in value && typeof value.error === \"string\"\n\t\t? value.error\n\t\t: null;\n\n/**\n * Upload one file for a cart line. Throws `LineItemUploadError` with the platform's message and\n * HTTP status (400 unsupported file, 404 uploads off for this store, 429 too many uploads).\n */\nexport async function uploadLineItemFile(\n\tfile: File,\n\toptions: {\n\t\tvariantId: string;\n\t\t/** Defaults to the platform endpoint every tenant proxy forwards. */\n\t\tendpoint?: string;\n\t\tonUploadProgress?: (event: { loaded: number; total: number; percentage: number }) => void;\n\t\tabortSignal?: AbortSignal;\n\t},\n): Promise<{ uploadId: string }> {\n\tconst contentType = contentTypeOf(file);\n\tif (!contentType) {\n\t\tthrow new LineItemUploadError(\"This file type can't be uploaded.\", 400);\n\t}\n\tif (file.size > MAX_LINE_ITEM_UPLOAD_BYTES) {\n\t\tthrow new LineItemUploadError(\"The file is larger than 20 MB.\", 400);\n\t}\n\n\tconst response = await fetch(options.endpoint ?? LINE_ITEM_UPLOAD_ENDPOINT, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tcredentials: \"same-origin\",\n\t\tbody: JSON.stringify({ variantId: options.variantId, filename: file.name, contentType, size: file.size }),\n\t\t...(options.abortSignal ? { signal: options.abortSignal } : {}),\n\t});\n\tconst body: unknown = await response.json().catch(() => null);\n\tif (!response.ok || !isTokenResponse(body)) {\n\t\tthrow new LineItemUploadError(errorMessageOf(body) ?? \"The upload could not start.\", response.status);\n\t}\n\n\tawait put(body.pathname, file, {\n\t\taccess: \"private\",\n\t\ttoken: body.clientToken,\n\t\tcontentType,\n\t\tmultipart: file.size > 8 * 1024 * 1024,\n\t\t...(options.onUploadProgress ? { onUploadProgress: options.onUploadProgress } : {}),\n\t\t...(options.abortSignal ? { abortSignal: options.abortSignal } : {}),\n\t});\n\treturn { uploadId: body.uploadId };\n}\n\n/** The cart line property that attaches an uploaded file. */\nexport const lineItemFileProperty = ({\n\tkey,\n\tlabel,\n\tuploadId,\n}: {\n\tkey: string;\n\tlabel?: string;\n\tuploadId: string;\n}): { key: string; label?: string; type: \"file\"; value: string } => ({\n\tkey,\n\t...(label !== undefined ? { label } : {}),\n\ttype: \"file\",\n\tvalue: uploadId,\n});\n"],"mappings":"2yBAAA,IAAAA,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cAOAA,GAAO,QAAU,SAAmBC,EAAK,CACvC,OAAOA,GAAO,MAAQA,EAAI,aAAe,MACvC,OAAOA,EAAI,YAAY,UAAa,YAAcA,EAAI,YAAY,SAASA,CAAG,CAClF,ICVA,IAAAC,GAAAC,EAAA,CAAAC,GAAAC,KAAA,cACA,IAAIC,GAAY,OAAO,eACnBC,GAAmB,OAAO,yBAC1BC,GAAoB,OAAO,oBAC3BC,GAAe,OAAO,UAAU,eAChCC,GAAW,CAACC,EAAQC,IAAQ,CAC9B,QAASC,KAAQD,EACfN,GAAUK,EAAQE,EAAM,CAAE,IAAKD,EAAIC,CAAI,EAAG,WAAY,EAAK,CAAC,CAChE,EACIC,GAAc,CAACC,EAAIC,EAAMC,EAAQC,IAAS,CAC5C,GAAIF,GAAQ,OAAOA,GAAS,UAAY,OAAOA,GAAS,WACtD,QAASG,KAAOX,GAAkBQ,CAAI,EAChC,CAACP,GAAa,KAAKM,EAAII,CAAG,GAAKA,IAAQF,GACzCX,GAAUS,EAAII,EAAK,CAAE,IAAK,I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AQ,WAAY,EAAI,CAAC,CACnE,CAAC,EACM,CAAE,SAAUG,EAAK,QAAS,CAClC,CAGO,IAAME,GAAuB,CAAC,CACpC,IAAAC,EACA,MAAAC,EACA,SAAAC,CACD,KAIqE,CACpE,IAAAF,EACA,GAAIC,IAAU,OAAY,CAAE,MAAAA,CAAM,EAAI,CAAC,EACvC,KAAM,OACN,MAAOC,CACR","names":["require_is_buffer","__commonJSMin","exports","module","obj","require_get_context","__commonJSMin","exports","module","__defProp","__getOwnPropDesc","__getOwnPropNames","__hasOwnProp","__export","target","all","name","__copyProps","to","from","except","desc","key","__toCommonJS","mod","get_context_exports","SYMBOL_FOR_REQ_CONTEXT","getContext","webcrypto_default","isCryptoKey","init_webcrypto","__esmMin","key","digest","digest_default","init_digest","__esmMin","init_webcrypto","algorithm","data","subtleDigest","webcrypto_default","concat","buffers","size","acc","length","buf","i","buffer","p2s","alg","p2sInput","encoder","writeUInt32BE","value","offset","MAX_INT32","uint64be","high","low","uint32be","lengthAndInput","input","concatKdf","secret","bits","iterations","res","iter","digest_default","decoder","init_buffer_utils","__esmMin","init_digest","encodeBase64","encode","decodeBase64","decode","init_base64url","__esmMin","init_buffer_utils","input","unencoded","encoder","CHUNK_SIZE","arr","i","encoded","binary","bytes","decoder","errors_exports","__export","JOSEAlgNotAllowed","JOSEError","JOSENotSupported","JWEDecryptionFailed","JWEInvalid","JWKInvalid","JWKSInvalid","JWKSMultipleMatchingKeys","JWKSNoMatchingKey","JWKSTimeout","JWSInvalid","JWSSignatureVerificationFailed","JWTClaimValidationFailed","JWTExpired","JWTInvalid","init_errors","__esmMin","message","options","payload","claim","reason","random_default","init_random","__esmMin","init_webcrypto","webcrypto_default","bitLength","alg","JOSENotSupported","iv_default","init_iv","__esmMin","init_errors","init_random","random_default","checkIvLength","check_iv_length_default","init_check_iv_length","__esmMin","init_errors","init_iv","enc","iv","bitLength","JWEInvalid","checkCekLength","check_cek_length_default","init_check_cek_length","__esmMin","init_errors","cek","expected","actual","JWEInvalid","timingSafeEqual","timing_safe_equal_default","init_timing_safe_equal","__esmMin","a","b","len","out","i","unusable","name","prop","isAlgorithm","algorithm","getHashLength","hash","getNamedCurve","alg","checkUsage","key","usages","expected","msg","last","checkSigCryptoKey","checkEncCryptoKey","init_crypto_key","__esmMin","message","msg","actual","types","last","withAlg","alg","invalid_key_input_default","init_invalid_key_input","__esmMin","is_key_like_default","types","init_is_key_like","__esmMin","init_webcrypto","key","isCryptoKey","cbcDecrypt","enc","cek","ciphertext","iv","tag","aad","invalid_key_input_default","keySize","encKey","webcrypto_default","macKey","macData","concat","uint64be","expectedTag","macCheckPassed","timing_safe_equal_default","JWEDecryptionFailed","plaintext","gcmDecrypt","checkEncCryptoKey","decrypt","decrypt_default","init_decrypt","__esmMin","init_buffer_utils","init_check_iv_length","init_check_cek_length","init_timing_safe_equal","init_errors","init_webcrypto","init_crypto_key","init_invalid_key_input","init_is_key_like","isCryptoKey","types","JWEInvalid","check_iv_length_default","check_cek_length_default","JOSENotSupported","isDisjoint","is_disjoint_default","init_is_disjoint","__esmMin","headers","sources","acc","header","parameters","parameter","isObjectLike","value","isObject","input","proto","init_is_object","__esmMin","bogusWebCrypto","bogus_default","init_bogus","__esmMin","checkKeySize","key","alg","getCryptoKey","usage","isCryptoKey","checkEncCryptoKey","webcrypto_default","invalid_key_input_default","types","wrap","unwrap","init_aeskw","__esmMin","init_bogus","init_webcrypto","init_crypto_key","init_invalid_key_input","init_is_key_like","cek","cryptoKey","cryptoKeyCek","bogus_default","encryptedKey","deriveKey","publicKey","privateKey","algorithm","keyLength","apu","apv","isCryptoKey","invalid_key_input_default","types","checkEncCryptoKey","value","concat","lengthAndInput","encoder","uint32be","length","sharedSecret","webcrypto_default","concatKdf","generateEpk","key","ecdhAllowed","init_ecdhes","__esmMin","init_buffer_utils","init_webcrypto","init_crypto_key","init_invalid_key_input","init_is_key_like","checkP2s","p2s","JWEInvalid","init_check_p2s","__esmMin","init_errors","getCryptoKey","key","alg","webcrypto_default","isCryptoKey","checkEncCryptoKey","invalid_key_input_default","types","deriveKey","p2s","p2c","checkP2s","salt","keylen","subtleAlg","wrapAlg","cryptoKey","encrypt","decrypt","init_pbes2kw","__esmMin","init_random","init_buffer_utils","init_base64url","init_aeskw","init_check_p2s","init_webcrypto","init_crypto_key","init_invalid_key_input","init_is_key_like","cek","random_default","derived","wrap","encode","encryptedKey","unwrap","subtleRsaEs","alg","JOSENotSupported","init_subtle_rsaes","__esmMin","init_errors","check_key_length_default","init_check_key_length","__esmMin","alg","key","modulusLength","encrypt","decrypt","init_rsaes","__esmMin","init_subtle_rsaes","init_bogus","init_webcrypto","init_crypto_key","init_check_key_length","init_invalid_key_input","init_is_key_like","alg","key","cek","isCryptoKey","invalid_key_input_default","types","checkEncCryptoKey","check_key_length_default","webcrypto_default","subtleRsaEs","cryptoKeyCek","bogus_default","encryptedKey","isJWK","key","isObject","isPrivateJWK","isPublicJWK","isSecretJWK","init_is_jwk","__esmMin","init_is_object","subtleMapping","jwk","algorithm","keyUsages","JOSENotSupported","parse","jwk_to_key_default","init_jwk_to_key","__esmMin","init_webcrypto","init_errors","rest","keyData","webcrypto_default","exportKeyValue","privCache","pubCache","isKeyObject","importAndCache","normalizePublicKey","normalizePrivateKey","normalize_key_default","init_normalize_key","__esmMin","init_is_jwk","init_base64url","init_jwk_to_key","k","decode","key","cache","jwk","alg","freeze","cached","cryptoKey","jwk_to_key_default","isJWK","bitLength","alg","JOSENotSupported","cek_default","init_cek","__esmMin","init_errors","init_random","random_default","format_pem_default","init_format_pem","__esmMin","b64","descriptor","newlined","getElement","seq","result","next","nextPart","parseElement","bytes","position","tag","length","byteLength","numberOfDigits","spkiFromX509","buf","tbsCertificate","encodeBase64","getSPKI","x509","pem","raw","decodeBase64","format_pem_default","genericExport","toSPKI","toPKCS8","findOid","getNamedCurve","genericImport","fromPKCS8","fromSPKI","fromX509","init_asn1","__esmMin","init_webcrypto","init_invalid_key_input","init_base64url","init_format_pem","init_errors","init_is_key_like","keyType","keyFormat","key","isCryptoKey","invalid_key_input_default","types","webcrypto_default","keyData","oid","from","i","sub","value","index","JOSENotSupported","replace","alg","options","algorithm","keyUsages","c","isPublic","namedCurve","spki","cause","importSPKI","spki","alg","options","fromSPKI","importX509","x509","fromX509","importPKCS8","pkcs8","fromPKCS8","importJWK","jwk","isObject","decode","JOSENotSupported","jwk_to_key_default","init_import","__esmMin","init_base64url","init_asn1","init_jwk_to_key","init_errors","init_is_object","checkKeyType","allowJwk","alg","key","usage","symmetricTypeCheck","asymmetricTypeCheck","tag","jwkMatchesOp","check_key_type_default","checkKeyTypeWithJwk","init_check_key_type","__esmMin","init_invalid_key_input","init_is_key_like","init_is_jwk","isJWK","isSecretJWK","is_key_like_default","withAlg","types","isPrivateJWK","isPublicJWK","cbcEncrypt","enc","plaintext","cek","iv","aad","invalid_key_input_default","keySize","encKey","webcrypto_default","macKey","ciphertext","macData","concat","uint64be","tag","gcmEncrypt","checkEncCryptoKey","encrypted","encrypt","encrypt_default","init_encrypt","__esmMin","init_buffer_utils","init_check_iv_length","init_check_cek_length","init_webcrypto","init_crypto_key","init_invalid_key_input","init_iv","init_errors","init_is_key_like","isCryptoKey","types","check_iv_length_default","iv_default","check_cek_length_default","JOSENotSupported","wrap","alg","key","cek","iv","jweAlgorithm","wrapped","encrypt_default","encode","unwrap","encryptedKey","tag","decrypt_default","init_aesgcmkw","__esmMin","init_encrypt","init_decrypt","init_base64url","decryptKeyManagement","alg","key","encryptedKey","joseHeader","options","check_key_type_default","normalize_key_default","JWEInvalid","isObject","ecdhAllowed","JOSENotSupported","epk","importJWK","partyUInfo","partyVInfo","decode","sharedSecret","deriveKey","bitLength","unwrap","decrypt","p2cLimit","p2s","iv","tag","decrypt_key_management_default","init_decrypt_key_management","__esmMin","init_aeskw","init_ecdhes","init_pbes2kw","init_rsaes","init_base64url","init_normalize_key","init_errors","init_cek","init_import","init_check_key_type","init_is_object","init_aesgcmkw","validateCrit","Err","recognizedDefault","recognizedOption","protectedHeader","joseHeader","input","recognized","parameter","JOSENotSupported","validate_crit_default","init_validate_crit","__esmMin","init_errors","validateAlgorithms","validate_algorithms_default","init_validate_algorithms","__esmMin","option","algorithms","s","flattenedDecrypt","jwe","key","options","isObject","JWEInvalid","parsedProt","protectedHeader","decode","decoder","is_disjoint_default","joseHeader","validate_crit_default","JOSENotSupported","alg","enc","keyManagementAlgorithms","validate_algorithms_default","contentEncryptionAlgorithms","JOSEAlgNotAllowed","encryptedKey","resolvedKey","cek","decrypt_key_management_default","err","cek_default","iv","tag","encoder","additionalData","concat","ciphertext","result","decrypt_default","init_decrypt","__esmMin","init_base64url","init_errors","init_is_disjoint","init_is_object","init_decrypt_key_management","init_buffer_utils","init_cek","init_validate_crit","init_validate_algorithms","compactDecrypt","jwe","key","options","decoder","JWEInvalid","protectedHeader","encryptedKey","iv","ciphertext","tag","length","decrypted","flattenedDecrypt","result","init_decrypt","__esmMin","init_errors","init_buffer_utils","generalDecrypt","jwe","key","options","isObject","JWEInvalid","recipient","flattenedDecrypt","JWEDecryptionFailed","init_decrypt","__esmMin","init_errors","init_is_object","unprotected","init_private_symbols","__esmMin","keyToJWK","key_to_jwk_default","init_key_to_jwk","__esmMin","init_webcrypto","init_invalid_key_input","init_base64url","init_is_key_like","key","encode","isCryptoKey","invalid_key_input_default","types","ext","key_ops","alg","use","jwk","webcrypto_default","exportSPKI","key","toSPKI","exportPKCS8","toPKCS8","exportJWK","key_to_jwk_default","init_export","__esmMin","init_asn1","init_key_to_jwk","encryptKeyManagement","alg","enc","key","providedCek","providedParameters","encryptedKey","parameters","cek","check_key_type_default","normalize_key_default","ecdhAllowed","JOSENotSupported","apu","apv","ephemeralKey","generateEpk","x","y","crv","kty","exportJWK","sharedSecret","deriveKey","bitLength","encode","cek_default","kwAlg","wrap","encrypt","p2c","p2s","iv","encrypt_key_management_default","init_encrypt_key_management","__esmMin","init_aeskw","init_ecdhes","init_pbes2kw","init_rsaes","init_base64url","init_normalize_key","init_cek","init_errors","init_export","init_check_key_type","init_aesgcmkw","FlattenedEncrypt","init_encrypt","__esmMin","init_base64url","init_private_symbols","init_encrypt_key_management","init_errors","init_is_disjoint","init_buffer_utils","init_validate_crit","plaintext","parameters","protectedHeader","sharedUnprotectedHeader","unprotectedHeader","aad","cek","iv","key","options","JWEInvalid","is_disjoint_default","joseHeader","validate_crit_default","JOSENotSupported","alg","enc","encryptedKey","encrypt_key_management_default","unprotected","additionalData","aadMember","encoder","encode","concat","ciphertext","tag","encrypt_default","jwe","decoder","IndividualRecipient","GeneralEncrypt","init_encrypt","__esmMin","init_private_symbols","init_errors","init_cek","init_is_disjoint","init_encrypt_key_management","init_base64url","init_validate_crit","enc","key","options","unprotectedHeader","args","plaintext","recipient","protectedHeader","sharedUnprotectedHeader","aad","JWEInvalid","flattened","FlattenedEncrypt","jwe","i","is_disjoint_default","joseHeader","alg","validate_crit_default","JOSENotSupported","cek","cek_default","target","p2c","unprotected","encryptedKey","parameters","encrypt_key_management_default","encode","subtleDsa","alg","algorithm","hash","JOSENotSupported","init_subtle_dsa","__esmMin","init_errors","getCryptoKey","alg","key","usage","normalize_key_default","isCryptoKey","checkSigCryptoKey","invalid_key_input_default","types","webcrypto_default","init_get_sign_verify_key","__esmMin","init_webcrypto","init_crypto_key","init_invalid_key_input","init_is_key_like","init_normalize_key","verify","verify_default","init_verify","__esmMin","init_subtle_dsa","init_webcrypto","init_check_key_length","init_get_sign_verify_key","alg","key","signature","data","cryptoKey","getCryptoKey","check_key_length_default","algorithm","subtleDsa","webcrypto_default","flattenedVerify","jws","key","options","isObject","JWSInvalid","parsedProt","protectedHeader","decode","decoder","is_disjoint_default","joseHeader","extensions","validate_crit_default","b64","alg","algorithms","validate_algorithms_default","JOSEAlgNotAllowed","resolvedKey","checkKeyTypeWithJwk","isJWK","importJWK","data","concat","encoder","signature","verify_default","JWSSignatureVerificationFailed","payload","result","init_verify","__esmMin","init_base64url","init_errors","init_buffer_utils","init_is_disjoint","init_is_object","init_check_key_type","init_validate_crit","init_validate_algorithms","init_is_jwk","init_import","compactVerify","jws","key","options","decoder","JWSInvalid","protectedHeader","payload","signature","length","verified","flattenedVerify","result","init_verify","__esmMin","init_errors","init_buffer_utils","generalVerify","jws","key","options","isObject","JWSInvalid","signature","flattenedVerify","JWSSignatureVerificationFailed","init_verify","__esmMin","init_errors","init_is_object","epoch_default","init_epoch","__esmMin","date","REGEX","secs_default","init_secs","__esmMin","str","matched","value","unit","numericDate","normalizeTyp","checkAudiencePresence","jwt_claims_set_default","init_jwt_claims_set","__esmMin","init_errors","init_buffer_utils","init_epoch","init_secs","init_is_object","value","audPayload","audOption","protectedHeader","encodedPayload","options","payload","decoder","isObject","JWTInvalid","typ","JWTClaimValidationFailed","requiredClaims","issuer","subject","audience","maxTokenAge","presenceCheck","claim","tolerance","secs_default","currentDate","now","epoch_default","JWTExpired","age","max","jwtVerify","jwt","key","options","verified","compactVerify","JWTInvalid","result","jwt_claims_set_default","init_verify","__esmMin","init_jwt_claims_set","init_errors","jwtDecrypt","jwt","key","options","decrypted","compactDecrypt","payload","jwt_claims_set_default","protectedHeader","JWTClaimValidationFailed","result","init_decrypt","__esmMin","init_jwt_claims_set","init_errors","CompactEncrypt","init_encrypt","__esmMin","plaintext","FlattenedEncrypt","cek","iv","protectedHeader","parameters","key","options","jwe","sign","sign_default","init_sign","__esmMin","init_subtle_dsa","init_webcrypto","init_check_key_length","init_get_sign_verify_key","alg","key","data","cryptoKey","getCryptoKey","check_key_length_default","signature","webcrypto_default","subtleDsa","FlattenedSign","init_sign","__esmMin","init_base64url","init_is_disjoint","init_errors","init_buffer_utils","init_check_key_type","init_validate_crit","payload","protectedHeader","unprotectedHeader","key","options","JWSInvalid","is_disjoint_default","joseHeader","extensions","validate_crit_default","b64","alg","checkKeyTypeWithJwk","encoder","encode","data","concat","signature","sign_default","jws","decoder","CompactSign","init_sign","__esmMin","payload","FlattenedSign","protectedHeader","key","options","jws","IndividualSignature","GeneralSign","init_sign","__esmMin","init_errors","sig","key","options","protectedHeader","unprotectedHeader","args","payload","signature","JWSInvalid","jws","i","flattened","FlattenedSign","rest","validateInput","label","input","ProduceJWT","init_produce","__esmMin","init_epoch","init_is_object","init_secs","payload","isObject","issuer","subject","audience","jwtId","epoch_default","secs_default","SignJWT","init_sign","__esmMin","init_errors","init_buffer_utils","init_produce","ProduceJWT","protectedHeader","key","options","sig","CompactSign","encoder","JWTInvalid","EncryptJWT","init_encrypt","__esmMin","init_buffer_utils","init_produce","ProduceJWT","protectedHeader","parameters","cek","iv","key","options","enc","CompactEncrypt","encoder","calculateJwkThumbprint","jwk","digestAlgorithm","isObject","components","check","JOSENotSupported","data","encoder","encode","digest_default","calculateJwkThumbprintUri","thumbprint","init_thumbprint","__esmMin","init_digest","init_base64url","init_errors","init_buffer_utils","init_is_object","value","description","JWKInvalid","EmbeddedJWK","protectedHeader","token","joseHeader","isObject","JWSInvalid","key","importJWK","init_embedded","__esmMin","init_import","init_is_object","init_errors","getKtyFromAlg","alg","JOSENotSupported","isJWKSLike","jwks","isJWKLike","key","isObject","clone","obj","importWithAlgCache","cache","jwk","cached","importJWK","JWKSInvalid","createLocalJWKSet","set","LocalJWKSet","localJWKSet","protectedHeader","token","init_local","__esmMin","init_import","init_errors","init_is_object","kid","kty","candidates","candidate","length","JWKSNoMatchingKey","error","JWKSMultipleMatchingKeys","_cached","fetchJwks","fetch_jwks_default","init_fetch_jwks","__esmMin","init_errors","url","timeout","options","controller","id","timedOut","response","err","JWKSTimeout","JOSEError","isCloudflareWorkers","isFreshJwksCache","input","cacheMaxAge","isObject","createRemoteJWKSet","url","options","set","RemoteJWKSet","remoteJWKSet","protectedHeader","token","USER_AGENT","jwksCache","experimental_jwksCache","init_remote","__esmMin","init_fetch_jwks","init_errors","init_local","init_is_object","createLocalJWKSet","err","JWKSNoMatchingKey","headers","fetch_jwks_default","json","UnsecuredJWT","init_unsecured","__esmMin","init_base64url","init_buffer_utils","init_errors","init_jwt_claims_set","init_produce","ProduceJWT","header","encode","payload","jwt","options","JWTInvalid","encodedHeader","encodedPayload","signature","length","decoder","decode","jwt_claims_set_default","base64url_exports","__export","decode","encode","init_base64url","__esmMin","decodeProtectedHeader","token","protectedB64u","parts","result","decoder","decode","isObject","init_decode_protected_header","__esmMin","init_base64url","init_buffer_utils","init_is_object","decodeJwt","jwt","JWTInvalid","payload","length","decoded","decode","result","decoder","isObject","init_decode_jwt","__esmMin","init_base64url","init_buffer_utils","init_is_object","init_errors","generateSecret","alg","options","length","algorithm","keyUsages","random_default","JOSENotSupported","webcrypto_default","getModulusLengthOption","modulusLength","generateKeyPair","crv","init_generate","__esmMin","init_webcrypto","init_errors","init_random","generateKeyPair","alg","options","init_generate_key_pair","__esmMin","init_generate","generateSecret","alg","options","init_generate_secret","__esmMin","init_generate","runtime_default","init_runtime","__esmMin","runtime_default","init_runtime","__esmMin","browser_exports","__export","CompactEncrypt","CompactSign","EmbeddedJWK","EncryptJWT","FlattenedEncrypt","FlattenedSign","GeneralEncrypt","GeneralSign","SignJWT","UnsecuredJWT","base64url_exports","calculateJwkThumbprint","calculateJwkThumbprintUri","compactDecrypt","compactVerify","createLocalJWKSet","createRemoteJWKSet","runtime_default","decodeJwt","decodeProtectedHeader","errors_exports","experimental_jwksCache","exportJWK","exportPKCS8","exportSPKI","flattenedDecrypt","flattenedVerify","generalDecrypt","generalVerify","generateKeyPair","generateSecret","importJWK","importPKCS8","importSPKI","importX509","jwksCache","jwtDecrypt","jwtVerify","init_browser","__esmMin","init_decrypt","init_encrypt","init_verify","init_sign","init_thumbprint","init_embedded","init_local","init_remote","init_unsecured","init_export","init_import","init_decode_protected_header","init_decode_jwt","init_errors","init_generate_key_pair","init_generate_secret","init_base64url","init_runtime","require_verify_vercel_oidc_token","__commonJSMin","exports","module","__defProp","__getOwnPropDesc","__getOwnPropNames","__hasOwnProp","__export","target","all","name","__copyProps","to","from","except","desc","key","__toCommonJS","mod","verify_vercel_oidc_token_exports","verifyVercelOidcToken","import_jose","VERCEL_OIDC_ISSUER","VERCEL_OIDC_JWKS_URL","DEFAULT_ALGORITHMS","VERCEL_OIDC_JWKS","token","options","algorithms","projectId","environment","ownerId","verifyOptions","hasAudienceVerification","result","validateIssuer","validateClaim","validateOptionalClaim","audience","actual","claim","env","expected","option","value","require_auth_errors","__commonJSMin","exports","module","__defProp","__getOwnPropDesc","__getOwnPropNames","__hasOwnProp","__export","target","all","name","__copyProps","to","from","except","desc","key","__toCommonJS","mod","auth_errors_exports","AccessTokenMissingError","RefreshAccessTokenFailedError","cause","require_index_browser","__commonJSMin","exports","module","__defProp","__getOwnPropDesc","__getOwnPropNames","__hasOwnProp","__export","target","all","name","__copyProps","to","from","except","desc","key","__toCommonJS","mod","index_browser_exports","import_auth_errors","import_get_context","getVercelOidcToken","getVercelOidcTokenSync","getVercelToken","import_verify_vercel_oidc_token","require_retry_operation","__commonJSMin","exports","module","RetryOperation","timeouts","options","err","currentTime","timeout","self","fn","timeoutOps","counts","mainError","mainErrorCount","i","error","message","count","require_retry","__commonJSMin","exports","RetryOperation","options","timeouts","opts","key","i","b","attempt","random","timeout","obj","methods","method","original","op","args","callback","err","require_retry","__commonJSMin","exports","module","require_lib","__commonJSMin","exports","module","retrier","retry","fn","opts","run","resolve","reject","options","op","bail","err","onError","num","runAttempt","val","require_throttleit","__commonJSMin","exports","module","throttle","function_","wait","timeoutId","lastCallTime","arguments_","now","timeSinceLastCall","delayForNextCall","isNodeProcess","type","import_is_buffer","Readable","import_oidc","import_async_retry","fetch","import_throttleit","supportsNewBlobFromArrayBuffer","resolve","helloAsArrayBuffer","text","toReadableStream","value","isNodeJsReadableStream","Readable","streamValue","isNodeJsBuffer","stringToUint8Array","controller","s","isBuffer","getVercelOidcToken","token","getVercelOidcTokenWithRefresh","parseRegExp","map","bytes","val","results","floatValue","unit","res","unitMatch","defaultVercelBlobApiUrl","readEnv","name","parseStoreIdFromReadWriteToken","storeId","base64UrlDecodeDelegationSegment","segment","base64","padding","BlobError","parseStoreIdFromDelegationToken","delegationToken","dot","payloadSeg","parsed","normalizeStoreId","normalizeStoreId","storeId","resolveBlobAuth","options","_a","_b","parseStoreIdFromDelegationToken","parseStoreIdFromReadWriteToken","manualOidcToken","oidcToken","getVercelOidcToken","manualStoreId","blobStoreId","readEnv","BlobError","readWrite","BlobError","message","isPlainObject","value","prototype","disallowedPathnameCharacters","supportsRequestStreams","isNodeProcess","getApiUrl","duplexAccessed","hasContentType","pathname","baseUrl","defaultVercelBlobApiUrl","TEXT_ENCODER","computeBodyLength","body","createChunkTransformStream","chunkSize","onProgress","buffer","chunk","controller","newBuffer","newChunk","isReadableStream","isStream","isNodeJsReadableStream","addPresignedParams","url","presignedUrlPayload","urlObj","key","debugIsActive","_a","_b","debug","message","args","DOMException","err","objectToString","isError","value","errorMessages","isNetworkError","error","hasFetch","fetch","hasFetchWithUploadProgress","supportsRequestStreams","CHUNK_SIZE","blobFetch","input","init","onUploadProgress","body","stream","toReadableStream","loaded","chunkTransformStream","createChunkTransformStream","newLoaded","duplex","isStream","hasXhr","blobXhr","isReadableStream","resolve","reject","xhr","event","headers","line","parts","key","response","blobRequest","MAXIMUM_PATHNAME_LENGTH","BlobAccessError","BlobError","BlobOidcEnvironmentNotAllowedError","BlobContentTypeNotAllowedError","BlobPathnameMismatchError","BlobClientTokenExpiredError","BlobFileTooLargeError","BlobStoreNotFoundError","BlobStoreSuspendedError","BlobUnknownError","BlobNotFoundError","BlobServiceNotAvailable","BlobServiceRateLimited","seconds","BlobRequestAbortedError","BlobPreconditionFailedError","BLOB_API_VERSION","getApiVersion","versionOverride","getRetries","retries","createBlobServiceRateLimited","retryAfter","getBlobError","_c","code","data","requestApi","pathname","commandOptions","apiVersion","auth","resolveBlobAuth","bearerToken","extraHeaders","getProxyThroughAlternativeApiHeaderFromEnv","requestInput","getApiUrl","addPresignedParams","requestId","retryCount","bodyLength","totalLoaded","sendBodyLength","shouldUseXContentLength","computeBodyLength","apiResponse","retry","bail","res","total","percentage","optimizeImageFormatToMimeType","validateOptimizeImageOptions","optimizeImage","width","quality","format","validateOptimizeImageSourceContentType","contentType","addOptimizeImageParams","params","putOptionHeaderMap","createPutHeaders","allowedOptions","options","createPutOptions","extraChecks","getToken","invalidCharacter","disallowedPathnameCharacters","createCompleteMultipartUploadMethod","optionsInput","completeMultipartUpload","uploadId","createCreateMultipartUploadMethod","createMultipartUploadResponse","createMultipartUpload","createUploadPartMethod","isPlainObject","uploadPart","internalAbortController","part","responsePromise","handleAbort","maxConcurrentUploads","partSizeInBytes","maxBytesInMemory","uploadAllParts","totalToLoad","partsToUpload","completedParts","reader","activeUploads","reading","currentPartNumber","rejected","currentBytesInMemory","doneReading","bytesSent","arrayBuffers","currentPartBytesRead","totalLoadedPerPartNumber","throttle","acc","cur","read","cancel","bytes","done","sendParts","valueOffset","remainingPartSize","endOffset","chunk","sendPart","uploadProgressForPart","completedPart","partToSend","createCreateMultipartUploaderMethod","partNumber","uncontrolledMultipartUpload","optionsWithoutOnUploadProgress","createPutMethod","getPresignedUrlPayload","presignedUrlPayload","optionsWithPresignedUrlPayload","MAX_PRESIGN_CACHE_CONTROL_MAX_AGE_SECONDS","utf8Encoder","createPutExtraChecks","methodName","options","BlobError","put","createPutMethod","createMultipartUpload","createCreateMultipartUploadMethod","createMultipartUploader","createCreateMultipartUploaderMethod","uploadPart","createUploadPartMethod","completeMultipartUpload","createCompleteMultipartUploadMethod","upload","pathname","_a","_b","retrieveClientToken","uploadPresigned","retrievePresignedUrlPayload","EventTypes","retrieveClientToken","options","handleUploadUrl","pathname","url","isAbsoluteUrl","toAbsoluteUrl","event","EventTypes","res","fetch","BlobError","clientToken","retrievePresignedUrlPayload","presignedUrlPayload","error","LINE_ITEM_UPLOAD_ENDPOINT","MAX_LINE_ITEM_UPLOAD_BYTES","TYPE_BY_EXTENSION","ACCEPTED_LINE_ITEM_UPLOAD_TYPES","LineItemUploadError","message","status","__publicField","contentTypeOf","file","isTokenResponse","value","errorMessageOf","uploadLineItemFile","options","contentType","response","body","put","lineItemFileProperty","key","label","uploadId"]}
1
+ {"version":3,"sources":["../src/uploads.ts"],"sourcesContent":["import { put } from \"@vercel/blob/client\";\n\n/**\n * Shopper file uploads for personalised products (a photo for a portrait, a print-ready PDF).\n *\n * Browser-only. The storefront calls `uploadLineItemFile(file, { variantId })` from its product\n * page; the platform hands out a short-lived token for exactly one file (its `/checkout/api/**`\n * endpoint is already forwarded by every tenant's proxy, so the storefront needs no route of its\n * own and no API key in the browser), and the file goes straight into the store's private storage.\n * The returned `uploadId` is what a cart line's file property carries:\n *\n * ```ts\n * const { uploadId } = await uploadLineItemFile(file, { variantId });\n * await cartUpsert({ variantId, quantity: 1, properties: [lineItemFileProperty({ key: \"photo\", label: \"Photo\", uploadId })] });\n * ```\n *\n * Requires the store's Customer Uploads module. Images (JPEG, PNG, WebP, GIF, HEIC/HEIF, AVIF,\n * TIFF) and PDF, up to 20 MB.\n */\n\nexport const LINE_ITEM_UPLOAD_ENDPOINT = \"/checkout/api/line-item-uploads\";\nexport const MAX_LINE_ITEM_UPLOAD_BYTES = 20 * 1024 * 1024;\n\n/** Some browsers report HEIC/HEIF (and the occasional other image) with an empty type. */\nconst TYPE_BY_EXTENSION: Record<string, string> = {\n\tjpg: \"image/jpeg\",\n\tjpeg: \"image/jpeg\",\n\tpng: \"image/png\",\n\twebp: \"image/webp\",\n\tgif: \"image/gif\",\n\theic: \"image/heic\",\n\theif: \"image/heif\",\n\tavif: \"image/avif\",\n\ttif: \"image/tiff\",\n\ttiff: \"image/tiff\",\n\tpdf: \"application/pdf\",\n};\n\nexport const ACCEPTED_LINE_ITEM_UPLOAD_TYPES = [...new Set(Object.values(TYPE_BY_EXTENSION))].join(\",\");\n\nexport class LineItemUploadError extends Error {\n\treadonly status: number;\n\tconstructor(message: string, status: number) {\n\t\tsuper(message);\n\t\tthis.name = \"LineItemUploadError\";\n\t\tthis.status = status;\n\t}\n}\n\nconst contentTypeOf = (file: File): string =>\n\tfile.type || TYPE_BY_EXTENSION[file.name.split(\".\").pop()?.toLowerCase() ?? \"\"] || \"\";\n\nconst isTokenResponse = (\n\tvalue: unknown,\n): value is { uploadId: string; pathname: string; clientToken: string } =>\n\ttypeof value === \"object\" &&\n\tvalue !== null &&\n\t\"uploadId\" in value &&\n\ttypeof value.uploadId === \"string\" &&\n\t\"pathname\" in value &&\n\ttypeof value.pathname === \"string\" &&\n\t\"clientToken\" in value &&\n\ttypeof value.clientToken === \"string\";\n\nconst errorMessageOf = (value: unknown): string | null =>\n\ttypeof value === \"object\" && value !== null && \"error\" in value && typeof value.error === \"string\"\n\t\t? value.error\n\t\t: null;\n\n/**\n * Upload one file for a cart line. Throws `LineItemUploadError` with the platform's message and\n * HTTP status (400 unsupported file, 404 uploads off for this store, 429 too many uploads).\n */\nexport async function uploadLineItemFile(\n\tfile: File,\n\toptions: {\n\t\tvariantId: string;\n\t\t/** Defaults to the platform endpoint every tenant proxy forwards. */\n\t\tendpoint?: string;\n\t\tonUploadProgress?: (event: { loaded: number; total: number; percentage: number }) => void;\n\t\tabortSignal?: AbortSignal;\n\t},\n): Promise<{ uploadId: string }> {\n\tconst contentType = contentTypeOf(file);\n\tif (!contentType) {\n\t\tthrow new LineItemUploadError(\"This file type can't be uploaded.\", 400);\n\t}\n\tif (file.size > MAX_LINE_ITEM_UPLOAD_BYTES) {\n\t\tthrow new LineItemUploadError(\"The file is larger than 20 MB.\", 400);\n\t}\n\n\tconst response = await fetch(options.endpoint ?? LINE_ITEM_UPLOAD_ENDPOINT, {\n\t\tmethod: \"POST\",\n\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\tcredentials: \"same-origin\",\n\t\tbody: JSON.stringify({ variantId: options.variantId, filename: file.name, contentType, size: file.size }),\n\t\t...(options.abortSignal ? { signal: options.abortSignal } : {}),\n\t});\n\tconst body: unknown = await response.json().catch(() => null);\n\tif (!response.ok || !isTokenResponse(body)) {\n\t\tthrow new LineItemUploadError(errorMessageOf(body) ?? \"The upload could not start.\", response.status);\n\t}\n\n\tawait put(body.pathname, file, {\n\t\taccess: \"private\",\n\t\ttoken: body.clientToken,\n\t\tcontentType,\n\t\tmultipart: file.size > 8 * 1024 * 1024,\n\t\t...(options.onUploadProgress ? { onUploadProgress: options.onUploadProgress } : {}),\n\t\t...(options.abortSignal ? { abortSignal: options.abortSignal } : {}),\n\t});\n\treturn { uploadId: body.uploadId };\n}\n\n/** The cart line property that attaches an uploaded file. */\nexport const lineItemFileProperty = ({\n\tkey,\n\tlabel,\n\tuploadId,\n}: {\n\tkey: string;\n\tlabel?: string;\n\tuploadId: string;\n}): { key: string; label?: string; type: \"file\"; value: string } => ({\n\tkey,\n\t...(label !== undefined ? { label } : {}),\n\ttype: \"file\",\n\tvalue: uploadId,\n});\n"],"mappings":";;;;;AAAA,SAAS,WAAW;AAoBb,IAAM,4BAA4B;AAClC,IAAM,6BAA6B,KAAK,OAAO;AAGtD,IAAM,oBAA4C;AAAA,EACjD,KAAK;AAAA,EACL,MAAM;AAAA,EACN,KAAK;AAAA,EACL,MAAM;AAAA,EACN,KAAK;AAAA,EACL,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,KAAK;AAAA,EACL,MAAM;AAAA,EACN,KAAK;AACN;AAEO,IAAM,kCAAkC,CAAC,GAAG,IAAI,IAAI,OAAO,OAAO,iBAAiB,CAAC,CAAC,EAAE,KAAK,GAAG;AAE/F,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAE9C,YAAY,SAAiB,QAAgB;AAC5C,UAAM,OAAO;AAFd,wBAAS;AAGR,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EACf;AACD;AAEA,IAAM,gBAAgB,CAAC,SACtB,KAAK,QAAQ,kBAAkB,KAAK,KAAK,MAAM,GAAG,EAAE,IAAI,GAAG,YAAY,KAAK,EAAE,KAAK;AAEpF,IAAM,kBAAkB,CACvB,UAEA,OAAO,UAAU,YACjB,UAAU,QACV,cAAc,SACd,OAAO,MAAM,aAAa,YAC1B,cAAc,SACd,OAAO,MAAM,aAAa,YAC1B,iBAAiB,SACjB,OAAO,MAAM,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