@payloadcms/storage-vercel-blob 4.0.0-internal.d28e9fb → 4.0.0-internal.d3909a9

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.
Files changed (47) hide show
  1. package/LICENSE.md +1 -1
  2. package/README.md +11 -9
  3. package/dist/adapter.d.ts +3 -1
  4. package/dist/adapter.d.ts.map +1 -1
  5. package/dist/adapter.js +113 -19
  6. package/dist/adapter.js.map +1 -1
  7. package/dist/authorizeFileOverwrite.d.ts +16 -0
  8. package/dist/authorizeFileOverwrite.d.ts.map +1 -0
  9. package/dist/authorizeFileOverwrite.js +117 -0
  10. package/dist/authorizeFileOverwrite.js.map +1 -0
  11. package/dist/client/VercelBlobClientUploadHandler.d.ts +3 -8
  12. package/dist/client/VercelBlobClientUploadHandler.d.ts.map +1 -1
  13. package/dist/client/VercelBlobClientUploadHandler.js +8 -31
  14. package/dist/client/VercelBlobClientUploadHandler.js.map +1 -1
  15. package/dist/copyFile.d.ts +12 -0
  16. package/dist/copyFile.d.ts.map +1 -0
  17. package/dist/copyFile.js +86 -0
  18. package/dist/copyFile.js.map +1 -0
  19. package/dist/deleteFile.d.ts +2 -5
  20. package/dist/deleteFile.d.ts.map +1 -1
  21. package/dist/deleteFile.js +3 -10
  22. package/dist/deleteFile.js.map +1 -1
  23. package/dist/generateURL.d.ts +1 -0
  24. package/dist/generateURL.d.ts.map +1 -1
  25. package/dist/generateURL.js +13 -9
  26. package/dist/generateURL.js.map +1 -1
  27. package/dist/getCollectionSources.d.ts +20 -0
  28. package/dist/getCollectionSources.d.ts.map +1 -0
  29. package/dist/getCollectionSources.js +27 -0
  30. package/dist/getCollectionSources.js.map +1 -0
  31. package/dist/getFile.d.ts +5 -4
  32. package/dist/getFile.d.ts.map +1 -1
  33. package/dist/getFile.js +21 -13
  34. package/dist/getFile.js.map +1 -1
  35. package/dist/index.d.ts +14 -22
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +72 -76
  38. package/dist/index.js.map +1 -1
  39. package/dist/uploadFile.d.ts +2 -5
  40. package/dist/uploadFile.d.ts.map +1 -1
  41. package/dist/uploadFile.js +3 -9
  42. package/dist/uploadFile.js.map +1 -1
  43. package/package.json +16 -18
  44. package/dist/getClientUploadRoute.d.ts +0 -13
  45. package/dist/getClientUploadRoute.d.ts.map +0 -1
  46. package/dist/getClientUploadRoute.js +0 -35
  47. 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,IAA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;gBAAEC;YAAM;YAErC,IAAIc,YAAYC,IAAI,KAAKb,OAAOa,IAAI,EAAE;gBACpC,MAAM,IAAId,MAAM,CAAC,kEAAkE,EAAEF,IAAI;YAC3F;QACF;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"}
@@ -1,11 +1,8 @@
1
1
  interface DeleteFileArgs {
2
2
  baseUrl: string;
3
- collectionPrefix?: string;
4
- docPrefix: string;
5
- filename: string;
3
+ storageFilePath: string;
6
4
  token: string;
7
- useCompositePrefixes?: boolean;
8
5
  }
9
- export declare function deleteFile({ baseUrl, collectionPrefix, docPrefix, filename, token, useCompositePrefixes, }: DeleteFileArgs): Promise<void>;
6
+ export declare function deleteFile({ baseUrl, storageFilePath, token, }: DeleteFileArgs): Promise<void>;
10
7
  export {};
11
8
  //# sourceMappingURL=deleteFile.d.ts.map
@@ -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,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B;AAED,wBAAsB,UAAU,CAAC,EAC/B,OAAO,EACP,gBAAqB,EACrB,SAAS,EACT,QAAQ,EACR,KAAK,EACL,oBAA4B,GAC7B,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAUhC"}
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"}
@@ -1,14 +1,7 @@
1
1
  import { del } from '@vercel/blob';
2
- import { generateURL } from './generateURL.js';
3
- export async function deleteFile({ baseUrl, collectionPrefix = '', docPrefix, filename, token, useCompositePrefixes = false }) {
4
- const fileUrl = generateURL({
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
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/deleteFile.ts"],"sourcesContent":["import { del } from '@vercel/blob'\n\nimport { generateURL } from './generateURL.js'\n\ninterface DeleteFileArgs {\n baseUrl: string\n collectionPrefix?: string\n docPrefix: string\n filename: string\n token: string\n useCompositePrefixes?: boolean\n}\n\nexport async function deleteFile({\n baseUrl,\n collectionPrefix = '',\n docPrefix,\n filename,\n token,\n useCompositePrefixes = false,\n}: DeleteFileArgs): Promise<void> {\n const fileUrl = generateURL({\n baseUrl,\n collectionPrefix,\n filename,\n prefix: docPrefix,\n useCompositePrefixes,\n })\n\n await del(fileUrl, { token })\n}\n"],"names":["del","generateURL","deleteFile","baseUrl","collectionPrefix","docPrefix","filename","token","useCompositePrefixes","fileUrl","prefix"],"mappings":"AAAA,SAASA,GAAG,QAAQ,eAAc;AAElC,SAASC,WAAW,QAAQ,mBAAkB;AAW9C,OAAO,eAAeC,WAAW,EAC/BC,OAAO,EACPC,mBAAmB,EAAE,EACrBC,SAAS,EACTC,QAAQ,EACRC,KAAK,EACLC,uBAAuB,KAAK,EACb;IACf,MAAMC,UAAUR,YAAY;QAC1BE;QACAC;QACAE;QACAI,QAAQL;QACRG;IACF;IAEA,MAAMR,IAAIS,SAAS;QAAEF;IAAM;AAC7B"}
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"}
@@ -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,CAgB1B"}
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"}
@@ -1,19 +1,23 @@
1
- import { getFileKey } from '@payloadcms/plugin-cloud-storage/utilities';
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 { fileKey: fileKeyWithPrefix } = getFileKey({
14
+ const { storageFilePath } = buildStoragePathData({
5
15
  collectionPrefix,
6
16
  docPrefix: prefix,
7
17
  filename,
8
18
  useCompositePrefixes
9
19
  });
10
- // example: "my-collection/my-doc/my file.jpg" -> "my-collection/my-doc"
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
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/generateURL.ts"],"sourcesContent":["import { getFileKey } 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\nexport function generateURL({\n baseUrl,\n collectionPrefix = '',\n filename,\n prefix,\n useCompositePrefixes = false,\n}: GenerateURLArgs): string {\n const { fileKey: fileKeyWithPrefix } = getFileKey({\n collectionPrefix,\n docPrefix: prefix,\n filename,\n useCompositePrefixes,\n })\n // example: \"my-collection/my-doc/my file.jpg\" -> \"my-collection/my-doc\"\n const dir = path.posix.dirname(fileKeyWithPrefix)\n // example: \"my file.jpg\" -> \"my%20file.jpg\"\n const encodedFilename = encodeURIComponent(path.posix.basename(fileKeyWithPrefix))\n // example: \"my-collection/my-doc/my%20file.jpg\"\n const fileKeyWithEncodedFilename =\n dir === '.' ? encodedFilename : path.posix.join(dir, encodedFilename)\n\n return `${baseUrl}/${fileKeyWithEncodedFilename}`\n}\n"],"names":["getFileKey","path","generateURL","baseUrl","collectionPrefix","filename","prefix","useCompositePrefixes","fileKey","fileKeyWithPrefix","docPrefix","dir","posix","dirname","encodedFilename","encodeURIComponent","basename","fileKeyWithEncodedFilename","join"],"mappings":"AAAA,SAASA,UAAU,QAAQ,6CAA4C;AACvE,OAAOC,UAAU,OAAM;AAUvB,OAAO,SAASC,YAAY,EAC1BC,OAAO,EACPC,mBAAmB,EAAE,EACrBC,QAAQ,EACRC,MAAM,EACNC,uBAAuB,KAAK,EACZ;IAChB,MAAM,EAAEC,SAASC,iBAAiB,EAAE,GAAGT,WAAW;QAChDI;QACAM,WAAWJ;QACXD;QACAE;IACF;IACA,wEAAwE;IACxE,MAAMI,MAAMV,KAAKW,KAAK,CAACC,OAAO,CAACJ;IAC/B,4CAA4C;IAC5C,MAAMK,kBAAkBC,mBAAmBd,KAAKW,KAAK,CAACI,QAAQ,CAACP;IAC/D,gDAAgD;IAChD,MAAMQ,6BACJN,QAAQ,MAAMG,kBAAkBb,KAAKW,KAAK,CAACM,IAAI,CAACP,KAAKG;IAEvD,OAAO,GAAGX,QAAQ,CAAC,EAAEc,4BAA4B;AACnD"}
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
- prefixQueryParam?: string;
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, clientUploadContext, collection, collectionPrefix, filename, incomingHeaders, prefixQueryParam, req, token, useCompositePrefixes, }: GetFileArgs): Promise<Response>;
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
@@ -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;AAQ/D,UAAU,WAAW;IACnB,OAAO,EAAE,MAAM,CAAA;IACf,kBAAkB,EAAE,MAAM,CAAA;IAC1B,mBAAmB,CAAC,EAAE,OAAO,CAAA;IAC7B,UAAU,EAAE,gBAAgB,CAAA;IAC5B,gBAAgB,CAAC,EAAE,MAAM,CAAA;IACzB,QAAQ,EAAE,MAAM,CAAA;IAChB,eAAe,CAA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ile.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, clientUploadContext, collection, collectionPrefix = '', filename, incomingHeaders, prefixQueryParam, req, token, useCompositePrefixes = false }) {
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
- prefixQueryParam,
12
- req
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
- // Handle range request
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
- // Add Content-Security-Policy header for SVG files to prevent executable code
51
- if (contentType === 'image/svg+xml') {
52
- headers.append('Content-Security-Policy', "script-src 'none'");
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'
@@ -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 clientUploadContext?: unknown\n collection: CollectionConfig\n collectionPrefix?: string\n filename: string\n incomingHeaders?: Headers\n prefixQueryParam?: string\n req: PayloadRequest\n token: string\n useCompositePrefixes?: boolean\n}\n\nexport async function getFile({\n baseUrl,\n cacheControlMaxAge,\n clientUploadContext,\n collection,\n collectionPrefix = '',\n filename,\n incomingHeaders,\n prefixQueryParam,\n req,\n token,\n useCompositePrefixes = false,\n}: GetFileArgs): Promise<Response> {\n try {\n const docPrefix = await getDocPrefix({\n clientUploadContext,\n collection,\n filename,\n prefixQueryParam,\n req,\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 // Handle range request\n const rangeHeader = 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 // Add range-related headers from the result\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 // Add Content-Security-Policy header for SVG files to prevent executable code\n if (contentType === 'image/svg+xml') {\n headers.append('Content-Security-Policy', \"script-src 'none'\")\n }\n\n if (\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 (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 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","generateURL","getFile","baseUrl","cacheControlMaxAge","clientUploadContext","collection","collectionPrefix","filename","incomingHeaders","prefixQueryParam","req","token","useCompositePrefixes","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,QAAQ,mBAAkB;AAEtD,SAASC,WAAW,QAAQ,mBAAkB;AAgB9C,OAAO,eAAeC,QAAQ,EAC5BC,OAAO,EACPC,kBAAkB,EAClBC,mBAAmB,EACnBC,UAAU,EACVC,mBAAmB,EAAE,EACrBC,QAAQ,EACRC,eAAe,EACfC,gBAAgB,EAChBC,GAAG,EACHC,KAAK,EACLC,uBAAuB,KAAK,EAChB;IACZ,IAAI;QACF,MAAMC,YAAY,MAAMjB,aA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Operation, 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,EACHC,KAAK,EACLC,eAAe,EACfC,uBAAuB,KAAK,EAChB;IACZ,MAAMC,oBAAoBL,cAAc;IAExC,IAAI;QACF,MAAMM,YAAY,MAAMrB,aAAa;YACnCU;YACAC;YACAC;YACAC;YACAG;YACAE;YACAC;QACF;QAEA,MAAMG,UAAUhB,YAAY;YAC1BE;YACAG;YACAE;YACAU,QAAQF;YACRF;QACF;QACA,MAAMK,kBAAkBR,IAAIS,OAAO,CAACC,GAAG,CAAC,WAAWV,IAAIS,OAAO,CAACC,GAAG,CAAC;QACnE,MAAMC,eAAe,MAAMzB,KAAKoB,SAAS;YAAEL;QAAM;QACjD,MAAM,EAAEW,kBAAkB,EAAEC,WAAW,EAAEC,IAAI,EAAEC,UAAU,EAAE,GAAGJ;QAC9D,MAAMK,mBAAmBD,WAAWE,WAAW;QAC/C,MAAMC,iBAAiBZ,QAAQa,OAAO,CAAC,GAAG3B,QAAQ,CAAC,CAAC,EAAE;QACtD,MAAM4B,OAAO,CAAC,CAAC,EAAEF,eAAe,CAAC,EAAEF,iBAAiB,CAAC,CAAC;QAEtD,MAAMK,cAAcjB,oBAAoB,OAAOJ,IAAIS,OAAO,CAACC,GAAG,CAAC;QAC/D,MAAMY,cAAcnC,oBAAoB;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;QACF;QAEA,IAAI,CAACL,SAASM,EAAE,IAAI,CAACN,SAASO,IAAI,EAAE;YAClC,oGAAoG;YACpG,IAAItC,mBAAmB;gBACrB,OAAO,IAAIqB,SAAS,MAAM;oBAAEE,QAAQQ,SAASR,MAAM;oBAAEgB,YAAYR,SAASQ,UAAU;gBAAC;YACvF;YAEA,OAAO,IAAIlB,SAAS,MAAM;gBAAEE,QAAQ;gBAAKgB,YAAY;YAAa;QACpE;QAEAlC,QAAQuB,MAAM,CAAC,iBAAiBhB;QAEhC,OAAO,IAAIS,SAASU,SAASO,IAAI,EAAE;YACjCjC;YACAkB,QAAQL,YAAYK,MAAM;QAC5B;IACF,EAAE,OAAOiB,KAAc;QACrB,IAAIA,eAAe3D,mBAAmB;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
@@ -1,5 +1,5 @@
1
1
  import type { ClientUploadsConfig, CollectionOptions } from '@payloadcms/plugin-cloud-storage/types';
2
- import type { Plugin, UploadCollectionSlug } from 'payload';
2
+ import type { StorageAdapter, UploadCollectionSlug } from 'payload';
3
3
  export type VercelBlobStorageOptions = {
4
4
  /**
5
5
  * Access control level. Currently, only 'public' is supported.
@@ -9,21 +9,12 @@ export type VercelBlobStorageOptions = {
9
9
  */
10
10
  access?: 'public';
11
11
  /**
12
- * Add a random suffix to the uploaded file name in Vercel Blob storage
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
- * Do uploads directly on the client, to bypass limits on Vercel.
25
+ * Upload directly to Vercel Blob instead of through Payload.
35
26
  */
36
27
  clientUploads?: ClientUploadsConfig;
37
28
  /**
@@ -54,20 +45,21 @@ 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 overrides collection
58
- * prefix entirely.
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: `collection-prefix/`
62
- * - document prefix: `document-prefix/`
63
- * - resulting prefix with useCompositePrefixes=true: `collection-prefix/document-prefix/`
64
- * - resulting prefix with useCompositePrefixes=false: `document-prefix/`
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
  */
68
60
  useCompositePrefixes?: boolean;
69
61
  };
70
- type VercelBlobStoragePlugin = (vercelBlobStorageOpts: VercelBlobStorageOptions) => Plugin;
71
- export declare const vercelBlobStorage: VercelBlobStoragePlugin;
62
+ type VercelBlobStorageFactory = (vercelBlobStorageOpts: VercelBlobStorageOptions) => StorageAdapter;
63
+ export declare const vercelBlobStorage: VercelBlobStorageFactory;
72
64
  export {};
73
65
  //# sourceMappingURL=index.d.ts.map
@@ -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,MAAM,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAUnE,MAAM,MAAM,wBAAwB,GAAG;IACrC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,QAAQ,CAAA;IAEjB;;;;OAIG;IACH,eAAe,CAAC,EAAE,OAAO,CAAA;IAEzB;;;;;;;;OAQG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAE5B;;;;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;;;;;;;;;;;;OAYG;IACH,oBAAoB,CAAC,EAAE,OAAO,CAAA;CAC/B,CAAA;AASD,KAAK,uBAAuB,GAAG,CAAC,qBAAqB,EAAE,wBAAwB,KAAK,MAAM,CAAA;AAE1F,eAAO,MAAM,iBAAiB,EAAE,uBAsH7B,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,47 +1,31 @@
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 { getClientUploadRoute } from './getClientUploadRoute.js';
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)=>(incomingConfig)=>{
12
- // Parse storeId from token
13
- const storeId = options.token?.match(/^vercel_blob_rw_([a-z\d]+)_[a-z\d]+$/i)?.[1]?.toLowerCase();
14
- const isPluginDisabled = options.enabled === false || !options.token;
15
- // Don't throw if the plugin is disabled
16
- if (!storeId && !isPluginDisabled) {
17
- throw new Error('Invalid token format for Vercel Blob adapter. Should be vercel_blob_rw_<store_id>_<random_string>.');
18
- }
19
- const optionsWithDefaults = {
20
- ...defaultUploadOptions,
21
- ...options
22
- };
23
- // support overriding the base URL for emulator https://github.com/payloadcms/vercel-blob-emulator
24
- const baseUrl = process.env.STORAGE_VERCEL_BLOB_BASE_URL || `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`;
25
- initClientUploads({
26
- clientHandler: '@payloadcms/storage-vercel-blob/client#VercelBlobClientUploadHandler',
27
- collections: options.collections,
28
- config: incomingConfig,
29
- enabled: !isPluginDisabled && Boolean(options.clientUploads),
30
- extraClientHandlerProps: ()=>({
31
- addRandomSuffix: !!optionsWithDefaults.addRandomSuffix,
32
- useCompositePrefixes: !!options.useCompositePrefixes
33
- }),
34
- serverHandler: getClientUploadRoute({
35
- access: typeof options.clientUploads === 'object' ? options.clientUploads.access : undefined,
36
- addRandomSuffix: optionsWithDefaults.addRandomSuffix,
37
- cacheControlMaxAge: options.cacheControlMaxAge,
38
- token: options.token ?? ''
39
- }),
40
- serverHandlerPath: '/vercel-blob-client-upload-route'
41
- });
42
- // If the plugin is disabled or no token is provided, do not enable the plugin
43
- if (isPluginDisabled) {
44
- if (options.alwaysInsertFields) {
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 = {
14
+ name: 'vercel-blob',
15
+ collections: Object.keys(options.collections),
16
+ init: (incomingConfig)=>{
17
+ // Don't throw if the plugin is disabled
18
+ if (!storeId && !isPluginDisabled) {
19
+ throw new Error('Invalid token format for Vercel Blob adapter. Should be vercel_blob_rw_<store_id>_<random_string>.');
20
+ }
21
+ const optionsWithDefaults = {
22
+ ...defaultUploadOptions,
23
+ ...options
24
+ };
25
+ // support overriding the base URL for emulator https://github.com/payloadcms/vercel-blob-emulator
26
+ const baseUrl = process.env.STORAGE_VERCEL_BLOB_BASE_URL || `https://${storeId}.${optionsWithDefaults.access}.blob.vercel-storage.com`;
27
+ // If the plugin is disabled or no token is provided, do not enable the plugin
28
+ if (isPluginDisabled) {
45
29
  const collectionsWithoutAdapter = Object.entries(options.collections).reduce((acc, [slug, collOptions])=>({
46
30
  ...acc,
47
31
  [slug]: {
@@ -50,52 +34,64 @@ export const vercelBlobStorage = (options)=>(incomingConfig)=>{
50
34
  }
51
35
  }), {});
52
36
  return cloudStoragePlugin({
53
- alwaysInsertFields: true,
54
37
  collections: collectionsWithoutAdapter,
55
38
  enabled: false,
56
39
  useCompositePrefixes: options.useCompositePrefixes
57
40
  })(incomingConfig);
58
41
  }
59
- return incomingConfig;
60
- }
61
- const adapter = createVercelBlobAdapter({
62
- access: optionsWithDefaults.access ?? 'public',
63
- addRandomSuffix: optionsWithDefaults.addRandomSuffix,
64
- baseUrl,
65
- cacheControlMaxAge: optionsWithDefaults.cacheControlMaxAge ?? 60 * 60 * 24 * 365,
66
- clientUploads: optionsWithDefaults.clientUploads,
67
- token: options.token,
68
- useCompositePrefixes: options.useCompositePrefixes
69
- });
70
- // Add adapter to each collection option object
71
- const collectionsWithAdapter = Object.entries(options.collections).reduce((acc, [slug, collOptions])=>({
72
- ...acc,
73
- [slug]: {
74
- ...collOptions === true ? {} : collOptions,
75
- adapter
76
- }
77
- }), {});
78
- // Set disableLocalStorage: true for collections specified in the plugin options
79
- const config = {
80
- ...incomingConfig,
81
- collections: (incomingConfig.collections || []).map((collection)=>{
82
- if (!collectionsWithAdapter[collection.slug]) {
83
- return collection;
84
- }
85
- return {
86
- ...collection,
87
- upload: {
88
- ...typeof collection.upload === 'object' ? collection.upload : {},
89
- disableLocalStorage: true
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.');
44
+ }
45
+ const adapter = createVercelBlobAdapter({
46
+ access: optionsWithDefaults.access ?? 'public',
47
+ addRandomSuffix: optionsWithDefaults.addRandomSuffix,
48
+ baseUrl,
49
+ cacheControlMaxAge: optionsWithDefaults.cacheControlMaxAge ?? 60 * 60 * 24 * 365,
50
+ clientUploads: optionsWithDefaults.clientUploads,
51
+ collectionSources: getCollectionSources({
52
+ currentAdapter: storageAdapter,
53
+ storageAdapters: incomingConfig.storage
54
+ }),
55
+ token: options.token,
56
+ useCompositePrefixes: options.useCompositePrefixes
57
+ });
58
+ // Add adapter to each collection option object
59
+ const collectionsWithAdapter = Object.entries(options.collections).reduce((acc, [slug, collOptions])=>({
60
+ ...acc,
61
+ [slug]: {
62
+ ...collOptions === true ? {} : collOptions,
63
+ adapter
90
64
  }
91
- };
92
- })
93
- };
94
- return cloudStoragePlugin({
95
- alwaysInsertFields: options.alwaysInsertFields,
96
- collections: collectionsWithAdapter,
97
- useCompositePrefixes: options.useCompositePrefixes
98
- })(config);
65
+ }), {});
66
+ // Set disableLocalStorage: true for collections specified in the plugin options
67
+ const config = {
68
+ ...incomingConfig,
69
+ collections: (incomingConfig.collections || []).map((collection)=>{
70
+ if (!collectionsWithAdapter[collection.slug]) {
71
+ return collection;
72
+ }
73
+ return {
74
+ ...collection,
75
+ upload: {
76
+ ...typeof collection.upload === 'object' ? collection.upload : {},
77
+ disableLocalStorage: true
78
+ }
79
+ };
80
+ })
81
+ };
82
+ return cloudStoragePlugin({
83
+ collections: collectionsWithAdapter,
84
+ useCompositePrefixes: options.useCompositePrefixes
85
+ })(config);
86
+ },
87
+ [vercelBlobStorageMetadata]: {
88
+ collections: options.collections,
89
+ enabled: !isPluginDisabled,
90
+ storeId,
91
+ useCompositePrefixes: Boolean(options.useCompositePrefixes)
92
+ }
99
93
  };
94
+ return storageAdapter;
95
+ };
100
96
 
101
97
  //# sourceMappingURL=index.js.map