@payloadcms/storage-uploadthing 3.0.0-beta.30

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/LICENSE.md ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018-2022 Payload CMS, LLC <info@payloadcms.com>
4
+ Portions Copyright (c) Meta Platforms, Inc. and affiliates.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # Uploadthing Storage for Payload (beta)
2
+
3
+ This package provides a way to use [uploadthing](https://uploadthing.com) with Payload.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ pnpm add @paylaodcms/storage-uploadthing
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ - Configure the `collections` object to specify which collections should use uploadthing. The slug _must_ match one of your existing collection slugs and be an `upload` type.
14
+ - Get an API key from Uploadthing and set it as `apiKey` in the `options` object.
15
+ - `acl` is optional and defaults to `public-read`.
16
+
17
+ ```ts
18
+ export default buildConfig({
19
+ collections: [Media],
20
+ plugins: [
21
+ uploadthingStorage({
22
+ collections: {
23
+ [mediaSlug]: true,
24
+ },
25
+ options: {
26
+ apiKey: process.env.UPLOADTHING_SECRET,
27
+ acl: 'public-read',
28
+ },
29
+ }),
30
+ ],
31
+ })
32
+ ```
@@ -0,0 +1,3 @@
1
+ import type { GenerateURL } from '@payloadcms/plugin-cloud-storage/types';
2
+ export declare const generateURL: GenerateURL;
3
+ //# sourceMappingURL=generateURL.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateURL.d.ts","sourceRoot":"","sources":["../src/generateURL.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wCAAwC,CAAA;AAMzE,eAAO,MAAM,WAAW,EAAE,WAGzB,CAAA"}
@@ -0,0 +1,8 @@
1
+ import path from 'path';
2
+ import { getKeyFromFilename } from './utilities.js';
3
+ export const generateURL = ({ data, filename, prefix = '' })=>{
4
+ const key = getKeyFromFilename(data, filename);
5
+ return `https://utfs.io/f/${path.posix.join(prefix, key || '')}`;
6
+ };
7
+
8
+ //# sourceMappingURL=generateURL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/generateURL.ts"],"sourcesContent":["import type { GenerateURL } from '@payloadcms/plugin-cloud-storage/types'\n\nimport path from 'path'\n\nimport { getKeyFromFilename } from './utilities.js'\n\nexport const generateURL: GenerateURL = ({ data, filename, prefix = '' }) => {\n const key = getKeyFromFilename(data, filename)\n return `https://utfs.io/f/${path.posix.join(prefix, key || '')}`\n}\n"],"names":["path","getKeyFromFilename","generateURL","data","filename","prefix","key","posix","join"],"rangeMappings":";;;;;","mappings":"AAEA,OAAOA,UAAU,OAAM;AAEvB,SAASC,kBAAkB,QAAQ,iBAAgB;AAEnD,OAAO,MAAMC,cAA2B,CAAC,EAAEC,IAAI,EAAEC,QAAQ,EAAEC,SAAS,EAAE,EAAE;IACtE,MAAMC,MAAML,mBAAmBE,MAAMC;IACrC,OAAO,CAAC,kBAAkB,EAAEJ,KAAKO,KAAK,CAACC,IAAI,CAACH,QAAQC,OAAO,IAAI,CAAC;AAClE,EAAC"}
@@ -0,0 +1,8 @@
1
+ import type { HandleDelete } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { UTApi } from 'uploadthing/server';
3
+ type Args = {
4
+ utApi: UTApi;
5
+ };
6
+ export declare const getHandleDelete: ({ utApi }: Args) => HandleDelete;
7
+ export {};
8
+ //# sourceMappingURL=handleDelete.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handleDelete.d.ts","sourceRoot":"","sources":["../src/handleDelete.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAA;AAC1E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAM/C,KAAK,IAAI,GAAG;IACV,KAAK,EAAE,KAAK,CAAA;CACb,CAAA;AAED,eAAO,MAAM,eAAe,cAAe,IAAI,KAAG,YAuBjD,CAAA"}
@@ -0,0 +1,26 @@
1
+ import { APIError } from 'payload/errors';
2
+ import { getKeyFromFilename } from './utilities.js';
3
+ export const getHandleDelete = ({ utApi })=>{
4
+ return async ({ doc, filename, req })=>{
5
+ const key = getKeyFromFilename(doc, filename);
6
+ if (!key) {
7
+ req.payload.logger.error({
8
+ msg: `Error deleting file: ${filename} - unable to extract key from doc`
9
+ });
10
+ throw new APIError(`Error deleting file: ${filename}`);
11
+ }
12
+ try {
13
+ if (key) {
14
+ await utApi.deleteFiles(key);
15
+ }
16
+ } catch (err) {
17
+ req.payload.logger.error({
18
+ err,
19
+ msg: `Error deleting file with key: ${filename} - key: ${key}`
20
+ });
21
+ throw new APIError(`Error deleting file: ${filename}`);
22
+ }
23
+ };
24
+ };
25
+
26
+ //# sourceMappingURL=handleDelete.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/handleDelete.ts"],"sourcesContent":["import type { HandleDelete } from '@payloadcms/plugin-cloud-storage/types'\nimport type { UTApi } from 'uploadthing/server'\n\nimport { APIError } from 'payload/errors'\n\nimport { getKeyFromFilename } from './utilities.js'\n\ntype Args = {\n utApi: UTApi\n}\n\nexport const getHandleDelete = ({ utApi }: Args): HandleDelete => {\n return async ({ doc, filename, req }) => {\n const key = getKeyFromFilename(doc, filename)\n\n if (!key) {\n req.payload.logger.error({\n msg: `Error deleting file: ${filename} - unable to extract key from doc`,\n })\n throw new APIError(`Error deleting file: ${filename}`)\n }\n\n try {\n if (key) {\n await utApi.deleteFiles(key)\n }\n } catch (err) {\n req.payload.logger.error({\n err,\n msg: `Error deleting file with key: ${filename} - key: ${key}`,\n })\n throw new APIError(`Error deleting file: ${filename}`)\n }\n }\n}\n"],"names":["APIError","getKeyFromFilename","getHandleDelete","utApi","doc","filename","req","key","payload","logger","error","msg","deleteFiles","err"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,QAAQ,QAAQ,iBAAgB;AAEzC,SAASC,kBAAkB,QAAQ,iBAAgB;AAMnD,OAAO,MAAMC,kBAAkB,CAAC,EAAEC,KAAK,EAAQ;IAC7C,OAAO,OAAO,EAAEC,GAAG,EAAEC,QAAQ,EAAEC,GAAG,EAAE;QAClC,MAAMC,MAAMN,mBAAmBG,KAAKC;QAEpC,IAAI,CAACE,KAAK;YACRD,IAAIE,OAAO,CAACC,MAAM,CAACC,KAAK,CAAC;gBACvBC,KAAK,CAAC,qBAAqB,EAAEN,SAAS,iCAAiC,CAAC;YAC1E;YACA,MAAM,IAAIL,SAAS,CAAC,qBAAqB,EAAEK,SAAS,CAAC;QACvD;QAEA,IAAI;YACF,IAAIE,KAAK;gBACP,MAAMJ,MAAMS,WAAW,CAACL;YAC1B;QACF,EAAE,OAAOM,KAAK;YACZP,IAAIE,OAAO,CAACC,MAAM,CAACC,KAAK,CAAC;gBACvBG;gBACAF,KAAK,CAAC,8BAA8B,EAAEN,SAAS,QAAQ,EAAEE,IAAI,CAAC;YAChE;YACA,MAAM,IAAIP,SAAS,CAAC,qBAAqB,EAAEK,SAAS,CAAC;QACvD;IACF;AACF,EAAC"}
@@ -0,0 +1,10 @@
1
+ import type { HandleUpload } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { UTApi } from 'uploadthing/server';
3
+ import type { ACL } from './index.js';
4
+ type HandleUploadArgs = {
5
+ acl: ACL;
6
+ utApi: UTApi;
7
+ };
8
+ export declare const getHandleUpload: ({ acl, utApi }: HandleUploadArgs) => HandleUpload;
9
+ export {};
10
+ //# sourceMappingURL=handleUpload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handleUpload.d.ts","sourceRoot":"","sources":["../src/handleUpload.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAA;AAC1E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAK/C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,YAAY,CAAA;AAErC,KAAK,gBAAgB,GAAG;IACtB,GAAG,EAAE,GAAG,CAAA;IACR,KAAK,EAAE,KAAK,CAAA;CACb,CAAA;AAED,eAAO,MAAM,eAAe,mBAAoB,gBAAgB,KAAG,YA2ClE,CAAA"}
@@ -0,0 +1,45 @@
1
+ import { APIError } from 'payload/errors';
2
+ import { UTFile } from 'uploadthing/server';
3
+ export const getHandleUpload = ({ acl, utApi })=>{
4
+ return async ({ data, file })=>{
5
+ try {
6
+ const { buffer, filename, mimeType } = file;
7
+ const blob = new Blob([
8
+ buffer
9
+ ], {
10
+ type: mimeType
11
+ });
12
+ const res = await utApi.uploadFiles(new UTFile([
13
+ blob
14
+ ], filename), {
15
+ acl
16
+ });
17
+ if (res.error) {
18
+ throw new APIError(`Error uploading file: ${res.error.code} - ${res.error.message}`);
19
+ }
20
+ // Find matching data.sizes entry
21
+ const foundSize = Object.keys(data.sizes || {}).find((key)=>data.sizes?.[key]?.filename === filename);
22
+ if (foundSize) {
23
+ data.sizes[foundSize]._key = res.data?.key;
24
+ } else {
25
+ data._key = res.data?.key;
26
+ data.filename = res.data?.name;
27
+ }
28
+ return data;
29
+ } catch (error) {
30
+ if (error instanceof Error) {
31
+ // Interrogate uploadthing error which returns FiberFailure
32
+ if ('toJSON' in error && typeof error.toJSON === 'function') {
33
+ const json = error.toJSON();
34
+ if (json.cause?.defect?.error && json.cause.defect.data?.error) {
35
+ throw new APIError(`Error uploading file with uploadthing: ${json.cause.defect.error} - ${json.cause.defect.data.error}`);
36
+ }
37
+ } else {
38
+ throw new APIError(`Error uploading file with uploadthing: ${error.message}`);
39
+ }
40
+ }
41
+ }
42
+ };
43
+ };
44
+
45
+ //# sourceMappingURL=handleUpload.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/handleUpload.ts"],"sourcesContent":["import type { HandleUpload } from '@payloadcms/plugin-cloud-storage/types'\nimport type { UTApi } from 'uploadthing/server'\n\nimport { APIError } from 'payload/errors'\nimport { UTFile } from 'uploadthing/server'\n\nimport type { ACL } from './index.js'\n\ntype HandleUploadArgs = {\n acl: ACL\n utApi: UTApi\n}\n\nexport const getHandleUpload = ({ acl, utApi }: HandleUploadArgs): HandleUpload => {\n return async ({ data, file }) => {\n try {\n const { buffer, filename, mimeType } = file\n\n const blob = new Blob([buffer], { type: mimeType })\n const res = await utApi.uploadFiles(new UTFile([blob], filename), { acl })\n\n if (res.error) {\n throw new APIError(`Error uploading file: ${res.error.code} - ${res.error.message}`)\n }\n\n // Find matching data.sizes entry\n const foundSize = Object.keys(data.sizes || {}).find(\n (key) => data.sizes?.[key]?.filename === filename,\n )\n\n if (foundSize) {\n data.sizes[foundSize]._key = res.data?.key\n } else {\n data._key = res.data?.key\n data.filename = res.data?.name\n }\n\n return data\n } catch (error: unknown) {\n if (error instanceof Error) {\n // Interrogate uploadthing error which returns FiberFailure\n if ('toJSON' in error && typeof error.toJSON === 'function') {\n const json = error.toJSON() as {\n cause?: { defect?: { _id?: string; data?: { error?: string }; error?: string } }\n }\n if (json.cause?.defect?.error && json.cause.defect.data?.error) {\n throw new APIError(\n `Error uploading file with uploadthing: ${json.cause.defect.error} - ${json.cause.defect.data.error}`,\n )\n }\n } else {\n throw new APIError(`Error uploading file with uploadthing: ${error.message}`)\n }\n }\n }\n }\n}\n"],"names":["APIError","UTFile","getHandleUpload","acl","utApi","data","file","buffer","filename","mimeType","blob","Blob","type","res","uploadFiles","error","code","message","foundSize","Object","keys","sizes","find","key","_key","name","Error","toJSON","json","cause","defect"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAGA,SAASA,QAAQ,QAAQ,iBAAgB;AACzC,SAASC,MAAM,QAAQ,qBAAoB;AAS3C,OAAO,MAAMC,kBAAkB,CAAC,EAAEC,GAAG,EAAEC,KAAK,EAAoB;IAC9D,OAAO,OAAO,EAAEC,IAAI,EAAEC,IAAI,EAAE;QAC1B,IAAI;YACF,MAAM,EAAEC,MAAM,EAAEC,QAAQ,EAAEC,QAAQ,EAAE,GAAGH;YAEvC,MAAMI,OAAO,IAAIC,KAAK;gBAACJ;aAAO,EAAE;gBAAEK,MAAMH;YAAS;YACjD,MAAMI,MAAM,MAAMT,MAAMU,WAAW,CAAC,IAAIb,OAAO;gBAACS;aAAK,EAAEF,WAAW;gBAAEL;YAAI;YAExE,IAAIU,IAAIE,KAAK,EAAE;gBACb,MAAM,IAAIf,SAAS,CAAC,sBAAsB,EAAEa,IAAIE,KAAK,CAACC,IAAI,CAAC,GAAG,EAAEH,IAAIE,KAAK,CAACE,OAAO,CAAC,CAAC;YACrF;YAEA,iCAAiC;YACjC,MAAMC,YAAYC,OAAOC,IAAI,CAACf,KAAKgB,KAAK,IAAI,CAAC,GAAGC,IAAI,CAClD,CAACC,MAAQlB,KAAKgB,KAAK,EAAE,CAACE,IAAI,EAAEf,aAAaA;YAG3C,IAAIU,WAAW;gBACbb,KAAKgB,KAAK,CAACH,UAAU,CAACM,IAAI,GAAGX,IAAIR,IAAI,EAAEkB;YACzC,OAAO;gBACLlB,KAAKmB,IAAI,GAAGX,IAAIR,IAAI,EAAEkB;gBACtBlB,KAAKG,QAAQ,GAAGK,IAAIR,IAAI,EAAEoB;YAC5B;YAEA,OAAOpB;QACT,EAAE,OAAOU,OAAgB;YACvB,IAAIA,iBAAiBW,OAAO;gBAC1B,2DAA2D;gBAC3D,IAAI,YAAYX,SAAS,OAAOA,MAAMY,MAAM,KAAK,YAAY;oBAC3D,MAAMC,OAAOb,MAAMY,MAAM;oBAGzB,IAAIC,KAAKC,KAAK,EAAEC,QAAQf,SAASa,KAAKC,KAAK,CAACC,MAAM,CAACzB,IAAI,EAAEU,OAAO;wBAC9D,MAAM,IAAIf,SACR,CAAC,uCAAuC,EAAE4B,KAAKC,KAAK,CAACC,MAAM,CAACf,KAAK,CAAC,GAAG,EAAEa,KAAKC,KAAK,CAACC,MAAM,CAACzB,IAAI,CAACU,KAAK,CAAC,CAAC;oBAEzG;gBACF,OAAO;oBACL,MAAM,IAAIf,SAAS,CAAC,uCAAuC,EAAEe,MAAME,OAAO,CAAC,CAAC;gBAC9E;YACF;QACF;IACF;AACF,EAAC"}
@@ -0,0 +1,30 @@
1
+ import type { CollectionOptions } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { Plugin } from 'payload/config';
3
+ import type { UTApiOptions } from 'uploadthing/types';
4
+ export type UploadthingStorageOptions = {
5
+ /**
6
+ * Collection options to apply the adapter to.
7
+ */
8
+ collections: Record<string, Omit<CollectionOptions, 'adapter'> | true>;
9
+ /**
10
+ * Whether or not to enable the plugin
11
+ *
12
+ * Default: true
13
+ */
14
+ enabled?: boolean;
15
+ /**
16
+ * Uploadthing Options
17
+ */
18
+ options: UTApiOptions & {
19
+ /**
20
+ * @default 'public-read'
21
+ */
22
+ acl?: ACL;
23
+ };
24
+ };
25
+ type UploadthingPlugin = (uploadthingStorageOptions: UploadthingStorageOptions) => Plugin;
26
+ /** NOTE: not synced with uploadthing's internal types. Need to modify if more options added */
27
+ export type ACL = 'private' | 'public-read';
28
+ export declare const uploadthingStorage: UploadthingPlugin;
29
+ export {};
30
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,iBAAiB,EAElB,MAAM,wCAAwC,CAAA;AAC/C,OAAO,KAAK,EAAU,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAUrD,MAAM,MAAM,yBAAyB,GAAG;IACtC;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,SAAS,CAAC,GAAG,IAAI,CAAC,CAAA;IAEtE;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAA;IAEjB;;OAEG;IACH,OAAO,EAAE,YAAY,GAAG;QACtB;;WAEG;QACH,GAAG,CAAC,EAAE,GAAG,CAAA;KACV,CAAA;CACF,CAAA;AAED,KAAK,iBAAiB,GAAG,CAAC,yBAAyB,EAAE,yBAAyB,KAAK,MAAM,CAAA;AAEzF,+FAA+F;AAC/F,MAAM,MAAM,GAAG,GAAG,SAAS,GAAG,aAAa,CAAA;AAE3C,eAAO,MAAM,kBAAkB,EAAE,iBAuD9B,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,79 @@
1
+ import { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage';
2
+ import { UTApi } from 'uploadthing/server';
3
+ import { generateURL } from './generateURL.js';
4
+ import { getHandleDelete } from './handleDelete.js';
5
+ import { getHandleUpload } from './handleUpload.js';
6
+ import { getHandler } from './staticHandler.js';
7
+ export const uploadthingStorage = (uploadthingStorageOptions)=>(incomingConfig)=>{
8
+ if (uploadthingStorageOptions.enabled === false) {
9
+ return incomingConfig;
10
+ }
11
+ // Default ACL to public-read
12
+ if (!uploadthingStorageOptions.options.acl) {
13
+ uploadthingStorageOptions.options.acl = 'public-read';
14
+ }
15
+ const adapter = uploadthingInternal(uploadthingStorageOptions, incomingConfig);
16
+ // Add adapter to each collection option object
17
+ const collectionsWithAdapter = Object.entries(uploadthingStorageOptions.collections).reduce((acc, [slug, collOptions])=>({
18
+ ...acc,
19
+ [slug]: {
20
+ ...collOptions === true ? {} : collOptions,
21
+ // Disable payload access control if the ACL is public-read or not set
22
+ // ...(uploadthingStorageOptions.options.acl === 'public-read'
23
+ // ? { disablePayloadAccessControl: true }
24
+ // : {}),
25
+ adapter
26
+ }
27
+ }), {});
28
+ // Set disableLocalStorage: true for collections specified in the plugin options
29
+ const config = {
30
+ ...incomingConfig,
31
+ collections: (incomingConfig.collections || []).map((collection)=>{
32
+ if (!collectionsWithAdapter[collection.slug]) {
33
+ return collection;
34
+ }
35
+ return {
36
+ ...collection,
37
+ upload: {
38
+ ...typeof collection.upload === 'object' ? collection.upload : {},
39
+ disableLocalStorage: true
40
+ }
41
+ };
42
+ })
43
+ };
44
+ return cloudStoragePlugin({
45
+ collections: collectionsWithAdapter
46
+ })(config);
47
+ };
48
+ function uploadthingInternal(options, incomingConfig) {
49
+ const fields = [
50
+ {
51
+ name: '_key',
52
+ type: 'text',
53
+ admin: {
54
+ hidden: true
55
+ }
56
+ }
57
+ ];
58
+ return ()=>{
59
+ const { options: { acl = 'public-read', ...utOptions } } = options;
60
+ const utApi = new UTApi(utOptions);
61
+ return {
62
+ name: 'uploadthing',
63
+ fields,
64
+ generateURL,
65
+ handleDelete: getHandleDelete({
66
+ utApi
67
+ }),
68
+ handleUpload: getHandleUpload({
69
+ acl,
70
+ utApi
71
+ }),
72
+ staticHandler: getHandler({
73
+ utApi
74
+ })
75
+ };
76
+ };
77
+ }
78
+
79
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n Adapter,\n PluginOptions as CloudStoragePluginOptions,\n CollectionOptions,\n GeneratedAdapter,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type { Config, Plugin } from 'payload/config'\nimport type { Field } from 'payload/types'\nimport type { UTApiOptions } from 'uploadthing/types'\n\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport { UTApi } from 'uploadthing/server'\n\nimport { generateURL } from './generateURL.js'\nimport { getHandleDelete } from './handleDelete.js'\nimport { getHandleUpload } from './handleUpload.js'\nimport { getHandler } from './staticHandler.js'\n\nexport type UploadthingStorageOptions = {\n /**\n * Collection options to apply the adapter to.\n */\n collections: Record<string, Omit<CollectionOptions, 'adapter'> | true>\n\n /**\n * Whether or not to enable the plugin\n *\n * Default: true\n */\n enabled?: boolean\n\n /**\n * Uploadthing Options\n */\n options: UTApiOptions & {\n /**\n * @default 'public-read'\n */\n acl?: ACL\n }\n}\n\ntype UploadthingPlugin = (uploadthingStorageOptions: UploadthingStorageOptions) => Plugin\n\n/** NOTE: not synced with uploadthing's internal types. Need to modify if more options added */\nexport type ACL = 'private' | 'public-read'\n\nexport const uploadthingStorage: UploadthingPlugin =\n (uploadthingStorageOptions: UploadthingStorageOptions) =>\n (incomingConfig: Config): Config => {\n if (uploadthingStorageOptions.enabled === false) {\n return incomingConfig\n }\n\n // Default ACL to public-read\n if (!uploadthingStorageOptions.options.acl) {\n uploadthingStorageOptions.options.acl = 'public-read'\n }\n\n const adapter = uploadthingInternal(uploadthingStorageOptions, incomingConfig)\n\n // Add adapter to each collection option object\n const collectionsWithAdapter: CloudStoragePluginOptions['collections'] = Object.entries(\n uploadthingStorageOptions.collections,\n ).reduce(\n (acc, [slug, collOptions]) => ({\n ...acc,\n [slug]: {\n ...(collOptions === true ? {} : collOptions),\n\n // Disable payload access control if the ACL is public-read or not set\n // ...(uploadthingStorageOptions.options.acl === 'public-read'\n // ? { disablePayloadAccessControl: true }\n // : {}),\n\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 })(config)\n }\n\nfunction uploadthingInternal(options: UploadthingStorageOptions, incomingConfig: Config): Adapter {\n const fields: Field[] = [\n {\n name: '_key',\n type: 'text',\n admin: {\n hidden: true,\n },\n },\n ]\n\n return (): GeneratedAdapter => {\n const {\n options: { acl = 'public-read', ...utOptions },\n } = options\n\n const utApi = new UTApi(utOptions)\n\n return {\n name: 'uploadthing',\n fields,\n generateURL,\n handleDelete: getHandleDelete({ utApi }),\n handleUpload: getHandleUpload({ acl, utApi }),\n staticHandler: getHandler({ utApi }),\n }\n }\n}\n"],"names":["cloudStoragePlugin","UTApi","generateURL","getHandleDelete","getHandleUpload","getHandler","uploadthingStorage","uploadthingStorageOptions","incomingConfig","enabled","options","acl","adapter","uploadthingInternal","collectionsWithAdapter","Object","entries","collections","reduce","acc","slug","collOptions","config","map","collection","upload","disableLocalStorage","fields","name","type","admin","hidden","utOptions","utApi","handleDelete","handleUpload","staticHandler"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAUA,SAASA,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,KAAK,QAAQ,qBAAoB;AAE1C,SAASC,WAAW,QAAQ,mBAAkB;AAC9C,SAASC,eAAe,QAAQ,oBAAmB;AACnD,SAASC,eAAe,QAAQ,oBAAmB;AACnD,SAASC,UAAU,QAAQ,qBAAoB;AA+B/C,OAAO,MAAMC,qBACX,CAACC,4BACD,CAACC;QACC,IAAID,0BAA0BE,OAAO,KAAK,O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YACLJ,MAAM;YACND;YACAzB;YACAgC,cAAc/B,gBAAgB;gBAAE8B;YAAM;YACtCE,cAAc/B,gBAAgB;gBAAEO;gBAAKsB;YAAM;YAC3CG,eAAe/B,WAAW;gBAAE4B;YAAM;QACpC;IACF;AACF"}
@@ -0,0 +1,8 @@
1
+ import type { StaticHandler } from '@payloadcms/plugin-cloud-storage/types';
2
+ import type { UTApi } from 'uploadthing/server';
3
+ type Args = {
4
+ utApi: UTApi;
5
+ };
6
+ export declare const getHandler: ({ utApi }: Args) => StaticHandler;
7
+ export {};
8
+ //# sourceMappingURL=staticHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"staticHandler.d.ts","sourceRoot":"","sources":["../src/staticHandler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wCAAwC,CAAA;AAE3E,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAI/C,KAAK,IAAI,GAAG;IACV,KAAK,EAAE,KAAK,CAAA;CACb,CAAA;AAED,eAAO,MAAM,UAAU,cAAe,IAAI,KAAG,aAqE5C,CAAA"}
@@ -0,0 +1,80 @@
1
+ import { getKeyFromFilename } from './utilities.js';
2
+ export const getHandler = ({ utApi })=>{
3
+ return async (req, { doc, params: { collection, filename } })=>{
4
+ try {
5
+ const collectionConfig = req.payload.collections[collection]?.config;
6
+ let retrievedDoc = doc;
7
+ if (!retrievedDoc) {
8
+ const or = [
9
+ {
10
+ filename: {
11
+ equals: filename
12
+ }
13
+ }
14
+ ];
15
+ if (collectionConfig.upload.imageSizes) {
16
+ collectionConfig.upload.imageSizes.forEach(({ name })=>{
17
+ or.push({
18
+ [`sizes.${name}.filename`]: {
19
+ equals: filename
20
+ }
21
+ });
22
+ });
23
+ }
24
+ const result = await req.payload.db.findOne({
25
+ collection,
26
+ req,
27
+ where: {
28
+ or
29
+ }
30
+ });
31
+ if (result) retrievedDoc = result;
32
+ }
33
+ if (!retrievedDoc) {
34
+ return new Response(null, {
35
+ status: 404,
36
+ statusText: 'Not Found'
37
+ });
38
+ }
39
+ const key = getKeyFromFilename(retrievedDoc, filename);
40
+ if (!key) {
41
+ return new Response(null, {
42
+ status: 404,
43
+ statusText: 'Not Found'
44
+ });
45
+ }
46
+ const { url: signedURL } = await utApi.getSignedURL(key);
47
+ if (!signedURL) {
48
+ return new Response(null, {
49
+ status: 404,
50
+ statusText: 'Not Found'
51
+ });
52
+ }
53
+ const response = await fetch(signedURL);
54
+ if (!response.ok) {
55
+ return new Response(null, {
56
+ status: 404,
57
+ statusText: 'Not Found'
58
+ });
59
+ }
60
+ const blob = await response.blob();
61
+ return new Response(blob, {
62
+ headers: new Headers({
63
+ 'Content-Length': String(blob.size),
64
+ 'Content-Type': blob.type
65
+ }),
66
+ status: 200
67
+ });
68
+ } catch (err) {
69
+ req.payload.logger.error({
70
+ err,
71
+ msg: 'Unexpected error in staticHandler'
72
+ });
73
+ return new Response('Internal Server Error', {
74
+ status: 500
75
+ });
76
+ }
77
+ };
78
+ };
79
+
80
+ //# sourceMappingURL=staticHandler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/staticHandler.ts"],"sourcesContent":["import type { StaticHandler } from '@payloadcms/plugin-cloud-storage/types'\nimport type { Where } from 'payload/types'\nimport type { UTApi } from 'uploadthing/server'\n\nimport { getKeyFromFilename } from './utilities.js'\n\ntype Args = {\n utApi: UTApi\n}\n\nexport const getHandler = ({ utApi }: Args): StaticHandler => {\n return async (req, { doc, params: { collection, filename } }) => {\n try {\n const collectionConfig = req.payload.collections[collection]?.config\n let retrievedDoc = doc\n\n if (!retrievedDoc) {\n const or: Where[] = [\n {\n filename: {\n equals: filename,\n },\n },\n ]\n\n if (collectionConfig.upload.imageSizes) {\n collectionConfig.upload.imageSizes.forEach(({ name }) => {\n or.push({\n [`sizes.${name}.filename`]: {\n equals: filename,\n },\n })\n })\n }\n\n const result = await req.payload.db.findOne({\n collection,\n req,\n where: { or },\n })\n\n if (result) retrievedDoc = result\n }\n\n if (!retrievedDoc) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n\n const key = getKeyFromFilename(retrievedDoc, filename)\n if (!key) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n\n const { url: signedURL } = await utApi.getSignedURL(key)\n\n if (!signedURL) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n\n const response = await fetch(signedURL)\n\n if (!response.ok) {\n return new Response(null, { status: 404, statusText: 'Not Found' })\n }\n\n const blob = await response.blob()\n\n return new Response(blob, {\n headers: new Headers({\n 'Content-Length': String(blob.size),\n 'Content-Type': blob.type,\n }),\n status: 200,\n })\n } catch (err) {\n req.payload.logger.error({ err, msg: 'Unexpected error in staticHandler' })\n return new Response('Internal Server Error', { status: 500 })\n }\n }\n}\n"],"names":["getKeyFromFilename","getHandler","utApi","req","doc","params","collection","filename","collectionConfig","payload","collections","config","retrievedDoc","or","equals","upload","imageSizes","forEach","name","push","result","db","findOne","where","Response","status","statusText","key","url","signedURL","getSignedURL","response","fetch","ok","blob","headers","Headers","String","size","type","err","logger","error","msg"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAIA,SAASA,kBAAkB,QAAQ,iBAAgB;AAMnD,OAAO,MAAMC,aAAa,CAAC,EAAEC,KAAK,EAAQ;IACxC,OAAO,OAAOC,KAAK,EAAEC,GAAG,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,QAAQ,EAAE,EAAE;QAC1D,IAAI;YACF,MAAMC,mBAAmBL,IAAIM,OAAO,CAACC,WAAW,CAACJ,WAAW,EAAEK;YAC9D,IAAIC,eAAeR;YAEnB,IAAI,CAACQ,cAAc;gBACjB,MAAMC,KAAc;oBAClB;wBACEN,UAAU;4BACRO,QAAQP;wBACV;oBACF;iBACD;gBAED,IAAIC,iBAAiBO,MAAM,CAACC,UAAU,EAAE;oBACt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ACzE,OAAO,IAAInB,SAAS,yBAAyB;gBAAEC,QAAQ;YAAI;QAC7D;IACF;AACF,EAAC"}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Extract '_key' value from the doc safely
3
+ */
4
+ export declare const getKeyFromFilename: (doc: unknown, filename: string) => string | undefined;
5
+ //# sourceMappingURL=utilities.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../src/utilities.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,kBAAkB,QAAS,OAAO,YAAY,MAAM,uBAoBhE,CAAA"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Extract '_key' value from the doc safely
3
+ */ export const getKeyFromFilename = (doc, filename)=>{
4
+ if (doc && typeof doc === 'object' && 'filename' in doc && doc.filename === filename && '_key' in doc) {
5
+ return doc._key;
6
+ }
7
+ if (doc && typeof doc === 'object' && 'sizes' in doc) {
8
+ const sizes = doc.sizes;
9
+ if (typeof sizes === 'object' && sizes !== null) {
10
+ for (const size of Object.values(sizes)){
11
+ if (size?.filename === filename && '_key' in size) {
12
+ return size._key;
13
+ }
14
+ }
15
+ }
16
+ }
17
+ };
18
+
19
+ //# sourceMappingURL=utilities.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utilities.ts"],"sourcesContent":["/**\n * Extract '_key' value from the doc safely\n */\nexport const getKeyFromFilename = (doc: unknown, filename: string) => {\n if (\n doc &&\n typeof doc === 'object' &&\n 'filename' in doc &&\n doc.filename === filename &&\n '_key' in doc\n ) {\n return doc._key as string\n }\n if (doc && typeof doc === 'object' && 'sizes' in doc) {\n const sizes = doc.sizes\n if (typeof sizes === 'object' && sizes !== null) {\n for (const size of Object.values(sizes)) {\n if (size?.filename === filename && '_key' in size) {\n return size._key as string\n }\n }\n }\n }\n}\n"],"names":["getKeyFromFilename","doc","filename","_key","sizes","size","Object","values"],"rangeMappings":";;;;;;;;;;;;;;;;","mappings":"AAAA;;CAEC,GACD,OAAO,MAAMA,qBAAqB,CAACC,KAAcC;IAC/C,IACED,OACA,OAAOA,QAAQ,YACf,cAAcA,OACdA,IAAIC,QAAQ,KAAKA,YACjB,UAAUD,KACV;QACA,OAAOA,IAAIE,IAAI;IACjB;IACA,IAAIF,OAAO,OAAOA,QAAQ,YAAY,WAAWA,KAAK;QACpD,MAAMG,QAAQH,IAAIG,KAAK;QACvB,IAAI,OAAOA,UAAU,YAAYA,UAAU,MAAM;YAC/C,KAAK,MAAMC,QAAQC,OAAOC,MAAM,CAACH,OAAQ;gBACvC,IAAIC,MAAMH,aAAaA,YAAY,UAAUG,MAAM;oBACjD,OAAOA,KAAKF,IAAI;gBAClB;YACF;QACF;IACF;AACF,EAAC"}
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@payloadcms/storage-uploadthing",
3
+ "version": "3.0.0-beta.30",
4
+ "description": "Payload storage adapter for uploadthing",
5
+ "homepage": "https://payloadcms.com",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/payloadcms/payload.git",
9
+ "directory": "packages/storage-uploadthing"
10
+ },
11
+ "license": "MIT",
12
+ "author": "Payload <dev@payloadcms.com> (https://payloadcms.com)",
13
+ "type": "module",
14
+ "exports": {
15
+ ".": {
16
+ "import": "./dist/index.js",
17
+ "require": "./dist/index.js",
18
+ "types": "./dist/index.d.ts"
19
+ }
20
+ },
21
+ "main": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "dependencies": {
27
+ "uploadthing": "^6.10.1",
28
+ "@payloadcms/plugin-cloud-storage": "3.0.0-beta.30"
29
+ },
30
+ "devDependencies": {
31
+ "payload": "3.0.0-beta.30"
32
+ },
33
+ "peerDependencies": {
34
+ "payload": "3.0.0-beta.30"
35
+ },
36
+ "engines": {
37
+ "node": ">=18.20.2"
38
+ },
39
+ "scripts": {
40
+ "build": "pnpm build:swc && pnpm build:types",
41
+ "build:clean": "find . \\( -type d \\( -name build -o -name dist -o -name .cache \\) -o -type f -name tsconfig.tsbuildinfo \\) -exec rm -rf {} + && pnpm build",
42
+ "build:swc": "swc ./src -d ./dist --config-file .swcrc",
43
+ "build:types": "tsc --emitDeclarationOnly --outDir dist",
44
+ "clean": "rimraf {dist,*.tsbuildinfo}"
45
+ }
46
+ }