@vercel/blob 2.0.0 → 2.1.0-06d6754-20260122183144
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-4ACRCP3X.cjs} +95 -99
- package/dist/chunk-4ACRCP3X.cjs.map +1 -0
- package/dist/{chunk-Z56QURM6.js → chunk-XABT64U6.js} +90 -94
- package/dist/chunk-XABT64U6.js.map +1 -0
- package/dist/client.cjs +24 -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 +3 -3
- package/dist/client.js.map +1 -1
- package/dist/{create-folder-C02EFEPE.d.cts → create-folder-Dfl_PTiT.d.cts} +4 -2
- package/dist/{create-folder-C02EFEPE.d.ts → create-folder-Dfl_PTiT.d.ts} +4 -2
- package/dist/index.cjs +95 -19
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +60 -8
- package/dist/index.d.ts +60 -8
- package/dist/index.js +79 -3
- package/dist/index.js.map +1 -1
- package/package.json +3 -6
- package/dist/chunk-KLNTTDLT.cjs.map +0 -1
- package/dist/chunk-Z56QURM6.js.map +0 -1
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["// eslint-disable-next-line unicorn/prefer-node-protocol -- node:crypto does not resolve correctly in browser and edge runtime\nimport * as crypto from 'crypto';\nimport type { IncomingMessage } from 'node:http';\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 { BlobCommandOptions, WithUploadProgress } from './helpers';\nimport { BlobError, getTokenFromOptionsOrEnv } from './helpers';\nimport { createPutMethod } from './put';\nimport type { PutBlobResult } from './put-helpers';\nimport type { CommonCompleteMultipartUploadOptions } from './multipart/complete';\nimport { createCompleteMultipartUploadMethod } from './multipart/complete';\nimport { createCreateMultipartUploadMethod } from './multipart/create';\nimport { createUploadPartMethod } from './multipart/upload';\nimport type { CommonMultipartUploadOptions } from './multipart/upload';\nimport { createCreateMultipartUploaderMethod } from './multipart/create-uploader';\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 */\n access: 'public';\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' as blobs are publicly accessible.\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' as blobs are publicly accessible.\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' as blobs are publicly accessible.\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' as blobs are publicly accessible.\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' as blobs are publicly accessible.\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' as blobs are publicly accessible.\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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Runtime check for DX.\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.createPutExtraChecks !== undefined ||\n // @ts-expect-error -- Runtime check for DX.\n options.cacheControlMaxAge !== undefined\n ) {\n throw new BlobError(\n \"client/`upload` doesn't allow `addRandomSuffix`, `cacheControlMaxAge` or `allowOverwrite`. 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 * @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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Node.js < 20: globalThis.crypto is undefined (in a real script.js, because the REPL has it linked to the crypto module). Node.js >= 20, Browsers and Cloudflare workers: globalThis.crypto is defined and is the Web Crypto API.\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 * @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 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Node.js < 20: globalThis.crypto is undefined (in a real script.js, because the REPL has it linked to the crypto module). Node.js >= 20, Browsers and Cloudflare workers: globalThis.crypto is defined and is the Web Crypto API.\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 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 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\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 * 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 > & { 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 = getTokenFromOptionsOrEnv({ 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 // eslint-disable-next-line no-console -- Warning is important for developers to understand configuration issues\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 * @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 (e) {\n throw new BlobError('Failed to retrieve the client token');\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 (e) {\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 * @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 const timestamp = new Date();\n timestamp.setSeconds(timestamp.getSeconds() + 30);\n const readWriteToken = getTokenFromOptionsOrEnv({ token });\n\n const [, , , storeId = null] = readWriteToken.split('_');\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 extends BlobCommandOptions {\n /**\n * The destination path for the blob\n */\n pathname: string;\n\n /**\n * Configuration for upload completion callback\n */\n onUploadCompleted?: {\n callbackUrl: string;\n tokenPayload?: string | null;\n };\n\n /**\n * A number specifying the maximum size in bytes that can be uploaded. The maximum is 5TB.\n */\n maximumSizeInBytes?: number;\n\n /**\n * An array of strings specifying the media type that are allowed to be uploaded.\n * By default, it's all content types. Wildcards are supported (text/*)\n */\n allowedContentTypes?: string[];\n\n /**\n * A number specifying the timestamp in ms when the token will expire.\n * By default, it's now + 1 hour.\n */\n validUntil?: number;\n\n /**\n * Adds a random suffix to the filename.\n * @defaultvalue false\n */\n addRandomSuffix?: boolean;\n\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 /**\n * Number in seconds to configure how long Blobs are cached. Defaults to one month. Cannot be set to a value lower than 1 minute.\n * @defaultvalue 30 * 24 * 60 * 60 (1 Month)\n */\n cacheControlMaxAge?: number;\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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- request.url is guaranteed to be defined in web server context\n const reqPath = getPathFromRequestUrl(request.url!);\n\n if (!reqPath) {\n // eslint-disable-next-line no-console -- Warning is important for developers to understand configuration requirements\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 // eslint-disable-next-line no-console -- Warning is important for developers to understand configuration requirements\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"],"mappings":";;;;;;;;;;;;AACA,YAAY,YAAY;AAKxB,SAAS,aAAa;AA2DtB,SAAS,qBAEP,YAAoB;AACpB,SAAO,SAAS,YAAY,SAAmB;AAC7C,QAAI,CAAC,QAAQ,MAAM,WAAW,qBAAqB,GAAG;AACpD,YAAM,IAAI,UAAU,GAAG,UAAU,qCAAqC;AAAA,IACxE;AAEA;AAAA;AAAA,MAEE,QAAQ,oBAAoB;AAAA,MAE5B,QAAQ,mBAAmB;AAAA,MAE3B,QAAQ,uBAAuB;AAAA,MAC/B;AACA,YAAM,IAAI;AAAA,QACR,GAAG,UAAU;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACF;AAsBO,IAAM,MAAM,gBAAyC;AAAA,EAC1D,gBAA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2DA,SAAS,eAAe,SAA0C;AAEhE,QAAM,UAAU,sBAAsB,QAAQ,GAAI;AAElD,MAAI,CAAC,SAAS;AAEZ,YAAQ;AAAA,MACN;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAGA,MAAI,QAAQ,IAAI,0BAA0B;AACxC,WAAO,GAAG,QAAQ,IAAI,wBAAwB,GAAG,OAAO;AAAA,EAC1D;AAGA,MAAI,QAAQ,IAAI,WAAW,KAAK;AAE9B,YAAQ;AAAA,MACN;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAIA,MAAI,QAAQ,IAAI,eAAe,WAAW;AACxC,QAAI,QAAQ,IAAI,mBAAmB;AACjC,aAAO,WAAW,QAAQ,IAAI,iBAAiB,GAAG,OAAO;AAAA,IAC3D;AACA,QAAI,QAAQ,IAAI,YAAY;AAC1B,aAAO,WAAW,QAAQ,IAAI,UAAU,GAAG,OAAO;AAAA,IACpD;AAAA,EACF;AAEA,MACE,QAAQ,IAAI,eAAe,gBAC3B,QAAQ,IAAI,+BACZ;AACA,WAAO,WAAW,QAAQ,IAAI,6BAA6B,GAAG,OAAO;AAAA,EACvE;AAEA,SAAO;AACT;AAMA,SAAS,sBAAsB,KAA4B;AACzD,MAAI;AAEF,UAAM,YAAY,IAAI,IAAI,KAAK,mBAAmB;AAClD,WAAO,UAAU,WAAW,UAAU;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["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 { BlobCommandOptions, WithUploadProgress } from './helpers';\nimport { BlobError, getTokenFromOptionsOrEnv } 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';\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: 'public' | 'private';\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.createPutExtraChecks !== undefined ||\n // @ts-expect-error -- Runtime check for DX.\n options.cacheControlMaxAge !== undefined\n ) {\n throw new BlobError(\n \"client/`upload` doesn't allow `addRandomSuffix`, `cacheControlMaxAge` or `allowOverwrite`. 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 * @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 * @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 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 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\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 * 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 > & { 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 = getTokenFromOptionsOrEnv({ 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 * @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 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 * @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 const timestamp = new Date();\n timestamp.setSeconds(timestamp.getSeconds() + 30);\n const readWriteToken = getTokenFromOptionsOrEnv({ token });\n\n const [, , , storeId = null] = readWriteToken.split('_');\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 extends BlobCommandOptions {\n /**\n * The destination path for the blob\n */\n pathname: string;\n\n /**\n * Configuration for upload completion callback\n */\n onUploadCompleted?: {\n callbackUrl: string;\n tokenPayload?: string | null;\n };\n\n /**\n * A number specifying the maximum size in bytes that can be uploaded. The maximum is 5TB.\n */\n maximumSizeInBytes?: number;\n\n /**\n * An array of strings specifying the media type that are allowed to be uploaded.\n * By default, it's all content types. Wildcards are supported (text/*)\n */\n allowedContentTypes?: string[];\n\n /**\n * A number specifying the timestamp in ms when the token will expire.\n * By default, it's now + 1 hour.\n */\n validUntil?: number;\n\n /**\n * Adds a random suffix to the filename.\n * @defaultvalue false\n */\n addRandomSuffix?: boolean;\n\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 /**\n * Number in seconds to configure how long Blobs are cached. Defaults to one month. Cannot be set to a value lower than 1 minute.\n * @defaultvalue 30 * 24 * 60 * 60 (1 Month)\n */\n cacheControlMaxAge?: number;\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"],"mappings":";;;;;;;;;;;;AACA,YAAY,YAAY;AAIxB,SAAS,aAAa;AA6DtB,SAAS,qBAEP,YAAoB;AACpB,SAAO,SAAS,YAAY,SAAmB;AAC7C,QAAI,CAAC,QAAQ,MAAM,WAAW,qBAAqB,GAAG;AACpD,YAAM,IAAI,UAAU,GAAG,UAAU,qCAAqC;AAAA,IACxE;AAEA;AAAA;AAAA,MAEE,QAAQ,oBAAoB;AAAA,MAE5B,QAAQ,mBAAmB;AAAA,MAE3B,QAAQ,uBAAuB;AAAA,MAC/B;AACA,YAAM,IAAI;AAAA,QACR,GAAG,UAAU;AAAA,MACf;AAAA,IACF;AAAA,EACF;AACF;AAsBO,IAAM,MAAM,gBAAyC;AAAA,EAC1D,gBAAgB,CAAC,aAAa;AAAA,EAC9B,aAAa,qBAAqB,cAAc;AAClD,CAAC;AAqBM,IAAM,wBACX,kCAA6E;AAAA,EAC3E,gBAAgB,CAAC,aAAa;AAAA,EAC9B,aAAa,qBAAqB,gCAAgC;AACpE,CAAC;AAkBI,IAAM,0BACX;AAAA,EACE;AAAA,IACE,gBAAgB,CAAC,aAAa;AAAA,IAC9B,aAAa,qBAAqB,gCAAgC;AAAA,EACpE;AACF;AA2BK,IAAM,aACX,uBAA4D;AAAA,EAC1D,gBAAg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,MAAI,QAAQ,IAAI,eAAe,WAAW;AACxC,QAAI,QAAQ,IAAI,mBAAmB;AACjC,aAAO,WAAW,QAAQ,IAAI,iBAAiB,GAAG,OAAO;AAAA,IAC3D;AACA,QAAI,QAAQ,IAAI,YAAY;AAC1B,aAAO,WAAW,QAAQ,IAAI,UAAU,GAAG,OAAO;AAAA,IACpD;AAAA,EACF;AAEA,MACE,QAAQ,IAAI,eAAe,gBAC3B,QAAQ,IAAI,+BACZ;AACA,WAAO,WAAW,QAAQ,IAAI,6BAA6B,GAAG,OAAO;AAAA,EACvE;AAEA,SAAO;AACT;AAMA,SAAS,sBAAsB,KAA4B;AACzD,MAAI;AAEF,UAAM,YAAY,IAAI,IAAI,KAAK,mBAAmB;AAClD,WAAO,UAAU,WAAW,UAAU;AAAA,EACxC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
@@ -14,9 +14,11 @@ interface BlobCommandOptions {
|
|
|
14
14
|
}
|
|
15
15
|
interface CommonCreateBlobOptions extends BlobCommandOptions {
|
|
16
16
|
/**
|
|
17
|
-
* Whether the blob should be publicly accessible.
|
|
17
|
+
* Whether the blob should be publicly accessible.
|
|
18
|
+
* - 'public': The blob will be publicly accessible via its URL.
|
|
19
|
+
* - 'private': The blob will require authentication to access.
|
|
18
20
|
*/
|
|
19
|
-
access: 'public';
|
|
21
|
+
access: 'public' | 'private';
|
|
20
22
|
/**
|
|
21
23
|
* Adds a random suffix to the filename.
|
|
22
24
|
* @defaultvalue false
|
|
@@ -14,9 +14,11 @@ interface BlobCommandOptions {
|
|
|
14
14
|
}
|
|
15
15
|
interface CommonCreateBlobOptions extends BlobCommandOptions {
|
|
16
16
|
/**
|
|
17
|
-
* Whether the blob should be publicly accessible.
|
|
17
|
+
* Whether the blob should be publicly accessible.
|
|
18
|
+
* - 'public': The blob will be publicly accessible via its URL.
|
|
19
|
+
* - 'private': The blob will require authentication to access.
|
|
18
20
|
*/
|
|
19
|
-
access: 'public';
|
|
21
|
+
access: 'public' | 'private';
|
|
20
22
|
/**
|
|
21
23
|
* Adds a random suffix to the filename.
|
|
22
24
|
* @defaultvalue false
|
package/dist/index.cjs
CHANGED
|
@@ -22,11 +22,12 @@
|
|
|
22
22
|
|
|
23
23
|
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
|
|
26
|
+
var _chunk4ACRCP3Xcjs = require('./chunk-4ACRCP3X.cjs');
|
|
26
27
|
|
|
27
28
|
// src/del.ts
|
|
28
29
|
async function del(urlOrPathname, options) {
|
|
29
|
-
await
|
|
30
|
+
await _chunk4ACRCP3Xcjs.requestApi.call(void 0,
|
|
30
31
|
"/delete",
|
|
31
32
|
{
|
|
32
33
|
method: "POST",
|
|
@@ -43,7 +44,7 @@ async function del(urlOrPathname, options) {
|
|
|
43
44
|
// src/head.ts
|
|
44
45
|
async function head(urlOrPathname, options) {
|
|
45
46
|
const searchParams = new URLSearchParams({ url: urlOrPathname });
|
|
46
|
-
const response = await
|
|
47
|
+
const response = await _chunk4ACRCP3Xcjs.requestApi.call(void 0,
|
|
47
48
|
`?${searchParams.toString()}`,
|
|
48
49
|
// HEAD can't have body as a response, so we use GET
|
|
49
50
|
{
|
|
@@ -80,7 +81,7 @@ async function list(options) {
|
|
|
80
81
|
if (options == null ? void 0 : options.mode) {
|
|
81
82
|
searchParams.set("mode", options.mode);
|
|
82
83
|
}
|
|
83
|
-
const response = await
|
|
84
|
+
const response = await _chunk4ACRCP3Xcjs.requestApi.call(void 0,
|
|
84
85
|
`?${searchParams.toString()}`,
|
|
85
86
|
{
|
|
86
87
|
method: "GET",
|
|
@@ -112,27 +113,101 @@ function mapBlobResult(blobResult) {
|
|
|
112
113
|
};
|
|
113
114
|
}
|
|
114
115
|
|
|
116
|
+
// src/get.ts
|
|
117
|
+
function isUrl(urlOrPathname) {
|
|
118
|
+
return urlOrPathname.startsWith("http://") || urlOrPathname.startsWith("https://");
|
|
119
|
+
}
|
|
120
|
+
function extractPathnameFromUrl(url) {
|
|
121
|
+
try {
|
|
122
|
+
const parsedUrl = new URL(url);
|
|
123
|
+
return parsedUrl.pathname.slice(1);
|
|
124
|
+
} catch (e) {
|
|
125
|
+
return url;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
async function get(urlOrPathname, options) {
|
|
129
|
+
if (!urlOrPathname) {
|
|
130
|
+
throw new (0, _chunk4ACRCP3Xcjs.BlobError)("url or pathname is required");
|
|
131
|
+
}
|
|
132
|
+
if (!options) {
|
|
133
|
+
throw new (0, _chunk4ACRCP3Xcjs.BlobError)("missing options, see usage");
|
|
134
|
+
}
|
|
135
|
+
if (options.access !== "public" && options.access !== "private") {
|
|
136
|
+
throw new (0, _chunk4ACRCP3Xcjs.BlobError)('access must be "public" or "private"');
|
|
137
|
+
}
|
|
138
|
+
const token = _chunk4ACRCP3Xcjs.getTokenFromOptionsOrEnv.call(void 0, options);
|
|
139
|
+
let blobUrl;
|
|
140
|
+
let pathname;
|
|
141
|
+
let size;
|
|
142
|
+
if (isUrl(urlOrPathname)) {
|
|
143
|
+
blobUrl = urlOrPathname;
|
|
144
|
+
pathname = extractPathnameFromUrl(urlOrPathname);
|
|
145
|
+
} else {
|
|
146
|
+
const listResult = await list({
|
|
147
|
+
prefix: urlOrPathname,
|
|
148
|
+
limit: 1,
|
|
149
|
+
token,
|
|
150
|
+
abortSignal: options.abortSignal
|
|
151
|
+
});
|
|
152
|
+
const blobInfo = listResult.blobs.find(
|
|
153
|
+
(blob2) => blob2.pathname === urlOrPathname
|
|
154
|
+
);
|
|
155
|
+
if (!blobInfo) {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
blobUrl = blobInfo.url;
|
|
159
|
+
pathname = blobInfo.pathname;
|
|
160
|
+
size = blobInfo.size;
|
|
161
|
+
}
|
|
162
|
+
const headers = {
|
|
163
|
+
authorization: `Bearer ${token}`,
|
|
164
|
+
"x-vercel-blob-access": options.access
|
|
165
|
+
};
|
|
166
|
+
const response = await fetch(blobUrl, {
|
|
167
|
+
method: "GET",
|
|
168
|
+
headers,
|
|
169
|
+
signal: options.abortSignal
|
|
170
|
+
});
|
|
171
|
+
if (!response.ok) {
|
|
172
|
+
if (response.status === 404) {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
throw new (0, _chunk4ACRCP3Xcjs.BlobError)(
|
|
176
|
+
`Failed to fetch blob: ${response.status} ${response.statusText}`
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
const blob = await response.blob();
|
|
180
|
+
return {
|
|
181
|
+
blob,
|
|
182
|
+
url: blobUrl,
|
|
183
|
+
pathname,
|
|
184
|
+
contentType: response.headers.get("content-type") || "application/octet-stream",
|
|
185
|
+
size: size != null ? size : blob.size
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
115
189
|
// src/copy.ts
|
|
116
190
|
async function copy(fromUrlOrPathname, toPathname, options) {
|
|
117
191
|
if (!options) {
|
|
118
|
-
throw new (0,
|
|
192
|
+
throw new (0, _chunk4ACRCP3Xcjs.BlobError)("missing options, see usage");
|
|
119
193
|
}
|
|
120
|
-
if (options.access !== "public") {
|
|
121
|
-
throw new (0,
|
|
194
|
+
if (options.access !== "public" && options.access !== "private") {
|
|
195
|
+
throw new (0, _chunk4ACRCP3Xcjs.BlobError)('access must be "public" or "private"');
|
|
122
196
|
}
|
|
123
|
-
if (toPathname.length >
|
|
124
|
-
throw new (0,
|
|
125
|
-
`pathname is too long, maximum length is ${
|
|
197
|
+
if (toPathname.length > _chunk4ACRCP3Xcjs.MAXIMUM_PATHNAME_LENGTH) {
|
|
198
|
+
throw new (0, _chunk4ACRCP3Xcjs.BlobError)(
|
|
199
|
+
`pathname is too long, maximum length is ${_chunk4ACRCP3Xcjs.MAXIMUM_PATHNAME_LENGTH}`
|
|
126
200
|
);
|
|
127
201
|
}
|
|
128
|
-
for (const invalidCharacter of
|
|
202
|
+
for (const invalidCharacter of _chunk4ACRCP3Xcjs.disallowedPathnameCharacters) {
|
|
129
203
|
if (toPathname.includes(invalidCharacter)) {
|
|
130
|
-
throw new (0,
|
|
204
|
+
throw new (0, _chunk4ACRCP3Xcjs.BlobError)(
|
|
131
205
|
`pathname cannot contain "${invalidCharacter}", please encode it if needed`
|
|
132
206
|
);
|
|
133
207
|
}
|
|
134
208
|
}
|
|
135
209
|
const headers = {};
|
|
210
|
+
headers["x-vercel-blob-access"] = options.access;
|
|
136
211
|
if (options.addRandomSuffix !== void 0) {
|
|
137
212
|
headers["x-add-random-suffix"] = options.addRandomSuffix ? "1" : "0";
|
|
138
213
|
}
|
|
@@ -149,7 +224,7 @@ async function copy(fromUrlOrPathname, toPathname, options) {
|
|
|
149
224
|
pathname: toPathname,
|
|
150
225
|
fromUrl: fromUrlOrPathname
|
|
151
226
|
});
|
|
152
|
-
const response = await
|
|
227
|
+
const response = await _chunk4ACRCP3Xcjs.requestApi.call(void 0,
|
|
153
228
|
`?${params.toString()}`,
|
|
154
229
|
{
|
|
155
230
|
method: "PUT",
|
|
@@ -168,7 +243,7 @@ async function copy(fromUrlOrPathname, toPathname, options) {
|
|
|
168
243
|
}
|
|
169
244
|
|
|
170
245
|
// src/index.ts
|
|
171
|
-
var put =
|
|
246
|
+
var put = _chunk4ACRCP3Xcjs.createPutMethod.call(void 0, {
|
|
172
247
|
allowedOptions: [
|
|
173
248
|
"cacheControlMaxAge",
|
|
174
249
|
"addRandomSuffix",
|
|
@@ -176,7 +251,7 @@ var put = _chunkKLNTTDLTcjs.createPutMethod.call(void 0, {
|
|
|
176
251
|
"contentType"
|
|
177
252
|
]
|
|
178
253
|
});
|
|
179
|
-
var createMultipartUpload =
|
|
254
|
+
var createMultipartUpload = _chunk4ACRCP3Xcjs.createCreateMultipartUploadMethod.call(void 0, {
|
|
180
255
|
allowedOptions: [
|
|
181
256
|
"cacheControlMaxAge",
|
|
182
257
|
"addRandomSuffix",
|
|
@@ -184,7 +259,7 @@ var createMultipartUpload = _chunkKLNTTDLTcjs.createCreateMultipartUploadMethod.
|
|
|
184
259
|
"contentType"
|
|
185
260
|
]
|
|
186
261
|
});
|
|
187
|
-
var createMultipartUploader =
|
|
262
|
+
var createMultipartUploader = _chunk4ACRCP3Xcjs.createCreateMultipartUploaderMethod.call(void 0, {
|
|
188
263
|
allowedOptions: [
|
|
189
264
|
"cacheControlMaxAge",
|
|
190
265
|
"addRandomSuffix",
|
|
@@ -192,7 +267,7 @@ var createMultipartUploader = _chunkKLNTTDLTcjs.createCreateMultipartUploaderMet
|
|
|
192
267
|
"contentType"
|
|
193
268
|
]
|
|
194
269
|
});
|
|
195
|
-
var uploadPart =
|
|
270
|
+
var uploadPart = _chunk4ACRCP3Xcjs.createUploadPartMethod.call(void 0, {
|
|
196
271
|
allowedOptions: [
|
|
197
272
|
"cacheControlMaxAge",
|
|
198
273
|
"addRandomSuffix",
|
|
@@ -200,7 +275,7 @@ var uploadPart = _chunkKLNTTDLTcjs.createUploadPartMethod.call(void 0, {
|
|
|
200
275
|
"contentType"
|
|
201
276
|
]
|
|
202
277
|
});
|
|
203
|
-
var completeMultipartUpload =
|
|
278
|
+
var completeMultipartUpload = _chunk4ACRCP3Xcjs.createCompleteMultipartUploadMethod.call(void 0, {
|
|
204
279
|
allowedOptions: [
|
|
205
280
|
"cacheControlMaxAge",
|
|
206
281
|
"addRandomSuffix",
|
|
@@ -233,5 +308,6 @@ var completeMultipartUpload = _chunkKLNTTDLTcjs.createCompleteMultipartUploadMet
|
|
|
233
308
|
|
|
234
309
|
|
|
235
310
|
|
|
236
|
-
|
|
311
|
+
|
|
312
|
+
exports.BlobAccessError = _chunk4ACRCP3Xcjs.BlobAccessError; exports.BlobClientTokenExpiredError = _chunk4ACRCP3Xcjs.BlobClientTokenExpiredError; exports.BlobContentTypeNotAllowedError = _chunk4ACRCP3Xcjs.BlobContentTypeNotAllowedError; exports.BlobError = _chunk4ACRCP3Xcjs.BlobError; exports.BlobFileTooLargeError = _chunk4ACRCP3Xcjs.BlobFileTooLargeError; exports.BlobNotFoundError = _chunk4ACRCP3Xcjs.BlobNotFoundError; exports.BlobPathnameMismatchError = _chunk4ACRCP3Xcjs.BlobPathnameMismatchError; exports.BlobRequestAbortedError = _chunk4ACRCP3Xcjs.BlobRequestAbortedError; exports.BlobServiceNotAvailable = _chunk4ACRCP3Xcjs.BlobServiceNotAvailable; exports.BlobServiceRateLimited = _chunk4ACRCP3Xcjs.BlobServiceRateLimited; exports.BlobStoreNotFoundError = _chunk4ACRCP3Xcjs.BlobStoreNotFoundError; exports.BlobStoreSuspendedError = _chunk4ACRCP3Xcjs.BlobStoreSuspendedError; exports.BlobUnknownError = _chunk4ACRCP3Xcjs.BlobUnknownError; exports.completeMultipartUpload = completeMultipartUpload; exports.copy = copy; exports.createFolder = _chunk4ACRCP3Xcjs.createFolder; exports.createMultipartUpload = createMultipartUpload; exports.createMultipartUploader = createMultipartUploader; exports.del = del; exports.get = get; exports.getDownloadUrl = _chunk4ACRCP3Xcjs.getDownloadUrl; exports.head = head; exports.list = list; exports.put = put; exports.uploadPart = uploadPart;
|
|
237
313
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/storage/storage/packages/blob/dist/index.cjs","../src/del.ts","../src/head.ts","../src/list.ts","../src/copy.ts","../src/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;AChBA,MAAA,SAAsB,GAAA,CACpB,aAAA,EACA,OAAA,EACe;AACf,EAAA,MAAM,0CAAA;AAAA,IACJ,SAAA;AAAA,IACA;AAAA,MACE,MAAA,EAAQ,MAAA;AAAA,MACR,OAAA,EAAS,EAAE,cAAA,EAAgB,mBAAmB,CAAA;AAAA,MAC9C,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU;AAAA,QACnB,IAAA,EAAM,KAAA,CAAM,OA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A;AACQ,IAAA;AACtB,EAAA;AAGuB,EAAA;AACD,IAAA;AACtB,EAAA;AAEwB,EAAA;AACZ,IAAA;AACR,MAAA;AACF,IAAA;AACF,EAAA;AAEW,EAAA;AACe,IAAA;AACZ,MAAA;AACR,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AAEyC,EAAA;AAE7B,EAAA;AACF,IAAA;AACV,EAAA;AAEY,EAAA;AACiB,IAAA;AAC7B,EAAA;AAEyB,EAAA;AACK,IAAA;AAC9B,EAAA;AAEY,EAAA;AACF,IAAA;AACV,EAAA;AAEmB,EAAA;AACP,IAAA;AACD,IAAA;AACV,EAAA;AAEsB,EAAA;AACA,IAAA;AACrB,IAAA;AACU,MAAA;AACR,MAAA;AACgB,MAAA;AAClB,IAAA;AACA,IAAA;AACF,EAAA;AAEO,EAAA;AACS,IAAA;AACQ,IAAA;AACH,IAAA;AACG,IAAA;AACF,IAAA;AACtB,EAAA;AACF;AJ6EgC;AACA;AK9GsB;AACpC,EAAA;AACd,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACD;AAgDC;AACkB,EAAA;AACd,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACD;AAsBD;AACkB,EAAA;AACd,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACD;AAwBuB;AACR,EAAA;AACd,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACD;AAuBC;AACkB,EAAA;AACd,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACD;ALD6B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/storage/storage/packages/blob/dist/index.cjs","sourcesContent":[null,"import { requestApi } from './api';\nimport type { BlobCommandOptions } from './helpers';\n\n/**\n * Deletes one or multiple blobs from your store.\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#delete-a-blob\n *\n * @param urlOrPathname - Blob url (or pathname) to delete. You can pass either a single value or an array of values. You can only delete blobs that are located in a store, that your 'BLOB_READ_WRITE_TOKEN' has access to.\n * @param options - Additional options for the request.\n */\nexport async function del(\n urlOrPathname: string[] | string,\n options?: BlobCommandOptions,\n): Promise<void> {\n await requestApi(\n '/delete',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n urls: Array.isArray(urlOrPathname) ? urlOrPathname : [urlOrPathname],\n }),\n signal: options?.abortSignal,\n },\n options,\n );\n}\n","import { requestApi } from './api';\nimport type { BlobCommandOptions } from './helpers';\n\n/**\n * Result of the head method containing metadata about a blob.\n */\nexport interface HeadBlobResult {\n /**\n * The size of the blob in bytes.\n */\n size: number;\n\n /**\n * The date when the blob was uploaded.\n */\n uploadedAt: Date;\n\n /**\n * The pathname of the blob within the store.\n */\n pathname: string;\n\n /**\n * The content type of the blob.\n */\n contentType: string;\n\n /**\n * The content disposition header value.\n */\n contentDisposition: string;\n\n /**\n * The URL of the blob.\n */\n url: string;\n\n /**\n * A URL that will cause browsers to download the file instead of displaying it inline.\n */\n downloadUrl: string;\n\n /**\n * The cache control header value.\n */\n cacheControl: string;\n}\n\ninterface HeadBlobApiResponse extends Omit<HeadBlobResult, 'uploadedAt'> {\n uploadedAt: string; // when receiving data from our API, uploadedAt is a string\n}\n\n/**\n * Fetches metadata of a blob object.\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#get-blob-metadata\n *\n * @param urlOrPathname - Blob url or pathname to lookup.\n * @param options - Additional options for the request.\n */\nexport async function head(\n urlOrPathname: string,\n options?: BlobCommandOptions,\n): Promise<HeadBlobResult> {\n const searchParams = new URLSearchParams({ url: urlOrPathname });\n\n const response = await requestApi<HeadBlobApiResponse>(\n `?${searchParams.toString()}`,\n // HEAD can't have body as a response, so we use GET\n {\n method: 'GET',\n signal: options?.abortSignal,\n },\n options,\n );\n\n return {\n url: response.url,\n downloadUrl: response.downloadUrl,\n pathname: response.pathname,\n size: response.size,\n contentType: response.contentType,\n contentDisposition: response.contentDisposition,\n cacheControl: response.cacheControl,\n uploadedAt: new Date(response.uploadedAt),\n };\n}\n","import { requestApi } from './api';\nimport type { BlobCommandOptions } from './helpers';\n\n/**\n * Basic blob object information returned by the list method.\n */\nexport interface ListBlobResultBlob {\n /**\n * The URL of the blob.\n */\n url: string;\n\n /**\n * A URL that will cause browsers to download the file instead of displaying it inline.\n */\n downloadUrl: string;\n\n /**\n * The pathname of the blob within the store.\n */\n pathname: string;\n\n /**\n * The size of the blob in bytes.\n */\n size: number;\n\n /**\n * The date when the blob was uploaded.\n */\n uploadedAt: Date;\n}\n\n/**\n * Result of the list method in expanded mode (default).\n */\nexport interface ListBlobResult {\n /**\n * Array of blob objects in the store.\n */\n blobs: ListBlobResultBlob[];\n\n /**\n * Pagination cursor for the next set of results, if hasMore is true.\n */\n cursor?: string;\n\n /**\n * Indicates if there are more results available.\n */\n hasMore: boolean;\n}\n\n/**\n * Result of the list method in folded mode.\n */\nexport interface ListFoldedBlobResult extends ListBlobResult {\n /**\n * Array of folder paths in the store.\n */\n folders: string[];\n}\n\n/**\n * @internal Internal interface for the API response blob structure.\n * Maps the API response format where uploadedAt is a string, not a Date.\n */\ninterface ListBlobApiResponseBlob\n extends Omit<ListBlobResultBlob, 'uploadedAt'> {\n uploadedAt: string;\n}\n\n/**\n * @internal Internal interface for the API response structure.\n */\ninterface ListBlobApiResponse extends Omit<ListBlobResult, 'blobs'> {\n blobs: ListBlobApiResponseBlob[];\n folders?: string[];\n}\n\n/**\n * Options for the list method.\n */\nexport interface ListCommandOptions<\n M extends 'expanded' | 'folded' | undefined = undefined,\n> extends BlobCommandOptions {\n /**\n * The maximum number of blobs to return.\n * @defaultvalue 1000\n */\n limit?: number;\n\n /**\n * Filters the result to only include blobs that start with this prefix.\n * If used together with `mode: 'folded'`, make sure to include a trailing slash after the foldername.\n */\n prefix?: string;\n\n /**\n * The cursor to use for pagination. Can be obtained from the response of a previous `list` request.\n */\n cursor?: string;\n\n /**\n * Defines how the blobs are listed\n * - `expanded` the blobs property contains all blobs.\n * - `folded` the blobs property contains only the blobs at the root level of your store. Blobs that are located inside a folder get merged into a single entry in the folder response property.\n * @defaultvalue 'expanded'\n */\n mode?: M;\n}\n\n/**\n * @internal Type helper to determine the return type based on the mode parameter.\n */\ntype ListCommandResult<\n M extends 'expanded' | 'folded' | undefined = undefined,\n> = M extends 'folded' ? ListFoldedBlobResult : ListBlobResult;\n\n/**\n * Fetches a paginated list of blob objects from your store.\n *\n * @param options - Configuration options including:\n * - token - (Optional) A string specifying the read-write token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\n * - limit - (Optional) The maximum number of blobs to return. Defaults to 1000.\n * - prefix - (Optional) Filters the result to only include blobs that start with this prefix. If used with mode: 'folded', include a trailing slash after the folder name.\n * - cursor - (Optional) The cursor to use for pagination. Can be obtained from the response of a previous list request.\n * - mode - (Optional) Defines how the blobs are listed. Can be 'expanded' (default) or 'folded'. In folded mode, blobs located inside a folder are merged into a single entry in the folders response property.\n * - abortSignal - (Optional) AbortSignal to cancel the operation.\n * @returns A promise that resolves to an object containing:\n * - blobs: An array of blob objects with size, uploadedAt, pathname, url, and downloadUrl properties\n * - cursor: A string for pagination (if hasMore is true)\n * - hasMore: A boolean indicating if there are more results available\n * - folders: (Only in 'folded' mode) An array of folder paths\n */\nexport async function list<\n M extends 'expanded' | 'folded' | undefined = undefined,\n>(options?: ListCommandOptions<M>): Promise<ListCommandResult<M>> {\n const searchParams = new URLSearchParams();\n\n if (options?.limit) {\n searchParams.set('limit', options.limit.toString());\n }\n if (options?.prefix) {\n searchParams.set('prefix', options.prefix);\n }\n if (options?.cursor) {\n searchParams.set('cursor', options.cursor);\n }\n if (options?.mode) {\n searchParams.set('mode', options.mode);\n }\n\n const response = await requestApi<ListBlobApiResponse>(\n `?${searchParams.toString()}`,\n {\n method: 'GET',\n signal: options?.abortSignal,\n },\n options,\n );\n\n if (options?.mode === 'folded') {\n return {\n folders: response.folders ?? [],\n cursor: response.cursor,\n hasMore: response.hasMore,\n blobs: response.blobs.map(mapBlobResult),\n } as ListCommandResult<M>;\n }\n\n return {\n cursor: response.cursor,\n hasMore: response.hasMore,\n blobs: response.blobs.map(mapBlobResult),\n } as ListCommandResult<M>;\n}\n\n/**\n * @internal Helper function to map API response blob format to the expected return type.\n * Converts the uploadedAt string into a Date object.\n */\nfunction mapBlobResult(\n blobResult: ListBlobApiResponseBlob,\n): ListBlobResultBlob {\n return {\n url: blobResult.url,\n downloadUrl: blobResult.downloadUrl,\n pathname: blobResult.pathname,\n size: blobResult.size,\n uploadedAt: new Date(blobResult.uploadedAt),\n };\n}\n","import { MAXIMUM_PATHNAME_LENGTH, requestApi } from './api';\nimport type { CommonCreateBlobOptions } from './helpers';\nimport { BlobError, disallowedPathnameCharacters } from './helpers';\n\nexport type CopyCommandOptions = CommonCreateBlobOptions;\n\nexport interface CopyBlobResult {\n url: string;\n downloadUrl: string;\n pathname: string;\n contentType: string;\n contentDisposition: string;\n}\n\n/**\n * Copies a blob to another location in your store.\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#copy-a-blob\n *\n * @param fromUrlOrPathname - The blob URL (or pathname) to copy. You can only copy blobs that are in the store, that your 'BLOB_READ_WRITE_TOKEN' has access to.\n * @param toPathname - The pathname to copy the blob to. This includes the filename.\n * @param options - Additional options. The copy method will not preserve any metadata configuration (e.g.: 'cacheControlMaxAge') of the source blob. If you want to copy the metadata, you need to define it here again.\n */\nexport async function copy(\n fromUrlOrPathname: string,\n toPathname: string,\n options: CopyCommandOptions,\n): Promise<CopyBlobResult> {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Runtime check for DX.\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 (toPathname.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 (toPathname.includes(invalidCharacter)) {\n throw new BlobError(\n `pathname cannot contain \"${invalidCharacter}\", please encode it if needed`,\n );\n }\n }\n\n const headers: Record<string, string> = {};\n\n if (options.addRandomSuffix !== undefined) {\n headers['x-add-random-suffix'] = options.addRandomSuffix ? '1' : '0';\n }\n\n if (options.allowOverwrite !== undefined) {\n headers['x-allow-overwrite'] = options.allowOverwrite ? '1' : '0';\n }\n\n if (options.contentType) {\n headers['x-content-type'] = options.contentType;\n }\n\n if (options.cacheControlMaxAge !== undefined) {\n headers['x-cache-control-max-age'] = options.cacheControlMaxAge.toString();\n }\n\n const params = new URLSearchParams({\n pathname: toPathname,\n fromUrl: fromUrlOrPathname,\n });\n\n const response = await requestApi<CopyBlobResult>(\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 downloadUrl: response.downloadUrl,\n pathname: response.pathname,\n contentType: response.contentType,\n contentDisposition: response.contentDisposition,\n };\n}\n","import type { PutCommandOptions } from './put';\nimport { createPutMethod } from './put';\nimport { createCreateMultipartUploadMethod } from './multipart/create';\nimport type { UploadPartCommandOptions } from './multipart/upload';\nimport { createUploadPartMethod } from './multipart/upload';\nimport type { CompleteMultipartUploadCommandOptions } from './multipart/complete';\nimport { createCompleteMultipartUploadMethod } from './multipart/complete';\nimport type { CommonCreateBlobOptions } from './helpers';\nimport { createCreateMultipartUploaderMethod } from './multipart/create-uploader';\n\n// expose generic BlobError and download url util\nexport {\n BlobError,\n getDownloadUrl,\n type OnUploadProgressCallback,\n type UploadProgressEvent,\n} from './helpers';\n\n// expose api BlobErrors\nexport {\n BlobAccessError,\n BlobNotFoundError,\n BlobStoreNotFoundError,\n BlobStoreSuspendedError,\n BlobUnknownError,\n BlobServiceNotAvailable,\n BlobRequestAbortedError,\n BlobServiceRateLimited,\n BlobContentTypeNotAllowedError,\n BlobPathnameMismatchError,\n BlobClientTokenExpiredError,\n BlobFileTooLargeError,\n} from './api';\n\n// vercelBlob.put()\n\nexport type { PutBlobResult } from './put-helpers';\nexport type { PutCommandOptions };\n\n/**\n * Uploads a blob into your store from your server.\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#upload-a-blob\n *\n * If you want to upload from the browser directly, or if you're hitting Vercel upload limits, check out the documentation for client uploads: https://vercel.com/docs/vercel-blob/using-blob-sdk#client-uploads\n *\n * @param pathname - The pathname to upload the blob to, including the extension. This will influence the URL of your blob like https://$storeId.public.blob.vercel-storage.com/$pathname.\n * @param body - The content of your blob, can be a: string, File, Blob, Buffer or Stream. We support almost everything fetch supports: https://developer.mozilla.org/en-US/docs/Web/API/RequestInit#body.\n * @param options - Configuration options including:\n * - access - (Required) Must be 'public' as blobs are publicly accessible.\n * - addRandomSuffix - (Optional) A boolean specifying whether to add a random suffix to the pathname. It defaults to false. We recommend using this option to ensure there are no conflicts in your blob filenames.\n * - allowOverwrite - (Optional) A boolean to allow overwriting blobs. By default an error will be thrown if you try to overwrite a blob by using the same pathname for multiple blobs.\n * - contentType - (Optional) A string indicating the media type. By default, it's extracted from the pathname's extension.\n * - cacheControlMaxAge - (Optional) A number in seconds to configure how long Blobs are cached. Defaults to one month. Cannot be set to a value lower than 1 minute.\n * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\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<PutCommandOptions>({\n allowedOptions: [\n 'cacheControlMaxAge',\n 'addRandomSuffix',\n 'allowOverwrite',\n 'contentType',\n ],\n});\n\n// vercelBlob.del()\n\nexport { del } from './del';\n\n// vercelBlob.head()\n\nexport type { HeadBlobResult } from './head';\nexport { head } from './head';\n\n// vercelBlob.list()\n\nexport type {\n ListBlobResultBlob,\n ListBlobResult,\n ListCommandOptions,\n ListFoldedBlobResult,\n} from './list';\nexport { list } from './list';\n\n// vercelBlob.copy()\n\nexport type { CopyBlobResult, CopyCommandOptions } from './copy';\nexport { copy } from './copy';\n\n// vercelBlob. createMultipartUpload()\n// vercelBlob. uploadPart()\n// vercelBlob. completeMultipartUpload()\n// vercelBlob. createMultipartUploader()\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' as blobs are publicly accessible.\n * - addRandomSuffix - (Optional) A boolean specifying whether to add a random suffix to the pathname. It defaults to true.\n * - allowOverwrite - (Optional) A boolean to allow overwriting blobs. By default an error will be thrown if you try to overwrite a blob by using the same pathname for multiple blobs.\n * - contentType - (Optional) The media type for the file. If not specified, it's derived from the file extension. Falls back to application/octet-stream when no extension exists or can't be matched.\n * - cacheControlMaxAge - (Optional) A number in seconds to configure the edge and browser cache. Defaults to one year.\n * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\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<CommonCreateBlobOptions>({\n allowedOptions: [\n 'cacheControlMaxAge',\n 'addRandomSuffix',\n 'allowOverwrite',\n 'contentType',\n ],\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' as blobs are publicly accessible.\n * - addRandomSuffix - (Optional) A boolean specifying whether to add a random suffix to the pathname. It defaults to true.\n * - allowOverwrite - (Optional) A boolean to allow overwriting blobs. By default an error will be thrown if you try to overwrite a blob by using the same pathname for multiple blobs.\n * - contentType - (Optional) The media type for the file. If not specified, it's derived from the file extension. Falls back to application/octet-stream when no extension exists or can't be matched.\n * - cacheControlMaxAge - (Optional) A number in seconds to configure the edge and browser cache. Defaults to one year.\n * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\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<CommonCreateBlobOptions>({\n allowedOptions: [\n 'cacheControlMaxAge',\n 'addRandomSuffix',\n 'allowOverwrite',\n 'contentType',\n ],\n });\n\nexport type { UploadPartCommandOptions };\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' as blobs are publicly accessible.\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 * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\n * - addRandomSuffix - (Optional) A boolean specifying whether to add a random suffix to the pathname.\n * - allowOverwrite - (Optional) A boolean to allow overwriting blobs.\n * - cacheControlMaxAge - (Optional) A number in seconds to configure how long Blobs are cached.\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 = createUploadPartMethod<UploadPartCommandOptions>({\n allowedOptions: [\n 'cacheControlMaxAge',\n 'addRandomSuffix',\n 'allowOverwrite',\n 'contentType',\n ],\n});\n\nexport type { CompleteMultipartUploadCommandOptions };\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' as blobs are publicly accessible.\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 * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\n * - addRandomSuffix - (Optional) A boolean specifying whether to add a random suffix to the pathname. It defaults to true.\n * - allowOverwrite - (Optional) A boolean to allow overwriting blobs.\n * - cacheControlMaxAge - (Optional) A number in seconds to configure the edge and browser cache. Defaults to one year.\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<CompleteMultipartUploadCommandOptions>({\n allowedOptions: [\n 'cacheControlMaxAge',\n 'addRandomSuffix',\n 'allowOverwrite',\n 'contentType',\n ],\n });\n\nexport type { Part, PartInput } from './multipart/helpers';\n\nexport { createFolder } from './create-folder';\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/storage/storage/packages/blob/dist/index.cjs","../src/del.ts","../src/head.ts","../src/list.ts","../src/get.ts","../src/copy.ts","../src/index.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACjBA,MAAA,SAAsB,GAAA,CACpB,aAAA,EACA,OAAA,EACe;AACf,EAAA,MAAM,0CAAA;AAAA,IACJ,SAAA;AAAA,IACA;AAAA,MACE,MAAA,EAAQ,MAAA;AAAA,MACR,OAAA,EAAS,EAAE,cAAA,EAAgB,mBAAmB,CAAA;AAAA,MAC9C,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU;AAAA,QACnB,IAAA,EAAM,KAAA,CAAM,OAAA,CAAQ,aAAa,EAAA,EAAI,cAAA,EAAgB,CAAC,aAAa;AAAA,MACrE,CAAC,CAAA;AAAA,MACD,MAAA,EAAQ,QAAA,GAAA,KAAA,EAAA,KAAA,EAAA,EAAA,OAAA,CAAS;AAAA,IACnB,CAAA;AAAA,IACA;AAAA,EACF,CAAA;AACF;ADgBA;AACA;AEgBA,MAAA,SAAsB,IAAA,CACpB,aAAA,EACA,OAAA,EACyB;AACzB,EAAA,MAAM,aAAA,EAAe,IAAI,eAAA,CAAgB,EAAE,GAAA,EAAK,cAAc,CAAC,CAAA;AAE/D,EAAA,MAAM,SAAA,EAAW,MAAM,0CAAA;AAAA,IACrB,CAAA,CAAA,EAAI,YAAA,CAAa,QAAA,CAAS,CAAC,CAAA,CAAA;AA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,IAAA;AACA,IAAA;AACF,EAAA;AACD;AAuBC;AACkB,EAAA;AACd,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACD;ANsE6B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/storage/storage/packages/blob/dist/index.cjs","sourcesContent":[null,"import { requestApi } from './api';\nimport type { BlobCommandOptions } from './helpers';\n\n/**\n * Deletes one or multiple blobs from your store.\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#delete-a-blob\n *\n * @param urlOrPathname - Blob url (or pathname) to delete. You can pass either a single value or an array of values. You can only delete blobs that are located in a store, that your 'BLOB_READ_WRITE_TOKEN' has access to.\n * @param options - Additional options for the request.\n */\nexport async function del(\n urlOrPathname: string[] | string,\n options?: BlobCommandOptions,\n): Promise<void> {\n await requestApi(\n '/delete',\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n urls: Array.isArray(urlOrPathname) ? urlOrPathname : [urlOrPathname],\n }),\n signal: options?.abortSignal,\n },\n options,\n );\n}\n","import { requestApi } from './api';\nimport type { BlobCommandOptions } from './helpers';\n\n/**\n * Result of the head method containing metadata about a blob.\n */\nexport interface HeadBlobResult {\n /**\n * The size of the blob in bytes.\n */\n size: number;\n\n /**\n * The date when the blob was uploaded.\n */\n uploadedAt: Date;\n\n /**\n * The pathname of the blob within the store.\n */\n pathname: string;\n\n /**\n * The content type of the blob.\n */\n contentType: string;\n\n /**\n * The content disposition header value.\n */\n contentDisposition: string;\n\n /**\n * The URL of the blob.\n */\n url: string;\n\n /**\n * A URL that will cause browsers to download the file instead of displaying it inline.\n */\n downloadUrl: string;\n\n /**\n * The cache control header value.\n */\n cacheControl: string;\n}\n\ninterface HeadBlobApiResponse extends Omit<HeadBlobResult, 'uploadedAt'> {\n uploadedAt: string; // when receiving data from our API, uploadedAt is a string\n}\n\n/**\n * Fetches metadata of a blob object.\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#get-blob-metadata\n *\n * @param urlOrPathname - Blob url or pathname to lookup.\n * @param options - Additional options for the request.\n */\nexport async function head(\n urlOrPathname: string,\n options?: BlobCommandOptions,\n): Promise<HeadBlobResult> {\n const searchParams = new URLSearchParams({ url: urlOrPathname });\n\n const response = await requestApi<HeadBlobApiResponse>(\n `?${searchParams.toString()}`,\n // HEAD can't have body as a response, so we use GET\n {\n method: 'GET',\n signal: options?.abortSignal,\n },\n options,\n );\n\n return {\n url: response.url,\n downloadUrl: response.downloadUrl,\n pathname: response.pathname,\n size: response.size,\n contentType: response.contentType,\n contentDisposition: response.contentDisposition,\n cacheControl: response.cacheControl,\n uploadedAt: new Date(response.uploadedAt),\n };\n}\n","import { requestApi } from './api';\nimport type { BlobCommandOptions } from './helpers';\n\n/**\n * Basic blob object information returned by the list method.\n */\nexport interface ListBlobResultBlob {\n /**\n * The URL of the blob.\n */\n url: string;\n\n /**\n * A URL that will cause browsers to download the file instead of displaying it inline.\n */\n downloadUrl: string;\n\n /**\n * The pathname of the blob within the store.\n */\n pathname: string;\n\n /**\n * The size of the blob in bytes.\n */\n size: number;\n\n /**\n * The date when the blob was uploaded.\n */\n uploadedAt: Date;\n}\n\n/**\n * Result of the list method in expanded mode (default).\n */\nexport interface ListBlobResult {\n /**\n * Array of blob objects in the store.\n */\n blobs: ListBlobResultBlob[];\n\n /**\n * Pagination cursor for the next set of results, if hasMore is true.\n */\n cursor?: string;\n\n /**\n * Indicates if there are more results available.\n */\n hasMore: boolean;\n}\n\n/**\n * Result of the list method in folded mode.\n */\nexport interface ListFoldedBlobResult extends ListBlobResult {\n /**\n * Array of folder paths in the store.\n */\n folders: string[];\n}\n\n/**\n * @internal Internal interface for the API response blob structure.\n * Maps the API response format where uploadedAt is a string, not a Date.\n */\ninterface ListBlobApiResponseBlob\n extends Omit<ListBlobResultBlob, 'uploadedAt'> {\n uploadedAt: string;\n}\n\n/**\n * @internal Internal interface for the API response structure.\n */\ninterface ListBlobApiResponse extends Omit<ListBlobResult, 'blobs'> {\n blobs: ListBlobApiResponseBlob[];\n folders?: string[];\n}\n\n/**\n * Options for the list method.\n */\nexport interface ListCommandOptions<\n M extends 'expanded' | 'folded' | undefined = undefined,\n> extends BlobCommandOptions {\n /**\n * The maximum number of blobs to return.\n * @defaultvalue 1000\n */\n limit?: number;\n\n /**\n * Filters the result to only include blobs that start with this prefix.\n * If used together with `mode: 'folded'`, make sure to include a trailing slash after the foldername.\n */\n prefix?: string;\n\n /**\n * The cursor to use for pagination. Can be obtained from the response of a previous `list` request.\n */\n cursor?: string;\n\n /**\n * Defines how the blobs are listed\n * - `expanded` the blobs property contains all blobs.\n * - `folded` the blobs property contains only the blobs at the root level of your store. Blobs that are located inside a folder get merged into a single entry in the folder response property.\n * @defaultvalue 'expanded'\n */\n mode?: M;\n}\n\n/**\n * @internal Type helper to determine the return type based on the mode parameter.\n */\ntype ListCommandResult<\n M extends 'expanded' | 'folded' | undefined = undefined,\n> = M extends 'folded' ? ListFoldedBlobResult : ListBlobResult;\n\n/**\n * Fetches a paginated list of blob objects from your store.\n *\n * @param options - Configuration options including:\n * - token - (Optional) A string specifying the read-write token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\n * - limit - (Optional) The maximum number of blobs to return. Defaults to 1000.\n * - prefix - (Optional) Filters the result to only include blobs that start with this prefix. If used with mode: 'folded', include a trailing slash after the folder name.\n * - cursor - (Optional) The cursor to use for pagination. Can be obtained from the response of a previous list request.\n * - mode - (Optional) Defines how the blobs are listed. Can be 'expanded' (default) or 'folded'. In folded mode, blobs located inside a folder are merged into a single entry in the folders response property.\n * - abortSignal - (Optional) AbortSignal to cancel the operation.\n * @returns A promise that resolves to an object containing:\n * - blobs: An array of blob objects with size, uploadedAt, pathname, url, and downloadUrl properties\n * - cursor: A string for pagination (if hasMore is true)\n * - hasMore: A boolean indicating if there are more results available\n * - folders: (Only in 'folded' mode) An array of folder paths\n */\nexport async function list<\n M extends 'expanded' | 'folded' | undefined = undefined,\n>(options?: ListCommandOptions<M>): Promise<ListCommandResult<M>> {\n const searchParams = new URLSearchParams();\n\n if (options?.limit) {\n searchParams.set('limit', options.limit.toString());\n }\n if (options?.prefix) {\n searchParams.set('prefix', options.prefix);\n }\n if (options?.cursor) {\n searchParams.set('cursor', options.cursor);\n }\n if (options?.mode) {\n searchParams.set('mode', options.mode);\n }\n\n const response = await requestApi<ListBlobApiResponse>(\n `?${searchParams.toString()}`,\n {\n method: 'GET',\n signal: options?.abortSignal,\n },\n options,\n );\n\n if (options?.mode === 'folded') {\n return {\n folders: response.folders ?? [],\n cursor: response.cursor,\n hasMore: response.hasMore,\n blobs: response.blobs.map(mapBlobResult),\n } as ListCommandResult<M>;\n }\n\n return {\n cursor: response.cursor,\n hasMore: response.hasMore,\n blobs: response.blobs.map(mapBlobResult),\n } as ListCommandResult<M>;\n}\n\n/**\n * @internal Helper function to map API response blob format to the expected return type.\n * Converts the uploadedAt string into a Date object.\n */\nfunction mapBlobResult(\n blobResult: ListBlobApiResponseBlob,\n): ListBlobResultBlob {\n return {\n url: blobResult.url,\n downloadUrl: blobResult.downloadUrl,\n pathname: blobResult.pathname,\n size: blobResult.size,\n uploadedAt: new Date(blobResult.uploadedAt),\n };\n}\n","import type { BlobCommandOptions } from './helpers';\nimport { BlobError, getTokenFromOptionsOrEnv } from './helpers';\nimport { list } from './list';\n\n/**\n * Options for the get method.\n */\nexport interface GetCommandOptions extends BlobCommandOptions {\n /**\n * Whether the blob is publicly accessible or private.\n * - 'public': The blob is publicly accessible via its URL.\n * - 'private': The blob requires authentication to access.\n */\n access: 'public' | 'private';\n}\n\n/**\n * Result of the get method containing the blob content and metadata.\n */\nexport interface GetBlobResult {\n /**\n * The blob content as a Blob object.\n */\n blob: Blob;\n\n /**\n * The URL of the blob.\n */\n url: string;\n\n /**\n * The pathname of the blob within the store.\n */\n pathname: string;\n\n /**\n * The content type of the blob.\n */\n contentType: string;\n\n /**\n * The size of the blob in bytes.\n */\n size: number;\n}\n\n/**\n * Checks if the input is a URL (starts with http:// or https://).\n */\nfunction isUrl(urlOrPathname: string): boolean {\n return (\n urlOrPathname.startsWith('http://') || urlOrPathname.startsWith('https://')\n );\n}\n\n/**\n * Extracts the pathname from a blob URL.\n */\nfunction extractPathnameFromUrl(url: string): string {\n try {\n const parsedUrl = new URL(url);\n // Remove leading slash from pathname\n return parsedUrl.pathname.slice(1);\n } catch {\n return url;\n }\n}\n\n/**\n * Fetches blob content by URL or pathname.\n * - If a URL is provided, fetches the blob directly (bypasses list operation).\n * - If a pathname is provided, uses list to find the blob first.\n *\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk\n *\n * @param urlOrPathname - The URL or pathname of the blob to fetch.\n * @param options - Configuration options including:\n * - access - (Required) Must be 'public' or 'private'. Determines the access level of the blob.\n * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\n * - abortSignal - (Optional) AbortSignal to cancel the operation.\n * @returns A promise that resolves to the blob content and metadata, or null if not found.\n */\nexport async function get(\n urlOrPathname: string,\n options: GetCommandOptions,\n): Promise<GetBlobResult | null> {\n if (!urlOrPathname) {\n throw new BlobError('url or pathname is required');\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('access must be \"public\" or \"private\"');\n }\n\n const token = getTokenFromOptionsOrEnv(options);\n\n let blobUrl: string;\n let pathname: string;\n let size: number | undefined;\n\n // Check if input is a URL - if so, bypass list operation\n if (isUrl(urlOrPathname)) {\n blobUrl = urlOrPathname;\n pathname = extractPathnameFromUrl(urlOrPathname);\n } else {\n // Use list to find the blob by pathname\n const listResult = await list({\n prefix: urlOrPathname,\n limit: 1,\n token,\n abortSignal: options.abortSignal,\n });\n\n // Find exact match by pathname\n const blobInfo = listResult.blobs.find(\n (blob) => blob.pathname === urlOrPathname,\n );\n\n if (!blobInfo) {\n return null;\n }\n\n blobUrl = blobInfo.url;\n pathname = blobInfo.pathname;\n size = blobInfo.size;\n }\n\n // Fetch the blob content with authentication headers\n const headers: Record<string, string> = {\n authorization: `Bearer ${token}`,\n 'x-vercel-blob-access': options.access,\n };\n\n const response = await fetch(blobUrl, {\n method: 'GET',\n headers,\n signal: options.abortSignal,\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null;\n }\n throw new BlobError(\n `Failed to fetch blob: ${response.status} ${response.statusText}`,\n );\n }\n\n const blob = await response.blob();\n\n return {\n blob,\n url: blobUrl,\n pathname,\n contentType:\n response.headers.get('content-type') || 'application/octet-stream',\n size: size ?? blob.size,\n };\n}\n","import { MAXIMUM_PATHNAME_LENGTH, requestApi } from './api';\nimport type { CommonCreateBlobOptions } from './helpers';\nimport { BlobError, disallowedPathnameCharacters } from './helpers';\n\nexport type CopyCommandOptions = CommonCreateBlobOptions;\n\nexport interface CopyBlobResult {\n url: string;\n downloadUrl: string;\n pathname: string;\n contentType: string;\n contentDisposition: string;\n}\n\n/**\n * Copies a blob to another location in your store.\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#copy-a-blob\n *\n * @param fromUrlOrPathname - The blob URL (or pathname) to copy. You can only copy blobs that are in the store, that your 'BLOB_READ_WRITE_TOKEN' has access to.\n * @param toPathname - The pathname to copy the blob to. This includes the filename.\n * @param options - Additional options. The copy method will not preserve any metadata configuration (e.g.: 'cacheControlMaxAge') of the source blob. If you want to copy the metadata, you need to define it here again.\n */\nexport async function copy(\n fromUrlOrPathname: string,\n toPathname: string,\n options: CopyCommandOptions,\n): Promise<CopyBlobResult> {\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('access must be \"public\" or \"private\"');\n }\n\n if (toPathname.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 (toPathname.includes(invalidCharacter)) {\n throw new BlobError(\n `pathname cannot contain \"${invalidCharacter}\", please encode it if needed`,\n );\n }\n }\n\n const headers: Record<string, string> = {};\n\n // access is always required, so always add it to headers\n headers['x-vercel-blob-access'] = options.access;\n\n if (options.addRandomSuffix !== undefined) {\n headers['x-add-random-suffix'] = options.addRandomSuffix ? '1' : '0';\n }\n\n if (options.allowOverwrite !== undefined) {\n headers['x-allow-overwrite'] = options.allowOverwrite ? '1' : '0';\n }\n\n if (options.contentType) {\n headers['x-content-type'] = options.contentType;\n }\n\n if (options.cacheControlMaxAge !== undefined) {\n headers['x-cache-control-max-age'] = options.cacheControlMaxAge.toString();\n }\n\n const params = new URLSearchParams({\n pathname: toPathname,\n fromUrl: fromUrlOrPathname,\n });\n\n const response = await requestApi<CopyBlobResult>(\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 downloadUrl: response.downloadUrl,\n pathname: response.pathname,\n contentType: response.contentType,\n contentDisposition: response.contentDisposition,\n };\n}\n","import type { CommonCreateBlobOptions } from './helpers';\nimport type { CompleteMultipartUploadCommandOptions } from './multipart/complete';\nimport { createCompleteMultipartUploadMethod } from './multipart/complete';\nimport { createCreateMultipartUploadMethod } from './multipart/create';\nimport { createCreateMultipartUploaderMethod } from './multipart/create-uploader';\nimport type { UploadPartCommandOptions } from './multipart/upload';\nimport { createUploadPartMethod } from './multipart/upload';\nimport type { PutCommandOptions } from './put';\nimport { createPutMethod } from './put';\n\n// expose api BlobErrors\nexport {\n BlobAccessError,\n BlobClientTokenExpiredError,\n BlobContentTypeNotAllowedError,\n BlobFileTooLargeError,\n BlobNotFoundError,\n BlobPathnameMismatchError,\n BlobRequestAbortedError,\n BlobServiceNotAvailable,\n BlobServiceRateLimited,\n BlobStoreNotFoundError,\n BlobStoreSuspendedError,\n BlobUnknownError,\n} from './api';\n// expose generic BlobError and download url util\nexport {\n BlobError,\n getDownloadUrl,\n type OnUploadProgressCallback,\n type UploadProgressEvent,\n} from './helpers';\n\n// vercelBlob.put()\n\nexport type { PutBlobResult } from './put-helpers';\nexport type { PutCommandOptions };\n\n/**\n * Uploads a blob into your store from your server.\n * Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#upload-a-blob\n *\n * If you want to upload from the browser directly, or if you're hitting Vercel upload limits, check out the documentation for client uploads: https://vercel.com/docs/vercel-blob/using-blob-sdk#client-uploads\n *\n * @param pathname - The pathname to upload the blob to, including the extension. This will influence the URL of your blob like https://$storeId.public.blob.vercel-storage.com/$pathname.\n * @param body - The content of your blob, can be a: string, File, Blob, Buffer or Stream. We support almost everything fetch supports: https://developer.mozilla.org/en-US/docs/Web/API/RequestInit#body.\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 * - addRandomSuffix - (Optional) A boolean specifying whether to add a random suffix to the pathname. It defaults to false. We recommend using this option to ensure there are no conflicts in your blob filenames.\n * - allowOverwrite - (Optional) A boolean to allow overwriting blobs. By default an error will be thrown if you try to overwrite a blob by using the same pathname for multiple blobs.\n * - contentType - (Optional) A string indicating the media type. By default, it's extracted from the pathname's extension.\n * - cacheControlMaxAge - (Optional) A number in seconds to configure how long Blobs are cached. Defaults to one month. Cannot be set to a value lower than 1 minute.\n * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\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<PutCommandOptions>({\n allowedOptions: [\n 'cacheControlMaxAge',\n 'addRandomSuffix',\n 'allowOverwrite',\n 'contentType',\n ],\n});\n\n// vercelBlob.del()\n\nexport { del } from './del';\n\n// vercelBlob.head()\n\nexport type { HeadBlobResult } from './head';\nexport { head } from './head';\n\n// vercelBlob.get()\n\nexport type { GetBlobResult, GetCommandOptions } from './get';\nexport { get } from './get';\n\n// vercelBlob.list()\n\nexport type {\n ListBlobResult,\n ListBlobResultBlob,\n ListCommandOptions,\n ListFoldedBlobResult,\n} from './list';\nexport { list } from './list';\n\n// vercelBlob.copy()\n\nexport type { CopyBlobResult, CopyCommandOptions } from './copy';\nexport { copy } from './copy';\n\n// vercelBlob. createMultipartUpload()\n// vercelBlob. uploadPart()\n// vercelBlob. completeMultipartUpload()\n// vercelBlob. createMultipartUploader()\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 * - addRandomSuffix - (Optional) A boolean specifying whether to add a random suffix to the pathname. It defaults to true.\n * - allowOverwrite - (Optional) A boolean to allow overwriting blobs. By default an error will be thrown if you try to overwrite a blob by using the same pathname for multiple blobs.\n * - contentType - (Optional) The media type for the file. If not specified, it's derived from the file extension. Falls back to application/octet-stream when no extension exists or can't be matched.\n * - cacheControlMaxAge - (Optional) A number in seconds to configure the edge and browser cache. Defaults to one year.\n * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\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<CommonCreateBlobOptions>({\n allowedOptions: [\n 'cacheControlMaxAge',\n 'addRandomSuffix',\n 'allowOverwrite',\n 'contentType',\n ],\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 * - addRandomSuffix - (Optional) A boolean specifying whether to add a random suffix to the pathname. It defaults to true.\n * - allowOverwrite - (Optional) A boolean to allow overwriting blobs. By default an error will be thrown if you try to overwrite a blob by using the same pathname for multiple blobs.\n * - contentType - (Optional) The media type for the file. If not specified, it's derived from the file extension. Falls back to application/octet-stream when no extension exists or can't be matched.\n * - cacheControlMaxAge - (Optional) A number in seconds to configure the edge and browser cache. Defaults to one year.\n * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\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<CommonCreateBlobOptions>({\n allowedOptions: [\n 'cacheControlMaxAge',\n 'addRandomSuffix',\n 'allowOverwrite',\n 'contentType',\n ],\n });\n\nexport type { UploadPartCommandOptions };\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 * - 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 * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\n * - addRandomSuffix - (Optional) A boolean specifying whether to add a random suffix to the pathname.\n * - allowOverwrite - (Optional) A boolean to allow overwriting blobs.\n * - cacheControlMaxAge - (Optional) A number in seconds to configure how long Blobs are cached.\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 = createUploadPartMethod<UploadPartCommandOptions>({\n allowedOptions: [\n 'cacheControlMaxAge',\n 'addRandomSuffix',\n 'allowOverwrite',\n 'contentType',\n ],\n});\n\nexport type { CompleteMultipartUploadCommandOptions };\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 * - 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 * - token - (Optional) A string specifying the token to use when making requests. It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.\n * - addRandomSuffix - (Optional) A boolean specifying whether to add a random suffix to the pathname. It defaults to true.\n * - allowOverwrite - (Optional) A boolean to allow overwriting blobs.\n * - cacheControlMaxAge - (Optional) A number in seconds to configure the edge and browser cache. Defaults to one year.\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<CompleteMultipartUploadCommandOptions>({\n allowedOptions: [\n 'cacheControlMaxAge',\n 'addRandomSuffix',\n 'allowOverwrite',\n 'contentType',\n ],\n });\n\nexport { createFolder } from './create-folder';\nexport type { Part, PartInput } from './multipart/helpers';\n"]}
|