@vercel/blob 2.0.0 → 2.1.0-062a059-20260128141057
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-KLNTTDLT.cjs → chunk-7TB5OCQA.cjs} +96 -99
- package/dist/chunk-7TB5OCQA.cjs.map +1 -0
- package/dist/{chunk-Z56QURM6.js → chunk-IMAXVSQW.js} +91 -94
- package/dist/chunk-IMAXVSQW.js.map +1 -0
- package/dist/client.cjs +25 -24
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +11 -9
- package/dist/client.d.ts +11 -9
- package/dist/client.js +4 -3
- package/dist/client.js.map +1 -1
- package/dist/{create-folder-C02EFEPE.d.cts → create-folder-BvLlL5az.d.cts} +11 -3
- package/dist/{create-folder-C02EFEPE.d.ts → create-folder-BvLlL5az.d.ts} +11 -3
- package/dist/index.cjs +106 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +72 -8
- package/dist/index.d.ts +72 -8
- package/dist/index.js +90 -3
- package/dist/index.js.map +1 -1
- package/package.json +11 -14
- package/dist/chunk-KLNTTDLT.cjs.map +0 -1
- package/dist/chunk-Z56QURM6.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/helpers.ts","../src/multipart/helpers.ts","../src/bytes.ts","../src/api.ts","../src/is-network-error.ts","../src/debug.ts","../src/fetch.ts","../src/xhr.ts","../src/request.ts","../src/dom-exception.ts","../src/put-helpers.ts","../src/multipart/complete.ts","../src/multipart/create.ts","../src/multipart/upload.ts","../src/put.ts","../src/multipart/uncontrolled.ts","../src/multipart/create-uploader.ts","../src/create-folder.ts"],"sourcesContent":["// 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 type { RequestInit, Response } from 'undici';\nimport { isNodeProcess } from 'is-node-process';\nimport { isNodeJsReadableStream } from './multipart/helpers';\nimport type { PutBody } from './put-helpers';\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 * @defaultvalue process.env.BLOB_READ_WRITE_TOKEN\n */\n token?: 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// shared interface for put, copy and multipart upload\nexport interface CommonCreateBlobOptions extends BlobCommandOptions {\n /**\n * Whether the blob should be publicly accessible. The only currently allowed value is `public`.\n */\n access: 'public';\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\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\nexport function getTokenFromOptionsOrEnv(options?: BlobCommandOptions): string {\n if (options?.token) {\n return options.token;\n }\n\n if (process.env.BLOB_READ_WRITE_TOKEN) {\n return process.env.BLOB_READ_WRITE_TOKEN;\n }\n\n throw new BlobError(\n 'No 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 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment -- ok\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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- could be false\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 queueMicrotask(() => {\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\n flush(controller) {\n queueMicrotask(() => {\n // Send any remaining data\n if (buffer.length > 0) {\n controller.enqueue(buffer);\n onProgress?.(buffer.byteLength);\n }\n });\n },\n });\n};\n\nexport function isReadableStream(value: PutBody): value is ReadableStream {\n return (\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Not present in Node.js 16\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","// eslint-disable-next-line unicorn/prefer-node-protocol -- node:stream does not resolve correctly in browser and edge\nimport { Readable } from 'stream';\n// eslint-disable-next-line unicorn/prefer-node-protocol -- node:buffer does not resolve correctly in browser and edge\nimport type { Buffer } from 'buffer';\nimport isBuffer from 'is-buffer';\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 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","/*!\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\n// eslint-disable-next-line prefer-named-capture-group -- fine\nconst parseRegExp = /^((-|\\+)?(\\d+(?:\\.\\d+)?)) *(kb|mb|gb|tb|pb)$/i;\n\nconst map: ByteUnitMap = {\n b: 1,\n // eslint-disable-next-line no-bitwise -- fine\n kb: 1 << 10,\n // eslint-disable-next-line no-bitwise -- fine\n mb: 1 << 20,\n // eslint-disable-next-line no-bitwise -- fine\n gb: 1 << 30,\n tb: Math.pow(1024, 4),\n pb: Math.pow(1024, 5),\n};\n\nexport function bytes(val: string | number): number | null {\n if (typeof val === '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 (isNaN(floatValue)) {\n return null;\n }\n\n return Math.floor(map[unit] * floatValue);\n}\n","import type { Response } from 'undici';\nimport retry from 'async-retry';\nimport isNetworkError from './is-network-error';\nimport { debug } from './debug';\nimport type {\n BlobCommandOptions,\n BlobRequestInit,\n WithUploadProgress,\n} from './helpers';\nimport {\n BlobError,\n computeBodyLength,\n getApiUrl,\n getTokenFromOptionsOrEnv,\n} from './helpers';\nimport { blobRequest } from './request';\nimport { DOMException } from './dom-exception';\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 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\ntype BlobApiErrorCodes =\n | 'store_suspended'\n | 'forbidden'\n | 'not_found'\n | 'unknown_error'\n | 'bad_request'\n | 'store_not_found'\n | '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\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 = 11;\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\nasync 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 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 'content_type_not_allowed':\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TS, be smarter\n error = new BlobContentTypeNotAllowedError(message!);\n break;\n case 'client_token_pathname_mismatch':\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TS, be smarter\n error = new BlobPathnameMismatchError(message!);\n break;\n case 'client_token_expired':\n error = new BlobClientTokenExpiredError();\n break;\n case 'file_too_large':\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- TS, be smarter\n error = new BlobFileTooLargeError(message!);\n break;\n case 'not_found':\n error = new BlobNotFoundError();\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 '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: (BlobCommandOptions & WithUploadProgress) | undefined,\n): Promise<TResponse> {\n const apiVersion = getApiVersion();\n const token = getTokenFromOptionsOrEnv(commandOptions);\n const extraHeaders = getProxyThroughAlternativeApiHeaderFromEnv();\n\n const [, , , storeId = ''] = token.split('_');\n const requestId = `${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: getApiUrl(pathname),\n init: {\n ...init,\n headers: {\n 'x-api-blob-request-id': requestId,\n 'x-api-blob-request-attempt': String(retryCount),\n 'x-api-version': apiVersion,\n ...(sendBodyLength\n ? { 'x-content-length': String(bodyLength) }\n : {}),\n authorization: `Bearer ${token}`,\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","/* eslint-disable -- This file is copy pasted*/\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","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 (error) {\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 // eslint-disable-next-line no-console -- Ok for debugging\n console.debug(`vercel-blob: ${message}`, ...args);\n }\n}\n","import type { BodyInit } from 'undici';\nimport { fetch } from 'undici';\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';\nimport { debug } from './debug';\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 { isReadableStream, type BlobRequest } from './helpers';\nimport { debug } from './debug';\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 { hasXhr, blobXhr } from './xhr';\nimport type { BlobRequest } from './helpers';\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","// TODO: Once Node 16 is no more needed internally, we can remove this file and use the native DOMException type.\n/* eslint-disable -- fine */\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","// eslint-disable-next-line unicorn/prefer-node-protocol -- node:stream does not resolve correctly in browser and edge\nimport 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 type { ClientCommonCreateBlobOptions } from './client';\nimport type { CommonCreateBlobOptions } from './helpers';\nimport { BlobError, disallowedPathnameCharacters } from './helpers';\nimport { MAXIMUM_PATHNAME_LENGTH } from './api';\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};\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\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 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 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 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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Runtime check for DX.\n if (options.access !== 'public') {\n throw new BlobError('access must be \"public\"');\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, BlobCommandOptions } 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: BlobCommandOptions;\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 { BlobCommandOptions, 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: BlobCommandOptions,\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 { BlobError, isPlainObject, bytes } from '../helpers';\nimport type {\n WithUploadProgress,\n CommonCreateBlobOptions,\n BlobCommandOptions,\n} from '../helpers';\nimport { createPutHeaders, createPutOptions } from '../put-helpers';\nimport type { PutBody, CreatePutMethodOptions } 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: BlobCommandOptions & 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: BlobCommandOptions & 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 // eslint-disable-next-line no-await-in-loop -- A for loop is fine here.\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 }\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 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 PutBody,\n PutBlobApiResponse,\n PutBlobResult,\n} from './put-helpers';\nimport { createPutOptions, createPutHeaders } 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\nexport function createPutMethod<TOptions extends PutCommandOptions>({\n allowedOptions,\n getToken,\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 headers = createPutHeaders(allowedOptions, options);\n\n if (options.multipart === true) {\n return uncontrolledMultipartUpload(pathname, body, headers, options);\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 ...options,\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 };\n };\n}\n","import { debug } from '../debug';\nimport { computeBodyLength } from '../helpers';\nimport type { WithUploadProgress, BlobCommandOptions } from '../helpers';\nimport type { PutBody, PutBlobResult } 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: BlobCommandOptions & WithUploadProgress,\n): Promise<PutBlobResult> {\n debug('mpu: init', 'pathname:', pathname, 'headers:', headers);\n\n const optionsWithoutOnUploadProgress = {\n ...options,\n onUploadProgress: undefined,\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 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","import {\n BlobError,\n isPlainObject,\n type CommonCreateBlobOptions,\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 { requestApi } from './api';\nimport type { BlobCommandOptions } from './helpers';\nimport { putOptionHeaderMap, type PutBlobApiResponse } from './put-helpers';\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 like `token`\n */\nexport async function createFolder(\n pathname: string,\n options: BlobCommandOptions = {},\n): Promise<CreateFolderResult> {\n const folderPathname = pathname.endsWith('/') ? pathname : `${pathname}/`;\n\n const headers: Record<string, string> = {};\n\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"],"mappings":";AAKA,SAAS,qBAAqB;;;ACJ9B,SAAS,gBAAgB;AAGzB,OAAO,cAAc;AAsCrB,IAAM,iCAAiC,IAAI,QAAiB,CAAC,YAAY;AAEvE,MAAI;AACF,UAAM,qBAAqB,IAAI,WAAW,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AACnE,UAAM,OAAO,IAAI,KAAK,CAAC,kBAAkB,CAAC;AAC1C,SACG,KAAK,EACL,KAAK,CAAC,SAAS;AACd,cAAQ,SAAS,OAAO;AAAA,IAC1B,CAAC,EACA,MAAM,MAAM;AACX,cAAQ,KAAK;AAAA,IACf,CAAC;AAAA,EACL,QAAQ;AACN,YAAQ,KAAK;AAAA,EACf;AACF,CAAC;AAED,eAAsB,iBACpB,OACmD;AAEnD,MAAI,iBAAiB,gBAAgB;AACnC,WAAO;AAAA,EACT;AAKA,MAAI,iBAAiB,MAAM;AACzB,WAAO,MAAM,OAAO;AAAA,EACtB;AAEA,MAAI,uBAAuB,KAAK,GAAG;AACjC,WAAO,SAAS,MAAM,KAAK;AAAA,EAC7B;AAEA,MAAI;AAIJ,MAAI,iBAAiB,aAAa;AAChC,kBAAc,IAAI,WAAW,KAAK;AAAA,EACpC,WAAW,eA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