@humaan/payload-storage-imagekit 2.7.0 → 2.8.0
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 +1 -1
- package/dist/index.js +110 -91
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -157,7 +157,7 @@ How it works:
|
|
|
157
157
|
- **Per-document status:** each document records its actual ImageKit privacy at upload time in `imagekit.isPrivate` (hidden from the admin form). A file's privacy on ImageKit is fixed when it is uploaded, so this stored flag — not the collection's current setting — is the **source of truth** for delivery. This means existing files keep working if you later flip a collection's `private` setting. (Documents uploaded before this flag existed fall back to the collection setting.)
|
|
158
158
|
- **Delivery:** files are served through Payload's own file route (`/api/<collection>/file/<filename>`), which enforces the collection's `access.read` control and then redirects to a freshly signed, expiring ImageKit URL. Nothing signed is ever persisted to the database.
|
|
159
159
|
- **Admin thumbnails** are routed through the same Payload file route so they sign on demand and respect access control (including ImageKit's `ik-thumbnail.jpg` previews for videos and PDFs, with `/ik-video.mp4` applied first for videos without a `.mp4` or `.mov` extension).
|
|
160
|
-
- **Admin indicators:** private collections get a note in their admin description (visible in the list and edit views). The ImageKit metadata
|
|
160
|
+
- **Admin indicators:** private collections get a note in their admin description (visible in the list and edit views). The ImageKit metadata sits in a "Storage: ImageKit" panel that is collapsed by default, hidden while uploading and shown after a file has been stored, with `imagekit.url` visible as a read-only field and `imagekit.isPrivate` shown as read-only when the stored file is private.
|
|
161
161
|
- **Signed URLs:** because the stored `imagekit.url` is the unsigned URL (which 401s for private files), private documents also expose a virtual `imagekit.signedUrl` field — a freshly signed, time-limited URL computed on each read (never persisted). Use it through Payload's API to reach the file directly on ImageKit. The access-control-gated alternative is the document's top-level `url` (the Payload file route).
|
|
162
162
|
- **Access control is required.** Because signing happens at request time behind Payload access control, `disablePayloadAccessControl` cannot be combined with private collections — doing so throws at startup. Set per-collection `access.read` rules to control who can read each file.
|
|
163
163
|
|
package/dist/index.js
CHANGED
|
@@ -187,89 +187,100 @@ const imagekitAdapter = ({ apiRoute, client, clientUploads, privateSlugs, rootFo
|
|
|
187
187
|
clientUploads,
|
|
188
188
|
fields: [
|
|
189
189
|
{
|
|
190
|
-
|
|
191
|
-
|
|
190
|
+
// Presentational wrapper: tucks the ImageKit details into a closed panel without
|
|
191
|
+
// changing the `imagekit.*` data paths.
|
|
192
|
+
type: 'collapsible',
|
|
192
193
|
admin: {
|
|
193
194
|
condition: (data)=>hasStoredImageKitURL(data),
|
|
194
|
-
|
|
195
|
-
disableListFilter: true
|
|
195
|
+
initCollapsed: true
|
|
196
196
|
},
|
|
197
197
|
fields: [
|
|
198
198
|
{
|
|
199
|
-
name: '
|
|
200
|
-
type: '
|
|
199
|
+
name: 'imagekit',
|
|
200
|
+
type: 'group',
|
|
201
201
|
admin: {
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
},
|
|
205
|
-
{
|
|
206
|
-
name: 'url',
|
|
207
|
-
type: 'text',
|
|
208
|
-
admin: {
|
|
209
|
-
readOnly: true
|
|
210
|
-
},
|
|
211
|
-
label: 'URL'
|
|
212
|
-
},
|
|
213
|
-
{
|
|
214
|
-
name: 'isPrivate',
|
|
215
|
-
type: 'checkbox',
|
|
216
|
-
admin: {
|
|
217
|
-
condition: (_data, siblingData)=>isDocumentPrivate({
|
|
218
|
-
imagekit: siblingData
|
|
219
|
-
}, isPrivate),
|
|
220
|
-
description: "Indicates whether this file was uploaded to ImageKit as private. Private files are delivered through signed URLs. Changes to this collection's private option in payload.config only affect future uploads.",
|
|
221
|
-
readOnly: true
|
|
202
|
+
disableListColumn: true,
|
|
203
|
+
disableListFilter: true
|
|
222
204
|
},
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
// Only relevant for private files; the plain `url` works directly for public ones.
|
|
230
|
-
condition: (_data, siblingData)=>isDocumentPrivate({
|
|
231
|
-
imagekit: siblingData
|
|
232
|
-
}, isPrivate),
|
|
233
|
-
description: `Temporary signed URL for reaching this private file directly on ImageKit. Expires ${signedUrlExpiresIn} seconds after load and is regenerated on every read. Note: anyone with this URL can access the file until it expires — it is not gated by Payload access control.`,
|
|
234
|
-
readOnly: true
|
|
235
|
-
},
|
|
236
|
-
hooks: {
|
|
237
|
-
// Computed server-side on read so it is always freshly signed and never persisted.
|
|
238
|
-
afterRead: [
|
|
239
|
-
({ data, siblingData })=>{
|
|
240
|
-
if (!isDocumentPrivate({
|
|
241
|
-
imagekit: siblingData
|
|
242
|
-
}, isPrivate)) {
|
|
243
|
-
return undefined;
|
|
244
|
-
}
|
|
245
|
-
const filename = data?.filename;
|
|
246
|
-
if (!filename) {
|
|
247
|
-
return undefined;
|
|
248
|
-
}
|
|
249
|
-
const source = data || {};
|
|
250
|
-
const documentPrefix = path.posix.join(source.prefix || prefix, source._objectKey || '');
|
|
251
|
-
const storageFilePath = buildStoragePathData({
|
|
252
|
-
collectionPrefix: prefix,
|
|
253
|
-
docPrefix: documentPrefix,
|
|
254
|
-
filename
|
|
255
|
-
}).storageFilePath;
|
|
256
|
-
return buildSignedURL(`/${storageFilePath}`);
|
|
205
|
+
fields: [
|
|
206
|
+
{
|
|
207
|
+
name: 'fileId',
|
|
208
|
+
type: 'text',
|
|
209
|
+
admin: {
|
|
210
|
+
hidden: true
|
|
257
211
|
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
212
|
+
},
|
|
213
|
+
{
|
|
214
|
+
name: 'url',
|
|
215
|
+
type: 'text',
|
|
216
|
+
admin: {
|
|
217
|
+
readOnly: true
|
|
218
|
+
},
|
|
219
|
+
label: 'URL'
|
|
220
|
+
},
|
|
221
|
+
{
|
|
222
|
+
name: 'isPrivate',
|
|
223
|
+
type: 'checkbox',
|
|
224
|
+
admin: {
|
|
225
|
+
condition: (_data, siblingData)=>isDocumentPrivate({
|
|
226
|
+
imagekit: siblingData
|
|
227
|
+
}, isPrivate),
|
|
228
|
+
description: "Indicates whether this file was uploaded to ImageKit as private. Private files are delivered through signed URLs. Changes to this collection's private option in payload.config only affect future uploads.",
|
|
229
|
+
readOnly: true
|
|
230
|
+
},
|
|
231
|
+
label: 'Private file'
|
|
232
|
+
},
|
|
233
|
+
{
|
|
234
|
+
name: 'signedUrl',
|
|
235
|
+
type: 'text',
|
|
236
|
+
admin: {
|
|
237
|
+
// Only relevant for private files; the plain `url` works directly for public ones.
|
|
238
|
+
condition: (_data, siblingData)=>isDocumentPrivate({
|
|
239
|
+
imagekit: siblingData
|
|
240
|
+
}, isPrivate),
|
|
241
|
+
description: `Temporary signed URL for reaching this private file directly on ImageKit. Expires ${signedUrlExpiresIn} seconds after load and is regenerated on every read. Note: anyone with this URL can access the file until it expires — it is not gated by Payload access control.`,
|
|
242
|
+
readOnly: true
|
|
243
|
+
},
|
|
244
|
+
hooks: {
|
|
245
|
+
// Computed server-side on read so it is always freshly signed and never persisted.
|
|
246
|
+
afterRead: [
|
|
247
|
+
({ data, siblingData })=>{
|
|
248
|
+
if (!isDocumentPrivate({
|
|
249
|
+
imagekit: siblingData
|
|
250
|
+
}, isPrivate)) {
|
|
251
|
+
return undefined;
|
|
252
|
+
}
|
|
253
|
+
const filename = data?.filename;
|
|
254
|
+
if (!filename) {
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
const source = data || {};
|
|
258
|
+
const documentPrefix = path.posix.join(source.prefix || prefix, source._objectKey || '');
|
|
259
|
+
const storageFilePath = buildStoragePathData({
|
|
260
|
+
collectionPrefix: prefix,
|
|
261
|
+
docPrefix: documentPrefix,
|
|
262
|
+
filename
|
|
263
|
+
}).storageFilePath;
|
|
264
|
+
return buildSignedURL(`/${storageFilePath}`);
|
|
265
|
+
}
|
|
266
|
+
]
|
|
267
|
+
},
|
|
268
|
+
label: 'Signed URL',
|
|
269
|
+
virtual: true
|
|
270
|
+
},
|
|
271
|
+
{
|
|
272
|
+
name: 'thumbnailUrl',
|
|
273
|
+
type: 'text',
|
|
274
|
+
admin: {
|
|
275
|
+
hidden: true
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
],
|
|
279
|
+
interfaceName: 'imagekitFields',
|
|
280
|
+
label: false
|
|
269
281
|
}
|
|
270
282
|
],
|
|
271
|
-
|
|
272
|
-
label: 'ImageKit'
|
|
283
|
+
label: 'Storage: ImageKit'
|
|
273
284
|
}
|
|
274
285
|
],
|
|
275
286
|
generateURL: ({ filename, prefix: documentPrefix = '' })=>client.helper.buildSrc({
|
|
@@ -624,26 +635,34 @@ export const imagekitStorage = (pluginOptions)=>(config)=>{
|
|
|
624
635
|
if (!configuredSlugs.has(collection.slug)) {
|
|
625
636
|
return collection;
|
|
626
637
|
}
|
|
638
|
+
const withUniqueIdentity = (field)=>{
|
|
639
|
+
if ('name' in field && field.name === '_objectKey') {
|
|
640
|
+
return {
|
|
641
|
+
...field,
|
|
642
|
+
unique: true
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
if (field.type === 'group' && 'name' in field && field.name === 'imagekit') {
|
|
646
|
+
return {
|
|
647
|
+
...field,
|
|
648
|
+
fields: field.fields.map((metadataField)=>'name' in metadataField && metadataField.name === 'fileId' ? {
|
|
649
|
+
...metadataField,
|
|
650
|
+
unique: true
|
|
651
|
+
} : metadataField)
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
// The imagekit group sits inside the adapter's presentational "Storage: ImageKit" panel.
|
|
655
|
+
if (field.type === 'collapsible') {
|
|
656
|
+
return {
|
|
657
|
+
...field,
|
|
658
|
+
fields: field.fields.map(withUniqueIdentity)
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
return field;
|
|
662
|
+
};
|
|
627
663
|
return {
|
|
628
664
|
...collection,
|
|
629
|
-
fields: collection.fields.map(
|
|
630
|
-
if ('name' in field && field.name === '_objectKey') {
|
|
631
|
-
return {
|
|
632
|
-
...field,
|
|
633
|
-
unique: true
|
|
634
|
-
};
|
|
635
|
-
}
|
|
636
|
-
if (field.type === 'group' && 'name' in field && field.name === 'imagekit') {
|
|
637
|
-
return {
|
|
638
|
-
...field,
|
|
639
|
-
fields: field.fields.map((metadataField)=>'name' in metadataField && metadataField.name === 'fileId' ? {
|
|
640
|
-
...metadataField,
|
|
641
|
-
unique: true
|
|
642
|
-
} : metadataField)
|
|
643
|
-
};
|
|
644
|
-
}
|
|
645
|
-
return field;
|
|
646
|
-
})
|
|
665
|
+
fields: collection.fields.map(withUniqueIdentity)
|
|
647
666
|
};
|
|
648
667
|
});
|
|
649
668
|
return output;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n Adapter,\n ClientUploadsConfig,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type {\n CollectionConfig,\n CollectionSlug,\n Config,\n PayloadRequest,\n TypeWithID,\n UploadCollectionSlug,\n Where,\n} from 'payload'\n\nimport ImageKit, { toFile } from '@imagekit/nodejs'\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport {\n buildStoragePathData,\n buildUploadStoragePathData,\n getStorageFilePath,\n initClientUploads,\n} from '@payloadcms/plugin-cloud-storage/utilities'\nimport { openAsBlob } from 'node:fs'\nimport path from 'node:path'\nimport { APIError } from 'payload'\nimport {\n getRangeRequestInfo,\n isXmlMimeType,\n UPLOAD_CONTENT_SECURITY_POLICY,\n} from 'payload/internal'\nimport { validateMimeType } from 'payload/shared'\n\nimport type { VerifiedImageKitUpload } from './clientUploadVerification.js'\n\nimport { imageKitUploadAuthPath, isImageKitReceiptContext } from './clientUploads.js'\nimport {\n createImageKitClientUploadVerifier,\n getClientUploadStorageFilePath,\n} from './clientUploadVerification.js'\nimport { createImageKitUploadAuthHandler } from './endpoints/createImageKitUploadAuthHandler.js'\nimport {\n getAdminThumbnailURL,\n getPrivateAdminThumbnailURL,\n isPdfMimeType,\n isVideoMimeType,\n} from './getAdminThumbnailURL.js'\nimport { getImageKitThumbnailSrc, getVideoPosterSrc } from './imageTransforms.js'\n\nexport type ImageKitCollectionOptions = {\n /**\n * Override Payload's native focal-point picker (`upload.focalPoint`) for this\n * collection.\n */\n focalPoint?: boolean\n /**\n * Upload files in this collection as ImageKit private files (`isPrivateFile: true`)\n * and deliver them only through short-lived signed URLs, behind Payload access control.\n */\n private?: boolean\n}\ntype ImageKitCollectionConfig = ImageKitCollectionOptions | true\ntype ImageKitCollectionMap = Partial<Record<UploadCollectionSlug, ImageKitCollectionConfig>>\n\nconst DEFAULT_SIGNED_URL_EXPIRES_IN = 900\n/**\n * ImageKit re-encodes some uploads and serves the smaller derivative from the plain\n * delivery URL — a 1.9 MB MP4 can come back as 868 KB. That is exactly what we want\n * for visitors, but not when reading the file back to verify a client upload: the\n * bytes and the byte count would both belong to a file ImageKit's API never reported.\n * `orig-true` asks for the untouched original and does not disable optimisation for\n * anyone else.\n */\nconst ORIGINAL_FILE_TRANSFORMATION = 'orig-true'\n\nconst PRIVATE_COLLECTION_DESCRIPTION =\n 'Files in this collection are uploaded to ImageKit as private files and delivered through short-lived signed URLs.'\n\nconst isPrivateCollectionConfig = (value: ImageKitCollectionConfig | undefined): boolean =>\n value !== true && typeof value === 'object' && value?.private === true\n\nconst XML_FAMILY_MIME_TYPES = ['application/xml', 'image/svg+xml', 'text/xml']\n\nconst collectionCanStoreXml = (collection: CollectionConfig): boolean => {\n const upload = collection.upload\n\n if (!upload || upload === true) {\n return Boolean(upload)\n }\n\n // Payload skips MIME and content restrictions when this escape hatch is enabled.\n if (upload.allowRestrictedFileTypes) {\n return true\n }\n\n const allowedMimeTypes = upload.mimeTypes\n\n return (\n !allowedMimeTypes?.length ||\n allowedMimeTypes.some((mimeType) => mimeType.includes('*') || isXmlMimeType(mimeType)) ||\n XML_FAMILY_MIME_TYPES.some((mimeType) => validateMimeType(mimeType, allowedMimeTypes))\n )\n}\n\n/**\n * Whether a specific document is private. The flag stored on the document at upload time\n * (`imagekit.isPrivate`) is the source of truth — a file's privacy on ImageKit is fixed\n * when it is uploaded and does not change if the collection's `private` setting changes\n * later. Falls back to the collection setting for documents uploaded before this flag existed.\n */\nconst isDocumentPrivate = (doc: unknown, collectionIsPrivate: boolean): boolean => {\n const stored = (doc as { imagekit?: { isPrivate?: boolean } } | undefined)?.imagekit?.isPrivate\n\n return typeof stored === 'boolean' ? stored : collectionIsPrivate\n}\ntype ImageKitReference = {\n imagekit?: {\n fileId?: string\n isPrivate?: boolean\n thumbnailUrl?: string\n url?: string\n }\n}\n\ntype UploadDocumentData = {\n thumbnailURL?: string\n} & ImageKitReference\n\nexport type PayloadStorageImageKitConfig = {\n alwaysInsertFields?: boolean\n clientUploads?: ClientUploadsConfig\n collections: ImageKitCollectionMap\n disablePayloadAccessControl?: true\n enabled?: boolean\n /**\n * Broad default for Payload's native focal-point picker (`upload.focalPoint`)\n * on every configured collection. Focal points are disabled by default for\n * configured collections, so prefer collection-level `focalPoint: true` for\n * image collections. A collection's own `upload.focalPoint` still takes\n * precedence.\n */\n focalPoint?: boolean\n folder: string\n privateKey: string\n publicKey: string\n /**\n * Expiry (in seconds) applied to signed URLs generated for private collections.\n * Defaults to 900 (15 minutes). URLs are signed fresh on every request, so a short\n * window is safe.\n */\n signedUrlExpiresIn?: number\n urlEndpoint: string\n}\n\nconst normalizeFolder = (folder: string): string => {\n const normalized = folder.trim().replace(/^\\/+|\\/+$/g, '')\n\n if (!normalized) {\n throw new Error('imagekitStorage: `folder` is required.')\n }\n\n return `/${normalized}`\n}\n\nconst getCollectionFolder = (rootFolder: string, collectionSlug: string): string =>\n path.posix.join(rootFolder, collectionSlug)\n\nconst findImageKitFileId = async (\n imagekit: ImageKit,\n filePath: string,\n): Promise<string | undefined> => {\n const parentPath = path.posix.dirname(filePath)\n const name = path.posix.basename(filePath)\n\n const limit = 100\n\n for (let skip = 0; ; skip += limit) {\n const assets = await imagekit.assets.list({\n type: 'file',\n limit,\n path: parentPath === '/' ? '/' : `${parentPath}/`,\n skip,\n })\n\n const found = assets.find(\n (asset) => 'fileId' in asset && asset.filePath === filePath && asset.name === name,\n )\n\n if (found && 'fileId' in found) {\n return found.fileId\n }\n\n if (assets.length < limit) {\n break\n }\n }\n\n return undefined\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object'\n\nconst getStoredImageKitURL = (doc: unknown): string | undefined => {\n const storedURL = (doc as ImageKitReference | undefined)?.imagekit?.url\n\n return typeof storedURL === 'string' && storedURL.trim().length > 0 ? storedURL : undefined\n}\n\nconst hasStoredImageKitURL = (doc: unknown): boolean => !!getStoredImageKitURL(doc)\n\nconst findUploadDocumentByFilename = async ({\n collection,\n filename,\n prefix,\n req,\n}: {\n collection: string\n filename: string\n prefix?: string\n req: PayloadRequest\n}): Promise<null | TypeWithID> => {\n const constraints: Where[] = [\n {\n filename: {\n equals: filename,\n },\n },\n ]\n\n if (typeof prefix === 'string') {\n constraints.push({\n prefix: {\n equals: prefix,\n },\n })\n }\n\n return req.payload.db.findOne({\n collection,\n req,\n where: {\n and: constraints,\n },\n })\n}\n\nconst applyVerifiedClientUploadToData = <T extends UploadDocumentData>(\n data: T,\n uploaded: VerifiedImageKitUpload,\n buildThumbnailURL: (data: T) => string = getAdminThumbnailURL,\n isPrivate: boolean,\n): T => {\n data.imagekit = {\n fileId: uploaded.fileId,\n isPrivate,\n thumbnailUrl: uploaded.thumbnailUrl,\n url: uploaded.url,\n }\n\n // Preserve the admin preview when the original file was already uploaded client-side.\n data.thumbnailURL = buildThumbnailURL(data)\n\n return data\n}\n\nconst imagekitAdapter = ({\n apiRoute,\n client,\n clientUploads,\n privateSlugs,\n rootFolder,\n signedUrlExpiresIn,\n urlEndpoint,\n verifyClientUpload,\n}: {\n apiRoute: string\n client: ImageKit\n clientUploads?: ClientUploadsConfig\n privateSlugs: Set<string>\n rootFolder: string\n signedUrlExpiresIn: number\n urlEndpoint: string\n verifyClientUpload: ReturnType<typeof createImageKitClientUploadVerifier>\n}): Adapter => {\n const fetchUploadedFile = async ({\n fileSize,\n fileURL,\n mimeType,\n range,\n }: {\n fileSize: number\n fileURL: string\n mimeType: string\n range?: null | string\n }): Promise<Response> => {\n const rangeResult = getRangeRequestInfo({ fileSize, rangeHeader: range ?? null })\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 const normalizedRange =\n rangeResult.type === 'partial'\n ? `bytes=${rangeResult.rangeStart}-${rangeResult.rangeEnd}`\n : undefined\n // Payload cancels image probes after reading a bounded prefix. Next.js memoizes\n // GET responses by teeing their streams; cancelling one branch can then wait\n // forever for its unread cached sibling. An explicit signal opts out of that\n // memoization, while no-store also excludes these reads from the data cache.\n const response = await fetch(fileURL, {\n cache: 'no-store',\n ...(normalizedRange ? { headers: { Range: normalizedRange } } : {}),\n signal: new AbortController().signal,\n })\n\n if (!response.ok || response.status !== rangeResult.status) {\n void response.body?.cancel().catch(() => undefined)\n throw new Error(\n `imagekitStorage: ImageKit returned an unexpected file response (${response.status}).`,\n )\n }\n\n const upstreamLength = response.headers.get('Content-Length')\n const expectedLength = rangeResult.headers['Content-Length']\n const upstreamRange = response.headers.get('Content-Range')\n const expectedRange =\n rangeResult.type === 'partial' ? rangeResult.headers['Content-Range'] : undefined\n\n if (\n (upstreamLength !== null && upstreamLength !== expectedLength) ||\n (expectedRange && upstreamRange !== expectedRange)\n ) {\n void response.body?.cancel().catch(() => undefined)\n throw new Error('imagekitStorage: ImageKit returned mismatched file content metadata.')\n }\n\n const headers = new Headers(rangeResult.headers)\n headers.set('Content-Type', mimeType)\n if (isXmlMimeType(mimeType)) {\n headers.set('Content-Security-Policy', UPLOAD_CONTENT_SECURITY_POLICY)\n }\n\n return new Response(response.body, {\n headers,\n status: response.status,\n })\n }\n\n return ({ collection, prefix = getCollectionFolder(rootFolder, collection.slug) }) => {\n const isPrivate = privateSlugs.has(collection.slug)\n\n // Sign a relative ImageKit path against the configured urlEndpoint. We always sign\n // a computed path (never a stored absolute URL) because ImageKit's signature is\n // derived from the path after stripping urlEndpoint, so the host must match.\n const buildSignedURL = (src: string, tr?: null | string): string =>\n client.helper.buildSrc({\n expiresIn: signedUrlExpiresIn,\n signed: true,\n src,\n transformation: tr ? [{ raw: tr }] : undefined,\n urlEndpoint,\n })\n\n const buildThumbnailURL = (doc: UploadDocumentData): string =>\n isDocumentPrivate(doc, isPrivate)\n ? getPrivateAdminThumbnailURL(doc, collection.slug, apiRoute)\n : getAdminThumbnailURL(doc)\n\n return {\n name: 'imagekit',\n clientUploads,\n fields: [\n {\n name: 'imagekit',\n type: 'group',\n admin: {\n condition: (data) => hasStoredImageKitURL(data),\n disableListColumn: true,\n disableListFilter: true,\n },\n fields: [\n {\n name: 'fileId',\n type: 'text',\n admin: {\n hidden: true,\n },\n },\n {\n name: 'url',\n type: 'text',\n admin: {\n readOnly: true,\n },\n label: 'URL',\n },\n {\n name: 'isPrivate',\n type: 'checkbox',\n admin: {\n condition: (_data, siblingData) =>\n isDocumentPrivate({ imagekit: siblingData }, isPrivate),\n description:\n \"Indicates whether this file was uploaded to ImageKit as private. Private files are delivered through signed URLs. Changes to this collection's private option in payload.config only affect future uploads.\",\n readOnly: true,\n },\n label: 'Private file',\n },\n {\n name: 'signedUrl',\n type: 'text',\n admin: {\n // Only relevant for private files; the plain `url` works directly for public ones.\n condition: (_data, siblingData) =>\n isDocumentPrivate({ imagekit: siblingData }, isPrivate),\n description: `Temporary signed URL for reaching this private file directly on ImageKit. Expires ${signedUrlExpiresIn} seconds after load and is regenerated on every read. Note: anyone with this URL can access the file until it expires — it is not gated by Payload access control.`,\n readOnly: true,\n },\n hooks: {\n // Computed server-side on read so it is always freshly signed and never persisted.\n afterRead: [\n ({ data, siblingData }) => {\n if (!isDocumentPrivate({ imagekit: siblingData }, isPrivate)) {\n return undefined\n }\n\n const filename = (data as { filename?: string } | undefined)?.filename\n\n if (!filename) {\n return undefined\n }\n\n const source = (data || {}) as { _objectKey?: string; prefix?: string }\n const documentPrefix = path.posix.join(\n source.prefix || prefix,\n source._objectKey || '',\n )\n const storageFilePath = buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: documentPrefix,\n filename,\n }).storageFilePath\n\n return buildSignedURL(`/${storageFilePath}`)\n },\n ],\n },\n label: 'Signed URL',\n virtual: true,\n },\n {\n name: 'thumbnailUrl',\n type: 'text',\n admin: {\n hidden: true,\n },\n },\n ],\n interfaceName: 'imagekitFields',\n label: 'ImageKit',\n },\n ],\n generateURL: ({ filename, prefix: documentPrefix = '' }) =>\n client.helper.buildSrc({\n src: `/${buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: documentPrefix,\n filename,\n }).storageFilePath}`,\n urlEndpoint,\n }),\n handleDelete: async ({ doc, storageFilePath }) => {\n const storedFileId = (doc as ImageKitReference & typeof doc).imagekit?.fileId\n const fileId =\n storedFileId || (await findImageKitFileId(client, `/${storageFilePath.replace(/^\\/+/, '')}`))\n\n if (!fileId) {\n return\n }\n\n await client.files.delete(fileId)\n },\n handleUpload: async ({ clientUploadContext, data, file, storageFilePath }) => {\n if (clientUploadContext) {\n const uploaded = await verifyClientUpload({\n collectionSlug: collection.slug,\n context: clientUploadContext,\n })\n\n return applyVerifiedClientUploadToData(data, uploaded, buildThumbnailURL, isPrivate)\n }\n\n // ImageKit's `toFile()` consumes async iterables before starting the request. A file-backed\n // Blob keeps temporary-file uploads lazy so FormData can stream them from disk instead.\n const uploadSource = file.tempFilePath\n ? await openAsBlob(file.tempFilePath, { type: file.mimeType })\n : file.buffer\n const uploadFile = await toFile(uploadSource, file.filename, { type: file.mimeType })\n const uploadFolder = path.posix.dirname(`/${storageFilePath.replace(/^\\/+/, '')}`)\n const uploadFilename = path.posix.basename(storageFilePath)\n\n const uploaded = await client.files.upload({\n file: uploadFile,\n fileName: uploadFilename,\n folder: uploadFolder,\n useUniqueFileName: false,\n ...(isPrivate ? { isPrivateFile: true } : {}),\n })\n\n data.imagekit = {\n fileId: uploaded.fileId,\n isPrivate,\n thumbnailUrl: uploaded.thumbnailUrl,\n url: uploaded.url,\n }\n\n // Set the root-level thumbnailURL that Payload's admin interface expects.\n // `buildThumbnailURL` needs the filename, which Payload may not have copied onto\n // `data` yet at this point, so fall back to the uploaded file's name.\n data.thumbnailURL = buildThumbnailURL({\n ...data,\n filename: (data as { filename?: string }).filename || uploadFilename,\n })\n\n return data\n },\n requiresClientUploadReceipt: true,\n staticHandler: async (req, args) => {\n const requestURL = new URL(req.url || 'http://localhost')\n const tr = requestURL.searchParams.get('tr')\n const hasClientUploadContext = 'clientUploadContext' in args.params\n\n if (hasClientUploadContext) {\n const clientUploadContext = args.params.clientUploadContext\n\n if (!isImageKitReceiptContext(clientUploadContext)) {\n throw new APIError('Invalid ImageKit client upload context.', 400)\n }\n\n const uploadedFile = await verifyClientUpload({\n collectionSlug: collection.slug,\n context: clientUploadContext,\n })\n const expectedFilePath = getClientUploadStorageFilePath({\n collectionPrefix: prefix,\n context: clientUploadContext,\n })\n const verifiedFileURL = isPrivate\n ? buildSignedURL(`/${expectedFilePath}`, ORIGINAL_FILE_TRANSFORMATION)\n : client.helper.buildSrc({\n src: `/${expectedFilePath}`,\n transformation: [{ raw: ORIGINAL_FILE_TRANSFORMATION }],\n urlEndpoint,\n })\n\n return fetchUploadedFile({\n fileSize: uploadedFile.size,\n fileURL: verifiedFileURL,\n mimeType: uploadedFile.mimeType,\n range: req.headers.get('Range'),\n })\n }\n\n const doc =\n args.doc ||\n (await findUploadDocumentByFilename({\n collection: args.params.collection,\n filename: args.params.filename,\n prefix: args.params.prefix,\n req,\n }))\n\n const storageFilePath = await getStorageFilePath({\n collection,\n collectionPrefix: prefix,\n doc: doc || undefined,\n filename: args.params.filename,\n prefixQueryParam: args.params.prefix,\n req,\n })\n const imageKitPath = `/${storageFilePath.replace(/^\\/+/, '')}`\n const mimeType = (doc as { mimeType?: string } | null)?.mimeType\n\n // XML-family uploads (including SVG) must pass through Payload so its CSP is\n // present even when ImageKit uses a custom, same-origin delivery domain.\n if (typeof mimeType === 'string' && isXmlMimeType(mimeType)) {\n const filesize = (doc as { filesize?: number } | null)?.filesize\n\n if (typeof filesize !== 'number' || !Number.isSafeInteger(filesize) || filesize < 0) {\n throw new APIError('Stored ImageKit file metadata is incomplete.', 500)\n }\n\n const fileURL = isDocumentPrivate(doc, isPrivate)\n ? buildSignedURL(imageKitPath, ORIGINAL_FILE_TRANSFORMATION)\n : client.helper.buildSrc({\n src: imageKitPath,\n transformation: [{ raw: ORIGINAL_FILE_TRANSFORMATION }],\n urlEndpoint,\n })\n\n return fetchUploadedFile({\n fileSize: filesize,\n fileURL,\n mimeType,\n range: req.headers.get('Range'),\n })\n }\n\n // Sign based on the document's stored status, not the collection's current\n // setting, so files keep working if the collection's privacy is changed later.\n if (isDocumentPrivate(doc, isPrivate)) {\n let signSrc = imageKitPath\n\n // A `tr` request for a video/PDF is a thumbnail request (the plain transform\n // can't render a preview); serve ImageKit's generated thumbnail instead.\n if (tr && isVideoMimeType(mimeType)) {\n signSrc = getVideoPosterSrc(signSrc)\n } else if (tr && isPdfMimeType(mimeType)) {\n signSrc = getImageKitThumbnailSrc(signSrc)\n }\n\n return Response.redirect(buildSignedURL(signSrc, tr), 302)\n }\n\n const imageKitURL = client.helper.buildSrc({\n src:\n getStoredImageKitURL(doc) ||\n imageKitPath,\n transformation: tr ? [{ raw: tr }] : undefined,\n urlEndpoint,\n })\n\n return Response.redirect(imageKitURL, 302)\n },\n }\n }\n}\n\nconst toCloudStorageCollections = (\n collections: ImageKitCollectionMap,\n adapter: Adapter,\n privateSlugs: Set<string>,\n rootFolder: string,\n disablePayloadAccessControl?: true,\n): Partial<Record<CollectionSlug, CollectionOptions>> => {\n const mappedCollections: Partial<Record<CollectionSlug, CollectionOptions>> = {}\n\n for (const collectionSlug of Object.keys(collections)) {\n mappedCollections[collectionSlug] = {\n adapter,\n disableLocalStorage: true,\n // Private files require Payload access control so URLs can be signed at serve time.\n disablePayloadAccessControl: privateSlugs.has(collectionSlug)\n ? undefined\n : disablePayloadAccessControl,\n prefix: getCollectionFolder(rootFolder, collectionSlug),\n }\n }\n\n return mappedCollections\n}\n\nexport const imagekitStorage =\n (pluginOptions: PayloadStorageImageKitConfig) =>\n (config: Config): Config => {\n const {\n alwaysInsertFields,\n clientUploads,\n collections,\n disablePayloadAccessControl,\n enabled,\n focalPoint,\n folder,\n privateKey,\n publicKey,\n signedUrlExpiresIn: signedUrlExpiresInOption,\n urlEndpoint,\n } = pluginOptions\n\n if (!privateKey?.trim()) {\n throw new Error('imagekitStorage: `privateKey` is required.')\n }\n\n if (!publicKey?.trim()) {\n throw new Error('imagekitStorage: `publicKey` is required.')\n }\n\n if (!urlEndpoint?.trim()) {\n throw new Error('imagekitStorage: `urlEndpoint` is required.')\n }\n\n if (!collections || Object.keys(collections).length === 0) {\n throw new Error('imagekitStorage: `collections` must include at least one upload collection.')\n }\n\n const privateSlugs = new Set(\n Object.entries(collections)\n .filter(([, value]) => isPrivateCollectionConfig(value))\n .map(([slug]) => slug),\n )\n const configuredSlugs = new Set(Object.keys(collections))\n\n if (disablePayloadAccessControl && privateSlugs.size > 0) {\n throw new Error(\n 'imagekitStorage: `disablePayloadAccessControl` cannot be used with private collections. Private files require Payload access control to remain enabled so URLs can be signed at serve time.',\n )\n }\n\n if (disablePayloadAccessControl) {\n const xmlCollectionSlugs = (config.collections || [])\n .filter(\n (collection) =>\n configuredSlugs.has(collection.slug) && collectionCanStoreXml(collection),\n )\n .map((collection) => collection.slug)\n\n if (xmlCollectionSlugs.length > 0) {\n throw new Error(\n `imagekitStorage: \\`disablePayloadAccessControl\\` cannot be used with collections that can store XML-family files (${xmlCollectionSlugs.join(', ')}). XML-family files require Payload's file route so its Content Security Policy is applied. Configure a MIME allow list that excludes SVG/XML, or keep Payload access control enabled.`,\n )\n }\n }\n\n const signedUrlExpiresIn =\n typeof signedUrlExpiresInOption === 'number' && signedUrlExpiresInOption > 0\n ? signedUrlExpiresInOption\n : DEFAULT_SIGNED_URL_EXPIRES_IN\n const apiRoute = config.routes?.api ?? '/api'\n\n const rootFolder = normalizeFolder(folder)\n\n const imageKitClient = new ImageKit({ privateKey })\n const collectionSecurity = Object.fromEntries(\n (config.collections || [])\n .filter((collection) => configuredSlugs.has(collection.slug))\n .map((collection) => [\n collection.slug,\n {\n collection,\n isPrivate: privateSlugs.has(collection.slug),\n prefix: getCollectionFolder(rootFolder, collection.slug),\n },\n ]),\n )\n const verifyClientUpload = createImageKitClientUploadVerifier({\n client: imageKitClient,\n collections: collectionSecurity,\n })\n const adapter = imagekitAdapter({\n apiRoute,\n client: imageKitClient,\n clientUploads,\n privateSlugs,\n rootFolder,\n signedUrlExpiresIn,\n urlEndpoint,\n verifyClientUpload,\n })\n\n const configWithCropDisabled: Config = {\n ...config,\n collections: (config.collections || []).map((collection) => {\n if (!configuredSlugs.has(collection.slug)) {\n return collection\n }\n\n const isCollectionPrivate = privateSlugs.has(collection.slug)\n const buildThumbnailURL = (doc: unknown): string =>\n isDocumentPrivate(doc, isCollectionPrivate)\n ? getPrivateAdminThumbnailURL(doc, collection.slug, apiRoute)\n : getAdminThumbnailURL(doc)\n\n const collectionOptions = collections[collection.slug]\n const collectionFocalPoint =\n collectionOptions !== true &&\n typeof collectionOptions === 'object' &&\n typeof collectionOptions.focalPoint === 'boolean'\n ? collectionOptions.focalPoint\n : undefined\n\n // Surface a \"this is a private collection\" note in the list and edit views.\n // Preserve an existing string description by appending; leave custom\n // component descriptions untouched.\n const existingDescription = collection.admin?.description\n const baseAdmin = isCollectionPrivate\n ? {\n ...(collection.admin || {}),\n description:\n typeof existingDescription === 'string' && existingDescription.trim().length > 0\n ? `${existingDescription} ${PRIVATE_COLLECTION_DESCRIPTION}`\n : (existingDescription ?? PRIVATE_COLLECTION_DESCRIPTION),\n }\n : collection.admin\n\n return {\n ...collection,\n admin: baseAdmin,\n hooks: {\n ...(collection.hooks || {}),\n beforeChange: [\n ...(collection.hooks?.beforeChange || []),\n async ({ data, req }) => {\n if (!isRecord(data) || !req.file?.clientUploadContext) {\n return data\n }\n\n const context = req.file.clientUploadContext\n const requestMimeType = req.file.mimetype.split(';', 1)[0]?.trim().toLowerCase()\n if (\n !isImageKitReceiptContext(context) ||\n context.filename !== data.filename ||\n context.filename !== req.file.name ||\n context.expectedMimeType !== requestMimeType ||\n // Payload can clear req.file.size when preparing an in-memory image.\n // generateFileData preserves the original size on the document.\n context.expectedSize !== data.filesize\n ) {\n throw new APIError('ImageKit client upload reference does not match this request.', 400)\n }\n\n const uploaded = await verifyClientUpload({\n collectionSlug: collection.slug,\n context,\n })\n // A provider file can only be claimed once, including through legacy receipts.\n // The unique file ID index also rejects concurrent claims.\n const existing = await req.payload.db.findOne({\n collection: collection.slug,\n req,\n where: {\n 'imagekit.fileId': {\n equals: uploaded.fileId,\n },\n },\n })\n if (existing) {\n throw new APIError('This ImageKit client upload receipt has already been used.', 400)\n }\n\n data.filename = uploaded.name\n data.filesize = uploaded.size\n data.mimeType = uploaded.mimeType\n\n return applyVerifiedClientUploadToData(\n data,\n uploaded,\n buildThumbnailURL,\n isCollectionPrivate,\n )\n },\n ],\n beforeOperation: [\n ...(collection.hooks?.beforeOperation || []),\n ({ args, operation, req }) => {\n if (\n (operation !== 'create' && operation !== 'update') ||\n req.context?.skipCloudStorage ||\n !req.file ||\n req.file.clientUploadContext ||\n !('data' in args) ||\n !isRecord(args.data) ||\n typeof args.data.prefix !== 'string'\n ) {\n return args\n }\n\n // Payload checks filename uniqueness before cloud storage's beforeChange\n // normalizes the prefix. Use the persisted form during that lookup too.\n args.data.prefix = buildUploadStoragePathData({\n collectionPrefix: getCollectionFolder(rootFolder, collection.slug),\n docPrefix: args.data.prefix,\n filename: req.file.name,\n }).sanitizedDocPrefix\n return args\n },\n ],\n },\n upload: {\n // Focal points are opt-in for configured collections. Plugin-level\n // and collection-level options can override this default; a\n // collection's own `upload.focalPoint` still wins because it is\n // spread in afterwards.\n focalPoint: false,\n ...(typeof focalPoint === 'boolean' ? { focalPoint } : {}),\n ...(typeof collectionFocalPoint === 'boolean'\n ? { focalPoint: collectionFocalPoint }\n : {}),\n ...(typeof collection.upload === 'object' ? collection.upload : {}),\n adminThumbnail: ({ doc }) => buildThumbnailURL(doc),\n crop: false,\n },\n }\n }),\n }\n\n const uploadCollections = Object.fromEntries(\n Object.keys(collections).map((collectionSlug) => [\n collectionSlug,\n {\n isPrivate: privateSlugs.has(collectionSlug),\n prefix: getCollectionFolder(rootFolder, collectionSlug),\n },\n ]),\n ) as Partial<\n Record<UploadCollectionSlug, { isPrivate: boolean; prefix: string }>\n >\n\n initClientUploads({\n clientHandler: '@humaan/payload-storage-imagekit/client#ImageKitUploadHandler',\n collections: uploadCollections,\n config: configWithCropDisabled,\n enabled: enabled !== false && Boolean(clientUploads),\n serverHandler: createImageKitUploadAuthHandler({\n access: typeof clientUploads === 'object' ? clientUploads.access : undefined,\n collections: uploadCollections,\n privateKey,\n publicKey,\n verifyClientUpload,\n }),\n serverHandlerPath: imageKitUploadAuthPath,\n })\n\n const output = cloudStoragePlugin({\n alwaysInsertFields,\n collections: toCloudStorageCollections(\n collections,\n adapter,\n privateSlugs,\n rootFolder,\n disablePayloadAccessControl,\n ),\n enabled,\n })(configWithCropDisabled)\n\n // Make the provider identity unique at persistence time to reject concurrent receipt replays.\n // Keep the legacy object key index for existing uploads.\n output.collections = (output.collections || []).map((collection) => {\n if (!configuredSlugs.has(collection.slug)) {\n return collection\n }\n\n return {\n ...collection,\n fields: collection.fields.map((field) => {\n if ('name' in field && field.name === '_objectKey') {\n return { ...field, unique: true }\n }\n if (field.type === 'group' && 'name' in field && field.name === 'imagekit') {\n return {\n ...field,\n fields: field.fields.map((metadataField) =>\n 'name' in metadataField && metadataField.name === 'fileId'\n ? { ...metadataField, unique: true }\n : metadataField,\n ),\n }\n }\n return field\n }),\n }\n })\n\n return output\n }\n\nexport { migrateFolder } from './migrate.js'\nexport type { MigrateFolderOptions, MigrationJobResult } from './migrate.js'\n\n// Backward-compatible alias\nexport const payloadStorageImagekit = imagekitStorage\nexport const payloadStorageImageKit = imagekitStorage\n\nexport type PayloadStorageImagekitConfig = PayloadStorageImageKitConfig\n"],"names":["ImageKit","toFile","cloudStoragePlugin","buildStoragePathData","buildUploadStoragePathData","getStorageFilePath","initClientUploads","openAsBlob","path","APIError","getRangeRequestInfo","isXmlMimeType","UPLOAD_CONTENT_SECURITY_POLICY","validateMimeType","imageKitUploadAuthPath","isImageKitReceiptContext","createImageKitClientUploadVerifier","getClientUploadStorageFilePath","createImageKitUploadAuthHandler","getAdminThumbnailURL","getPrivateAdminThumbnailURL","isPdfMimeType","isVideoMimeType","getImageKitThumbnailSrc","getVideoPosterSrc","DEFAULT_SIGNED_URL_EXPIRES_IN","ORIGINAL_FILE_TRANSFORMATION","PRIVATE_COLLECTION_DESCRIPTION","isPrivateCollectionConfig","value","private","XML_FAMILY_MIME_TYPES","collectionCanStoreXml","collection","upload","Boolean","allowRestrictedFileTypes","allowedMimeTypes","mimeTypes","length","some","mimeType","includes","isDocumentPrivate","doc","collectionIsPrivate","stored","imagekit","isPrivate","normalizeFolder","folder","normalized","trim","replace","Error","getCollectionFolder","rootFolder","collectionSlug","posix","join","findImageKitFileId","filePath","parentPath","dirname","name","basename","limit","skip","assets","list","type","found","find","asset","fileId","undefined","isRecord","getStoredImageKitURL","storedURL","url","hasStoredImageKitURL","findUploadDocumentByFilename","filename","prefix","req","constraints","equals","push","payload","db","findOne","where","and","applyVerifiedClientUploadToData","data","uploaded","buildThumbnailURL","thumbnailUrl","thumbnailURL","imagekitAdapter","apiRoute","client","clientUploads","privateSlugs","signedUrlExpiresIn","urlEndpoint","verifyClientUpload","fetchUploadedFile","fileSize","fileURL","range","rangeResult","rangeHeader","Response","headers","Headers","status","normalizedRange","rangeStart","rangeEnd","response","fetch","cache","Range","signal","AbortController","ok","body","cancel","catch","upstreamLength","get","expectedLength","upstreamRange","expectedRange","set","slug","has","buildSignedURL","src","tr","helper","buildSrc","expiresIn","signed","transformation","raw","fields","admin","condition","disableListColumn","disableListFilter","hidden","readOnly","label","_data","siblingData","description","hooks","afterRead","source","documentPrefix","_objectKey","storageFilePath","collectionPrefix","docPrefix","virtual","interfaceName","generateURL","handleDelete","storedFileId","files","delete","handleUpload","clientUploadContext","file","context","uploadSource","tempFilePath","buffer","uploadFile","uploadFolder","uploadFilename","fileName","useUniqueFileName","isPrivateFile","requiresClientUploadReceipt","staticHandler","args","requestURL","URL","searchParams","hasClientUploadContext","params","uploadedFile","expectedFilePath","verifiedFileURL","size","prefixQueryParam","imageKitPath","filesize","Number","isSafeInteger","signSrc","redirect","imageKitURL","toCloudStorageCollections","collections","adapter","disablePayloadAccessControl","mappedCollections","Object","keys","disableLocalStorage","imagekitStorage","pluginOptions","config","alwaysInsertFields","enabled","focalPoint","privateKey","publicKey","signedUrlExpiresInOption","Set","entries","filter","map","configuredSlugs","xmlCollectionSlugs","routes","api","imageKitClient","collectionSecurity","fromEntries","configWithCropDisabled","isCollectionPrivate","collectionOptions","collectionFocalPoint","existingDescription","baseAdmin","beforeChange","requestMimeType","mimetype","split","toLowerCase","expectedMimeType","expectedSize","existing","beforeOperation","operation","skipCloudStorage","sanitizedDocPrefix","adminThumbnail","crop","uploadCollections","clientHandler","serverHandler","access","serverHandlerPath","output","field","unique","metadataField","migrateFolder","payloadStorageImagekit","payloadStorageImageKit"],"mappings":"AAeA,OAAOA,YAAYC,MAAM,QAAQ,mBAAkB;AACnD,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SACEC,oBAAoB,EACpBC,0BAA0B,EAC1BC,kBAAkB,EAClBC,iBAAiB,QACZ,6CAA4C;AACnD,SAASC,UAAU,QAAQ,UAAS;AACpC,OAAOC,UAAU,YAAW;AAC5B,SAASC,QAAQ,QAAQ,UAAS;AAClC,SACEC,mBAAmB,EACnBC,aAAa,EACbC,8BAA8B,QACzB,mBAAkB;AACzB,SAASC,gBAAgB,QAAQ,iB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EH,8FAA8F;QAC9F,yDAAyD;QACzDyB,OAAOpD,WAAW,GAAG,AAACoD,CAAAA,OAAOpD,WAAW,IAAI,EAAE,AAAD,EAAGmB,GAAG,CAAC,CAACjM;YACnD,IAAI,CAACkM,gBAAgB1F,GAAG,CAACxG,WAAWuG,IAAI,GAAG;gBACzC,OAAOvG;YACT;YAEA,OAAO;gBACL,GAAGA,UAAU;gBACbkH,QAAQlH,WAAWkH,MAAM,CAAC+E,GAAG,CAAC,CAACkC;oBAC7B,IAAI,UAAUA,SAASA,MAAMpM,IAAI,KAAK,cAAc;wBAClD,OAAO;4BAAE,GAAGoM,KAAK;4BAAEC,QAAQ;wBAAK;oBAClC;oBACA,IAAID,MAAM9L,IAAI,KAAK,WAAW,UAAU8L,SAASA,MAAMpM,IAAI,KAAK,YAAY;wBAC1E,OAAO;4BACL,GAAGoM,KAAK;4BACRjH,QAAQiH,MAAMjH,MAAM,CAAC+E,GAAG,CAAC,CAACoC,gBACxB,UAAUA,iBAAiBA,cAActM,IAAI,KAAK,WAC9C;oCAAE,GAAGsM,aAAa;oCAAED,QAAQ;gCAAK,IACjCC;wBAER;oBACF;oBACA,OAAOF;gBACT;YACF;QACF;QAEA,OAAOD;IACT,EAAC;AAEH,SAASI,aAAa,QAAQ,eAAc;AAG5C,4BAA4B;AAC5B,OAAO,MAAMC,yBAAyBlD,gBAAe;AACrD,OAAO,MAAMmD,yBAAyBnD,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n Adapter,\n ClientUploadsConfig,\n CollectionOptions,\n} from '@payloadcms/plugin-cloud-storage/types'\nimport type {\n CollectionConfig,\n CollectionSlug,\n Config,\n Field,\n PayloadRequest,\n TypeWithID,\n UploadCollectionSlug,\n Where,\n} from 'payload'\n\nimport ImageKit, { toFile } from '@imagekit/nodejs'\nimport { cloudStoragePlugin } from '@payloadcms/plugin-cloud-storage'\nimport {\n buildStoragePathData,\n buildUploadStoragePathData,\n getStorageFilePath,\n initClientUploads,\n} from '@payloadcms/plugin-cloud-storage/utilities'\nimport { openAsBlob } from 'node:fs'\nimport path from 'node:path'\nimport { APIError } from 'payload'\nimport {\n getRangeRequestInfo,\n isXmlMimeType,\n UPLOAD_CONTENT_SECURITY_POLICY,\n} from 'payload/internal'\nimport { validateMimeType } from 'payload/shared'\n\nimport type { VerifiedImageKitUpload } from './clientUploadVerification.js'\n\nimport { imageKitUploadAuthPath, isImageKitReceiptContext } from './clientUploads.js'\nimport {\n createImageKitClientUploadVerifier,\n getClientUploadStorageFilePath,\n} from './clientUploadVerification.js'\nimport { createImageKitUploadAuthHandler } from './endpoints/createImageKitUploadAuthHandler.js'\nimport {\n getAdminThumbnailURL,\n getPrivateAdminThumbnailURL,\n isPdfMimeType,\n isVideoMimeType,\n} from './getAdminThumbnailURL.js'\nimport { getImageKitThumbnailSrc, getVideoPosterSrc } from './imageTransforms.js'\n\nexport type ImageKitCollectionOptions = {\n /**\n * Override Payload's native focal-point picker (`upload.focalPoint`) for this\n * collection.\n */\n focalPoint?: boolean\n /**\n * Upload files in this collection as ImageKit private files (`isPrivateFile: true`)\n * and deliver them only through short-lived signed URLs, behind Payload access control.\n */\n private?: boolean\n}\ntype ImageKitCollectionConfig = ImageKitCollectionOptions | true\ntype ImageKitCollectionMap = Partial<Record<UploadCollectionSlug, ImageKitCollectionConfig>>\n\nconst DEFAULT_SIGNED_URL_EXPIRES_IN = 900\n/**\n * ImageKit re-encodes some uploads and serves the smaller derivative from the plain\n * delivery URL — a 1.9 MB MP4 can come back as 868 KB. That is exactly what we want\n * for visitors, but not when reading the file back to verify a client upload: the\n * bytes and the byte count would both belong to a file ImageKit's API never reported.\n * `orig-true` asks for the untouched original and does not disable optimisation for\n * anyone else.\n */\nconst ORIGINAL_FILE_TRANSFORMATION = 'orig-true'\n\nconst PRIVATE_COLLECTION_DESCRIPTION =\n 'Files in this collection are uploaded to ImageKit as private files and delivered through short-lived signed URLs.'\n\nconst isPrivateCollectionConfig = (value: ImageKitCollectionConfig | undefined): boolean =>\n value !== true && typeof value === 'object' && value?.private === true\n\nconst XML_FAMILY_MIME_TYPES = ['application/xml', 'image/svg+xml', 'text/xml']\n\nconst collectionCanStoreXml = (collection: CollectionConfig): boolean => {\n const upload = collection.upload\n\n if (!upload || upload === true) {\n return Boolean(upload)\n }\n\n // Payload skips MIME and content restrictions when this escape hatch is enabled.\n if (upload.allowRestrictedFileTypes) {\n return true\n }\n\n const allowedMimeTypes = upload.mimeTypes\n\n return (\n !allowedMimeTypes?.length ||\n allowedMimeTypes.some((mimeType) => mimeType.includes('*') || isXmlMimeType(mimeType)) ||\n XML_FAMILY_MIME_TYPES.some((mimeType) => validateMimeType(mimeType, allowedMimeTypes))\n )\n}\n\n/**\n * Whether a specific document is private. The flag stored on the document at upload time\n * (`imagekit.isPrivate`) is the source of truth — a file's privacy on ImageKit is fixed\n * when it is uploaded and does not change if the collection's `private` setting changes\n * later. Falls back to the collection setting for documents uploaded before this flag existed.\n */\nconst isDocumentPrivate = (doc: unknown, collectionIsPrivate: boolean): boolean => {\n const stored = (doc as { imagekit?: { isPrivate?: boolean } } | undefined)?.imagekit?.isPrivate\n\n return typeof stored === 'boolean' ? stored : collectionIsPrivate\n}\ntype ImageKitReference = {\n imagekit?: {\n fileId?: string\n isPrivate?: boolean\n thumbnailUrl?: string\n url?: string\n }\n}\n\ntype UploadDocumentData = {\n thumbnailURL?: string\n} & ImageKitReference\n\nexport type PayloadStorageImageKitConfig = {\n alwaysInsertFields?: boolean\n clientUploads?: ClientUploadsConfig\n collections: ImageKitCollectionMap\n disablePayloadAccessControl?: true\n enabled?: boolean\n /**\n * Broad default for Payload's native focal-point picker (`upload.focalPoint`)\n * on every configured collection. Focal points are disabled by default for\n * configured collections, so prefer collection-level `focalPoint: true` for\n * image collections. A collection's own `upload.focalPoint` still takes\n * precedence.\n */\n focalPoint?: boolean\n folder: string\n privateKey: string\n publicKey: string\n /**\n * Expiry (in seconds) applied to signed URLs generated for private collections.\n * Defaults to 900 (15 minutes). URLs are signed fresh on every request, so a short\n * window is safe.\n */\n signedUrlExpiresIn?: number\n urlEndpoint: string\n}\n\nconst normalizeFolder = (folder: string): string => {\n const normalized = folder.trim().replace(/^\\/+|\\/+$/g, '')\n\n if (!normalized) {\n throw new Error('imagekitStorage: `folder` is required.')\n }\n\n return `/${normalized}`\n}\n\nconst getCollectionFolder = (rootFolder: string, collectionSlug: string): string =>\n path.posix.join(rootFolder, collectionSlug)\n\nconst findImageKitFileId = async (\n imagekit: ImageKit,\n filePath: string,\n): Promise<string | undefined> => {\n const parentPath = path.posix.dirname(filePath)\n const name = path.posix.basename(filePath)\n\n const limit = 100\n\n for (let skip = 0; ; skip += limit) {\n const assets = await imagekit.assets.list({\n type: 'file',\n limit,\n path: parentPath === '/' ? '/' : `${parentPath}/`,\n skip,\n })\n\n const found = assets.find(\n (asset) => 'fileId' in asset && asset.filePath === filePath && asset.name === name,\n )\n\n if (found && 'fileId' in found) {\n return found.fileId\n }\n\n if (assets.length < limit) {\n break\n }\n }\n\n return undefined\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object'\n\nconst getStoredImageKitURL = (doc: unknown): string | undefined => {\n const storedURL = (doc as ImageKitReference | undefined)?.imagekit?.url\n\n return typeof storedURL === 'string' && storedURL.trim().length > 0 ? storedURL : undefined\n}\n\nconst hasStoredImageKitURL = (doc: unknown): boolean => !!getStoredImageKitURL(doc)\n\nconst findUploadDocumentByFilename = async ({\n collection,\n filename,\n prefix,\n req,\n}: {\n collection: string\n filename: string\n prefix?: string\n req: PayloadRequest\n}): Promise<null | TypeWithID> => {\n const constraints: Where[] = [\n {\n filename: {\n equals: filename,\n },\n },\n ]\n\n if (typeof prefix === 'string') {\n constraints.push({\n prefix: {\n equals: prefix,\n },\n })\n }\n\n return req.payload.db.findOne({\n collection,\n req,\n where: {\n and: constraints,\n },\n })\n}\n\nconst applyVerifiedClientUploadToData = <T extends UploadDocumentData>(\n data: T,\n uploaded: VerifiedImageKitUpload,\n buildThumbnailURL: (data: T) => string = getAdminThumbnailURL,\n isPrivate: boolean,\n): T => {\n data.imagekit = {\n fileId: uploaded.fileId,\n isPrivate,\n thumbnailUrl: uploaded.thumbnailUrl,\n url: uploaded.url,\n }\n\n // Preserve the admin preview when the original file was already uploaded client-side.\n data.thumbnailURL = buildThumbnailURL(data)\n\n return data\n}\n\nconst imagekitAdapter = ({\n apiRoute,\n client,\n clientUploads,\n privateSlugs,\n rootFolder,\n signedUrlExpiresIn,\n urlEndpoint,\n verifyClientUpload,\n}: {\n apiRoute: string\n client: ImageKit\n clientUploads?: ClientUploadsConfig\n privateSlugs: Set<string>\n rootFolder: string\n signedUrlExpiresIn: number\n urlEndpoint: string\n verifyClientUpload: ReturnType<typeof createImageKitClientUploadVerifier>\n}): Adapter => {\n const fetchUploadedFile = async ({\n fileSize,\n fileURL,\n mimeType,\n range,\n }: {\n fileSize: number\n fileURL: string\n mimeType: string\n range?: null | string\n }): Promise<Response> => {\n const rangeResult = getRangeRequestInfo({ fileSize, rangeHeader: range ?? null })\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 const normalizedRange =\n rangeResult.type === 'partial'\n ? `bytes=${rangeResult.rangeStart}-${rangeResult.rangeEnd}`\n : undefined\n // Payload cancels image probes after reading a bounded prefix. Next.js memoizes\n // GET responses by teeing their streams; cancelling one branch can then wait\n // forever for its unread cached sibling. An explicit signal opts out of that\n // memoization, while no-store also excludes these reads from the data cache.\n const response = await fetch(fileURL, {\n cache: 'no-store',\n ...(normalizedRange ? { headers: { Range: normalizedRange } } : {}),\n signal: new AbortController().signal,\n })\n\n if (!response.ok || response.status !== rangeResult.status) {\n void response.body?.cancel().catch(() => undefined)\n throw new Error(\n `imagekitStorage: ImageKit returned an unexpected file response (${response.status}).`,\n )\n }\n\n const upstreamLength = response.headers.get('Content-Length')\n const expectedLength = rangeResult.headers['Content-Length']\n const upstreamRange = response.headers.get('Content-Range')\n const expectedRange =\n rangeResult.type === 'partial' ? rangeResult.headers['Content-Range'] : undefined\n\n if (\n (upstreamLength !== null && upstreamLength !== expectedLength) ||\n (expectedRange && upstreamRange !== expectedRange)\n ) {\n void response.body?.cancel().catch(() => undefined)\n throw new Error('imagekitStorage: ImageKit returned mismatched file content metadata.')\n }\n\n const headers = new Headers(rangeResult.headers)\n headers.set('Content-Type', mimeType)\n if (isXmlMimeType(mimeType)) {\n headers.set('Content-Security-Policy', UPLOAD_CONTENT_SECURITY_POLICY)\n }\n\n return new Response(response.body, {\n headers,\n status: response.status,\n })\n }\n\n return ({ collection, prefix = getCollectionFolder(rootFolder, collection.slug) }) => {\n const isPrivate = privateSlugs.has(collection.slug)\n\n // Sign a relative ImageKit path against the configured urlEndpoint. We always sign\n // a computed path (never a stored absolute URL) because ImageKit's signature is\n // derived from the path after stripping urlEndpoint, so the host must match.\n const buildSignedURL = (src: string, tr?: null | string): string =>\n client.helper.buildSrc({\n expiresIn: signedUrlExpiresIn,\n signed: true,\n src,\n transformation: tr ? [{ raw: tr }] : undefined,\n urlEndpoint,\n })\n\n const buildThumbnailURL = (doc: UploadDocumentData): string =>\n isDocumentPrivate(doc, isPrivate)\n ? getPrivateAdminThumbnailURL(doc, collection.slug, apiRoute)\n : getAdminThumbnailURL(doc)\n\n return {\n name: 'imagekit',\n clientUploads,\n fields: [\n {\n // Presentational wrapper: tucks the ImageKit details into a closed panel without\n // changing the `imagekit.*` data paths.\n type: 'collapsible',\n admin: {\n condition: (data) => hasStoredImageKitURL(data),\n initCollapsed: true,\n },\n fields: [\n {\n name: 'imagekit',\n type: 'group',\n admin: {\n disableListColumn: true,\n disableListFilter: true,\n },\n fields: [\n {\n name: 'fileId',\n type: 'text',\n admin: {\n hidden: true,\n },\n },\n {\n name: 'url',\n type: 'text',\n admin: {\n readOnly: true,\n },\n label: 'URL',\n },\n {\n name: 'isPrivate',\n type: 'checkbox',\n admin: {\n condition: (_data, siblingData) =>\n isDocumentPrivate({ imagekit: siblingData }, isPrivate),\n description:\n \"Indicates whether this file was uploaded to ImageKit as private. Private files are delivered through signed URLs. Changes to this collection's private option in payload.config only affect future uploads.\",\n readOnly: true,\n },\n label: 'Private file',\n },\n {\n name: 'signedUrl',\n type: 'text',\n admin: {\n // Only relevant for private files; the plain `url` works directly for public ones.\n condition: (_data, siblingData) =>\n isDocumentPrivate({ imagekit: siblingData }, isPrivate),\n description: `Temporary signed URL for reaching this private file directly on ImageKit. Expires ${signedUrlExpiresIn} seconds after load and is regenerated on every read. Note: anyone with this URL can access the file until it expires — it is not gated by Payload access control.`,\n readOnly: true,\n },\n hooks: {\n // Computed server-side on read so it is always freshly signed and never persisted.\n afterRead: [\n ({ data, siblingData }) => {\n if (!isDocumentPrivate({ imagekit: siblingData }, isPrivate)) {\n return undefined\n }\n\n const filename = (data as { filename?: string } | undefined)?.filename\n\n if (!filename) {\n return undefined\n }\n\n const source = (data || {}) as { _objectKey?: string; prefix?: string }\n const documentPrefix = path.posix.join(\n source.prefix || prefix,\n source._objectKey || '',\n )\n const storageFilePath = buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: documentPrefix,\n filename,\n }).storageFilePath\n\n return buildSignedURL(`/${storageFilePath}`)\n },\n ],\n },\n label: 'Signed URL',\n virtual: true,\n },\n {\n name: 'thumbnailUrl',\n type: 'text',\n admin: {\n hidden: true,\n },\n },\n ],\n interfaceName: 'imagekitFields',\n label: false,\n },\n ],\n label: 'Storage: ImageKit',\n },\n ],\n generateURL: ({ filename, prefix: documentPrefix = '' }) =>\n client.helper.buildSrc({\n src: `/${buildStoragePathData({\n collectionPrefix: prefix,\n docPrefix: documentPrefix,\n filename,\n }).storageFilePath}`,\n urlEndpoint,\n }),\n handleDelete: async ({ doc, storageFilePath }) => {\n const storedFileId = (doc as ImageKitReference & typeof doc).imagekit?.fileId\n const fileId =\n storedFileId || (await findImageKitFileId(client, `/${storageFilePath.replace(/^\\/+/, '')}`))\n\n if (!fileId) {\n return\n }\n\n await client.files.delete(fileId)\n },\n handleUpload: async ({ clientUploadContext, data, file, storageFilePath }) => {\n if (clientUploadContext) {\n const uploaded = await verifyClientUpload({\n collectionSlug: collection.slug,\n context: clientUploadContext,\n })\n\n return applyVerifiedClientUploadToData(data, uploaded, buildThumbnailURL, isPrivate)\n }\n\n // ImageKit's `toFile()` consumes async iterables before starting the request. A file-backed\n // Blob keeps temporary-file uploads lazy so FormData can stream them from disk instead.\n const uploadSource = file.tempFilePath\n ? await openAsBlob(file.tempFilePath, { type: file.mimeType })\n : file.buffer\n const uploadFile = await toFile(uploadSource, file.filename, { type: file.mimeType })\n const uploadFolder = path.posix.dirname(`/${storageFilePath.replace(/^\\/+/, '')}`)\n const uploadFilename = path.posix.basename(storageFilePath)\n\n const uploaded = await client.files.upload({\n file: uploadFile,\n fileName: uploadFilename,\n folder: uploadFolder,\n useUniqueFileName: false,\n ...(isPrivate ? { isPrivateFile: true } : {}),\n })\n\n data.imagekit = {\n fileId: uploaded.fileId,\n isPrivate,\n thumbnailUrl: uploaded.thumbnailUrl,\n url: uploaded.url,\n }\n\n // Set the root-level thumbnailURL that Payload's admin interface expects.\n // `buildThumbnailURL` needs the filename, which Payload may not have copied onto\n // `data` yet at this point, so fall back to the uploaded file's name.\n data.thumbnailURL = buildThumbnailURL({\n ...data,\n filename: (data as { filename?: string }).filename || uploadFilename,\n })\n\n return data\n },\n requiresClientUploadReceipt: true,\n staticHandler: async (req, args) => {\n const requestURL = new URL(req.url || 'http://localhost')\n const tr = requestURL.searchParams.get('tr')\n const hasClientUploadContext = 'clientUploadContext' in args.params\n\n if (hasClientUploadContext) {\n const clientUploadContext = args.params.clientUploadContext\n\n if (!isImageKitReceiptContext(clientUploadContext)) {\n throw new APIError('Invalid ImageKit client upload context.', 400)\n }\n\n const uploadedFile = await verifyClientUpload({\n collectionSlug: collection.slug,\n context: clientUploadContext,\n })\n const expectedFilePath = getClientUploadStorageFilePath({\n collectionPrefix: prefix,\n context: clientUploadContext,\n })\n const verifiedFileURL = isPrivate\n ? buildSignedURL(`/${expectedFilePath}`, ORIGINAL_FILE_TRANSFORMATION)\n : client.helper.buildSrc({\n src: `/${expectedFilePath}`,\n transformation: [{ raw: ORIGINAL_FILE_TRANSFORMATION }],\n urlEndpoint,\n })\n\n return fetchUploadedFile({\n fileSize: uploadedFile.size,\n fileURL: verifiedFileURL,\n mimeType: uploadedFile.mimeType,\n range: req.headers.get('Range'),\n })\n }\n\n const doc =\n args.doc ||\n (await findUploadDocumentByFilename({\n collection: args.params.collection,\n filename: args.params.filename,\n prefix: args.params.prefix,\n req,\n }))\n\n const storageFilePath = await getStorageFilePath({\n collection,\n collectionPrefix: prefix,\n doc: doc || undefined,\n filename: args.params.filename,\n prefixQueryParam: args.params.prefix,\n req,\n })\n const imageKitPath = `/${storageFilePath.replace(/^\\/+/, '')}`\n const mimeType = (doc as { mimeType?: string } | null)?.mimeType\n\n // XML-family uploads (including SVG) must pass through Payload so its CSP is\n // present even when ImageKit uses a custom, same-origin delivery domain.\n if (typeof mimeType === 'string' && isXmlMimeType(mimeType)) {\n const filesize = (doc as { filesize?: number } | null)?.filesize\n\n if (typeof filesize !== 'number' || !Number.isSafeInteger(filesize) || filesize < 0) {\n throw new APIError('Stored ImageKit file metadata is incomplete.', 500)\n }\n\n const fileURL = isDocumentPrivate(doc, isPrivate)\n ? buildSignedURL(imageKitPath, ORIGINAL_FILE_TRANSFORMATION)\n : client.helper.buildSrc({\n src: imageKitPath,\n transformation: [{ raw: ORIGINAL_FILE_TRANSFORMATION }],\n urlEndpoint,\n })\n\n return fetchUploadedFile({\n fileSize: filesize,\n fileURL,\n mimeType,\n range: req.headers.get('Range'),\n })\n }\n\n // Sign based on the document's stored status, not the collection's current\n // setting, so files keep working if the collection's privacy is changed later.\n if (isDocumentPrivate(doc, isPrivate)) {\n let signSrc = imageKitPath\n\n // A `tr` request for a video/PDF is a thumbnail request (the plain transform\n // can't render a preview); serve ImageKit's generated thumbnail instead.\n if (tr && isVideoMimeType(mimeType)) {\n signSrc = getVideoPosterSrc(signSrc)\n } else if (tr && isPdfMimeType(mimeType)) {\n signSrc = getImageKitThumbnailSrc(signSrc)\n }\n\n return Response.redirect(buildSignedURL(signSrc, tr), 302)\n }\n\n const imageKitURL = client.helper.buildSrc({\n src:\n getStoredImageKitURL(doc) ||\n imageKitPath,\n transformation: tr ? [{ raw: tr }] : undefined,\n urlEndpoint,\n })\n\n return Response.redirect(imageKitURL, 302)\n },\n }\n }\n}\n\nconst toCloudStorageCollections = (\n collections: ImageKitCollectionMap,\n adapter: Adapter,\n privateSlugs: Set<string>,\n rootFolder: string,\n disablePayloadAccessControl?: true,\n): Partial<Record<CollectionSlug, CollectionOptions>> => {\n const mappedCollections: Partial<Record<CollectionSlug, CollectionOptions>> = {}\n\n for (const collectionSlug of Object.keys(collections)) {\n mappedCollections[collectionSlug] = {\n adapter,\n disableLocalStorage: true,\n // Private files require Payload access control so URLs can be signed at serve time.\n disablePayloadAccessControl: privateSlugs.has(collectionSlug)\n ? undefined\n : disablePayloadAccessControl,\n prefix: getCollectionFolder(rootFolder, collectionSlug),\n }\n }\n\n return mappedCollections\n}\n\nexport const imagekitStorage =\n (pluginOptions: PayloadStorageImageKitConfig) =>\n (config: Config): Config => {\n const {\n alwaysInsertFields,\n clientUploads,\n collections,\n disablePayloadAccessControl,\n enabled,\n focalPoint,\n folder,\n privateKey,\n publicKey,\n signedUrlExpiresIn: signedUrlExpiresInOption,\n urlEndpoint,\n } = pluginOptions\n\n if (!privateKey?.trim()) {\n throw new Error('imagekitStorage: `privateKey` is required.')\n }\n\n if (!publicKey?.trim()) {\n throw new Error('imagekitStorage: `publicKey` is required.')\n }\n\n if (!urlEndpoint?.trim()) {\n throw new Error('imagekitStorage: `urlEndpoint` is required.')\n }\n\n if (!collections || Object.keys(collections).length === 0) {\n throw new Error('imagekitStorage: `collections` must include at least one upload collection.')\n }\n\n const privateSlugs = new Set(\n Object.entries(collections)\n .filter(([, value]) => isPrivateCollectionConfig(value))\n .map(([slug]) => slug),\n )\n const configuredSlugs = new Set(Object.keys(collections))\n\n if (disablePayloadAccessControl && privateSlugs.size > 0) {\n throw new Error(\n 'imagekitStorage: `disablePayloadAccessControl` cannot be used with private collections. Private files require Payload access control to remain enabled so URLs can be signed at serve time.',\n )\n }\n\n if (disablePayloadAccessControl) {\n const xmlCollectionSlugs = (config.collections || [])\n .filter(\n (collection) =>\n configuredSlugs.has(collection.slug) && collectionCanStoreXml(collection),\n )\n .map((collection) => collection.slug)\n\n if (xmlCollectionSlugs.length > 0) {\n throw new Error(\n `imagekitStorage: \\`disablePayloadAccessControl\\` cannot be used with collections that can store XML-family files (${xmlCollectionSlugs.join(', ')}). XML-family files require Payload's file route so its Content Security Policy is applied. Configure a MIME allow list that excludes SVG/XML, or keep Payload access control enabled.`,\n )\n }\n }\n\n const signedUrlExpiresIn =\n typeof signedUrlExpiresInOption === 'number' && signedUrlExpiresInOption > 0\n ? signedUrlExpiresInOption\n : DEFAULT_SIGNED_URL_EXPIRES_IN\n const apiRoute = config.routes?.api ?? '/api'\n\n const rootFolder = normalizeFolder(folder)\n\n const imageKitClient = new ImageKit({ privateKey })\n const collectionSecurity = Object.fromEntries(\n (config.collections || [])\n .filter((collection) => configuredSlugs.has(collection.slug))\n .map((collection) => [\n collection.slug,\n {\n collection,\n isPrivate: privateSlugs.has(collection.slug),\n prefix: getCollectionFolder(rootFolder, collection.slug),\n },\n ]),\n )\n const verifyClientUpload = createImageKitClientUploadVerifier({\n client: imageKitClient,\n collections: collectionSecurity,\n })\n const adapter = imagekitAdapter({\n apiRoute,\n client: imageKitClient,\n clientUploads,\n privateSlugs,\n rootFolder,\n signedUrlExpiresIn,\n urlEndpoint,\n verifyClientUpload,\n })\n\n const configWithCropDisabled: Config = {\n ...config,\n collections: (config.collections || []).map((collection) => {\n if (!configuredSlugs.has(collection.slug)) {\n return collection\n }\n\n const isCollectionPrivate = privateSlugs.has(collection.slug)\n const buildThumbnailURL = (doc: unknown): string =>\n isDocumentPrivate(doc, isCollectionPrivate)\n ? getPrivateAdminThumbnailURL(doc, collection.slug, apiRoute)\n : getAdminThumbnailURL(doc)\n\n const collectionOptions = collections[collection.slug]\n const collectionFocalPoint =\n collectionOptions !== true &&\n typeof collectionOptions === 'object' &&\n typeof collectionOptions.focalPoint === 'boolean'\n ? collectionOptions.focalPoint\n : undefined\n\n // Surface a \"this is a private collection\" note in the list and edit views.\n // Preserve an existing string description by appending; leave custom\n // component descriptions untouched.\n const existingDescription = collection.admin?.description\n const baseAdmin = isCollectionPrivate\n ? {\n ...(collection.admin || {}),\n description:\n typeof existingDescription === 'string' && existingDescription.trim().length > 0\n ? `${existingDescription} ${PRIVATE_COLLECTION_DESCRIPTION}`\n : (existingDescription ?? PRIVATE_COLLECTION_DESCRIPTION),\n }\n : collection.admin\n\n return {\n ...collection,\n admin: baseAdmin,\n hooks: {\n ...(collection.hooks || {}),\n beforeChange: [\n ...(collection.hooks?.beforeChange || []),\n async ({ data, req }) => {\n if (!isRecord(data) || !req.file?.clientUploadContext) {\n return data\n }\n\n const context = req.file.clientUploadContext\n const requestMimeType = req.file.mimetype.split(';', 1)[0]?.trim().toLowerCase()\n if (\n !isImageKitReceiptContext(context) ||\n context.filename !== data.filename ||\n context.filename !== req.file.name ||\n context.expectedMimeType !== requestMimeType ||\n // Payload can clear req.file.size when preparing an in-memory image.\n // generateFileData preserves the original size on the document.\n context.expectedSize !== data.filesize\n ) {\n throw new APIError('ImageKit client upload reference does not match this request.', 400)\n }\n\n const uploaded = await verifyClientUpload({\n collectionSlug: collection.slug,\n context,\n })\n // A provider file can only be claimed once, including through legacy receipts.\n // The unique file ID index also rejects concurrent claims.\n const existing = await req.payload.db.findOne({\n collection: collection.slug,\n req,\n where: {\n 'imagekit.fileId': {\n equals: uploaded.fileId,\n },\n },\n })\n if (existing) {\n throw new APIError('This ImageKit client upload receipt has already been used.', 400)\n }\n\n data.filename = uploaded.name\n data.filesize = uploaded.size\n data.mimeType = uploaded.mimeType\n\n return applyVerifiedClientUploadToData(\n data,\n uploaded,\n buildThumbnailURL,\n isCollectionPrivate,\n )\n },\n ],\n beforeOperation: [\n ...(collection.hooks?.beforeOperation || []),\n ({ args, operation, req }) => {\n if (\n (operation !== 'create' && operation !== 'update') ||\n req.context?.skipCloudStorage ||\n !req.file ||\n req.file.clientUploadContext ||\n !('data' in args) ||\n !isRecord(args.data) ||\n typeof args.data.prefix !== 'string'\n ) {\n return args\n }\n\n // Payload checks filename uniqueness before cloud storage's beforeChange\n // normalizes the prefix. Use the persisted form during that lookup too.\n args.data.prefix = buildUploadStoragePathData({\n collectionPrefix: getCollectionFolder(rootFolder, collection.slug),\n docPrefix: args.data.prefix,\n filename: req.file.name,\n }).sanitizedDocPrefix\n return args\n },\n ],\n },\n upload: {\n // Focal points are opt-in for configured collections. Plugin-level\n // and collection-level options can override this default; a\n // collection's own `upload.focalPoint` still wins because it is\n // spread in afterwards.\n focalPoint: false,\n ...(typeof focalPoint === 'boolean' ? { focalPoint } : {}),\n ...(typeof collectionFocalPoint === 'boolean'\n ? { focalPoint: collectionFocalPoint }\n : {}),\n ...(typeof collection.upload === 'object' ? collection.upload : {}),\n adminThumbnail: ({ doc }) => buildThumbnailURL(doc),\n crop: false,\n },\n }\n }),\n }\n\n const uploadCollections = Object.fromEntries(\n Object.keys(collections).map((collectionSlug) => [\n collectionSlug,\n {\n isPrivate: privateSlugs.has(collectionSlug),\n prefix: getCollectionFolder(rootFolder, collectionSlug),\n },\n ]),\n ) as Partial<\n Record<UploadCollectionSlug, { isPrivate: boolean; prefix: string }>\n >\n\n initClientUploads({\n clientHandler: '@humaan/payload-storage-imagekit/client#ImageKitUploadHandler',\n collections: uploadCollections,\n config: configWithCropDisabled,\n enabled: enabled !== false && Boolean(clientUploads),\n serverHandler: createImageKitUploadAuthHandler({\n access: typeof clientUploads === 'object' ? clientUploads.access : undefined,\n collections: uploadCollections,\n privateKey,\n publicKey,\n verifyClientUpload,\n }),\n serverHandlerPath: imageKitUploadAuthPath,\n })\n\n const output = cloudStoragePlugin({\n alwaysInsertFields,\n collections: toCloudStorageCollections(\n collections,\n adapter,\n privateSlugs,\n rootFolder,\n disablePayloadAccessControl,\n ),\n enabled,\n })(configWithCropDisabled)\n\n // Make the provider identity unique at persistence time to reject concurrent receipt replays.\n // Keep the legacy object key index for existing uploads.\n output.collections = (output.collections || []).map((collection) => {\n if (!configuredSlugs.has(collection.slug)) {\n return collection\n }\n\n const withUniqueIdentity = (field: Field): Field => {\n if ('name' in field && field.name === '_objectKey') {\n return { ...field, unique: true } as Field\n }\n if (field.type === 'group' && 'name' in field && field.name === 'imagekit') {\n return {\n ...field,\n fields: field.fields.map((metadataField) =>\n 'name' in metadataField && metadataField.name === 'fileId'\n ? { ...metadataField, unique: true }\n : metadataField,\n ),\n }\n }\n // The imagekit group sits inside the adapter's presentational \"Storage: ImageKit\" panel.\n if (field.type === 'collapsible') {\n return { ...field, fields: field.fields.map(withUniqueIdentity) }\n }\n return field\n }\n\n return {\n ...collection,\n fields: collection.fields.map(withUniqueIdentity),\n }\n })\n\n return output\n }\n\nexport { migrateFolder } from './migrate.js'\nexport type { MigrateFolderOptions, MigrationJobResult } from './migrate.js'\n\n// Backward-compatible alias\nexport const payloadStorageImagekit = imagekitStorage\nexport const payloadStorageImageKit = imagekitStorage\n\nexport type PayloadStorageImagekitConfig = PayloadStorageImageKitConfig\n"],"names":["ImageKit","toFile","cloudStoragePlugin","buildStoragePathData","buildUploadStoragePathData","getStorageFilePath","initClientUploads","openAsBlob","path","APIError","getRangeRequestInfo","isXmlMimeType","UPLOAD_CONTENT_SECURITY_POLICY","validateMimeType","imageKitUploadAuthPath","isImageKitReceiptContext","createImageKitClientUploadVerifier","getClientUploadStorageFilePath","createImageKitUploadAuthHandler","getAdminThumbnailURL","getPrivateAdminThumbnailURL","isPdfMimeType","isVideoMimeType","getImageKitThumbnailSrc","getVideoPosterSrc","DEFAULT_SIGNED_URL_EXPIRES_IN","ORIGINAL_FILE_TRANSFORMATION","PRIVATE_COLLECTION_DESCRIPTION","isPrivateCollectionConfig","value","private","XML_FAMILY_MIME_TYPES","collectionCanStoreXml","collection","upload","Boolean","allowRestrictedFileTypes","allowedMimeTypes","mimeTypes","length","some","mimeType","includes","isDocumentPrivate","doc","collectionIsPrivate","stored","imagekit","isPrivate","normalizeFolder","folder","normalized","trim","replace","Error","getCollectionFolder","rootFolder","collectionSlug","posix","join","findImageKitFileId","filePath","parentPath","dirname","name","basename","limit","skip","assets","list","type","found","find","asset","fileId","undefined","isRecord","getStoredImageKitURL","storedURL","url","hasStoredImageKitURL","findUploadDocumentByFilename","filename","prefix","req","constraints","equals","push","payload","db","findOne","where","and","applyVerifiedClientUploadToData","data","uploaded","buildThumbnailURL","thumbnailUrl","thumbnailURL","imagekitAdapter","apiRoute","client","clientUploads","privateSlugs","signedUrlExpiresIn","urlEndpoint","verifyClientUpload","fetchUploadedFile","fileSize","fileURL","range","rangeResult","rangeHeader","Response","headers","Headers","status","normalizedRange","rangeStart","rangeEnd","response","fetch","cache","Range","signal","AbortController","ok","body","cancel","catch","upstreamLength","get","expectedLength","upstreamRange","expectedRange","set","slug","has","buildSignedURL","src","tr","helper","buildSrc","expiresIn","signed","transformation","raw","fields","admin","condition","initCollapsed","disableListColumn","disableListFilter","hidden","readOnly","label","_data","siblingData","description","hooks","afterRead","source","documentPrefix","_objectKey","storageFilePath","collectionPrefix","docPrefix","virtual","interfaceName","generateURL","handleDelete","storedFileId","files","delete","handleUpload","clientUploadContext","file","context","uploadSource","tempFilePath","buffer","uploadFile","uploadFolder","uploadFilename","fileName","useUniqueFileName","isPrivateFile","requiresClientUploadReceipt","staticHandler","args","requestURL","URL","searchParams","hasClientUploadContext","params","uploadedFile","expectedFilePath","verifiedFileURL","size","prefixQueryParam","imageKitPath","filesize","Number","isSafeInteger","signSrc","redirect","imageKitURL","toCloudStorageCollections","collections","adapter","disablePayloadAccessControl","mappedCollections","Object","keys","disableLocalStorage","imagekitStorage","pluginOptions","config","alwaysInsertFields","enabled","focalPoint","privateKey","publicKey","signedUrlExpiresInOption","Set","entries","filter","map","configuredSlugs","xmlCollectionSlugs","routes","api","imageKitClient","collectionSecurity","fromEntries","configWithCropDisabled","isCollectionPrivate","collectionOptions","collectionFocalPoint","existingDescription","baseAdmin","beforeChange","requestMimeType","mimetype","split","toLowerCase","expectedMimeType","expectedSize","existing","beforeOperation","operation","skipCloudStorage","sanitizedDocPrefix","adminThumbnail","crop","uploadCollections","clientHandler","serverHandler","access","serverHandlerPath","output","withUniqueIdentity","field","unique","metadataField","migrateFolder","payloadStorageImagekit","payloadStorageImageKit"],"mappings":"AAgBA,OAAOA,YAAYC,MAAM,QAAQ,mBAAkB;AACnD,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SACEC,oBAAoB,EACpBC,0BAA0B,EAC1BC,kBAAkB,EAClBC,iBAAiB,QACZ,6CAA4C;AACnD,SAASC,UAAU,QAAQ,UAAS;AACpC,OAAOC,UAAU,YAAW;AAC5B,SAASC,QAAQ,QAAQ,UAAS;AAClC,SACEC,mBAAmB,EACnBC,aAAa,EACbC,8BAA8B,QACzB,mBAAkB;AACzB,SAASC,gBAAgB,QAAQ,iBAAgB;AAIjD,SAASC,sBAAsB,EAAEC,wBAAwB,QAAQ,qBAAoB;AACrF,SACEC,kCAAkC,EAClCC,8BAA8B,QACzB,gCAA+B;AACtC,SAASC,+BAA+B,QAAQ,iDAAgD;AAChG,SACEC,oBAAoB,EACpBC,2BAA2B,EAC3BC,aAAa,EACbC,eAAe,QACV,4BAA2B;AAClC,SAASC,uBAAuB,EAAEC,iBAAiB,QAAQ,uBAAsB;AAiBjF,MAAMC,gCAAgC;AACtC;;;;;;;CAOC,GACD,MAAMC,+BAA+B;AAErC,MAAMC,iCACJ;AAEF,MAAMC,4BAA4B,CAACC,QACjCA,UAAU,QAAQ,OAAOA,UAAU,YAAYA,OAAOC,YAAY;AAEpE,MAAMC,wBAAwB;IAAC;IAAmB;IAAiB;CAAW;AAE9E,MAAMC,wBAA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KAAK,WAAW,UAAUgM,SAASA,MAAMtM,IAAI,KAAK,YAAY;oBAC1E,OAAO;wBACL,GAAGsM,KAAK;wBACRnH,QAAQmH,MAAMnH,MAAM,CAACgF,GAAG,CAAC,CAACqC,gBACxB,UAAUA,iBAAiBA,cAAcxM,IAAI,KAAK,WAC9C;gCAAE,GAAGwM,aAAa;gCAAED,QAAQ;4BAAK,IACjCC;oBAER;gBACF;gBACA,yFAAyF;gBACzF,IAAIF,MAAMhM,IAAI,KAAK,eAAe;oBAChC,OAAO;wBAAE,GAAGgM,KAAK;wBAAEnH,QAAQmH,MAAMnH,MAAM,CAACgF,GAAG,CAACkC;oBAAoB;gBAClE;gBACA,OAAOC;YACT;YAEA,OAAO;gBACL,GAAGrO,UAAU;gBACbkH,QAAQlH,WAAWkH,MAAM,CAACgF,GAAG,CAACkC;YAChC;QACF;QAEA,OAAOD;IACT,EAAC;AAEH,SAASK,aAAa,QAAQ,eAAc;AAG5C,4BAA4B;AAC5B,OAAO,MAAMC,yBAAyBnD,gBAAe;AACrD,OAAO,MAAMoD,yBAAyBpD,gBAAe"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@humaan/payload-storage-imagekit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.8.0",
|
|
4
4
|
"description": "ImageKit storage adapter plugin for Payload CMS uploads",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -55,10 +55,10 @@
|
|
|
55
55
|
"copyfiles": "2.4.1",
|
|
56
56
|
"cross-env": "10.1.0",
|
|
57
57
|
"eslint": "^9.39.5",
|
|
58
|
-
"eslint-config-next": "16.3.
|
|
58
|
+
"eslint-config-next": "16.3.6",
|
|
59
59
|
"graphql": "^16.14.2",
|
|
60
60
|
"mongodb-memory-server": "11.2.0",
|
|
61
|
-
"next": "16.3.
|
|
61
|
+
"next": "16.3.6",
|
|
62
62
|
"open": "^11.0.4",
|
|
63
63
|
"payload": "3.90.1",
|
|
64
64
|
"prettier": "^3.9.8",
|