@payloadcms/storage-vercel-blob 4.0.0-internal.e55ccef → 4.0.0-internal.ea6e8f8
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/README.md +11 -9
- package/dist/adapter.d.ts +3 -1
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js +113 -19
- package/dist/adapter.js.map +1 -1
- package/dist/authorizeFileOverwrite.d.ts +16 -0
- package/dist/authorizeFileOverwrite.d.ts.map +1 -0
- package/dist/authorizeFileOverwrite.js +117 -0
- package/dist/authorizeFileOverwrite.js.map +1 -0
- package/dist/client/VercelBlobClientUploadHandler.d.ts +3 -8
- package/dist/client/VercelBlobClientUploadHandler.d.ts.map +1 -1
- package/dist/client/VercelBlobClientUploadHandler.js +9 -31
- package/dist/client/VercelBlobClientUploadHandler.js.map +1 -1
- package/dist/copyFile.d.ts +12 -0
- package/dist/copyFile.d.ts.map +1 -0
- package/dist/copyFile.js +86 -0
- package/dist/copyFile.js.map +1 -0
- package/dist/deleteFile.d.ts +2 -5
- package/dist/deleteFile.d.ts.map +1 -1
- package/dist/deleteFile.js +3 -10
- package/dist/deleteFile.js.map +1 -1
- package/dist/generateURL.d.ts +1 -0
- package/dist/generateURL.d.ts.map +1 -1
- package/dist/generateURL.js +13 -9
- package/dist/generateURL.js.map +1 -1
- package/dist/getCollectionSources.d.ts +20 -0
- package/dist/getCollectionSources.d.ts.map +1 -0
- package/dist/getCollectionSources.js +27 -0
- package/dist/getCollectionSources.js.map +1 -0
- package/dist/getFile.d.ts +5 -4
- package/dist/getFile.d.ts.map +1 -1
- package/dist/getFile.js +21 -13
- package/dist/getFile.js.map +1 -1
- package/dist/index.d.ts +11 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +33 -41
- package/dist/index.js.map +1 -1
- package/dist/uploadFile.d.ts +2 -5
- package/dist/uploadFile.d.ts.map +1 -1
- package/dist/uploadFile.js +3 -9
- package/dist/uploadFile.js.map +1 -1
- package/package.json +4 -4
- package/dist/getClientUploadRoute.d.ts +0 -13
- package/dist/getClientUploadRoute.d.ts.map +0 -1
- package/dist/getClientUploadRoute.js +0 -35
- package/dist/getClientUploadRoute.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/copyFile.ts"],"sourcesContent":["import type { PayloadRequest } from 'payload'\n\nimport { BlobNotFoundError, copy, del, head, put } from '@vercel/blob'\n\ntype Args = {\n access: 'public'\n cacheControlMaxAge: number\n from: string\n req?: PayloadRequest\n to: string\n token: string\n}\n\nexport const copyVercelBlobFile = async ({\n access,\n cacheControlMaxAge,\n from,\n req,\n to,\n token,\n}: Args): Promise<void> => {\n if (from === to) {\n throw new Error('Storage copy requires different source and destination keys')\n }\n\n const source = await head(from, { token })\n\n try {\n await head(to, { token })\n throw new Error(`Storage destination already exists: ${to}`)\n } catch (err) {\n if (!isBlobNotFound(err)) {\n throw err\n }\n }\n\n const sourceMaxAge = /(?:^|,)\\s*max-age=(\\d+)/.exec(source.cacheControl)\n let copied: { etag: string; pathname: string } | undefined = await copy(from, to, {\n access,\n addRandomSuffix: false,\n allowOverwrite: false,\n cacheControlMaxAge: sourceMaxAge ? Number(sourceMaxAge[1]) : cacheControlMaxAge,\n contentType: source.contentType,\n token,\n })\n\n try {\n if (copied.pathname !== to) {\n throw new Error(`Vercel Blob assigned an unexpected destination key: ${copied.pathname}`)\n }\n\n let destination = await head(to, { token })\n\n if (destination.size !== source.size) {\n await del(to, { ifMatch: copied.etag, token })\n // The first copy is gone; a rejected fallback must not delete another upload's object.\n copied = undefined\n\n const sourceResponse = await fetch(source.url)\n\n if (!sourceResponse.ok || !sourceResponse.body) {\n throw new Error(`Vercel Blob source is not readable: ${from}`)\n }\n\n copied = await put(to, sourceResponse.body, {\n access,\n addRandomSuffix: false,\n allowOverwrite: false,\n cacheControlMaxAge: sourceMaxAge ? Number(sourceMaxAge[1]) : cacheControlMaxAge,\n contentType: source.contentType,\n token,\n })\n\n if (copied.pathname !== to) {\n throw new Error(`Vercel Blob assigned an unexpected destination key: ${copied.pathname}`)\n }\n\n destination = await head(to, { token })\n\n if (destination.size !== source.size) {\n throw new Error(`Copied Vercel Blob object is not readable at its expected length: ${to}`)\n }\n }\n } catch (err) {\n if (copied) {\n try {\n if (copied.pathname === from || !copied.etag) {\n throw new Error('Vercel Blob copy did not return a safe destination for cleanup')\n }\n await del(copied.pathname, { ifMatch: copied.etag, token })\n } catch (cleanupError) {\n req?.payload.logger.error({\n err: cleanupError,\n msg: `Failed to remove unsuccessful Vercel Blob copy at ${copied.pathname}`,\n })\n }\n }\n throw err\n }\n}\n\nconst isBlobNotFound = (err: unknown): boolean =>\n err instanceof BlobNotFoundError ||\n (err !== null && typeof err === 'object' && 'name' in err && err.name === 'BlobNotFoundError')\n"],"names":["BlobNotFoundError","copy","del","head","put","copyVercelBlobFile","access","cacheControlMaxAge","from","req","to","token","Error","source","err","isBlobNotFound","sourceMaxAge","exec","cacheControl","copied","addRandomSuffix","allowOverwrite","Number","contentType","pathname","destination","size","ifMatch","etag","undefined","sourceResponse","fetch","url","ok","body","cleanupError","payload","logger","error","msg","name"],"mappings":"AAEA,SAASA,iBAAiB,EAAEC,IAAI,EAAEC,GAAG,EAAEC,IAAI,EAAEC,GAAG,QAAQ,eAAc;AAWtE,OAAO,MAAMC,qBAAqB,OAAO,EACvCC,MAAM,EACNC,kBAAkB,EAClBC,IAAI,EACJC,GAAG,EACHC,EAAE,EACFC,KAAK,EACA;IACL,IAAIH,SAASE,IAAI;QACf,MAAM,IAAIE,MAAM;IAClB;IAEA,MAAMC,SAAS,MAAMV,KAAKK,MAAM;QAAEG;IAAM;IAExC,IAAI;QACF,MAAMR,KAAKO,IAAI;YAAEC;QAAM;QACvB,MAAM,IAAIC,MAAM,CAAC,oCAAoC,EAAEF,IAAI;IAC7D,EAAE,OAAOI,KAAK;QACZ,IAAI,CAACC,eAAeD,MAAM;YACxB,MAAMA;QACR;IACF;IAEA,MAAME,eA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;IACF,EAAE,OAAOI,KAAK;QACZ,IAAIK,QAAQ;YACV,IAAI;gBACF,IAAIA,OAAOK,QAAQ,KAAKhB,QAAQ,CAACW,OAAOS,IAAI,EAAE;oBAC5C,MAAM,IAAIhB,MAAM;gBAClB;gBACA,MAAMV,IAAIiB,OAAOK,QAAQ,EAAE;oBAAEG,SAASR,OAAOS,IAAI;oBAAEjB;gBAAM;YAC3D,EAAE,OAAOwB,cAAc;gBACrB1B,KAAK2B,QAAQC,OAAOC,MAAM;oBACxBxB,KAAKqB;oBACLI,KAAK,CAAC,kDAAkD,EAAEpB,OAAOK,QAAQ,EAAE;gBAC7E;YACF;QACF;QACA,MAAMV;IACR;AACF,EAAC;AAED,MAAMC,iBAAiB,CAACD,MACtBA,eAAed,qBACdc,QAAQ,QAAQ,OAAOA,QAAQ,YAAY,UAAUA,OAAOA,IAAI0B,IAAI,KAAK"}
|
package/dist/deleteFile.d.ts
CHANGED
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
interface DeleteFileArgs {
|
|
2
2
|
baseUrl: string;
|
|
3
|
-
|
|
4
|
-
docPrefix: string;
|
|
5
|
-
filename: string;
|
|
3
|
+
storageFilePath: string;
|
|
6
4
|
token: string;
|
|
7
|
-
useCompositePrefixes?: boolean;
|
|
8
5
|
}
|
|
9
|
-
export declare function deleteFile({ baseUrl,
|
|
6
|
+
export declare function deleteFile({ baseUrl, storageFilePath, token, }: DeleteFileArgs): Promise<void>;
|
|
10
7
|
export {};
|
|
11
8
|
//# sourceMappingURL=deleteFile.d.ts.map
|
package/dist/deleteFile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deleteFile.d.ts","sourceRoot":"","sources":["../src/deleteFile.ts"],"names":[],"mappings":"AAIA,UAAU,cAAc;IACtB,OAAO,EAAE,MAAM,CAAA;IACf,
|
|
1
|
+
{"version":3,"file":"deleteFile.d.ts","sourceRoot":"","sources":["../src/deleteFile.ts"],"names":[],"mappings":"AAIA,UAAU,cAAc;IACtB,OAAO,EAAE,MAAM,CAAA;IACf,eAAe,EAAE,MAAM,CAAA;IACvB,KAAK,EAAE,MAAM,CAAA;CACd;AAED,wBAAsB,UAAU,CAAC,EAC/B,OAAO,EACP,eAAe,EACf,KAAK,GACN,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhC"}
|
package/dist/deleteFile.js
CHANGED
|
@@ -1,14 +1,7 @@
|
|
|
1
1
|
import { del } from '@vercel/blob';
|
|
2
|
-
import {
|
|
3
|
-
export async function deleteFile({ baseUrl,
|
|
4
|
-
|
|
5
|
-
baseUrl,
|
|
6
|
-
collectionPrefix,
|
|
7
|
-
filename,
|
|
8
|
-
prefix: docPrefix,
|
|
9
|
-
useCompositePrefixes
|
|
10
|
-
});
|
|
11
|
-
await del(fileUrl, {
|
|
2
|
+
import { buildBlobUrl } from './generateURL.js';
|
|
3
|
+
export async function deleteFile({ baseUrl, storageFilePath, token }) {
|
|
4
|
+
await del(buildBlobUrl(baseUrl, storageFilePath), {
|
|
12
5
|
token
|
|
13
6
|
});
|
|
14
7
|
}
|
package/dist/deleteFile.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/deleteFile.ts"],"sourcesContent":["import { del } from '@vercel/blob'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../src/deleteFile.ts"],"sourcesContent":["import { del } from '@vercel/blob'\n\nimport { buildBlobUrl } from './generateURL.js'\n\ninterface DeleteFileArgs {\n baseUrl: string\n storageFilePath: string\n token: string\n}\n\nexport async function deleteFile({\n baseUrl,\n storageFilePath,\n token,\n}: DeleteFileArgs): Promise<void> {\n await del(buildBlobUrl(baseUrl, storageFilePath), { token })\n}\n"],"names":["del","buildBlobUrl","deleteFile","baseUrl","storageFilePath","token"],"mappings":"AAAA,SAASA,GAAG,QAAQ,eAAc;AAElC,SAASC,YAAY,QAAQ,mBAAkB;AAQ/C,OAAO,eAAeC,WAAW,EAC/BC,OAAO,EACPC,eAAe,EACfC,KAAK,EACU;IACf,MAAML,IAAIC,aAAaE,SAASC,kBAAkB;QAAEC;IAAM;AAC5D"}
|
package/dist/generateURL.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ interface GenerateURLArgs {
|
|
|
5
5
|
prefix: string;
|
|
6
6
|
useCompositePrefixes?: boolean;
|
|
7
7
|
}
|
|
8
|
+
export declare function buildBlobUrl(baseUrl: string, storageFilePath: string): string;
|
|
8
9
|
export declare function generateURL({ baseUrl, collectionPrefix, filename, prefix, useCompositePrefixes, }: GenerateURLArgs): string;
|
|
9
10
|
export {};
|
|
10
11
|
//# sourceMappingURL=generateURL.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateURL.d.ts","sourceRoot":"","sources":["../src/generateURL.ts"],"names":[],"mappings":"AAGA,UAAU,eAAe;IACvB,OAAO,EAAE,MAAM,CAAA;IACf,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,wBAAgB,WAAW,CAAC,EAC1B,OAAO,EACP,gBAAqB,EACrB,QAAQ,EACR,MAAM,EACN,oBAA4B,GAC7B,EAAE,eAAe,GAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"generateURL.d.ts","sourceRoot":"","sources":["../src/generateURL.ts"],"names":[],"mappings":"AAGA,UAAU,eAAe;IACvB,OAAO,EAAE,MAAM,CAAA;IACf,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAGD,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,MAAM,CAU7E;AAED,wBAAgB,WAAW,CAAC,EAC1B,OAAO,EACP,gBAAqB,EACrB,QAAQ,EACR,MAAM,EACN,oBAA4B,GAC7B,EAAE,eAAe,GAAG,MAAM,CAS1B"}
|
package/dist/generateURL.js
CHANGED
|
@@ -1,19 +1,23 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { buildStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
2
2
|
import path from 'path';
|
|
3
|
+
// Builds the public blob URL for a storage path, URL-encoding only the filename segment.
|
|
4
|
+
export function buildBlobUrl(baseUrl, storageFilePath) {
|
|
5
|
+
// example: "my-collection/my-doc/my file.jpg" -> "my-collection/my-doc"
|
|
6
|
+
const dir = path.posix.dirname(storageFilePath);
|
|
7
|
+
// example: "my file.jpg" -> "my%20file.jpg"
|
|
8
|
+
const encodedFilename = encodeURIComponent(path.posix.basename(storageFilePath));
|
|
9
|
+
// example: "my-collection/my-doc/my%20file.jpg"
|
|
10
|
+
const storageFilePathWithEncodedFilename = dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename);
|
|
11
|
+
return `${baseUrl}/${storageFilePathWithEncodedFilename}`;
|
|
12
|
+
}
|
|
3
13
|
export function generateURL({ baseUrl, collectionPrefix = '', filename, prefix, useCompositePrefixes = false }) {
|
|
4
|
-
const {
|
|
14
|
+
const { storageFilePath } = buildStoragePathData({
|
|
5
15
|
collectionPrefix,
|
|
6
16
|
docPrefix: prefix,
|
|
7
17
|
filename,
|
|
8
18
|
useCompositePrefixes
|
|
9
19
|
});
|
|
10
|
-
|
|
11
|
-
const dir = path.posix.dirname(fileKeyWithPrefix);
|
|
12
|
-
// example: "my file.jpg" -> "my%20file.jpg"
|
|
13
|
-
const encodedFilename = encodeURIComponent(path.posix.basename(fileKeyWithPrefix));
|
|
14
|
-
// example: "my-collection/my-doc/my%20file.jpg"
|
|
15
|
-
const fileKeyWithEncodedFilename = dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename);
|
|
16
|
-
return `${baseUrl}/${fileKeyWithEncodedFilename}`;
|
|
20
|
+
return buildBlobUrl(baseUrl, storageFilePath);
|
|
17
21
|
}
|
|
18
22
|
|
|
19
23
|
//# sourceMappingURL=generateURL.js.map
|
package/dist/generateURL.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/generateURL.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../src/generateURL.ts"],"sourcesContent":["import { buildStoragePathData } from '@payloadcms/plugin-cloud-storage/utilities'\nimport path from 'path'\n\ninterface GenerateURLArgs {\n baseUrl: string\n collectionPrefix?: string\n filename: string\n prefix: string\n useCompositePrefixes?: boolean\n}\n\n// Builds the public blob URL for a storage path, URL-encoding only the filename segment.\nexport function buildBlobUrl(baseUrl: string, storageFilePath: string): string {\n // example: \"my-collection/my-doc/my file.jpg\" -> \"my-collection/my-doc\"\n const dir = path.posix.dirname(storageFilePath)\n // example: \"my file.jpg\" -> \"my%20file.jpg\"\n const encodedFilename = encodeURIComponent(path.posix.basename(storageFilePath))\n // example: \"my-collection/my-doc/my%20file.jpg\"\n const storageFilePathWithEncodedFilename =\n dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename)\n\n return `${baseUrl}/${storageFilePathWithEncodedFilename}`\n}\n\nexport function generateURL({\n baseUrl,\n collectionPrefix = '',\n filename,\n prefix,\n useCompositePrefixes = false,\n}: GenerateURLArgs): string {\n const { storageFilePath } = buildStoragePathData({\n collectionPrefix,\n docPrefix: prefix,\n filename,\n useCompositePrefixes,\n })\n\n return buildBlobUrl(baseUrl, storageFilePath)\n}\n"],"names":["buildStoragePathData","path","buildBlobUrl","baseUrl","storageFilePath","dir","posix","dirname","encodedFilename","encodeURIComponent","basename","storageFilePathWithEncodedFilename","join","generateURL","collectionPrefix","filename","prefix","useCompositePrefixes","docPrefix"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,6CAA4C;AACjF,OAAOC,UAAU,OAAM;AAUvB,yFAAyF;AACzF,OAAO,SAASC,aAAaC,OAAe,EAAEC,eAAuB;IACnE,wEAAwE;IACxE,MAAMC,MAAMJ,KAAKK,KAAK,CAACC,OAAO,CAACH;IAC/B,4CAA4C;IAC5C,MAAMI,kBAAkBC,mBAAmBR,KAAKK,KAAK,CAACI,QAAQ,CAACN;IAC/D,gDAAgD;IAChD,MAAMO,qCACJN,QAAQ,MAAMG,kBAAkBP,KAAKK,KAAK,CAACM,IAAI,CAACP,KAAKG;IAEvD,OAAO,GAAGL,QAAQ,CAAC,EAAEQ,oCAAoC;AAC3D;AAEA,OAAO,SAASE,YAAY,EAC1BV,OAAO,EACPW,mBAAmB,EAAE,EACrBC,QAAQ,EACRC,MAAM,EACNC,uBAAuB,KAAK,EACZ;IAChB,MAAM,EAAEb,eAAe,EAAE,GAAGJ,qBAAqB;QAC/Cc;QACAI,WAAWF;QACXD;QACAE;IACF;IAEA,OAAOf,aAAaC,SAASC;AAC/B"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { StorageAdapter } from 'payload';
|
|
2
|
+
import type { VercelBlobCollectionSource } from './authorizeFileOverwrite.js';
|
|
3
|
+
type VercelBlobStorageMetadata = {
|
|
4
|
+
collections: Record<string, {
|
|
5
|
+
prefix?: string;
|
|
6
|
+
} | true | undefined>;
|
|
7
|
+
enabled: boolean;
|
|
8
|
+
storeId?: string;
|
|
9
|
+
useCompositePrefixes: boolean;
|
|
10
|
+
};
|
|
11
|
+
export declare const vercelBlobStorageMetadata: unique symbol;
|
|
12
|
+
export type InternalVercelBlobStorageAdapter = {
|
|
13
|
+
[vercelBlobStorageMetadata]: VercelBlobStorageMetadata;
|
|
14
|
+
} & StorageAdapter;
|
|
15
|
+
export declare const getCollectionSources: ({ currentAdapter, storageAdapters, }: {
|
|
16
|
+
currentAdapter: InternalVercelBlobStorageAdapter;
|
|
17
|
+
storageAdapters?: StorageAdapter[];
|
|
18
|
+
}) => VercelBlobCollectionSource[];
|
|
19
|
+
export {};
|
|
20
|
+
//# sourceMappingURL=getCollectionSources.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"getCollectionSources.d.ts","sourceRoot":"","sources":["../src/getCollectionSources.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAE7C,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,6BAA6B,CAAA;AAE7E,KAAK,yBAAyB,GAAG;IAC/B,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,GAAG,SAAS,CAAC,CAAA;IACnE,OAAO,EAAE,OAAO,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,oBAAoB,EAAE,OAAO,CAAA;CAC9B,CAAA;AAED,eAAO,MAAM,yBAAyB,eAAsC,CAAA;AAE5E,MAAM,MAAM,gCAAgC,GAAG;IAC7C,CAAC,yBAAyB,CAAC,EAAE,yBAAyB,CAAA;CACvD,GAAG,cAAc,CAAA;AAMlB,eAAO,MAAM,oBAAoB,yCAG9B;IACD,cAAc,EAAE,gCAAgC,CAAA;IAChD,eAAe,CAAC,EAAE,cAAc,EAAE,CAAA;CACnC,KAAG,0BAA0B,EAoB7B,CAAA"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export const vercelBlobStorageMetadata = Symbol('vercelBlobStorageMetadata');
|
|
2
|
+
const isInternalVercelBlobStorageAdapter = (adapter)=>vercelBlobStorageMetadata in adapter;
|
|
3
|
+
export const getCollectionSources = ({ currentAdapter, storageAdapters = [] })=>{
|
|
4
|
+
const currentMetadata = currentAdapter[vercelBlobStorageMetadata];
|
|
5
|
+
const adapters = new Set([
|
|
6
|
+
currentAdapter,
|
|
7
|
+
...storageAdapters
|
|
8
|
+
]);
|
|
9
|
+
return [
|
|
10
|
+
...adapters
|
|
11
|
+
].flatMap((adapter)=>{
|
|
12
|
+
if (!isInternalVercelBlobStorageAdapter(adapter)) {
|
|
13
|
+
return [];
|
|
14
|
+
}
|
|
15
|
+
const metadata = adapter[vercelBlobStorageMetadata];
|
|
16
|
+
if (!metadata.enabled || metadata.storeId !== currentMetadata.storeId) {
|
|
17
|
+
return [];
|
|
18
|
+
}
|
|
19
|
+
return Object.entries(metadata.collections).map(([collectionSlug, options])=>({
|
|
20
|
+
collectionPrefix: options === true ? '' : options?.prefix || '',
|
|
21
|
+
collectionSlug,
|
|
22
|
+
useCompositePrefixes: metadata.useCompositePrefixes
|
|
23
|
+
}));
|
|
24
|
+
});
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=getCollectionSources.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/getCollectionSources.ts"],"sourcesContent":["import type { StorageAdapter } from 'payload'\n\nimport type { VercelBlobCollectionSource } from './authorizeFileOverwrite.js'\n\ntype VercelBlobStorageMetadata = {\n collections: Record<string, { prefix?: string } | true | undefined>\n enabled: boolean\n storeId?: string\n useCompositePrefixes: boolean\n}\n\nexport const vercelBlobStorageMetadata = Symbol('vercelBlobStorageMetadata')\n\nexport type InternalVercelBlobStorageAdapter = {\n [vercelBlobStorageMetadata]: VercelBlobStorageMetadata\n} & StorageAdapter\n\nconst isInternalVercelBlobStorageAdapter = (\n adapter: StorageAdapter,\n): adapter is InternalVercelBlobStorageAdapter => vercelBlobStorageMetadata in adapter\n\nexport const getCollectionSources = ({\n currentAdapter,\n storageAdapters = [],\n}: {\n currentAdapter: InternalVercelBlobStorageAdapter\n storageAdapters?: StorageAdapter[]\n}): VercelBlobCollectionSource[] => {\n const currentMetadata = currentAdapter[vercelBlobStorageMetadata]\n const adapters = new Set([currentAdapter, ...storageAdapters])\n\n return [...adapters].flatMap((adapter) => {\n if (!isInternalVercelBlobStorageAdapter(adapter)) {\n return []\n }\n\n const metadata = adapter[vercelBlobStorageMetadata]\n if (!metadata.enabled || metadata.storeId !== currentMetadata.storeId) {\n return []\n }\n\n return Object.entries(metadata.collections).map(([collectionSlug, options]) => ({\n collectionPrefix: options === true ? '' : options?.prefix || '',\n collectionSlug,\n useCompositePrefixes: metadata.useCompositePrefixes,\n }))\n })\n}\n"],"names":["vercelBlobStorageMetadata","Symbol","isInternalVercelBlobStorageAdapter","adapter","getCollectionSources","currentAdapter","storageAdapters","currentMetadata","adapters","Set","flatMap","metadata","enabled","storeId","Object","entries","collections","map","collectionSlug","options","collectionPrefix","prefix","useCompositePrefixes"],"mappings":"AAWA,OAAO,MAAMA,4BAA4BC,OAAO,6BAA4B;AAM5E,MAAMC,qCAAqC,CACzCC,UACgDH,6BAA6BG;AAE/E,OAAO,MAAMC,uBAAuB,CAAC,EACnCC,cAAc,EACdC,kBAAkB,EAAE,EAIrB;IACC,MAAMC,kBAAkBF,cAAc,CAACL,0BAA0B;IACjE,MAAMQ,WAAW,IAAIC,IAAI;QAACJ;WAAmBC;KAAgB;IAE7D,OAAO;WAAIE;KAAS,CAACE,OAAO,CAAC,CAACP;QAC5B,IAAI,CAACD,mCAAmCC,UAAU;YAChD,OAAO,EAAE;QACX;QAEA,MAAMQ,WAAWR,OAAO,CAACH,0BAA0B;QACnD,IAAI,CAACW,SAASC,OAAO,IAAID,SAASE,OAAO,KAAKN,gBAAgBM,OAAO,EAAE;YACrE,OAAO,EAAE;QACX;QAEA,OAAOC,OAAOC,OAAO,CAACJ,SAASK,WAAW,EAAEC,GAAG,CAAC,CAAC,CAACC,gBAAgBC,QAAQ,GAAM,CAAA;gBAC9EC,kBAAkBD,YAAY,OAAO,KAAKA,SAASE,UAAU;gBAC7DH;gBACAI,sBAAsBX,SAASW,oBAAoB;YACrD,CAAA;IACF;AACF,EAAC"}
|
package/dist/getFile.d.ts
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
|
-
import type { CollectionConfig, PayloadRequest } from 'payload';
|
|
1
|
+
import type { CollectionConfig, FileHandlerOperation, PayloadRequest, TypeWithID } from 'payload';
|
|
2
2
|
interface GetFileArgs {
|
|
3
3
|
baseUrl: string;
|
|
4
4
|
cacheControlMaxAge: number;
|
|
5
|
-
clientUploadContext?: unknown;
|
|
6
5
|
collection: CollectionConfig;
|
|
7
6
|
collectionPrefix?: string;
|
|
7
|
+
doc?: TypeWithID;
|
|
8
8
|
filename: string;
|
|
9
9
|
incomingHeaders?: Headers;
|
|
10
|
-
|
|
10
|
+
operation?: FileHandlerOperation;
|
|
11
11
|
req: PayloadRequest;
|
|
12
12
|
token: string;
|
|
13
|
+
uploadReference?: unknown;
|
|
13
14
|
useCompositePrefixes?: boolean;
|
|
14
15
|
}
|
|
15
|
-
export declare function getFile({ baseUrl, cacheControlMaxAge,
|
|
16
|
+
export declare function getFile({ baseUrl, cacheControlMaxAge, collection, collectionPrefix, doc, filename, incomingHeaders, operation, req, token, uploadReference, useCompositePrefixes, }: GetFileArgs): Promise<Response>;
|
|
16
17
|
export {};
|
|
17
18
|
//# sourceMappingURL=getFile.d.ts.map
|
package/dist/getFile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getFile.d.ts","sourceRoot":"","sources":["../src/getFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"getFile.d.ts","sourceRoot":"","sources":["../src/getFile.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAQjG,UAAU,WAAW;IACnB,OAAO,EAAE,MAAM,CAAA;IACf,kBAAkB,EAAE,MAAM,CAAA;IAC1B,UAAU,EAAE,gBAAgB,CAAA;IAC5B,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,GAAG,CAAC,EAAE,UAAU,CAAA;IAChB,QAAQ,EAAE,MAAM,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,SAAS,CAAC,EAAE,oBAAoB,CAAA;IAChC,GAAG,EAAE,cAAc,CAAA;IACnB,KAAK,EAAE,MAAM,CAAA;IACb,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,wBAAsB,OAAO,CAAC,EAC5B,OAAO,EACP,kBAAkB,EAClB,UAAU,EACV,gBAAqB,EACrB,GAAG,EACH,QAAQ,EACR,eAAe,EACf,SAAkB,EAClB,GAAG,EACH,KAAK,EACL,eAAe,EACf,oBAA4B,GAC7B,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsGjC"}
|
package/dist/getFile.js
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
import { getFilePrefix as getDocPrefix } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
2
2
|
import { BlobNotFoundError, head } from '@vercel/blob';
|
|
3
|
-
import { getRangeRequestInfo } from 'payload/internal';
|
|
3
|
+
import { getRangeRequestInfo, isXmlMimeType, uploadContentSecurityPolicy } from 'payload/internal';
|
|
4
4
|
import { generateURL } from './generateURL.js';
|
|
5
|
-
export async function getFile({ baseUrl, cacheControlMaxAge,
|
|
5
|
+
export async function getFile({ baseUrl, cacheControlMaxAge, collection, collectionPrefix = '', doc, filename, incomingHeaders, operation = 'read', req, token, uploadReference, useCompositePrefixes = false }) {
|
|
6
|
+
const isTransformSource = operation === 'transform';
|
|
6
7
|
try {
|
|
7
8
|
const docPrefix = await getDocPrefix({
|
|
8
|
-
clientUploadContext,
|
|
9
9
|
collection,
|
|
10
|
+
collectionPrefix,
|
|
11
|
+
doc,
|
|
10
12
|
filename,
|
|
11
|
-
|
|
12
|
-
|
|
13
|
+
req,
|
|
14
|
+
uploadReference,
|
|
15
|
+
useCompositePrefixes
|
|
13
16
|
});
|
|
14
17
|
const fileUrl = generateURL({
|
|
15
18
|
baseUrl,
|
|
@@ -26,8 +29,7 @@ export async function getFile({ baseUrl, cacheControlMaxAge, clientUploadContext
|
|
|
26
29
|
const uploadedAtString = uploadedAt.toISOString();
|
|
27
30
|
const fileKeyForETag = fileUrl.replace(`${baseUrl}/`, '');
|
|
28
31
|
const ETag = `"${fileKeyForETag}-${uploadedAtString}"`;
|
|
29
|
-
|
|
30
|
-
const rangeHeader = req.headers.get('range');
|
|
32
|
+
const rangeHeader = isTransformSource ? null : req.headers.get('range');
|
|
31
33
|
const rangeResult = getRangeRequestInfo({
|
|
32
34
|
fileSize: size,
|
|
33
35
|
rangeHeader
|
|
@@ -39,7 +41,6 @@ export async function getFile({ baseUrl, cacheControlMaxAge, clientUploadContext
|
|
|
39
41
|
});
|
|
40
42
|
}
|
|
41
43
|
let headers = new Headers(incomingHeaders);
|
|
42
|
-
// Add range-related headers from the result
|
|
43
44
|
for (const [key, value] of Object.entries(rangeResult.headers)){
|
|
44
45
|
headers.append(key, value);
|
|
45
46
|
}
|
|
@@ -47,16 +48,16 @@ export async function getFile({ baseUrl, cacheControlMaxAge, clientUploadContext
|
|
|
47
48
|
headers.append('Content-Disposition', contentDisposition);
|
|
48
49
|
headers.append('Content-Type', contentType);
|
|
49
50
|
headers.append('ETag', ETag);
|
|
50
|
-
//
|
|
51
|
-
if (contentType
|
|
52
|
-
headers.append('Content-Security-Policy',
|
|
51
|
+
// Apply a restrictive policy to XML-family responses served through Payload.
|
|
52
|
+
if (isXmlMimeType(contentType)) {
|
|
53
|
+
headers.append('Content-Security-Policy', uploadContentSecurityPolicy);
|
|
53
54
|
}
|
|
54
|
-
if (collection.upload && typeof collection.upload === 'object' && typeof collection.upload.modifyResponseHeaders === 'function') {
|
|
55
|
+
if (!isTransformSource && collection.upload && typeof collection.upload === 'object' && typeof collection.upload.modifyResponseHeaders === 'function') {
|
|
55
56
|
headers = collection.upload.modifyResponseHeaders({
|
|
56
57
|
headers
|
|
57
58
|
}) || headers;
|
|
58
59
|
}
|
|
59
|
-
if (etagFromHeaders && etagFromHeaders === ETag) {
|
|
60
|
+
if (!isTransformSource && etagFromHeaders && etagFromHeaders === ETag) {
|
|
60
61
|
return new Response(null, {
|
|
61
62
|
headers,
|
|
62
63
|
status: 304
|
|
@@ -72,6 +73,13 @@ export async function getFile({ baseUrl, cacheControlMaxAge, clientUploadContext
|
|
|
72
73
|
}
|
|
73
74
|
});
|
|
74
75
|
if (!response.ok || !response.body) {
|
|
76
|
+
// A transformer needs the real failure status; masking it as 204 is only safe for a plain download.
|
|
77
|
+
if (isTransformSource) {
|
|
78
|
+
return new Response(null, {
|
|
79
|
+
status: response.status,
|
|
80
|
+
statusText: response.statusText
|
|
81
|
+
});
|
|
82
|
+
}
|
|
75
83
|
return new Response(null, {
|
|
76
84
|
status: 204,
|
|
77
85
|
statusText: 'No Content'
|
package/dist/getFile.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/getFile.ts"],"sourcesContent":["import type { CollectionConfig, PayloadRequest } from 'payload'\n\nimport { getFilePrefix as getDocPrefix } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { BlobNotFoundError, head } from '@vercel/blob'\nimport { getRangeRequestInfo } from 'payload/internal'\n\nimport { generateURL } from './generateURL.js'\n\ninterface GetFileArgs {\n baseUrl: string\n cacheControlMaxAge: number\n
|
|
1
|
+
{"version":3,"sources":["../src/getFile.ts"],"sourcesContent":["import type { CollectionConfig, FileHandlerOperation, PayloadRequest, TypeWithID } from 'payload'\n\nimport { getFilePrefix as getDocPrefix } from '@payloadcms/plugin-cloud-storage/utilities'\nimport { BlobNotFoundError, head } from '@vercel/blob'\nimport { getRangeRequestInfo, isXmlMimeType, uploadContentSecurityPolicy } from 'payload/internal'\n\nimport { generateURL } from './generateURL.js'\n\ninterface GetFileArgs {\n baseUrl: string\n cacheControlMaxAge: number\n collection: CollectionConfig\n collectionPrefix?: string\n doc?: TypeWithID\n filename: string\n incomingHeaders?: Headers\n operation?: FileHandlerOperation\n req: PayloadRequest\n token: string\n uploadReference?: unknown\n useCompositePrefixes?: boolean\n}\n\nexport async function getFile({\n baseUrl,\n cacheControlMaxAge,\n collection,\n collectionPrefix = '',\n doc,\n filename,\n incomingHeaders,\n operation = 'read',\n req,\n token,\n uploadReference,\n useCompositePrefixes = false,\n}: GetFileArgs): Promise<Response> {\n const isTransformSource = operation === 'transform'\n\n try {\n const docPrefix = await getDocPrefix({\n collection,\n collectionPrefix,\n doc,\n filename,\n req,\n uploadReference,\n useCompositePrefixes,\n })\n\n const fileUrl = generateURL({\n baseUrl,\n collectionPrefix,\n filename,\n prefix: docPrefix,\n useCompositePrefixes,\n })\n const etagFromHeaders = req.headers.get('etag') || req.headers.get('if-none-match')\n const blobMetadata = await head(fileUrl, { token })\n const { contentDisposition, contentType, size, uploadedAt } = blobMetadata\n const uploadedAtString = uploadedAt.toISOString()\n const fileKeyForETag = fileUrl.replace(`${baseUrl}/`, '')\n const ETag = `\"${fileKeyForETag}-${uploadedAtString}\"`\n\n const rangeHeader = isTransformSource ? null : req.headers.get('range')\n const rangeResult = getRangeRequestInfo({ fileSize: size, rangeHeader })\n\n if (rangeResult.type === 'invalid') {\n return new Response(null, {\n headers: new Headers(rangeResult.headers),\n status: rangeResult.status,\n })\n }\n\n let headers = new Headers(incomingHeaders)\n\n for (const [key, value] of Object.entries(rangeResult.headers)) {\n headers.append(key, value)\n }\n\n headers.append('Cache-Control', `public, max-age=${cacheControlMaxAge}`)\n headers.append('Content-Disposition', contentDisposition)\n headers.append('Content-Type', contentType)\n headers.append('ETag', ETag)\n\n // Apply a restrictive policy to XML-family responses served through Payload.\n if (isXmlMimeType(contentType)) {\n headers.append('Content-Security-Policy', uploadContentSecurityPolicy)\n }\n\n if (\n !isTransformSource &&\n collection.upload &&\n typeof collection.upload === 'object' &&\n typeof collection.upload.modifyResponseHeaders === 'function'\n ) {\n headers = collection.upload.modifyResponseHeaders({ headers }) || headers\n }\n\n if (!isTransformSource && etagFromHeaders && etagFromHeaders === ETag) {\n return new Response(null, {\n headers,\n status: 304,\n })\n }\n\n const response = await fetch(`${fileUrl}?${uploadedAtString}`, {\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate',\n Pragma: 'no-cache',\n ...(rangeResult.type === 'partial' && {\n Range: `bytes=${rangeResult.rangeStart}-${rangeResult.rangeEnd}`,\n }),\n },\n })\n\n if (!response.ok || !response.body) {\n // A transformer needs the real failure status; masking it as 204 is only safe for a plain download.\n if (isTransformSource) {\n return new Response(null, { status: response.status, statusText: response.statusText })\n }\n\n return new Response(null, { status: 204, statusText: 'No Content' })\n }\n\n headers.append('Last-Modified', uploadedAtString)\n\n return new Response(response.body, {\n headers,\n status: rangeResult.status,\n })\n } catch (err: unknown) {\n if (err instanceof BlobNotFoundError) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n req.payload.logger.error({ err, msg: 'Unexpected error in staticHandler' })\n return new Response('Internal Server Error', { status: 500 })\n }\n}\n"],"names":["getFilePrefix","getDocPrefix","BlobNotFoundError","head","getRangeRequestInfo","isXmlMimeType","uploadContentSecurityPolicy","generateURL","getFile","baseUrl","cacheControlMaxAge","collection","collectionPrefix","doc","filename","incomingHeaders","operation","req","token","uploadReference","useCompositePrefixes","isTransformSource","docPrefix","fileUrl","prefix","etagFromHeaders","headers","get","blobMetadata","contentDisposition","contentType","size","uploadedAt","uploadedAtString","toISOString","fileKeyForETag","replace","ETag","rangeHeader","rangeResult","fileSize","type","Response","Headers","status","key","value","Object","entries","append","upload","modifyResponseHeaders","response","fetch","Pragma","Range","rangeStart","rangeEnd","ok","body","statusText","err","payload","logger","error","msg"],"mappings":"AAEA,SAASA,iBAAiBC,YAAY,QAAQ,6CAA4C;AAC1F,SAASC,iBAAiB,EAAEC,IAAI,QAAQ,eAAc;AACtD,SAASC,mBAAmB,EAAEC,aAAa,EAAEC,2BAA2B,QAAQ,mBAAkB;AAElG,SAASC,WAAW,QAAQ,mBAAkB;AAiB9C,OAAO,eAAeC,QAAQ,EAC5BC,OAAO,EACPC,kBAAkB,EAClBC,UAAU,EACVC,mBAAmB,EAAE,EACrBC,GAAG,EACHC,QAAQ,EACRC,eAAe,EACfC,YAAY,MAAM,EAClBC,GAAG,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AmB;YACpC,OAAO,IAAIwC,SAAS,MAAM;gBAAEE,QAAQ;gBAAKgB,YAAY;YAAY;QACnE;QACA3C,IAAI6C,OAAO,CAACC,MAAM,CAACC,KAAK,CAAC;YAAEH;YAAKI,KAAK;QAAoC;QACzE,OAAO,IAAIvB,SAAS,yBAAyB;YAAEE,QAAQ;QAAI;IAC7D;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -9,21 +9,12 @@ export type VercelBlobStorageOptions = {
|
|
|
9
9
|
*/
|
|
10
10
|
access?: 'public';
|
|
11
11
|
/**
|
|
12
|
-
*
|
|
12
|
+
* Must be false or omitted for enabled adapters with configured collections.
|
|
13
|
+
* Payload requires exact storage paths and allocates unique object folders.
|
|
13
14
|
*
|
|
14
15
|
* @default false
|
|
15
16
|
*/
|
|
16
17
|
addRandomSuffix?: boolean;
|
|
17
|
-
/**
|
|
18
|
-
* When enabled, fields (like the prefix field) will always be inserted into
|
|
19
|
-
* the collection schema regardless of whether the plugin is enabled. This
|
|
20
|
-
* ensures a consistent schema across all environments.
|
|
21
|
-
*
|
|
22
|
-
* This will be enabled by default in Payload v4.
|
|
23
|
-
*
|
|
24
|
-
* @default false
|
|
25
|
-
*/
|
|
26
|
-
alwaysInsertFields?: boolean;
|
|
27
18
|
/**
|
|
28
19
|
* Cache-Control max-age in seconds
|
|
29
20
|
*
|
|
@@ -31,7 +22,7 @@ export type VercelBlobStorageOptions = {
|
|
|
31
22
|
*/
|
|
32
23
|
cacheControlMaxAge?: number;
|
|
33
24
|
/**
|
|
34
|
-
*
|
|
25
|
+
* Upload directly to Vercel Blob instead of through Payload.
|
|
35
26
|
*/
|
|
36
27
|
clientUploads?: ClientUploadsConfig;
|
|
37
28
|
/**
|
|
@@ -54,14 +45,15 @@ export type VercelBlobStorageOptions = {
|
|
|
54
45
|
token: string | undefined;
|
|
55
46
|
/**
|
|
56
47
|
* When true, the collection-level prefix and document-level prefix are combined
|
|
57
|
-
* (compositional). When false (default), document prefix
|
|
58
|
-
* prefix
|
|
48
|
+
* (compositional). When false (default), a document prefix already within the
|
|
49
|
+
* collection prefix is used as-is for new uploads; otherwise it is nested beneath it.
|
|
50
|
+
* Existing files retain their stored prefixes for reads, URLs, and cleanup.
|
|
59
51
|
*
|
|
60
|
-
* Example:
|
|
61
|
-
* - collection prefix: `
|
|
62
|
-
* - document prefix: `
|
|
63
|
-
* - resulting prefix with useCompositePrefixes=true: `
|
|
64
|
-
* - resulting prefix with useCompositePrefixes=false: `
|
|
52
|
+
* Example with a document prefix already contained by the collection prefix:
|
|
53
|
+
* - collection prefix: `uploads/`
|
|
54
|
+
* - document prefix: `uploads/documents/`
|
|
55
|
+
* - resulting prefix with useCompositePrefixes=true: `uploads/uploads/documents/`
|
|
56
|
+
* - resulting prefix with useCompositePrefixes=false: `uploads/documents/`
|
|
65
57
|
*
|
|
66
58
|
* @default false
|
|
67
59
|
*/
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EAEnB,iBAAiB,EAClB,MAAM,wCAAwC,CAAA;AAC/C,OAAO,KAAK,EAAU,cAAc,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EAEnB,iBAAiB,EAClB,MAAM,wCAAwC,CAAA;AAC/C,OAAO,KAAK,EAAU,cAAc,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAW3E,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAA;IAEjB;;;;;OAKG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IAEzB;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAE3B;;OAEG;IACH,aAAa,CAAC,EAAE,mBAAmB,CAAA;IAEnC;;OAEG;IACH,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,IAAI,CAAC,iBAAiB,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,CAAC,CAAA;IAE7F;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB;;;;;;OAMG;IACH,KAAK,EAAE,MAAM,GAAG,SAAS,CAAA;IAEzB;;;;;;;;;;;;;OAaG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,CAAA;AASD,KAAK,wBAAwB,GAAG,CAAC,qBAAqB,EAAE,wBAAwB,KAAK,cAAc,CAAA;AAEnG,eAAO,MAAM,iBAAiB,EAAE,wBA8G/B,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -1,20 +1,19 @@
|
|
|
1
1
|
import { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage';
|
|
2
|
-
import { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities';
|
|
3
2
|
import { createVercelBlobAdapter } from './adapter.js';
|
|
4
|
-
import {
|
|
3
|
+
import { getCollectionSources, vercelBlobStorageMetadata } from './getCollectionSources.js';
|
|
5
4
|
const defaultUploadOptions = {
|
|
6
5
|
access: 'public',
|
|
7
6
|
addRandomSuffix: false,
|
|
8
7
|
cacheControlMaxAge: 60 * 60 * 24 * 365,
|
|
9
8
|
enabled: true
|
|
10
9
|
};
|
|
11
|
-
export const vercelBlobStorage = (options)=>
|
|
10
|
+
export const vercelBlobStorage = (options)=>{
|
|
11
|
+
const storeId = options.token?.match(/^vercel_blob_rw_([a-z\d]+)_[a-z\d]+$/i)?.[1]?.toLowerCase();
|
|
12
|
+
const isPluginDisabled = options.enabled === false || !options.token;
|
|
13
|
+
const storageAdapter = {
|
|
12
14
|
name: 'vercel-blob',
|
|
13
15
|
collections: Object.keys(options.collections),
|
|
14
16
|
init: (incomingConfig)=>{
|
|
15
|
-
// Parse storeId from token
|
|
16
|
-
const storeId = options.token?.match(/^vercel_blob_rw_([a-z\d]+)_[a-z\d]+$/i)?.[1]?.toLowerCase();
|
|
17
|
-
const isPluginDisabled = options.enabled === false || !options.token;
|
|
18
17
|
// Don't throw if the plugin is disabled
|
|
19
18
|
if (!storeId && !isPluginDisabled) {
|
|
20
19
|
throw new Error('Invalid token format for Vercel Blob adapter. Should be vercel_blob_rw_<store_id>_<random_string>.');
|
|
@@ -25,41 +24,23 @@ export const vercelBlobStorage = (options)=>({
|
|
|
25
24
|
};
|
|
26
25
|
// support overriding the base URL for emulator https://github.com/payloadcms/vercel-blob-emulator
|
|
27
26
|
const baseUrl = process.env.STORAGE_VERCEL_BLOB_BASE_URL || `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`;
|
|
28
|
-
initClientUploads({
|
|
29
|
-
clientHandler: '@payloadcms/storage-vercel-blob/client#VercelBlobClientUploadHandler',
|
|
30
|
-
collections: options.collections,
|
|
31
|
-
config: incomingConfig,
|
|
32
|
-
enabled: !isPluginDisabled && Boolean(options.clientUploads),
|
|
33
|
-
extraClientHandlerProps: ()=>({
|
|
34
|
-
addRandomSuffix: !!optionsWithDefaults.addRandomSuffix,
|
|
35
|
-
useCompositePrefixes: !!options.useCompositePrefixes
|
|
36
|
-
}),
|
|
37
|
-
serverHandler: getClientUploadRoute({
|
|
38
|
-
access: typeof options.clientUploads === 'object' ? options.clientUploads.access : undefined,
|
|
39
|
-
addRandomSuffix: optionsWithDefaults.addRandomSuffix,
|
|
40
|
-
cacheControlMaxAge: options.cacheControlMaxAge,
|
|
41
|
-
token: options.token ?? ''
|
|
42
|
-
}),
|
|
43
|
-
serverHandlerPath: '/vercel-blob-client-upload-route'
|
|
44
|
-
});
|
|
45
27
|
// If the plugin is disabled or no token is provided, do not enable the plugin
|
|
46
28
|
if (isPluginDisabled) {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
return incomingConfig;
|
|
29
|
+
const collectionsWithoutAdapter = Object.entries(options.collections).reduce((acc, [slug, collOptions])=>({
|
|
30
|
+
...acc,
|
|
31
|
+
[slug]: {
|
|
32
|
+
...collOptions === true ? {} : collOptions,
|
|
33
|
+
adapter: null
|
|
34
|
+
}
|
|
35
|
+
}), {});
|
|
36
|
+
return cloudStoragePlugin({
|
|
37
|
+
collections: collectionsWithoutAdapter,
|
|
38
|
+
enabled: false,
|
|
39
|
+
useCompositePrefixes: options.useCompositePrefixes
|
|
40
|
+
})(incomingConfig);
|
|
41
|
+
}
|
|
42
|
+
if (options.addRandomSuffix && storageAdapter.collections.length > 0) {
|
|
43
|
+
throw new Error('Vercel Blob addRandomSuffix must be false. Payload requires exact storage paths and already allocates unique object folders.');
|
|
63
44
|
}
|
|
64
45
|
const adapter = createVercelBlobAdapter({
|
|
65
46
|
access: optionsWithDefaults.access ?? 'public',
|
|
@@ -67,6 +48,10 @@ export const vercelBlobStorage = (options)=>({
|
|
|
67
48
|
baseUrl,
|
|
68
49
|
cacheControlMaxAge: optionsWithDefaults.cacheControlMaxAge ?? 60 * 60 * 24 * 365,
|
|
69
50
|
clientUploads: optionsWithDefaults.clientUploads,
|
|
51
|
+
collectionSources: getCollectionSources({
|
|
52
|
+
currentAdapter: storageAdapter,
|
|
53
|
+
storageAdapters: incomingConfig.storage
|
|
54
|
+
}),
|
|
70
55
|
token: options.token,
|
|
71
56
|
useCompositePrefixes: options.useCompositePrefixes
|
|
72
57
|
});
|
|
@@ -95,11 +80,18 @@ export const vercelBlobStorage = (options)=>({
|
|
|
95
80
|
})
|
|
96
81
|
};
|
|
97
82
|
return cloudStoragePlugin({
|
|
98
|
-
alwaysInsertFields: options.alwaysInsertFields,
|
|
99
83
|
collections: collectionsWithAdapter,
|
|
100
84
|
useCompositePrefixes: options.useCompositePrefixes
|
|
101
85
|
})(config);
|
|
86
|
+
},
|
|
87
|
+
[vercelBlobStorageMetadata]: {
|
|
88
|
+
collections: options.collections,
|
|
89
|
+
enabled: !isPluginDisabled,
|
|
90
|
+
storeId,
|
|
91
|
+
useCompositePrefixes: Boolean(options.useCompositePrefixes)
|
|
102
92
|
}
|
|
103
|
-
}
|
|
93
|
+
};
|
|
94
|
+
return storageAdapter;
|
|
95
|
+
};
|
|
104
96
|
|
|
105
97
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n ClientUploadsConfig,\n PluginOptions as CloudStoragePluginOptions,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type { Config, StorageAdapter, UploadCollectionSlug } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { initClientUploads } from '@payloadcms/plugin-cloud-storage/utilities'\n\nimport type { VercelBlobClientUploadHandlerExtra } from './client/VercelBlobClientUploadHandler.js'\n\nimport { createVercelBlobAdapter } from './adapter.js'\nimport { getClientUploadRoute } from './getClientUploadRoute.js'\n\nexport type VercelBlobStorageOptions = {\n /**\n * Access control level. Currently, only 'public' is supported.\n * Vercel plans on adding support for private blobs in the future.\n *\n * @default 'public'\n */\n access?: 'public'\n\n /**\n * Add a random suffix to the uploaded file name in Vercel Blob storage\n *\n * @default false\n */\n addRandomSuffix?: boolean\n\n /**\n * When enabled, fields (like the prefix field) will always be inserted into\n * the collection schema regardless of whether the plugin is enabled. This\n * ensures a consistent schema across all environments.\n *\n * This will be enabled by default in Payload v4.\n *\n * @default false\n */\n alwaysInsertFields?: boolean\n\n /**\n * Cache-Control max-age in seconds\n *\n * @default 365 * 24 * 60 * 60 // (1 Year)\n */\n cacheControlMaxAge?: number\n\n /**\n * Do uploads directly on the client, to bypass limits on Vercel.\n */\n clientUploads?: ClientUploadsConfig\n\n /**\n * Collections to apply the Vercel Blob adapter to\n */\n collections: Partial<Record<UploadCollectionSlug, Omit<CollectionOptions, 'adapter'> | true>>\n\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n /**\n * Vercel Blob storage read/write token\n *\n * Usually process.env.BLOB_READ_WRITE_TOKEN set by Vercel\n *\n * If unset, the plugin will be disabled and will fallback to local storage\n */\n token: string | undefined\n\n /**\n * When true, the collection-level prefix and document-level prefix are combined\n * (compositional). When false (default), document prefix overrides collection\n * prefix entirely.\n *\n * Example:\n * - collection prefix: `collection-prefix/`\n * - document prefix: `document-prefix/`\n * - resulting prefix with useCompositePrefixes=true: `collection-prefix/document-prefix/`\n * - resulting prefix with useCompositePrefixes=false: `document-prefix/`\n *\n * @default false\n */\n useCompositePrefixes?: boolean\n}\n\nconst defaultUploadOptions: Partial<VercelBlobStorageOptions> = {\n access: 'public',\n addRandomSuffix: false,\n cacheControlMaxAge: 60 * 60 * 24 * 365, // 1 year\n enabled: true,\n}\n\ntype VercelBlobStorageFactory = (vercelBlobStorageOpts: VercelBlobStorageOptions) => StorageAdapter\n\nexport const vercelBlobStorage: VercelBlobStorageFactory = (\n options: VercelBlobStorageOptions,\n): StorageAdapter => ({\n name: 'vercel-blob',\n collections: Object.keys(options.collections),\n init: (incomingConfig: Config): Config => {\n // Parse storeId from token\n const storeId = options.token\n ?.match(/^vercel_blob_rw_([a-z\\d]+)_[a-z\\d]+$/i)?.[1]\n ?.toLowerCase()\n\n const isPluginDisabled = options.enabled === false || !options.token\n\n // Don't throw if the plugin is disabled\n if (!storeId && !isPluginDisabled) {\n throw new Error(\n 'Invalid token format for Vercel Blob adapter. Should be vercel_blob_rw_<store_id>_<random_string>.',\n )\n }\n\n const optionsWithDefaults = {\n ...defaultUploadOptions,\n ...options,\n }\n\n // support overriding the base URL for emulator https://github.com/payloadcms/vercel-blob-emulator\n const baseUrl =\n process.env.STORAGE_VERCEL_BLOB_BASE_URL ||\n `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`\n\n initClientUploads<\n VercelBlobClientUploadHandlerExtra,\n VercelBlobStorageOptions['collections'][string]\n >({\n clientHandler: '@payloadcms/storage-vercel-blob/client#VercelBlobClientUploadHandler',\n collections: options.collections,\n config: incomingConfig,\n enabled: !isPluginDisabled && Boolean(options.clientUploads),\n extraClientHandlerProps: () => ({\n addRandomSuffix: !!optionsWithDefaults.addRandomSuffix,\n useCompositePrefixes: !!options.useCompositePrefixes,\n }),\n serverHandler: getClientUploadRoute({\n access:\n typeof options.clientUploads === 'object' ? options.clientUploads.access : undefined,\n addRandomSuffix: optionsWithDefaults.addRandomSuffix,\n cacheControlMaxAge: options.cacheControlMaxAge,\n token: options.token ?? '',\n }),\n serverHandlerPath: '/vercel-blob-client-upload-route',\n })\n\n // If the plugin is disabled or no token is provided, do not enable the plugin\n if (isPluginDisabled) {\n if (options.alwaysInsertFields) {\n const collectionsWithoutAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n options.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: { ...(collOptions === true ? {} : collOptions), adapter: null },\n }),\n {} as Record<string, CollectionOptions>,\n )\n return cloudStoragePlugin({\n alwaysInsertFields: true,\n collections: collectionsWithoutAdapter,\n enabled: false,\n useCompositePrefixes: options.useCompositePrefixes,\n })(incomingConfig)\n }\n return incomingConfig\n }\n\n const adapter = createVercelBlobAdapter({\n access: optionsWithDefaults.access ?? 'public',\n addRandomSuffix: optionsWithDefaults.addRandomSuffix,\n baseUrl,\n cacheControlMaxAge: optionsWithDefaults.cacheControlMaxAge ?? 60 * 60 * 24 * 365,\n clientUploads: optionsWithDefaults.clientUploads,\n token: options.token!,\n useCompositePrefixes: options.useCompositePrefixes,\n })\n\n // Add adapter to each collection option object\n const collectionsWithAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n options.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: {\n ...(collOptions === true ? {} : collOptions),\n adapter,\n },\n }),\n {} as Record<string, CollectionOptions>,\n )\n\n // Set disableLocalStorage: true for collections specified in the plugin options\n const config = {\n ...incomingConfig,\n collections: (incomingConfig.collections || []).map((collection) => {\n if (!collectionsWithAdapter[collection.slug]) {\n return collection\n }\n\n return {\n ...collection,\n upload: {\n ...(typeof collection.upload === 'object' ? collection.upload : {}),\n disableLocalStorage: true,\n },\n }\n }),\n }\n\n return cloudStoragePlugin({\n alwaysInsertFields: options.alwaysInsertFields,\n collections: collectionsWithAdapter,\n useCompositePrefixes: options.useCompositePrefixes,\n })(config)\n },\n})\n"],"names":["cloudStoragePlugin","initClientUploads","createVercelBlobAdapter","getClientUploadRoute","defaultUploadOptions","access","addRandomSuffix","cacheControlMaxAge","enabled","vercelBlobStorage","options","name","collections","Object","keys","init","incomingConfig","storeId","token","match","toLowerCase","isPluginDisabled","Error","optionsWithDefaults","baseUrl","process","env","STORAGE_VERCEL_BLOB_BASE_URL","clientHandler","config","Boolean","clientUploads","extraClientHandlerProps","useCompositePrefixes","serverHandler","undefined","serverHandlerPath","alwaysInsertFields","collectionsWithoutAdapter","entries","reduce","acc","slug","collOptions","adapter","collectionsWithAdapter","map","collection","upload","disableLocalStorage"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,iBAAiB,QAAQ,6CAA4C;AAI9E,SAASC,uBAAuB,QAAQ,eAAc;AACtD,SAASC,oBAAoB,QAAQ,4BAA2B;AA6EhE,MAAMC,uBAA0D;IAC9DC,QAAQ;IACRC,iBAAiB;IACjBC,oBAAoB,KAAK,KAAK,KAAK;IACnCC,SAAS;AACX;AAIA,OAAO,MAAMC,oBAA8C,CACzDC,UACoB,CAAA;QACpBC,MAAM;QACNC,aAAaC,OAAOC,IAAI,CAACJ,QAAQE,WAAW;QAC5CG,MAAM,CAACC;YACL,2BAA2B;YAC3B,MAAMC,UAAUP,QAAQQ,KAAK,EACzBC,MAAM,0CAA0C,CAAC,EAAE,EAC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;QACL;IACF,CAAA,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n ClientUploadsConfig,\n PluginOptions as CloudStoragePluginOptions,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type { Config, StorageAdapter, UploadCollectionSlug } from 'payload'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\n\nimport { createVercelBlobAdapter } from './adapter.js'\nimport {\n getCollectionSources,\n type InternalVercelBlobStorageAdapter,\n vercelBlobStorageMetadata,\n} from './getCollectionSources.js'\n\nexport type VercelBlobStorageOptions = {\n /**\n * Access control level. Currently, only 'public' is supported.\n * Vercel plans on adding support for private blobs in the future.\n *\n * @default 'public'\n */\n access?: 'public'\n\n /**\n * Must be false or omitted for enabled adapters with configured collections.\n * Payload requires exact storage paths and allocates unique object folders.\n *\n * @default false\n */\n addRandomSuffix?: boolean\n\n /**\n * Cache-Control max-age in seconds\n *\n * @default 365 * 24 * 60 * 60 // (1 Year)\n */\n cacheControlMaxAge?: number\n\n /**\n * Upload directly to Vercel Blob instead of through Payload.\n */\n clientUploads?: ClientUploadsConfig\n\n /**\n * Collections to apply the Vercel Blob adapter to\n */\n collections: Partial<Record<UploadCollectionSlug, Omit<CollectionOptions, 'adapter'> | true>>\n\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n /**\n * Vercel Blob storage read/write token\n *\n * Usually process.env.BLOB_READ_WRITE_TOKEN set by Vercel\n *\n * If unset, the plugin will be disabled and will fallback to local storage\n */\n token: string | undefined\n\n /**\n * When true, the collection-level prefix and document-level prefix are combined\n * (compositional). When false (default), a document prefix already within the\n * collection prefix is used as-is for new uploads; otherwise it is nested beneath it.\n * Existing files retain their stored prefixes for reads, URLs, and cleanup.\n *\n * Example with a document prefix already contained by the collection prefix:\n * - collection prefix: `uploads/`\n * - document prefix: `uploads/documents/`\n * - resulting prefix with useCompositePrefixes=true: `uploads/uploads/documents/`\n * - resulting prefix with useCompositePrefixes=false: `uploads/documents/`\n *\n * @default false\n */\n useCompositePrefixes?: boolean\n}\n\nconst defaultUploadOptions: Partial<VercelBlobStorageOptions> = {\n access: 'public',\n addRandomSuffix: false,\n cacheControlMaxAge: 60 * 60 * 24 * 365, // 1 year\n enabled: true,\n}\n\ntype VercelBlobStorageFactory = (vercelBlobStorageOpts: VercelBlobStorageOptions) => StorageAdapter\n\nexport const vercelBlobStorage: VercelBlobStorageFactory = (\n options: VercelBlobStorageOptions,\n): StorageAdapter => {\n const storeId = options.token?.match(/^vercel_blob_rw_([a-z\\d]+)_[a-z\\d]+$/i)?.[1]?.toLowerCase()\n const isPluginDisabled = options.enabled === false || !options.token\n const storageAdapter: InternalVercelBlobStorageAdapter = {\n name: 'vercel-blob',\n collections: Object.keys(options.collections),\n init: (incomingConfig: Config): Config => {\n // Don't throw if the plugin is disabled\n if (!storeId && !isPluginDisabled) {\n throw new Error(\n 'Invalid token format for Vercel Blob adapter. Should be vercel_blob_rw_<store_id>_<random_string>.',\n )\n }\n\n const optionsWithDefaults = {\n ...defaultUploadOptions,\n ...options,\n }\n\n // support overriding the base URL for emulator https://github.com/payloadcms/vercel-blob-emulator\n const baseUrl =\n process.env.STORAGE_VERCEL_BLOB_BASE_URL ||\n `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`\n\n // If the plugin is disabled or no token is provided, do not enable the plugin\n if (isPluginDisabled) {\n const collectionsWithoutAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n options.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: { ...(collOptions === true ? {} : collOptions), adapter: null },\n }),\n {} as Record<string, CollectionOptions>,\n )\n return cloudStoragePlugin({\n collections: collectionsWithoutAdapter,\n enabled: false,\n useCompositePrefixes: options.useCompositePrefixes,\n })(incomingConfig)\n }\n\n if (options.addRandomSuffix && storageAdapter.collections.length > 0) {\n throw new Error(\n 'Vercel Blob addRandomSuffix must be false. Payload requires exact storage paths and already allocates unique object folders.',\n )\n }\n\n const adapter = createVercelBlobAdapter({\n access: optionsWithDefaults.access ?? 'public',\n addRandomSuffix: optionsWithDefaults.addRandomSuffix,\n baseUrl,\n cacheControlMaxAge: optionsWithDefaults.cacheControlMaxAge ?? 60 * 60 * 24 * 365,\n clientUploads: optionsWithDefaults.clientUploads,\n collectionSources: getCollectionSources({\n currentAdapter: storageAdapter,\n storageAdapters: incomingConfig.storage,\n }),\n token: options.token!,\n useCompositePrefixes: options.useCompositePrefixes,\n })\n\n // Add adapter to each collection option object\n const collectionsWithAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n options.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: {\n ...(collOptions === true ? {} : collOptions),\n adapter,\n },\n }),\n {} as Record<string, CollectionOptions>,\n )\n\n // Set disableLocalStorage: true for collections specified in the plugin options\n const config = {\n ...incomingConfig,\n collections: (incomingConfig.collections || []).map((collection) => {\n if (!collectionsWithAdapter[collection.slug]) {\n return collection\n }\n\n return {\n ...collection,\n upload: {\n ...(typeof collection.upload === 'object' ? collection.upload : {}),\n disableLocalStorage: true,\n },\n }\n }),\n }\n\n return cloudStoragePlugin({\n collections: collectionsWithAdapter,\n useCompositePrefixes: options.useCompositePrefixes,\n })(config)\n },\n [vercelBlobStorageMetadata]: {\n collections: options.collections,\n enabled: !isPluginDisabled,\n storeId,\n useCompositePrefixes: Boolean(options.useCompositePrefixes),\n },\n }\n\n return storageAdapter\n}\n"],"names":["cloudStoragePlugin","createVercelBlobAdapter","getCollectionSources","vercelBlobStorageMetadata","defaultUploadOptions","access","addRandomSuffix","cacheControlMaxAge","enabled","vercelBlobStorage","options","storeId","token","match","toLowerCase","isPluginDisabled","storageAdapter","name","collections","Object","keys","init","incomingConfig","Error","optionsWithDefaults","baseUrl","process","env","STORAGE_VERCEL_BLOB_BASE_URL","collectionsWithoutAdapter","entries","reduce","acc","slug","collOptions","adapter","useCompositePrefixes","length","clientUploads","collectionSources","currentAdapter","storageAdapters","storage","collectionsWithAdapter","config","map","collection","upload","disableLocalStorage","Boolean"],"mappings":"AAOA,SAASA,kBAAkB,QAAQ,mCAAkC;AAErE,SAASC,uBAAuB,QAAQ,eAAc;AACtD,SACEC,oBAAoB,EAEpBC,yBAAyB,QACpB,4BAA2B;AAoElC,MAAMC,uBAA0D;IAC9DC,QAAQ;IACRC,iBAAiB;IACjBC,oBAAoB,KAAK,KAAK,KAAK;IACnCC,SAAS;AACX;AAIA,OAAO,MAAMC,oBAA8C,CACzDC;IAEA,MAAMC,UAAUD,QAAQE,KAAK,EAAEC,MAAM,0CAA0C,CAAC,EAAE,EAAEC;IACpF,MAAMC,mBAAmBL,QAAQF,OAAO,KAAK,SAAS,CAACE,QAAQE,KAAK;IACpE,MAAMI,iBAAmD;QACvDC,MAAM;QACNC,aAAaC,OAAOC,IAAI,CAACV,QAAQQ,WAAW;QAC5CG,MAAM,CAACC;YACL,wCAAwC;YACxC,IAAI,CAACX,WAAW,CAACI,kBAAkB;gBACjC,MAAM,IAAIQ,MACR;YAEJ;YAEA,MAAMC,sBAAsB;gBAC1B,GAAGpB,oBAAoB;gBACvB,GAAGM,OAAO;YACZ;YAEA,kGAAkG;YAClG,MAAMe,UACJC,QAAQC,GAAG,CAACC,4BAA4B,IACxC,CAAC,QAAQ,EAAEjB,QAAQ,CAAC,EAAEa,oBAAoBnB,MAAM,CAAC,wBAAwB,CAAC;YAE5E,8EAA8E;YAC9E,IAAIU,kBAAkB;gBACpB,MAAMc,4BAAsEV,OAAOW,OAAO,CACxFpB,QAAQQ,WAAW,EACnBa,MAAM,CACN,CAACC,KAAK,CAACC,MAAMC,YAAY,GAAM,CAAA;wBAC7B,GAAGF,GAAG;wBACN,CAACC,KAAK,EAAE;4BAAE,GAAIC,gBAAgB,OAAO,CAAC,IAAIA,WAAW;4BAAGC,SAAS;wBAAK;oBACxE,CAAA,GACA,CAAC;gBAEH,OAAOnC,mBAAmB;oBACxBkB,aAAaW;oBACbrB,S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B;gBACbP,sBAAsB1B,QAAQ0B,oBAAoB;YACpD,GAAGQ;QACL;QACA,CAACzC,0BAA0B,EAAE;YAC3Be,aAAaR,QAAQQ,WAAW;YAChCV,SAAS,CAACO;YACVJ;YACAyB,sBAAsBa,QAAQvC,QAAQ0B,oBAAoB;QAC5D;IACF;IAEA,OAAOpB;AACT,EAAC"}
|
package/dist/uploadFile.d.ts
CHANGED
|
@@ -3,16 +3,13 @@ interface UploadFileArgs {
|
|
|
3
3
|
addRandomSuffix?: boolean;
|
|
4
4
|
buffer: Buffer;
|
|
5
5
|
cacheControlMaxAge?: number;
|
|
6
|
-
collectionPrefix?: string;
|
|
7
|
-
docPrefix?: string;
|
|
8
|
-
filename: string;
|
|
9
6
|
mimeType: string;
|
|
7
|
+
storageFilePath: string;
|
|
10
8
|
token: string;
|
|
11
|
-
useCompositePrefixes?: boolean;
|
|
12
9
|
}
|
|
13
10
|
interface UploadFileResult {
|
|
14
11
|
filename?: string;
|
|
15
12
|
}
|
|
16
|
-
export declare function uploadFile({ access, addRandomSuffix, buffer, cacheControlMaxAge,
|
|
13
|
+
export declare function uploadFile({ access, addRandomSuffix, buffer, cacheControlMaxAge, mimeType, storageFilePath, token, }: UploadFileArgs): Promise<UploadFileResult>;
|
|
17
14
|
export {};
|
|
18
15
|
//# sourceMappingURL=uploadFile.d.ts.map
|
package/dist/uploadFile.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uploadFile.d.ts","sourceRoot":"","sources":["../src/uploadFile.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"uploadFile.d.ts","sourceRoot":"","sources":["../src/uploadFile.ts"],"names":[],"mappings":"AAGA,UAAU,cAAc;IACtB,MAAM,EAAE,QAAQ,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,MAAM,EAAE,MAAM,CAAA;IACd,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,QAAQ,EAAE,MAAM,CAAA;IAChB,eAAe,EAAE,MAAM,CAAA;IACvB,KAAK,EAAE,MAAM,CAAA;CACd;AAED,UAAU,gBAAgB;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,wBAAsB,UAAU,CAAC,EAC/B,MAAM,EACN,eAAe,EACf,MAAM,EACN,kBAAkB,EAClB,QAAQ,EACR,eAAe,EACf,KAAK,GACN,EAAE,cAAc,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAiB5C"}
|