@vercel/blob 1.1.0 → 2.0.0-4d25be25-20250912070808
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/client.cjs +55 -7
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +4 -7
- package/dist/client.d.ts +4 -7
- package/dist/client.js +55 -7
- package/dist/client.js.map +1 -1
- package/dist/index.cjs +11 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +11 -6
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/client.cjs
CHANGED
|
@@ -129,7 +129,7 @@ function hexToArrayByte(input) {
|
|
|
129
129
|
}
|
|
130
130
|
const view = new Uint8Array(input.length / 2);
|
|
131
131
|
for (let i = 0; i < input.length; i += 2) {
|
|
132
|
-
view[i / 2] = parseInt(input.substring(i, i + 2), 16);
|
|
132
|
+
view[i / 2] = Number.parseInt(input.substring(i, i + 2), 16);
|
|
133
133
|
}
|
|
134
134
|
return Buffer.from(view);
|
|
135
135
|
}
|
|
@@ -155,26 +155,36 @@ async function handleUpload({
|
|
|
155
155
|
const type = body.type;
|
|
156
156
|
switch (type) {
|
|
157
157
|
case "blob.generate-client-token": {
|
|
158
|
-
const { pathname,
|
|
158
|
+
const { pathname, clientPayload, multipart } = body.payload;
|
|
159
159
|
const payload = await onBeforeGenerateToken(
|
|
160
160
|
pathname,
|
|
161
161
|
clientPayload,
|
|
162
162
|
multipart
|
|
163
163
|
);
|
|
164
164
|
const tokenPayload = (_a = payload.tokenPayload) != null ? _a : clientPayload;
|
|
165
|
+
const { callbackUrl: providedCallbackUrl, ...tokenOptions } = payload;
|
|
166
|
+
let callbackUrl = providedCallbackUrl;
|
|
167
|
+
if (onUploadCompleted && !callbackUrl) {
|
|
168
|
+
callbackUrl = getCallbackUrl(request);
|
|
169
|
+
}
|
|
170
|
+
if (!onUploadCompleted && callbackUrl) {
|
|
171
|
+
console.warn(
|
|
172
|
+
"callbackUrl was provided but onUploadCompleted is not defined. The callback will not be handled."
|
|
173
|
+
);
|
|
174
|
+
}
|
|
165
175
|
const oneHourInSeconds = 60 * 60;
|
|
166
176
|
const now = /* @__PURE__ */ new Date();
|
|
167
177
|
const validUntil = (_b = payload.validUntil) != null ? _b : now.setSeconds(now.getSeconds() + oneHourInSeconds);
|
|
168
178
|
return {
|
|
169
179
|
type,
|
|
170
180
|
clientToken: await generateClientTokenFromReadWriteToken({
|
|
171
|
-
...
|
|
181
|
+
...tokenOptions,
|
|
172
182
|
token: resolvedToken,
|
|
173
183
|
pathname,
|
|
174
|
-
onUploadCompleted: {
|
|
184
|
+
onUploadCompleted: callbackUrl ? {
|
|
175
185
|
callbackUrl,
|
|
176
186
|
tokenPayload
|
|
177
|
-
},
|
|
187
|
+
} : void 0,
|
|
178
188
|
validUntil
|
|
179
189
|
})
|
|
180
190
|
};
|
|
@@ -193,7 +203,9 @@ async function handleUpload({
|
|
|
193
203
|
if (!isVerified) {
|
|
194
204
|
throw new (0, _chunkKLNTTDLTcjs.BlobError)("Invalid callback signature");
|
|
195
205
|
}
|
|
196
|
-
|
|
206
|
+
if (onUploadCompleted) {
|
|
207
|
+
await onUploadCompleted(body.payload);
|
|
208
|
+
}
|
|
197
209
|
return { type, response: "ok" };
|
|
198
210
|
}
|
|
199
211
|
default:
|
|
@@ -207,7 +219,6 @@ async function retrieveClientToken(options) {
|
|
|
207
219
|
type: EventTypes.generateClientToken,
|
|
208
220
|
payload: {
|
|
209
221
|
pathname,
|
|
210
|
-
callbackUrl: url,
|
|
211
222
|
clientPayload: options.clientPayload,
|
|
212
223
|
multipart: options.multipart
|
|
213
224
|
}
|
|
@@ -274,6 +285,43 @@ async function generateClientTokenFromReadWriteToken({
|
|
|
274
285
|
`${securedKey}.${payload}`
|
|
275
286
|
).toString("base64")}`;
|
|
276
287
|
}
|
|
288
|
+
function getCallbackUrl(request) {
|
|
289
|
+
const reqUrl = getPathFromRequestUrl(request.url);
|
|
290
|
+
if (!reqUrl) {
|
|
291
|
+
console.warn(
|
|
292
|
+
"onUploadCompleted provided but no callbackUrl could be determined. Please provide a callbackUrl in onBeforeGenerateToken or set the VERCEL_BLOB_CALLBACK_URL environment variable."
|
|
293
|
+
);
|
|
294
|
+
return void 0;
|
|
295
|
+
}
|
|
296
|
+
if (process.env.VERCEL_BLOB_CALLBACK_URL) {
|
|
297
|
+
return `${process.env.VERCEL_BLOB_CALLBACK_URL}${reqUrl}`;
|
|
298
|
+
}
|
|
299
|
+
if (process.env.VERCEL !== "1") {
|
|
300
|
+
console.warn(
|
|
301
|
+
"onUploadCompleted provided but no callbackUrl could be determined. Please provide a callbackUrl in onBeforeGenerateToken or set the VERCEL_BLOB_CALLBACK_URL environment variable."
|
|
302
|
+
);
|
|
303
|
+
return void 0;
|
|
304
|
+
}
|
|
305
|
+
if (process.env.VERCEL_ENV === "preview") {
|
|
306
|
+
if (process.env.VERCEL_BRANCH_URL) {
|
|
307
|
+
return `${process.env.VERCEL_BRANCH_URL}${reqUrl}`;
|
|
308
|
+
}
|
|
309
|
+
if (process.env.VERCEL_URL) {
|
|
310
|
+
return `${process.env.VERCEL_URL}${reqUrl}`;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
|
|
314
|
+
return `${process.env.VERCEL_PROJECT_PRODUCTION_URL}${reqUrl}`;
|
|
315
|
+
}
|
|
316
|
+
return void 0;
|
|
317
|
+
}
|
|
318
|
+
function getPathFromRequestUrl(url) {
|
|
319
|
+
const parsedUrl = URL.parse(url, "https://dummy.com");
|
|
320
|
+
if (parsedUrl) {
|
|
321
|
+
return parsedUrl.pathname + parsedUrl.search;
|
|
322
|
+
}
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
277
325
|
|
|
278
326
|
|
|
279
327
|
|
package/dist/client.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/runner/work/storage/storage/packages/blob/dist/client.cjs","../src/client.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACVA,+EAAwB;AAKxB,gCAAsB;AA2DtB,SAAS,oBAAA,CAEP,UAAA,EAAoB;AACpB,EAAA,OAAO,SAAS,WAAA,CAAY,OAAA,EAAmB;AAC7C,IAAA,GAAA,CAAI,CAAC,OAAA,CAAQ,KAAA,CAAM,UAAA,CAAW,qBAAqB,CAAA,EAAG;AACpD,MAAA,MAAM,IAAI,gCAAA,CAAU,CAAA,EAAA;AACtB,IAAA;AAEA,IAAA;AAAA;AAEU,MAAA;AAEA,MAAA;AAEA,MAAA;AACR,IAAA;AACU,MAAA;AACK,QAAA;AACf,MAAA;AACF,IAAA;AACF,EAAA;AACF;AAsB4D;AACzC,EAAA;AACJ,EAAA;AACd;AAqBY;AAEQ,EAAA;AACJ,EAAA;AACd;AAkBU;AAET,EAAA;AACmB,IAAA;AACJ,IAAA;AACf,EAAA;AACF;AA4BA;AACmB,EAAA;AACJ,EAAA;AACd;AAyBU;AAET,EAAA;AACmB,IAAA;AACJ,IAAA;AACf,EAAA;AACF;AA+CoB;AACH,EAAA;AACI,EAAA;AAEP,IAAA;AACA,MAAA;AACR,QAAA;AACF,MAAA;AACF,IAAA;AAEA,IAAA;AAAA;AAEU,MAAA;AAEA,MAAA;AAEA,MAAA;AACR,IAAA;AACU,MAAA;AACR,QAAA;AACF,MAAA;AACF,IAAA;AACF,EAAA;AACyB,EAAA;AApS3B,IAAA;AAqSW,IAAA;AACY,MAAA;AACjB,MAAA;AACe,MAAA;AACJ,MAAA;AACM,MAAA;AAClB,IAAA;AACH,EAAA;AACD;AAKwB;AACE,EAAA;AACvB,IAAA;AACkB,IAAA;AACI,IAAA;AACtB,IAAA;AACiB,IAAA;AACnB,EAAA;AACF;AAME;AAIwB,EAAA;AACR,IAAA;AAChB,EAAA;A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AAA;AACI,MAAA;AACrB,IAAA;AACF,EAAA;AAEwB,EAAA;AACd,IAAA;AACa,IAAA;AACZ,IAAA;AACS,MAAA;AACL,MAAA;AACb,IAAA;AACgB,IAAA;AACjB,EAAA;AAEY,EAAA;AACS,IAAA;AACtB,EAAA;AAEI,EAAA;AACkB,IAAA;AACb,IAAA;AACG,EAAA;AACU,IAAA;AACtB,EAAA;AACF;AAKuB;AAED,EAAA;AACtB;AAKuB;AACjB,EAAA;AACqB,IAAA;AACb,EAAA;AACH,IAAA;AACT,EAAA;AACF;AAkBsB;AACpB,EAAA;AACG,EAAA;AAC2C;AAztBhD,EAAA;AA0tBwB,EAAA;AACV,IAAA;AACR,MAAA;AACF,IAAA;AACF,EAAA;AAEkB,EAAA;AACG,EAAA;AACE,EAAA;AAEA,EAAA;AAET,EAAA;AACF,IAAA;AACA,MAAA;AACV,IAAA;AACF,EAAA;AAEuB,EAAA;AACN,IAAA;AACV,MAAA;AACS,MAAA;AACb,IAAA;AACgB,EAAA;AAEM,EAAA;AAER,EAAA;AACK,IAAA;AACtB,EAAA;AACO,EAAA;AACY,IAAA;AACC,EAAA;AACtB;ADve2B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/storage/storage/packages/blob/dist/client.cjs","sourcesContent":[null,"// 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] = 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 * URL where upload completion callbacks will be sent.\n */\n callbackUrl: 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\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 }\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 - (Required) 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, callbackUrl, clientPayload, multipart } = body.payload;\n const payload = await onBeforeGenerateToken(\n pathname,\n clientPayload,\n multipart,\n );\n const tokenPayload = payload.tokenPayload ?? clientPayload;\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 ...payload,\n token: resolvedToken,\n pathname,\n onUploadCompleted: {\n callbackUrl,\n tokenPayload,\n },\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 await onUploadCompleted(body.payload);\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 callbackUrl: url,\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\nexport { createFolder } from './create-folder';\n"]}
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/storage/storage/packages/blob/dist/client.cjs","../src/client.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACVA,+EAAwB;AAKxB,gCAAsB;AA2DtB,SAAS,oBAAA,CAEP,UAAA,EAAoB;AACpB,EAAA,OAAO,SAAS,WAAA,CAAY,OAAA,EAAmB;AAC7C,IAAA,GAAA,CAAI,CAAC,OAAA,CAAQ,KAAA,CAAM,UAAA,CAAW,qBAAqB,CAAA,EAAG;AACpD,MAAA,MAAM,IAAI,gCAAA,CAAU,CAAA,EAAA;AACtB,IAAA;AAEA,IAAA;AAAA;AAEU,MAAA;AAEA,MAAA;AAEA,MAAA;AACR,IAAA;AACU,MAAA;AACK,QAAA;AACf,MAAA;AACF,IAAA;AACF,EAAA;AACF;AAsB4D;AACzC,EAAA;AACJ,EAAA;AACd;AAqBY;AAEQ,EAAA;AACJ,EAAA;AACd;AAkBU;AAET,EAAA;AACmB,IAAA;AACJ,IAAA;AACf,EAAA;AACF;AA4BA;AACmB,EAAA;AACJ,EAAA;AACd;AAyBU;AAET,EAAA;AACmB,IAAA;AACJ,IAAA;AACf,EAAA;AACF;AA+CoB;AACH,EAAA;AACI,EAAA;AAEP,IAAA;AACA,MAAA;AACR,QAAA;AACF,MAAA;AACF,IAAA;AAEA,IAAA;AAAA;AAEU,MA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AA;AACN,MAAA;AACF,IAAA;AACO,IAAA;AACT,EAAA;AAGgB,EAAA;AACQ,IAAA;AACxB,EAAA;AAGgB,EAAA;AAEN,IAAA;AACN,MAAA;AACF,IAAA;AACO,IAAA;AACT,EAAA;AAIgB,EAAA;AACE,IAAA;AACI,MAAA;AACpB,IAAA;AACgB,IAAA;AACI,MAAA;AACpB,IAAA;AACF,EAAA;AAGc,EAAA;AAGU,IAAA;AACxB,EAAA;AAEO,EAAA;AACT;AAMS;AACe,EAAA;AACP,EAAA;AACI,IAAA;AACnB,EAAA;AAEO,EAAA;AACT;AD1jB2B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/storage/storage/packages/blob/dist/client.cjs","sourcesContent":[null,"// 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 reqUrl = getPathFromRequestUrl(request.url!);\n\n if (!reqUrl) {\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}${reqUrl}`;\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 `${process.env.VERCEL_BRANCH_URL}${reqUrl}`;\n }\n if (process.env.VERCEL_URL) {\n return `${process.env.VERCEL_URL}${reqUrl}`;\n }\n }\n\n if (\n process.env.VERCEL_ENV === 'production' &&\n process.env.VERCEL_PROJECT_PRODUCTION_URL\n ) {\n return `${process.env.VERCEL_PROJECT_PRODUCTION_URL}${reqUrl}`;\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 const parsedUrl = URL.parse(url, 'https://dummy.com');\n if (parsedUrl) {\n return parsedUrl.pathname + parsedUrl.search;\n }\n\n return null;\n}\n\nexport { createFolder } from './create-folder';\n"]}
|
package/dist/client.d.cts
CHANGED
|
@@ -234,10 +234,6 @@ interface GenerateClientTokenEvent {
|
|
|
234
234
|
* The destination path for the blob.
|
|
235
235
|
*/
|
|
236
236
|
pathname: string;
|
|
237
|
-
/**
|
|
238
|
-
* URL where upload completion callbacks will be sent.
|
|
239
|
-
*/
|
|
240
|
-
callbackUrl: string;
|
|
241
237
|
/**
|
|
242
238
|
* Whether the upload will use multipart uploading.
|
|
243
239
|
*/
|
|
@@ -295,10 +291,11 @@ interface HandleUploadOptions {
|
|
|
295
291
|
* @param clientPayload - A string payload specified on the client when calling upload()
|
|
296
292
|
* @param multipart - A boolean specifying whether the file is a multipart upload
|
|
297
293
|
*
|
|
298
|
-
* @returns An object with configuration options for the client token
|
|
294
|
+
* @returns An object with configuration options for the client token including the optional callbackUrl
|
|
299
295
|
*/
|
|
300
296
|
onBeforeGenerateToken: (pathname: string, clientPayload: string | null, multipart: boolean) => Promise<Pick<GenerateClientTokenOptions, 'allowedContentTypes' | 'maximumSizeInBytes' | 'validUntil' | 'addRandomSuffix' | 'allowOverwrite' | 'cacheControlMaxAge'> & {
|
|
301
297
|
tokenPayload?: string | null;
|
|
298
|
+
callbackUrl?: string;
|
|
302
299
|
}>;
|
|
303
300
|
/**
|
|
304
301
|
* Function called by Vercel Blob when the client upload finishes.
|
|
@@ -306,7 +303,7 @@ interface HandleUploadOptions {
|
|
|
306
303
|
*
|
|
307
304
|
* @param body - Contains information about the completed upload including the blob details
|
|
308
305
|
*/
|
|
309
|
-
onUploadCompleted
|
|
306
|
+
onUploadCompleted?: (body: UploadCompletedEvent['payload']) => Promise<void>;
|
|
310
307
|
/**
|
|
311
308
|
* A string specifying the read-write token to use when making requests.
|
|
312
309
|
* It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.
|
|
@@ -326,7 +323,7 @@ interface HandleUploadOptions {
|
|
|
326
323
|
* - request - (Required) An IncomingMessage or Request object to be used to determine the action to take.
|
|
327
324
|
* - body - (Required) The request body containing upload information.
|
|
328
325
|
* - onBeforeGenerateToken - (Required) Function called before generating the client token for uploads.
|
|
329
|
-
* - onUploadCompleted - (
|
|
326
|
+
* - onUploadCompleted - (Optional) Function called by Vercel Blob when the client upload finishes.
|
|
330
327
|
* - token - (Optional) A string specifying the read-write token to use when making requests. Defaults to process.env.BLOB_READ_WRITE_TOKEN.
|
|
331
328
|
* @returns A promise that resolves to either a client token generation result or an upload completion result
|
|
332
329
|
*/
|
package/dist/client.d.ts
CHANGED
|
@@ -234,10 +234,6 @@ interface GenerateClientTokenEvent {
|
|
|
234
234
|
* The destination path for the blob.
|
|
235
235
|
*/
|
|
236
236
|
pathname: string;
|
|
237
|
-
/**
|
|
238
|
-
* URL where upload completion callbacks will be sent.
|
|
239
|
-
*/
|
|
240
|
-
callbackUrl: string;
|
|
241
237
|
/**
|
|
242
238
|
* Whether the upload will use multipart uploading.
|
|
243
239
|
*/
|
|
@@ -295,10 +291,11 @@ interface HandleUploadOptions {
|
|
|
295
291
|
* @param clientPayload - A string payload specified on the client when calling upload()
|
|
296
292
|
* @param multipart - A boolean specifying whether the file is a multipart upload
|
|
297
293
|
*
|
|
298
|
-
* @returns An object with configuration options for the client token
|
|
294
|
+
* @returns An object with configuration options for the client token including the optional callbackUrl
|
|
299
295
|
*/
|
|
300
296
|
onBeforeGenerateToken: (pathname: string, clientPayload: string | null, multipart: boolean) => Promise<Pick<GenerateClientTokenOptions, 'allowedContentTypes' | 'maximumSizeInBytes' | 'validUntil' | 'addRandomSuffix' | 'allowOverwrite' | 'cacheControlMaxAge'> & {
|
|
301
297
|
tokenPayload?: string | null;
|
|
298
|
+
callbackUrl?: string;
|
|
302
299
|
}>;
|
|
303
300
|
/**
|
|
304
301
|
* Function called by Vercel Blob when the client upload finishes.
|
|
@@ -306,7 +303,7 @@ interface HandleUploadOptions {
|
|
|
306
303
|
*
|
|
307
304
|
* @param body - Contains information about the completed upload including the blob details
|
|
308
305
|
*/
|
|
309
|
-
onUploadCompleted
|
|
306
|
+
onUploadCompleted?: (body: UploadCompletedEvent['payload']) => Promise<void>;
|
|
310
307
|
/**
|
|
311
308
|
* A string specifying the read-write token to use when making requests.
|
|
312
309
|
* It defaults to process.env.BLOB_READ_WRITE_TOKEN when deployed on Vercel.
|
|
@@ -326,7 +323,7 @@ interface HandleUploadOptions {
|
|
|
326
323
|
* - request - (Required) An IncomingMessage or Request object to be used to determine the action to take.
|
|
327
324
|
* - body - (Required) The request body containing upload information.
|
|
328
325
|
* - onBeforeGenerateToken - (Required) Function called before generating the client token for uploads.
|
|
329
|
-
* - onUploadCompleted - (
|
|
326
|
+
* - onUploadCompleted - (Optional) Function called by Vercel Blob when the client upload finishes.
|
|
330
327
|
* - token - (Optional) A string specifying the read-write token to use when making requests. Defaults to process.env.BLOB_READ_WRITE_TOKEN.
|
|
331
328
|
* @returns A promise that resolves to either a client token generation result or an upload completion result
|
|
332
329
|
*/
|
package/dist/client.js
CHANGED
|
@@ -129,7 +129,7 @@ function hexToArrayByte(input) {
|
|
|
129
129
|
}
|
|
130
130
|
const view = new Uint8Array(input.length / 2);
|
|
131
131
|
for (let i = 0; i < input.length; i += 2) {
|
|
132
|
-
view[i / 2] = parseInt(input.substring(i, i + 2), 16);
|
|
132
|
+
view[i / 2] = Number.parseInt(input.substring(i, i + 2), 16);
|
|
133
133
|
}
|
|
134
134
|
return Buffer.from(view);
|
|
135
135
|
}
|
|
@@ -155,26 +155,36 @@ async function handleUpload({
|
|
|
155
155
|
const type = body.type;
|
|
156
156
|
switch (type) {
|
|
157
157
|
case "blob.generate-client-token": {
|
|
158
|
-
const { pathname,
|
|
158
|
+
const { pathname, clientPayload, multipart } = body.payload;
|
|
159
159
|
const payload = await onBeforeGenerateToken(
|
|
160
160
|
pathname,
|
|
161
161
|
clientPayload,
|
|
162
162
|
multipart
|
|
163
163
|
);
|
|
164
164
|
const tokenPayload = (_a = payload.tokenPayload) != null ? _a : clientPayload;
|
|
165
|
+
const { callbackUrl: providedCallbackUrl, ...tokenOptions } = payload;
|
|
166
|
+
let callbackUrl = providedCallbackUrl;
|
|
167
|
+
if (onUploadCompleted && !callbackUrl) {
|
|
168
|
+
callbackUrl = getCallbackUrl(request);
|
|
169
|
+
}
|
|
170
|
+
if (!onUploadCompleted && callbackUrl) {
|
|
171
|
+
console.warn(
|
|
172
|
+
"callbackUrl was provided but onUploadCompleted is not defined. The callback will not be handled."
|
|
173
|
+
);
|
|
174
|
+
}
|
|
165
175
|
const oneHourInSeconds = 60 * 60;
|
|
166
176
|
const now = /* @__PURE__ */ new Date();
|
|
167
177
|
const validUntil = (_b = payload.validUntil) != null ? _b : now.setSeconds(now.getSeconds() + oneHourInSeconds);
|
|
168
178
|
return {
|
|
169
179
|
type,
|
|
170
180
|
clientToken: await generateClientTokenFromReadWriteToken({
|
|
171
|
-
...
|
|
181
|
+
...tokenOptions,
|
|
172
182
|
token: resolvedToken,
|
|
173
183
|
pathname,
|
|
174
|
-
onUploadCompleted: {
|
|
184
|
+
onUploadCompleted: callbackUrl ? {
|
|
175
185
|
callbackUrl,
|
|
176
186
|
tokenPayload
|
|
177
|
-
},
|
|
187
|
+
} : void 0,
|
|
178
188
|
validUntil
|
|
179
189
|
})
|
|
180
190
|
};
|
|
@@ -193,7 +203,9 @@ async function handleUpload({
|
|
|
193
203
|
if (!isVerified) {
|
|
194
204
|
throw new BlobError("Invalid callback signature");
|
|
195
205
|
}
|
|
196
|
-
|
|
206
|
+
if (onUploadCompleted) {
|
|
207
|
+
await onUploadCompleted(body.payload);
|
|
208
|
+
}
|
|
197
209
|
return { type, response: "ok" };
|
|
198
210
|
}
|
|
199
211
|
default:
|
|
@@ -207,7 +219,6 @@ async function retrieveClientToken(options) {
|
|
|
207
219
|
type: EventTypes.generateClientToken,
|
|
208
220
|
payload: {
|
|
209
221
|
pathname,
|
|
210
|
-
callbackUrl: url,
|
|
211
222
|
clientPayload: options.clientPayload,
|
|
212
223
|
multipart: options.multipart
|
|
213
224
|
}
|
|
@@ -274,6 +285,43 @@ async function generateClientTokenFromReadWriteToken({
|
|
|
274
285
|
`${securedKey}.${payload}`
|
|
275
286
|
).toString("base64")}`;
|
|
276
287
|
}
|
|
288
|
+
function getCallbackUrl(request) {
|
|
289
|
+
const reqUrl = getPathFromRequestUrl(request.url);
|
|
290
|
+
if (!reqUrl) {
|
|
291
|
+
console.warn(
|
|
292
|
+
"onUploadCompleted provided but no callbackUrl could be determined. Please provide a callbackUrl in onBeforeGenerateToken or set the VERCEL_BLOB_CALLBACK_URL environment variable."
|
|
293
|
+
);
|
|
294
|
+
return void 0;
|
|
295
|
+
}
|
|
296
|
+
if (process.env.VERCEL_BLOB_CALLBACK_URL) {
|
|
297
|
+
return `${process.env.VERCEL_BLOB_CALLBACK_URL}${reqUrl}`;
|
|
298
|
+
}
|
|
299
|
+
if (process.env.VERCEL !== "1") {
|
|
300
|
+
console.warn(
|
|
301
|
+
"onUploadCompleted provided but no callbackUrl could be determined. Please provide a callbackUrl in onBeforeGenerateToken or set the VERCEL_BLOB_CALLBACK_URL environment variable."
|
|
302
|
+
);
|
|
303
|
+
return void 0;
|
|
304
|
+
}
|
|
305
|
+
if (process.env.VERCEL_ENV === "preview") {
|
|
306
|
+
if (process.env.VERCEL_BRANCH_URL) {
|
|
307
|
+
return `${process.env.VERCEL_BRANCH_URL}${reqUrl}`;
|
|
308
|
+
}
|
|
309
|
+
if (process.env.VERCEL_URL) {
|
|
310
|
+
return `${process.env.VERCEL_URL}${reqUrl}`;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (process.env.VERCEL_ENV === "production" && process.env.VERCEL_PROJECT_PRODUCTION_URL) {
|
|
314
|
+
return `${process.env.VERCEL_PROJECT_PRODUCTION_URL}${reqUrl}`;
|
|
315
|
+
}
|
|
316
|
+
return void 0;
|
|
317
|
+
}
|
|
318
|
+
function getPathFromRequestUrl(url) {
|
|
319
|
+
const parsedUrl = URL.parse(url, "https://dummy.com");
|
|
320
|
+
if (parsedUrl) {
|
|
321
|
+
return parsedUrl.pathname + parsedUrl.search;
|
|
322
|
+
}
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
277
325
|
export {
|
|
278
326
|
completeMultipartUpload,
|
|
279
327
|
createFolder,
|
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] = 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 * URL where upload completion callbacks will be sent.\n */\n callbackUrl: 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\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 }\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 - (Required) 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, callbackUrl, clientPayload, multipart } = body.payload;\n const payload = await onBeforeGenerateToken(\n pathname,\n clientPayload,\n multipart,\n );\n const tokenPayload = payload.tokenPayload ?? clientPayload;\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 ...payload,\n token: resolvedToken,\n pathname,\n onUploadCompleted: {\n callbackUrl,\n tokenPayload,\n },\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 await onUploadCompleted(body.payload);\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 callbackUrl: url,\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\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,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,gBAAgB,CAAC,aAAa;AAAA,EAC9B,aAAa,qBAAqB,0BAA0B;AAC9D,CAAC;AAyBI,IAAM,0BACX;AAAA,EACE;AAAA,IACE,gBAAgB,CAAC,aAAa;AAAA,IAC9B,aAAa,qBAAqB,kCAAkC;AAAA,EACtE;AACF;AA+CK,IAAM,SAAS,gBAA+B;AAAA,EACnD,gBAAgB,CAAC,aAAa;AAAA,EAC9B,YAAY,SAAS;AAEnB,QAAI,QAAQ,oBAAoB,QAAW;AACzC,YAAM,IAAI;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AAAA,MACH,aAAY,sBAAiB,eAAjB,YAA+B,UAAU,QAAQ;AAAA,IAC/D,CAAC;AAAA,EACH,EAAE,SAAS,QAAQ;AAEnB,QAAM,aAAa,MAAM,YAAY,SAAS,cAAc;AAE5D,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,UAAU,6BAA6B;AAAA,EACnD;AACA,SAAO,sBAAsB,OAAO,IAAI,OAAO;AAAA,IAC7C,GAAG,UAAU,IAAI,OAAO;AAAA,EAC1B,EAAE,SAAS,QAAQ,CAAC;AACtB;","names":[]}
|
|
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 reqUrl = getPathFromRequestUrl(request.url!);\n\n if (!reqUrl) {\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}${reqUrl}`;\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 `${process.env.VERCEL_BRANCH_URL}${reqUrl}`;\n }\n if (process.env.VERCEL_URL) {\n return `${process.env.VERCEL_URL}${reqUrl}`;\n }\n }\n\n if (\n process.env.VERCEL_ENV === 'production' &&\n process.env.VERCEL_PROJECT_PRODUCTION_URL\n ) {\n return `${process.env.VERCEL_PROJECT_PRODUCTION_URL}${reqUrl}`;\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 const parsedUrl = URL.parse(url, 'https://dummy.com');\n if (parsedUrl) {\n return parsedUrl.pathname + parsedUrl.search;\n }\n\n return null;\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,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,gBAAgB,CAAC,aAAa;AAAA,EAC9B,aAAa,qBAAqB,0BAA0B;AAC9D,CAAC;AAyBI,IAAM,0BACX;AAAA,EACE;AAAA,IACE,gBAAgB,CAAC,aAAa;AAAA,IAC9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A,IAClD;AACA,QAAI,QAAQ,IAAI,YAAY;AAC1B,aAAO,GAAG,QAAQ,IAAI,UAAU,GAAG,MAAM;AAAA,IAC3C;AAAA,EACF;AAEA,MACE,QAAQ,IAAI,eAAe,gBAC3B,QAAQ,IAAI,+BACZ;AACA,WAAO,GAAG,QAAQ,IAAI,6BAA6B,GAAG,MAAM;AAAA,EAC9D;AAEA,SAAO;AACT;AAMA,SAAS,sBAAsB,KAA4B;AACzD,QAAM,YAAY,IAAI,MAAM,KAAK,mBAAmB;AACpD,MAAI,WAAW;AACb,WAAO,UAAU,WAAW,UAAU;AAAA,EACxC;AAEA,SAAO;AACT;","names":[]}
|
package/dist/index.cjs
CHANGED
|
@@ -25,13 +25,15 @@
|
|
|
25
25
|
var _chunkKLNTTDLTcjs = require('./chunk-KLNTTDLT.cjs');
|
|
26
26
|
|
|
27
27
|
// src/del.ts
|
|
28
|
-
async function del(
|
|
28
|
+
async function del(urlOrPathname, options) {
|
|
29
29
|
await _chunkKLNTTDLTcjs.requestApi.call(void 0,
|
|
30
30
|
"/delete",
|
|
31
31
|
{
|
|
32
32
|
method: "POST",
|
|
33
33
|
headers: { "content-type": "application/json" },
|
|
34
|
-
body: JSON.stringify({
|
|
34
|
+
body: JSON.stringify({
|
|
35
|
+
urls: Array.isArray(urlOrPathname) ? urlOrPathname : [urlOrPathname]
|
|
36
|
+
}),
|
|
35
37
|
signal: options == null ? void 0 : options.abortSignal
|
|
36
38
|
},
|
|
37
39
|
options
|
|
@@ -39,8 +41,8 @@ async function del(url, options) {
|
|
|
39
41
|
}
|
|
40
42
|
|
|
41
43
|
// src/head.ts
|
|
42
|
-
async function head(
|
|
43
|
-
const searchParams = new URLSearchParams({ url });
|
|
44
|
+
async function head(urlOrPathname, options) {
|
|
45
|
+
const searchParams = new URLSearchParams({ url: urlOrPathname });
|
|
44
46
|
const response = await _chunkKLNTTDLTcjs.requestApi.call(void 0,
|
|
45
47
|
`?${searchParams.toString()}`,
|
|
46
48
|
// HEAD can't have body as a response, so we use GET
|
|
@@ -111,7 +113,7 @@ function mapBlobResult(blobResult) {
|
|
|
111
113
|
}
|
|
112
114
|
|
|
113
115
|
// src/copy.ts
|
|
114
|
-
async function copy(
|
|
116
|
+
async function copy(fromUrlOrPathname, toPathname, options) {
|
|
115
117
|
if (!options) {
|
|
116
118
|
throw new (0, _chunkKLNTTDLTcjs.BlobError)("missing options, see usage");
|
|
117
119
|
}
|
|
@@ -143,7 +145,10 @@ async function copy(fromUrl, toPathname, options) {
|
|
|
143
145
|
if (options.cacheControlMaxAge !== void 0) {
|
|
144
146
|
headers["x-cache-control-max-age"] = options.cacheControlMaxAge.toString();
|
|
145
147
|
}
|
|
146
|
-
const params = new URLSearchParams({
|
|
148
|
+
const params = new URLSearchParams({
|
|
149
|
+
pathname: toPathname,
|
|
150
|
+
fromUrl: fromUrlOrPathname
|
|
151
|
+
});
|
|
147
152
|
const response = await _chunkKLNTTDLTcjs.requestApi.call(void 0,
|
|
148
153
|
`?${params.toString()}`,
|
|
149
154
|
{
|
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,GAAA,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,EAAE,IAAA,EAAM,KAAA,CAAM,OAAA,CAAQ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;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;AAEI,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;AJ2EgC;AACA;AKzGsB;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;ALN6B;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 url - Blob url or array of blob urls that identify the blobs to be deleted. 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 url: 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({ urls: Array.isArray(url) ? url : [url] }),\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 url - Blob url to lookup.\n * @param options - Additional options for the request.\n */\nexport async function head(\n url: string,\n options?: BlobCommandOptions,\n): Promise<HeadBlobResult> {\n const searchParams = new URLSearchParams({ url });\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 fromUrl - The blob URL 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 fromUrl: 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({ pathname: toPathname, fromUrl });\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/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,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;ADeA;AACA;AEiBA,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;AAAA;AAE3B,IAAA;AACU,MAAA;AACA,MAAA;AACV,IAAA;AACA,IAAA;AACF,EAAA;AAEO,EAAA;AACS,IAAA;AACQ,IAAA;AACH,IAAA;AACJ,IAAA;AACO,IAAA;AACF,IAAA;AACG,IAAA;AACF,IAAA;AACvB,EAAA;AACF;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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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -53,10 +53,10 @@ declare class BlobRequestAbortedError extends BlobError {
|
|
|
53
53
|
* Deletes one or multiple blobs from your store.
|
|
54
54
|
* Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#delete-a-blob
|
|
55
55
|
*
|
|
56
|
-
* @param
|
|
56
|
+
* @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.
|
|
57
57
|
* @param options - Additional options for the request.
|
|
58
58
|
*/
|
|
59
|
-
declare function del(
|
|
59
|
+
declare function del(urlOrPathname: string[] | string, options?: BlobCommandOptions): Promise<void>;
|
|
60
60
|
|
|
61
61
|
/**
|
|
62
62
|
* Result of the head method containing metadata about a blob.
|
|
@@ -99,10 +99,10 @@ interface HeadBlobResult {
|
|
|
99
99
|
* Fetches metadata of a blob object.
|
|
100
100
|
* Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#get-blob-metadata
|
|
101
101
|
*
|
|
102
|
-
* @param
|
|
102
|
+
* @param urlOrPathname - Blob url or pathname to lookup.
|
|
103
103
|
* @param options - Additional options for the request.
|
|
104
104
|
*/
|
|
105
|
-
declare function head(
|
|
105
|
+
declare function head(urlOrPathname: string, options?: BlobCommandOptions): Promise<HeadBlobResult>;
|
|
106
106
|
|
|
107
107
|
/**
|
|
108
108
|
* Basic blob object information returned by the list method.
|
|
@@ -215,11 +215,11 @@ interface CopyBlobResult {
|
|
|
215
215
|
* Copies a blob to another location in your store.
|
|
216
216
|
* Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#copy-a-blob
|
|
217
217
|
*
|
|
218
|
-
* @param
|
|
218
|
+
* @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.
|
|
219
219
|
* @param toPathname - The pathname to copy the blob to. This includes the filename.
|
|
220
220
|
* @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.
|
|
221
221
|
*/
|
|
222
|
-
declare function copy(
|
|
222
|
+
declare function copy(fromUrlOrPathname: string, toPathname: string, options: CopyCommandOptions): Promise<CopyBlobResult>;
|
|
223
223
|
|
|
224
224
|
/**
|
|
225
225
|
* Uploads a blob into your store from your server.
|
package/dist/index.d.ts
CHANGED
|
@@ -53,10 +53,10 @@ declare class BlobRequestAbortedError extends BlobError {
|
|
|
53
53
|
* Deletes one or multiple blobs from your store.
|
|
54
54
|
* Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#delete-a-blob
|
|
55
55
|
*
|
|
56
|
-
* @param
|
|
56
|
+
* @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.
|
|
57
57
|
* @param options - Additional options for the request.
|
|
58
58
|
*/
|
|
59
|
-
declare function del(
|
|
59
|
+
declare function del(urlOrPathname: string[] | string, options?: BlobCommandOptions): Promise<void>;
|
|
60
60
|
|
|
61
61
|
/**
|
|
62
62
|
* Result of the head method containing metadata about a blob.
|
|
@@ -99,10 +99,10 @@ interface HeadBlobResult {
|
|
|
99
99
|
* Fetches metadata of a blob object.
|
|
100
100
|
* Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#get-blob-metadata
|
|
101
101
|
*
|
|
102
|
-
* @param
|
|
102
|
+
* @param urlOrPathname - Blob url or pathname to lookup.
|
|
103
103
|
* @param options - Additional options for the request.
|
|
104
104
|
*/
|
|
105
|
-
declare function head(
|
|
105
|
+
declare function head(urlOrPathname: string, options?: BlobCommandOptions): Promise<HeadBlobResult>;
|
|
106
106
|
|
|
107
107
|
/**
|
|
108
108
|
* Basic blob object information returned by the list method.
|
|
@@ -215,11 +215,11 @@ interface CopyBlobResult {
|
|
|
215
215
|
* Copies a blob to another location in your store.
|
|
216
216
|
* Detailed documentation can be found here: https://vercel.com/docs/vercel-blob/using-blob-sdk#copy-a-blob
|
|
217
217
|
*
|
|
218
|
-
* @param
|
|
218
|
+
* @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.
|
|
219
219
|
* @param toPathname - The pathname to copy the blob to. This includes the filename.
|
|
220
220
|
* @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.
|
|
221
221
|
*/
|
|
222
|
-
declare function copy(
|
|
222
|
+
declare function copy(fromUrlOrPathname: string, toPathname: string, options: CopyCommandOptions): Promise<CopyBlobResult>;
|
|
223
223
|
|
|
224
224
|
/**
|
|
225
225
|
* Uploads a blob into your store from your server.
|
package/dist/index.js
CHANGED
|
@@ -25,13 +25,15 @@ import {
|
|
|
25
25
|
} from "./chunk-Z56QURM6.js";
|
|
26
26
|
|
|
27
27
|
// src/del.ts
|
|
28
|
-
async function del(
|
|
28
|
+
async function del(urlOrPathname, options) {
|
|
29
29
|
await requestApi(
|
|
30
30
|
"/delete",
|
|
31
31
|
{
|
|
32
32
|
method: "POST",
|
|
33
33
|
headers: { "content-type": "application/json" },
|
|
34
|
-
body: JSON.stringify({
|
|
34
|
+
body: JSON.stringify({
|
|
35
|
+
urls: Array.isArray(urlOrPathname) ? urlOrPathname : [urlOrPathname]
|
|
36
|
+
}),
|
|
35
37
|
signal: options == null ? void 0 : options.abortSignal
|
|
36
38
|
},
|
|
37
39
|
options
|
|
@@ -39,8 +41,8 @@ async function del(url, options) {
|
|
|
39
41
|
}
|
|
40
42
|
|
|
41
43
|
// src/head.ts
|
|
42
|
-
async function head(
|
|
43
|
-
const searchParams = new URLSearchParams({ url });
|
|
44
|
+
async function head(urlOrPathname, options) {
|
|
45
|
+
const searchParams = new URLSearchParams({ url: urlOrPathname });
|
|
44
46
|
const response = await requestApi(
|
|
45
47
|
`?${searchParams.toString()}`,
|
|
46
48
|
// HEAD can't have body as a response, so we use GET
|
|
@@ -111,7 +113,7 @@ function mapBlobResult(blobResult) {
|
|
|
111
113
|
}
|
|
112
114
|
|
|
113
115
|
// src/copy.ts
|
|
114
|
-
async function copy(
|
|
116
|
+
async function copy(fromUrlOrPathname, toPathname, options) {
|
|
115
117
|
if (!options) {
|
|
116
118
|
throw new BlobError("missing options, see usage");
|
|
117
119
|
}
|
|
@@ -143,7 +145,10 @@ async function copy(fromUrl, toPathname, options) {
|
|
|
143
145
|
if (options.cacheControlMaxAge !== void 0) {
|
|
144
146
|
headers["x-cache-control-max-age"] = options.cacheControlMaxAge.toString();
|
|
145
147
|
}
|
|
146
|
-
const params = new URLSearchParams({
|
|
148
|
+
const params = new URLSearchParams({
|
|
149
|
+
pathname: toPathname,
|
|
150
|
+
fromUrl: fromUrlOrPathname
|
|
151
|
+
});
|
|
147
152
|
const response = await requestApi(
|
|
148
153
|
`?${params.toString()}`,
|
|
149
154
|
{
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/del.ts","../src/head.ts","../src/list.ts","../src/copy.ts","../src/index.ts"],"sourcesContent":["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 url - Blob url or array of blob urls that identify the blobs to be deleted. 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 url: 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({ urls: Array.isArray(url) ? url : [url] }),\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 url - Blob url to lookup.\n * @param options - Additional options for the request.\n */\nexport async function head(\n url: string,\n options?: BlobCommandOptions,\n): Promise<HeadBlobResult> {\n const searchParams = new URLSearchParams({ url });\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 fromUrl - The blob URL 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 fromUrl: 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({ pathname: toPathname, fromUrl });\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,eAAsB,IACpB,KACA,SACe;AACf,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,KAAK,UAAU,EAAE,MAAM,MAAM,QAAQ,GAAG,IAAI,MAAM,CAAC,GAAG,EAAE,CAAC;AAAA,MAC/D,QAAQ,mCAAS;AAAA,IACnB;AAAA,IACA;AAAA,EACF;AACF;;;ACmCA,eAAsB,KACpB,KACA,SACyB;AACzB,QAAM,eAAe,IAAI,gBAAgB,EAAE,IAAI,CAAC;AAEhD,QAAM,WAAW,MAAM;AAAA,IACrB,IAAI,aAAa,SAAS,CAAC;AAAA;AAAA,IAE3B;AAAA,MACE,QAAQ;AAAA,MACR,QAAQ,mCAAS;AAAA,IACnB;AAAA,IACA;AAAA,EACF;AAEA,SAAO;AAAA,IACL,KAAK,SAAS;AAAA,IACd,aAAa,SAAS;AAAA,IACtB,UAAU,SAAS;AAAA,IACnB,MAAM,SAAS;AAAA,IACf,aAAa,SAAS;AAAA,IACtB,oBAAoB,SAAS;AAAA,IAC7B,cAAc,SAAS;AAAA,IACvB,YAAY,IAAI,KAAK,SAAS,UAAU;AAAA,EAC1C;AACF;;;ACkDA,eAAsB,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;AAqBI,IAAM,0BACX,oCAA6D;AAAA,EAC3D,gBAAgB;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF,CAAC;AAwBI,IAAM,aAAa,uBAAiD;AAAA,EACzE,gBAAgB;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF,CAAC;AAsBM,IAAM,0BACX,oCAA2E;AAAA,EACzE,gBAAgB;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF,CAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/del.ts","../src/head.ts","../src/list.ts","../src/copy.ts","../src/index.ts"],"sourcesContent":["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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,eAAsB,IACpB,eACA,SACe;AACf,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,MACE,QAAQ;AAAA,MACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,MAC9C,MAAM,KAAK,UAAU;AAAA,QACnB,MAAM,MAAM,QAAQ,aAAa,IAAI,gBAAgB,CAAC,aAAa;AAAA,MACrE,CAAC;AAAA,MACD,QAAQ,mCAAS;AAAA,IACnB;AAAA,IACA;AAAA,EACF;AACF;;;ACiCA,eAAsB,KACpB,eACA,SACyB;AACzB,QAAM,eAAe,IAAI,gBAAgB,EAAE,KAAK,cAAc,CAAC;AAE/D,QAAM,WAAW,MAAM;AAAA,IACrB,IAAI,aAAa,SAAS,CAAC;AAAA;AAAA,IAE3B;AAAA,MACE,QAAQ;AAAA,MACR,QAAQ,mCAAS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tB,UAAU,SAAS;AAAA,IACnB,aAAa,SAAS;AAAA,IACtB,oBAAoB,SAAS;AAAA,EAC/B;AACF;;;AChCO,IAAM,MAAM,gBAAmC;AAAA,EACpD,gBAAgB;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF,CAAC;AA+CM,IAAM,wBACX,kCAA2D;AAAA,EACzD,gBAAgB;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF,CAAC;AAqBI,IAAM,0BACX,oCAA6D;AAAA,EAC3D,gBAAgB;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF,CAAC;AAwBI,IAAM,aAAa,uBAAiD;AAAA,EACzE,gBAAgB;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF,CAAC;AAsBM,IAAM,0BACX,oCAA2E;AAAA,EACzE,gBAAgB;AAAA,IACd;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF,CAAC;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vercel/blob",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0-4d25be25-20250912070808",
|
|
4
4
|
"description": "The Vercel Blob JavaScript API client",
|
|
5
5
|
"homepage": "https://vercel.com/storage/blob",
|
|
6
6
|
"repository": {
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
"tsconfig": "0.0.0"
|
|
68
68
|
},
|
|
69
69
|
"engines": {
|
|
70
|
-
"node": ">=
|
|
70
|
+
"node": ">=20.18.0"
|
|
71
71
|
},
|
|
72
72
|
"scripts": {
|
|
73
73
|
"build": "tsup && pnpm run copy-shims",
|