payload 4.0.0-beta.6 → 4.0.0-beta.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/baseFields/sessions.d.ts.map +1 -1
- package/dist/auth/baseFields/sessions.js +8 -0
- package/dist/auth/baseFields/sessions.js.map +1 -1
- package/dist/auth/createAuthToken.d.ts +30 -0
- package/dist/auth/createAuthToken.d.ts.map +1 -0
- package/dist/auth/createAuthToken.js +39 -0
- package/dist/auth/createAuthToken.js.map +1 -0
- package/dist/auth/endpoints/refresh.d.ts.map +1 -1
- package/dist/auth/endpoints/refresh.js +2 -1
- package/dist/auth/endpoints/refresh.js.map +1 -1
- package/dist/auth/executeAuthStrategies.d.ts.map +1 -1
- package/dist/auth/executeAuthStrategies.js +1 -0
- package/dist/auth/executeAuthStrategies.js.map +1 -1
- package/dist/auth/extractJWT.d.ts.map +1 -1
- package/dist/auth/extractJWT.js +16 -0
- package/dist/auth/extractJWT.js.map +1 -1
- package/dist/auth/loginWithCookie.d.ts.map +1 -1
- package/dist/auth/loginWithCookie.js +1 -0
- package/dist/auth/loginWithCookie.js.map +1 -1
- package/dist/auth/operations/local/login.d.ts.map +1 -1
- package/dist/auth/operations/local/login.js +1 -0
- package/dist/auth/operations/local/login.js.map +1 -1
- package/dist/auth/operations/login.d.ts +2 -0
- package/dist/auth/operations/login.d.ts.map +1 -1
- package/dist/auth/operations/login.js +10 -20
- package/dist/auth/operations/login.js.map +1 -1
- package/dist/auth/operations/refresh.d.ts +7 -0
- package/dist/auth/operations/refresh.d.ts.map +1 -1
- package/dist/auth/operations/refresh.js +160 -96
- package/dist/auth/operations/refresh.js.map +1 -1
- package/dist/auth/operations/resetPassword.d.ts.map +1 -1
- package/dist/auth/operations/resetPassword.js +8 -20
- package/dist/auth/operations/resetPassword.js.map +1 -1
- package/dist/auth/redeemRefreshToken.d.ts +36 -0
- package/dist/auth/redeemRefreshToken.d.ts.map +1 -0
- package/dist/auth/redeemRefreshToken.js +120 -0
- package/dist/auth/redeemRefreshToken.js.map +1 -0
- package/dist/auth/sessions.d.ts +28 -2
- package/dist/auth/sessions.d.ts.map +1 -1
- package/dist/auth/sessions.js +36 -5
- package/dist/auth/sessions.js.map +1 -1
- package/dist/auth/strategies/local/authenticate.d.ts +3 -1
- package/dist/auth/strategies/local/authenticate.d.ts.map +1 -1
- package/dist/auth/strategies/local/authenticate.js +23 -19
- package/dist/auth/strategies/local/authenticate.js.map +1 -1
- package/dist/auth/strategies/local/generatePasswordSaltHash.d.ts +14 -1
- package/dist/auth/strategies/local/generatePasswordSaltHash.d.ts.map +1 -1
- package/dist/auth/strategies/local/generatePasswordSaltHash.js +31 -15
- package/dist/auth/strategies/local/generatePasswordSaltHash.js.map +1 -1
- package/dist/auth/types.d.ts +34 -1
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/collections/config/defaults.d.ts +2 -0
- package/dist/collections/config/defaults.d.ts.map +1 -1
- package/dist/collections/config/defaults.js +4 -0
- package/dist/collections/config/defaults.js.map +1 -1
- package/dist/collections/config/sanitize.d.ts.map +1 -1
- package/dist/collections/config/sanitize.js +3 -0
- package/dist/collections/config/sanitize.js.map +1 -1
- package/dist/collections/operations/create.js +11 -11
- package/dist/collections/operations/create.js.map +1 -1
- package/dist/collections/operations/renameFile.d.ts.map +1 -1
- package/dist/collections/operations/renameFile.js +30 -15
- package/dist/collections/operations/renameFile.js.map +1 -1
- package/dist/collections/operations/utilities/update.d.ts.map +1 -1
- package/dist/collections/operations/utilities/update.js +29 -40
- package/dist/collections/operations/utilities/update.js.map +1 -1
- package/dist/config/defaults.d.ts.map +1 -1
- package/dist/config/defaults.js +2 -1
- package/dist/config/defaults.js.map +1 -1
- package/dist/config/sanitize.d.ts.map +1 -1
- package/dist/config/sanitize.js +4 -0
- package/dist/config/sanitize.js.map +1 -1
- package/dist/config/types.d.ts +9 -0
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/database/getLocalizedPaths.d.ts.map +1 -1
- package/dist/database/getLocalizedPaths.js +16 -1
- package/dist/database/getLocalizedPaths.js.map +1 -1
- package/dist/database/queryValidation/hasReadAccessToQueryPath.d.ts +17 -0
- package/dist/database/queryValidation/hasReadAccessToQueryPath.d.ts.map +1 -0
- package/dist/database/queryValidation/hasReadAccessToQueryPath.js +59 -0
- package/dist/database/queryValidation/hasReadAccessToQueryPath.js.map +1 -0
- package/dist/database/queryValidation/validateSearchParams.d.ts.map +1 -1
- package/dist/database/queryValidation/validateSearchParams.js +20 -23
- package/dist/database/queryValidation/validateSearchParams.js.map +1 -1
- package/dist/errors/DuplicateGlobal.d.ts.map +1 -1
- package/dist/errors/DuplicateGlobal.js +1 -1
- package/dist/errors/DuplicateGlobal.js.map +1 -1
- package/dist/errors/InvalidFieldName.js +1 -1
- package/dist/errors/InvalidFieldName.js.map +1 -1
- package/dist/errors/InvalidFieldRelationship.d.ts.map +1 -1
- package/dist/errors/InvalidFieldRelationship.js +1 -1
- package/dist/errors/InvalidFieldRelationship.js.map +1 -1
- package/dist/errors/MissingFieldInputOptions.js +1 -1
- package/dist/errors/MissingFieldInputOptions.js.map +1 -1
- package/dist/errors/ReservedFieldName.d.ts.map +1 -1
- package/dist/errors/ReservedFieldName.js +1 -1
- package/dist/errors/ReservedFieldName.js.map +1 -1
- package/dist/exports/internal.d.ts +1 -1
- package/dist/exports/internal.d.ts.map +1 -1
- package/dist/exports/internal.js +1 -1
- package/dist/exports/internal.js.map +1 -1
- package/dist/fields/baseFields/authorship/index.d.ts +2 -1
- package/dist/fields/baseFields/authorship/index.d.ts.map +1 -1
- package/dist/fields/baseFields/authorship/index.js +12 -5
- package/dist/fields/baseFields/authorship/index.js.map +1 -1
- package/dist/fields/hooks/afterChange/promise.d.ts.map +1 -1
- package/dist/fields/hooks/afterChange/promise.js +2 -1
- package/dist/fields/hooks/afterChange/promise.js.map +1 -1
- package/dist/fields/hooks/afterRead/promise.d.ts.map +1 -1
- package/dist/fields/hooks/afterRead/promise.js +11 -9
- package/dist/fields/hooks/afterRead/promise.js.map +1 -1
- package/dist/fields/hooks/beforeChange/index.d.ts.map +1 -1
- package/dist/fields/hooks/beforeChange/index.js +4 -0
- package/dist/fields/hooks/beforeChange/index.js.map +1 -1
- package/dist/fields/hooks/beforeChange/promise.d.ts.map +1 -1
- package/dist/fields/hooks/beforeChange/promise.js +11 -1
- package/dist/fields/hooks/beforeChange/promise.js.map +1 -1
- package/dist/fields/hooks/beforeDuplicate/promise.d.ts.map +1 -1
- package/dist/fields/hooks/beforeDuplicate/promise.js +7 -2
- package/dist/fields/hooks/beforeDuplicate/promise.js.map +1 -1
- package/dist/fields/hooks/beforeValidate/promise.d.ts.map +1 -1
- package/dist/fields/hooks/beforeValidate/promise.js +19 -2
- package/dist/fields/hooks/beforeValidate/promise.js.map +1 -1
- package/dist/fields/validations.js +3 -3
- package/dist/fields/validations.js.map +1 -1
- package/dist/globals/operations/update.d.ts.map +1 -1
- package/dist/globals/operations/update.js +29 -40
- package/dist/globals/operations/update.js.map +1 -1
- package/dist/index.bundled.d.ts +125 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/uploads/docWithFilenameExists.d.ts +2 -1
- package/dist/uploads/docWithFilenameExists.d.ts.map +1 -1
- package/dist/uploads/docWithFilenameExists.js +19 -9
- package/dist/uploads/docWithFilenameExists.js.map +1 -1
- package/dist/uploads/downloadFileToBuffer.d.ts +11 -0
- package/dist/uploads/downloadFileToBuffer.d.ts.map +1 -1
- package/dist/uploads/downloadFileToBuffer.js +32 -21
- package/dist/uploads/downloadFileToBuffer.js.map +1 -1
- package/dist/uploads/endpoints/getFile.d.ts +2 -1
- package/dist/uploads/endpoints/getFile.d.ts.map +1 -1
- package/dist/uploads/endpoints/getFile.js +6 -1
- package/dist/uploads/endpoints/getFile.js.map +1 -1
- package/dist/uploads/fileVersioning/naming.d.ts +0 -3
- package/dist/uploads/fileVersioning/naming.d.ts.map +1 -1
- package/dist/uploads/fileVersioning/naming.js +0 -4
- package/dist/uploads/fileVersioning/naming.js.map +1 -1
- package/dist/uploads/generateFileData.d.ts.map +1 -1
- package/dist/uploads/generateFileData.js +77 -41
- package/dist/uploads/generateFileData.js.map +1 -1
- package/dist/uploads/generateFilePathOrURL.d.ts +3 -1
- package/dist/uploads/generateFilePathOrURL.d.ts.map +1 -1
- package/dist/uploads/generateFilePathOrURL.js +3 -2
- package/dist/uploads/generateFilePathOrURL.js.map +1 -1
- package/dist/uploads/getBaseFields.d.ts.map +1 -1
- package/dist/uploads/getBaseFields.js +7 -0
- package/dist/uploads/getBaseFields.js.map +1 -1
- package/dist/uploads/getFileFromUploadInstructions.d.ts.map +1 -1
- package/dist/uploads/getFileFromUploadInstructions.js +6 -9
- package/dist/uploads/getFileFromUploadInstructions.js.map +1 -1
- package/dist/uploads/getFileTypeIdentity.d.ts.map +1 -1
- package/dist/uploads/getFileTypeIdentity.js +6 -2
- package/dist/uploads/getFileTypeIdentity.js.map +1 -1
- package/dist/uploads/getSafeFilename.d.ts +3 -1
- package/dist/uploads/getSafeFilename.d.ts.map +1 -1
- package/dist/uploads/getSafeFilename.js +2 -1
- package/dist/uploads/getSafeFilename.js.map +1 -1
- package/dist/uploads/isOriginalFileRequest.d.ts +23 -0
- package/dist/uploads/isOriginalFileRequest.d.ts.map +1 -0
- package/dist/uploads/isOriginalFileRequest.js +12 -0
- package/dist/uploads/isOriginalFileRequest.js.map +1 -0
- package/dist/uploads/transformers/handleDynamicFileRequest.d.ts +2 -1
- package/dist/uploads/transformers/handleDynamicFileRequest.d.ts.map +1 -1
- package/dist/uploads/transformers/handleDynamicFileRequest.js +11 -2
- package/dist/uploads/transformers/handleDynamicFileRequest.js.map +1 -1
- package/dist/uploads/types.d.ts +13 -1
- package/dist/uploads/types.d.ts.map +1 -1
- package/dist/uploads/types.js.map +1 -1
- package/dist/utilities/getEntityPermissions/getEntityPermissions.d.ts.map +1 -1
- package/dist/utilities/getEntityPermissions/getEntityPermissions.js +5 -2
- package/dist/utilities/getEntityPermissions/getEntityPermissions.js.map +1 -1
- package/dist/utilities/getEntityPermissions/populateFieldPermissions.d.ts +4 -4
- package/dist/utilities/getEntityPermissions/populateFieldPermissions.d.ts.map +1 -1
- package/dist/utilities/getEntityPermissions/populateFieldPermissions.js +63 -32
- package/dist/utilities/getEntityPermissions/populateFieldPermissions.js.map +1 -1
- package/dist/utilities/mergeLocalizedData.d.ts +1 -1
- package/dist/utilities/mergeLocalizedData.d.ts.map +1 -1
- package/dist/utilities/mergeLocalizedData.js +6 -2
- package/dist/utilities/mergeLocalizedData.js.map +1 -1
- package/dist/utilities/sanitizePermissions.d.ts +4 -1
- package/dist/utilities/sanitizePermissions.d.ts.map +1 -1
- package/dist/utilities/sanitizePermissions.js +34 -3
- package/dist/utilities/sanitizePermissions.js.map +1 -1
- package/dist/versions/allLocalesPublicationStatus.d.ts +5 -5
- package/dist/versions/allLocalesPublicationStatus.d.ts.map +1 -1
- package/dist/versions/allLocalesPublicationStatus.js +2 -2
- package/dist/versions/allLocalesPublicationStatus.js.map +1 -1
- package/dist/versions/buildSingleLocalePublishData.d.ts +4 -4
- package/dist/versions/buildSingleLocalePublishData.d.ts.map +1 -1
- package/dist/versions/buildSingleLocalePublishData.js +8 -8
- package/dist/versions/buildSingleLocalePublishData.js.map +1 -1
- package/dist/versions/drafts/hasNonLocalizedDataChanged.d.ts +12 -0
- package/dist/versions/drafts/hasNonLocalizedDataChanged.d.ts.map +1 -0
- package/dist/versions/drafts/hasNonLocalizedDataChanged.js +165 -0
- package/dist/versions/drafts/hasNonLocalizedDataChanged.js.map +1 -0
- package/dist/versions/mergeLocalizedStatus.d.ts +9 -0
- package/dist/versions/mergeLocalizedStatus.d.ts.map +1 -0
- package/dist/versions/mergeLocalizedStatus.js +11 -0
- package/dist/versions/mergeLocalizedStatus.js.map +1 -0
- package/dist/versions/resolveLocalizedStatus.d.ts +19 -0
- package/dist/versions/resolveLocalizedStatus.d.ts.map +1 -0
- package/dist/versions/resolveLocalizedStatus.js +60 -0
- package/dist/versions/resolveLocalizedStatus.js.map +1 -0
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/types.ts"],"sourcesContent":["import type { CollectionConfig, TypeWithID } from '../collections/config/types.js'\nimport type { PayloadComponent } from '../config/types.js'\nimport type { UploadCollectionSlug } from '../index.js'\nimport type { PayloadRequest } from '../types/index.js'\nimport type { StagedObject } from './fileVersioning/fileOperationManager.js'\n\nexport type OriginalFileData = {\n _objectKey?: string\n filename: string\n filesize: number\n height?: null | number\n mimeType: string\n prefix?: string\n url: string\n width?: null | number\n}\n\nexport type FileSize = {\n _objectKey?: string\n filename: null | string\n filesize: null | number\n height: null | number\n mimeType: null | string\n prefix?: string\n url: null | string\n width: null | number\n}\n\nexport type FileSizes = {\n [size: string]: FileSize\n}\n\nexport type FileData = {\n _objectKey?: string\n filename: string\n filesize: number\n focalX?: number\n focalY?: number\n height: number\n mimeType: string\n original?: null | OriginalFileData\n prefix?: string\n tempFilePath?: string\n url?: string\n variants: FileSizes\n width: number\n}\n\nexport type ProbedImageSize = {\n height: number\n width: number\n}\n\nexport type GenerateImageName = (args: {\n extension: string\n height: number\n originalName: string\n sizeName: string\n width: number\n}) => string\n\ntype ImageSizeBase = {\n /**\n * Admin UI options that control how this image size appears in list views.\n */\n admin?: {\n /**\n * Controls visibility of this image size in the collection list view.\n * Defaults to hiding the image size from columns, filters, and group-by to reduce noise.\n *\n * - `column` — whether to hide this size from selectable list columns. @default false\n * - `filter` — whether to hide this size from filter options. @default false\n * - `groupBy` — whether to hide this size from group-by options. @default false\n */\n disabled?: {\n column?: boolean\n filter?: boolean\n groupBy?: boolean\n }\n }\n /**\n * Generate a custom name for the file of this image size.\n */\n generateImageName?: GenerateImageName\n name: string\n}\n\n/**\n * Interface to be module-augmented by image processing providers.\n *\n * When no provider is registered, ImageSize carries no processor-specific options.\n * When one or more providers are registered (e.g. `@payloadcms/transformer-sharp`),\n * ImageSize uses the union of their registered options instead.\n *\n * @example\n * declare module 'payload' {\n * interface RegisteredImageSizeOptions {\n * myProvider: MyProviderImageSizeOptions\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Intentionally empty so image processing providers can augment it.\nexport interface RegisteredImageSizeOptions {}\n\ntype ImageSizeOptions = keyof RegisteredImageSizeOptions extends never\n ? unknown\n : RegisteredImageSizeOptions[keyof RegisteredImageSizeOptions]\n\nexport type ImageSize = ImageSizeBase & ImageSizeOptions\n\nexport type GetAdminThumbnail = (args: { doc: Record<string, unknown> }) => false | null | string\n\nexport type AllowList = Array<{\n hostname: string\n pathname?: string\n port?: string\n protocol?: 'http' | 'https'\n search?: string\n}>\n\nexport type FileAllowList = Array<{\n extensions: string[]\n mimeType: string\n}>\n\nexport type UploadFilePreviewClientProps = {\n filename: string\n filesize: number\n /** Resolved URL of the file (data.url). */\n fileSrc: string\n height?: number\n mimeType: string\n width?: number\n}\n\ntype UploadFilePreviewMap = {\n [mimeTypePattern: string]: PayloadComponent\n}\n\n/**\n * Distinguishes an ordinary public file request (`read`) from Payload's internal\n * retrieval of a stored file's bytes for a dynamic transformation (`transform`).\n * Defaults to `read` when omitted, for third-party handler compatibility.\n */\nexport type FileHandlerOperation = 'read' | 'transform'\n\ntype Admin = {\n components?: {\n /**\n * The Controls component to extend the upload controls in the admin panel.\n */\n controls?: PayloadComponent[]\n /**\n * A custom component to render in place of the default Thumbnail in the upload side panel.\n *\n * Can be a single PayloadComponent (renders for all MIME types) or a Record keyed by\n * MIME type patterns. Pattern resolution priority: exact match → category wildcard\n * (e.g. `video/*`) → universal fallback (`*`). Falls back to the default Thumbnail\n * when nothing matches.\n */\n filePreview?: PayloadComponent | UploadFilePreviewMap\n }\n}\n\nexport type ExternalFileHeaderFilterContext = {\n isSameOrigin: boolean\n url: string\n}\n\nexport type UploadConfig = {\n /**\n * The adapter name to use for uploads. Used for storage adapter telemetry.\n * @default undefined\n */\n adapter?: string\n /**\n * The admin configuration for the upload field.\n */\n admin?: Admin\n /**\n * Represents an admin thumbnail, which can be either a React component or a string.\n * - If a string, it should be one of the image size names.\n * - A function that generates a fully qualified URL for the thumbnail, receives the doc as the only argument.\n **/\n adminThumbnail?: GetAdminThumbnail | string\n /**\n * Allow restricted file types known to be problematic.\n * - If set to `true`, it will allow all file types.\n * - If set to `false`, it will not allow file types and extensions known to be problematic.\n * - This setting is overriden by the `mimeTypes` option.\n * @default false\n */\n allowRestrictedFileTypes?: boolean\n /**\n * Enables bulk upload of files from the list view.\n * @default true\n */\n bulkUpload?: boolean\n /**\n * Appends a cache tag to the image URL when fetching the thumbnail in the admin panel. It may be desirable to disable this when hosting via CDNs with strict parameters.\n *\n * @default true\n */\n cacheTags?: boolean\n /**\n * Enables cropping of images.\n * @default true\n */\n crop?: boolean\n /**\n * Disable the ability to save files to disk.\n * @default false\n */\n disableLocalStorage?: boolean\n /**\n * Enable displaying preview of the uploaded file in Upload fields related to this Collection.\n * Can be locally overridden by `displayPreview` option in Upload field.\n * @default false\n */\n displayPreview?: boolean\n /**\n * Accepts existing headers and returns the headers after filtering or modifying. The optional\n * context identifies the destination for the current request, including each redirect hop.\n * `isSameOrigin` is true only when that destination matches a trusted origin established for a\n * relative file URL.\n * If using this option, you should handle the removal of any sensitive cookies\n * (like payload-prefixed cookies) to prevent leaking session information to external\n * services. By default, Payload automatically filters out payload-prefixed cookies\n * when this option is NOT defined.\n *\n * Useful for adding custom headers to fetch from external providers.\n * @default undefined\n */\n externalFileHeaderFilter?: (\n headers: Record<string, string>,\n context?: ExternalFileHeaderFilterContext,\n ) => Record<string, string>\n /**\n * Field slugs to use for a compound index instead of the default filename index.\n */\n filenameCompoundIndex?: string[]\n /** @internal Set by cloudStoragePlugin for versioned uploads; adapters do not implement this. */\n fileOperations?: {\n /** Copy before the document changes. Must preserve object metadata and reject an occupied key. */\n copy: (args: {\n from: string\n req: PayloadRequest\n to: string\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<void>\n delete: (args: { key: string; req: PayloadRequest }) => Promise<void>\n hasLegacyFile?: (args: {\n doc: Record<string, unknown>\n req: PayloadRequest\n }) => Promise<boolean>\n move?: (args: {\n from: string\n req: PayloadRequest\n to: string\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<void>\n resolveStorageKey: (args: { _objectKey?: string; filename: string; prefix?: string }) => string\n stage: (args: {\n data: Record<string, unknown>\n files: FileToSave[]\n req: PayloadRequest\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<{ metadata: Record<string, unknown> }>\n }\n /**\n * Require files to be uploaded when creating a document.\n * @default true\n */\n filesRequiredOnCreate?: boolean\n /**\n * Enables focal point positioning for image manipulation.\n * @default true\n */\n focalPoint?: boolean\n /**\n * Custom handlers to run when a file is fetched.\n *\n * - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.\n * - If a handler returns null, the next handler will be run.\n * - If no handlers return a response the file will be returned by default.\n *\n * @default undefined\n */\n handlers?: ((\n req: PayloadRequest,\n args: {\n doc: TypeWithID\n headers?: Headers\n params: {\n collection: string\n filename: string\n /** @default 'read' */\n operation?: FileHandlerOperation\n prefix?: string\n uploadReference?: unknown\n }\n },\n ) => Promise<Response> | Promise<void> | Response | void)[]\n /**\n * Whether a registered transformer performs additional processing on the main\n * uploaded file beyond simple pass-through (e.g. resizing, format conversion,\n * trimming). Written by a transformer's `init()`; not intended to be set\n * directly in collection config. Used by the Admin UI to decide whether to\n * show focal-point controls when no image sizes are configured.\n * @internal\n */\n hasImageAdjustments?: boolean\n /**\n * Set to `true` to prevent the admin UI from showing file inputs during document creation, useful for programmatic file generation.\n */\n hideFileInputOnCreate?: boolean\n /**\n * Set to `true` to prevent the admin UI having a way to remove an existing file while editing.\n */\n hideRemoveFile?: boolean\n /**\n * Restrict mimeTypes in the file picker. Array of valid mime types or mimetype wildcards\n * @example ['image/*', 'application/pdf']\n * @default undefined\n */\n mimeTypes?: string[]\n /**\n * Ability to modify the response headers fetching a file.\n * @default undefined\n */\n modifyResponseHeaders?: ({ headers }: { headers: Headers }) => Headers | void\n /**\n * Controls the behavior of pasting/uploading files from URLs.\n * If set to `false`, fetching from remote URLs is disabled.\n * If an `allowList` is provided, server-side fetching will be enabled for specified URLs.\n *\n * @default true (client-side fetching enabled)\n */\n pasteURL?:\n | {\n allowList: AllowList\n }\n | false\n /**\n * Skip safe fetch when using server-side fetching for external files from these URLs.\n * @default false\n */\n skipSafeFetch?: AllowList | boolean\n /**\n * The directory to serve static files from. Defaults to collection slug.\n * @default undefined\n */\n staticDir?: string\n /**\n * Adapter-provided upload instructions.\n * @internal\n */\n uploadInstructions?: UploadInstructionsCapability\n}\n\nexport type UploadInstructionsAccess = (args: {\n collectionSlug: UploadCollectionSlug\n req: PayloadRequest\n}) => boolean | Promise<boolean>\n\nexport type UploadInstructionsRequest = {\n collectionSlug: UploadCollectionSlug\n docPrefix?: string\n filename: string\n filesize: number\n mimeType: string\n}\n\nexport type UploadInstructions = {\n file: {\n filename: string\n mimeType: string\n size: number\n uploadReference: Record<string, unknown>\n }\n} & (\n | {\n data?: unknown\n name: string\n type: 'dispatch'\n }\n | {\n request: {\n headers?: Record<string, string>\n method: 'POST' | 'PUT'\n url: string\n }\n type: 'http'\n }\n)\n\nexport type GenerateUploadInstructions = (\n args: { overrideAccess?: boolean; req: PayloadRequest } & UploadInstructionsRequest,\n) => Promise<UploadInstructions> | UploadInstructions\n\nexport type UploadInstructionsCapability = {\n /** Generates upload instructions. The generator or supporting endpoint must check access. */\n generate: GenerateUploadInstructions\n /**\n * Require a receipt signed by `resolveSignedURLKey` before invoking upload handlers. Client\n * uploads keep an `original` and file history only when a receipt is verified.\n * @see https://payloadcms.com/docs/upload/storage-adapters#custom-upload-receipts\n */\n requiresUploadReceipt?: boolean\n /**\n * Whether the Admin panel should use these instructions before saving a document.\n * This can still be useful when upload chunks pass through Payload.\n */\n useInAdmin: boolean\n}\nexport type checkFileRestrictionsParams = {\n /** Set to false when the file bytes have not been uploaded yet. */\n checkFileContents?: boolean\n collection: CollectionConfig\n file: File\n req: PayloadRequest\n}\n\nexport type SanitizedUploadConfig = {\n staticDir: UploadConfig['staticDir']\n /**\n * The collection's image sizes, as written at startup by a registered transformer such as\n * `sharpTransformer({ collections: { <slug>: { variants } } })`. Names and admin options\n * only — not authored on the collection.\n */\n variants?: ImageSize[]\n} & UploadConfig\n\nexport type File = {\n /**\n * The buffer of the file.\n */\n data: Buffer\n /**\n * The mimetype of the file.\n */\n mimetype: string\n /**\n * The name of the file.\n */\n name: string\n /**\n * The size of the file in bytes.\n */\n size: number\n /**\n * Path to the temp file on disk when useTempFiles is enabled. In this case file.data will be an empty buffer.\n */\n tempFilePath?: string\n}\n\nexport type FileToSave =\n | {\n /**\n * The buffer of the file.\n */\n buffer: Buffer\n /**\n * The path to save the file.\n */\n path: string\n }\n | {\n /**\n * The path to save the file.\n */\n path: string\n /**\n * An existing file on disk to copy to `path`, instead of `buffer` - avoids loading a file\n * that's already on disk (e.g. a temp file) fully into memory just to write it back out.\n */\n sourcePath: string\n }\n\ntype Crop = {\n height: number\n unit: '%' | 'px'\n width: number\n x: number\n y: number\n}\n\nexport type FocalPoint = {\n x: number\n y: number\n}\n\nexport type UploadEdits = {\n crop?: Crop\n focalPoint?: FocalPoint\n heightInPixels?: number\n widthInPixels?: number\n}\n"],"names":[],"mappings":"AA4eA,WAKC"}
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/types.ts"],"sourcesContent":["import type { CollectionConfig, TypeWithID } from '../collections/config/types.js'\nimport type { PayloadComponent } from '../config/types.js'\nimport type { UploadCollectionSlug } from '../index.js'\nimport type { PayloadRequest } from '../types/index.js'\nimport type { StagedObject } from './fileVersioning/fileOperationManager.js'\nimport type { StoredFileRole } from './fileVersioning/types.js'\n\nexport type OriginalFileData = {\n _objectKey?: string\n filename: string\n filesize: number\n height?: null | number\n mimeType: string\n prefix?: string\n url: string\n width?: null | number\n}\n\nexport type FileSize = {\n _objectKey?: string\n filename: null | string\n filesize: null | number\n height: null | number\n mimeType: null | string\n prefix?: string\n url: null | string\n width: null | number\n}\n\nexport type FileSizes = {\n [size: string]: FileSize\n}\n\nexport type FileData = {\n _objectKey?: string\n filename: string\n filesize: number\n focalX?: number\n focalY?: number\n height: number\n mimeType: string\n original?: null | OriginalFileData\n prefix?: string\n tempFilePath?: string\n url?: string\n variants: FileSizes\n width: number\n}\n\nexport type ProbedImageSize = {\n height: number\n width: number\n}\n\nexport type GenerateImageName = (args: {\n extension: string\n height: number\n originalName: string\n sizeName: string\n width: number\n}) => string\n\ntype ImageSizeBase = {\n /**\n * Admin UI options that control how this image size appears in list views.\n */\n admin?: {\n /**\n * Controls visibility of this image size in the collection list view.\n * Defaults to hiding the image size from columns, filters, and group-by to reduce noise.\n *\n * - `column` — whether to hide this size from selectable list columns. @default false\n * - `filter` — whether to hide this size from filter options. @default false\n * - `groupBy` — whether to hide this size from group-by options. @default false\n */\n disabled?: {\n column?: boolean\n filter?: boolean\n groupBy?: boolean\n }\n }\n /**\n * Generate a custom name for the file of this image size.\n */\n generateImageName?: GenerateImageName\n name: string\n}\n\n/**\n * Interface to be module-augmented by image processing providers.\n *\n * When no provider is registered, ImageSize carries no processor-specific options.\n * When one or more providers are registered (e.g. `@payloadcms/transformer-sharp`),\n * ImageSize uses the union of their registered options instead.\n *\n * @example\n * declare module 'payload' {\n * interface RegisteredImageSizeOptions {\n * myProvider: MyProviderImageSizeOptions\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Intentionally empty so image processing providers can augment it.\nexport interface RegisteredImageSizeOptions {}\n\ntype ImageSizeOptions = keyof RegisteredImageSizeOptions extends never\n ? unknown\n : RegisteredImageSizeOptions[keyof RegisteredImageSizeOptions]\n\nexport type ImageSize = ImageSizeBase & ImageSizeOptions\n\nexport type GetAdminThumbnail = (args: { doc: Record<string, unknown> }) => false | null | string\n\nexport type AllowList = Array<{\n hostname: string\n pathname?: string\n port?: string\n protocol?: 'http' | 'https'\n search?: string\n}>\n\nexport type FileAllowList = Array<{\n extensions: string[]\n mimeType: string\n}>\n\nexport type UploadFilePreviewClientProps = {\n filename: string\n filesize: number\n /** Resolved URL of the file (data.url). */\n fileSrc: string\n height?: number\n mimeType: string\n width?: number\n}\n\ntype UploadFilePreviewMap = {\n [mimeTypePattern: string]: PayloadComponent\n}\n\n/**\n * Distinguishes an ordinary public file request (`read`) from Payload's internal\n * retrieval of a stored file's bytes for a dynamic transformation (`transform`).\n * Defaults to `read` when omitted, for third-party handler compatibility.\n */\nexport type FileHandlerOperation = 'read' | 'transform'\n\ntype Admin = {\n components?: {\n /**\n * The Controls component to extend the upload controls in the admin panel.\n */\n controls?: PayloadComponent[]\n /**\n * A custom component to render in place of the default Thumbnail in the upload side panel.\n *\n * Can be a single PayloadComponent (renders for all MIME types) or a Record keyed by\n * MIME type patterns. Pattern resolution priority: exact match → category wildcard\n * (e.g. `video/*`) → universal fallback (`*`). Falls back to the default Thumbnail\n * when nothing matches.\n */\n filePreview?: PayloadComponent | UploadFilePreviewMap\n }\n}\n\nexport type ExternalFileHeaderFilterContext = {\n isSameOrigin: boolean\n url: string\n}\n\nexport type UploadConfig = {\n /**\n * The adapter name to use for uploads. Used for storage adapter telemetry.\n * @default undefined\n */\n adapter?: string\n /**\n * The admin configuration for the upload field.\n */\n admin?: Admin\n /**\n * Represents an admin thumbnail, which can be either a React component or a string.\n * - If a string, it should be one of the image size names.\n * - A function that generates a fully qualified URL for the thumbnail, receives the doc as the only argument.\n **/\n adminThumbnail?: GetAdminThumbnail | string\n /**\n * Allow restricted file types known to be problematic.\n * - If set to `true`, it will allow all file types.\n * - If set to `false`, it will not allow file types and extensions known to be problematic.\n * - This setting is overriden by the `mimeTypes` option.\n * @default false\n */\n allowRestrictedFileTypes?: boolean\n /**\n * Enables bulk upload of files from the list view.\n * @default true\n */\n bulkUpload?: boolean\n /**\n * Appends a cache tag to the image URL when fetching the thumbnail in the admin panel. It may be desirable to disable this when hosting via CDNs with strict parameters.\n *\n * @default true\n */\n cacheTags?: boolean\n /**\n * Enables cropping of images.\n * @default true\n */\n crop?: boolean\n /**\n * Disable the ability to save files to disk.\n * @default false\n */\n disableLocalStorage?: boolean\n /**\n * Enable displaying preview of the uploaded file in Upload fields related to this Collection.\n * Can be locally overridden by `displayPreview` option in Upload field.\n * @default false\n */\n displayPreview?: boolean\n /**\n * Accepts existing headers and returns the headers after filtering or modifying. The optional\n * context identifies the destination for the current request, including each redirect hop.\n * `isSameOrigin` is true only when that destination matches a trusted origin established for a\n * relative file URL.\n * If using this option, you should handle the removal of any sensitive cookies\n * (like payload-prefixed cookies) to prevent leaking session information to external\n * services. By default, Payload automatically filters out payload-prefixed cookies\n * when this option is NOT defined.\n *\n * Useful for adding custom headers to fetch from external providers.\n * @default undefined\n */\n externalFileHeaderFilter?: (\n headers: Record<string, string>,\n context?: ExternalFileHeaderFilterContext,\n ) => Record<string, string>\n /**\n * Field slugs to use for a compound index instead of the default filename index.\n */\n filenameCompoundIndex?: string[]\n /** @internal Set by cloudStoragePlugin for versioned uploads; adapters do not implement this. */\n fileOperations?: {\n /** Copy before the document changes. Must preserve object metadata and reject an occupied key. */\n copy: (args: {\n from: string\n req: PayloadRequest\n to: string\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<void>\n delete: (args: { key: string; req: PayloadRequest }) => Promise<void>\n hasLegacyFile?: (args: {\n doc: Record<string, unknown>\n req: PayloadRequest\n }) => Promise<boolean>\n move?: (args: {\n from: string\n req: PayloadRequest\n to: string\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<void>\n resolveStorageKey: (args: { _objectKey?: string; filename: string; prefix?: string }) => string\n stage: (args: {\n data: Record<string, unknown>\n files: FileToSave[]\n req: PayloadRequest\n trackStagedObject: (object: StagedObject) => void\n }) => Promise<{ metadata: Record<string, unknown> }>\n }\n /**\n * Require files to be uploaded when creating a document.\n * @default true\n */\n filesRequiredOnCreate?: boolean\n /**\n * Enables focal point positioning for image manipulation.\n * @default true\n */\n focalPoint?: boolean\n /**\n * Custom handlers to run when a file is fetched.\n *\n * - If a handler returns a Response, the response will be sent to the client and no further handlers will be run.\n * - If a handler returns null, the next handler will be run.\n * - If no handlers return a response the file will be returned by default.\n *\n * @default undefined\n */\n handlers?: ((\n req: PayloadRequest,\n args: {\n doc: TypeWithID\n headers?: Headers\n params: {\n collection: string\n filename: string\n /**\n * True when the request asks for the original with `?original=true`. The original and\n * the main file can share a filename, so the filename alone does not say which to serve.\n */\n isOriginal?: boolean\n /** @default 'read' */\n operation?: FileHandlerOperation\n prefix?: string\n uploadReference?: unknown\n }\n },\n ) => Promise<Response> | Promise<void> | Response | void)[]\n /**\n * Whether a registered transformer performs additional processing on the main\n * uploaded file beyond simple pass-through (e.g. resizing, format conversion,\n * trimming). Written by a transformer's `init()`; not intended to be set\n * directly in collection config. Used by the Admin UI to decide whether to\n * show focal-point controls when no image sizes are configured.\n * @internal\n */\n hasImageAdjustments?: boolean\n /**\n * Set to `true` to prevent the admin UI from showing file inputs during document creation, useful for programmatic file generation.\n */\n hideFileInputOnCreate?: boolean\n /**\n * Set to `true` to prevent the admin UI having a way to remove an existing file while editing.\n */\n hideRemoveFile?: boolean\n /**\n * Restrict mimeTypes in the file picker. Array of valid mime types or mimetype wildcards\n * @example ['image/*', 'application/pdf']\n * @default undefined\n */\n mimeTypes?: string[]\n /**\n * Ability to modify the response headers fetching a file.\n * @default undefined\n */\n modifyResponseHeaders?: ({ headers }: { headers: Headers }) => Headers | void\n /**\n * Controls the behavior of pasting/uploading files from URLs.\n * If set to `false`, fetching from remote URLs is disabled.\n * If an `allowList` is provided, server-side fetching will be enabled for specified URLs.\n *\n * @default true (client-side fetching enabled)\n */\n pasteURL?:\n | {\n allowList: AllowList\n }\n | false\n /**\n * Skip safe fetch when using server-side fetching for external files from these URLs.\n * @default false\n */\n skipSafeFetch?: AllowList | boolean\n /**\n * The directory to serve static files from. Defaults to collection slug.\n * @default undefined\n */\n staticDir?: string\n /**\n * Adapter-provided upload instructions.\n * @internal\n */\n uploadInstructions?: UploadInstructionsCapability\n}\n\nexport type UploadInstructionsAccess = (args: {\n collectionSlug: UploadCollectionSlug\n req: PayloadRequest\n}) => boolean | Promise<boolean>\n\nexport type UploadInstructionsRequest = {\n collectionSlug: UploadCollectionSlug\n docPrefix?: string\n filename: string\n filesize: number\n mimeType: string\n}\n\nexport type UploadInstructions = {\n file: {\n filename: string\n mimeType: string\n size: number\n uploadReference: Record<string, unknown>\n }\n} & (\n | {\n data?: unknown\n name: string\n type: 'dispatch'\n }\n | {\n request: {\n headers?: Record<string, string>\n method: 'POST' | 'PUT'\n url: string\n }\n type: 'http'\n }\n)\n\nexport type GenerateUploadInstructions = (\n args: { overrideAccess?: boolean; req: PayloadRequest } & UploadInstructionsRequest,\n) => Promise<UploadInstructions> | UploadInstructions\n\nexport type UploadInstructionsCapability = {\n /** Generates upload instructions. The generator or supporting endpoint must check access. */\n generate: GenerateUploadInstructions\n /**\n * Require a receipt signed by `resolveSignedURLKey` before invoking upload handlers. Client\n * uploads keep an `original` and file history only when a receipt is verified.\n * @see https://payloadcms.com/docs/upload/storage-adapters#custom-upload-receipts\n */\n requiresUploadReceipt?: boolean\n /**\n * Whether the Admin panel should use these instructions before saving a document.\n * This can still be useful when upload chunks pass through Payload.\n */\n useInAdmin: boolean\n}\nexport type checkFileRestrictionsParams = {\n /** Set to false when the file bytes have not been uploaded yet. */\n checkFileContents?: boolean\n collection: CollectionConfig\n file: File\n req: PayloadRequest\n}\n\nexport type SanitizedUploadConfig = {\n staticDir: UploadConfig['staticDir']\n /**\n * The collection's image sizes, as written at startup by a registered transformer such as\n * `sharpTransformer({ collections: { <slug>: { variants } } })`. Names and admin options\n * only — not authored on the collection.\n */\n variants?: ImageSize[]\n} & UploadConfig\n\nexport type File = {\n /**\n * The buffer of the file.\n */\n data: Buffer\n /**\n * The mimetype of the file.\n */\n mimetype: string\n /**\n * The name of the file.\n */\n name: string\n /**\n * The size of the file in bytes.\n */\n size: number\n /**\n * Path to the temp file on disk when useTempFiles is enabled. In this case file.data will be an empty buffer.\n */\n tempFilePath?: string\n}\n\nexport type FileToSave = {\n /**\n * Which document field describes this file. Storage uses it to find the file's location,\n * because the main file and the original can share a filename.\n */\n role?: StoredFileRole\n} & (\n | {\n /**\n * The buffer of the file.\n */\n buffer: Buffer\n /**\n * The path to save the file.\n */\n path: string\n }\n | {\n /**\n * The path to save the file.\n */\n path: string\n /**\n * An existing file on disk to copy to `path`, instead of `buffer` - avoids loading a file\n * that's already on disk (e.g. a temp file) fully into memory just to write it back out.\n */\n sourcePath: string\n }\n)\n\ntype Crop = {\n height: number\n unit: '%' | 'px'\n width: number\n x: number\n y: number\n}\n\nexport type FocalPoint = {\n x: number\n y: number\n}\n\nexport type UploadEdits = {\n crop?: Crop\n focalPoint?: FocalPoint\n heightInPixels?: number\n widthInPixels?: number\n}\n"],"names":[],"mappings":"AAyfA,WAKC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getEntityPermissions.d.ts","sourceRoot":"","sources":["../../../src/utilities/getEntityPermissions/getEntityPermissions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,gBAAgB,EAChB,oBAAoB,EAEpB,gBAAgB,EAEjB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,KAAK,EAAE,yBAAyB,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AAC9F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAA;AAC1E,OAAO,KAAK,EAAE,SAAS,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAA;AACtE,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,cAAc,EAAS,MAAM,sBAAsB,CAAA;AAQ5F,MAAM,MAAM,0BAA0B,GAAG,MAAM,CAC7C,SAAS,EACT,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAC7C,CAAA;AAED,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,UAAU,CAAA;AAE/C,KAAK,UAAU,CAAC,WAAW,SAAS,YAAY,GAAG,QAAQ,IAAI,WAAW,SAAS,QAAQ,GACvF,gBAAgB,GAChB,oBAAoB,CAAA;AAExB,KAAK,IAAI,CAAC,WAAW,SAAS,YAAY,GAAG,QAAQ,IAAI;IACvD,0BAA0B,EAAE,0BAA0B,CAAA;IACtD;;OAEG;IACH,IAAI,CAAC,EAAE,UAAU,CAAA;IACjB,MAAM,EAAE,WAAW,SAAS,YAAY,GAAG,yBAAyB,GAAG,qBAAqB,CAAA;IAC5F,UAAU,EAAE,WAAW,CAAA;IACvB;;OAEG;IACH,UAAU,EAAE,aAAa,EAAE,CAAA;IAC3B,GAAG,EAAE,cAAc,CAAA;CACpB,GAAG,CACA;IACE,SAAS,EAAE,KAAK,CAAA;IAChB,EAAE,CAAC,EAAE,KAAK,CAAA;CACX,GACD;IACE,SAAS,EAAE,IAAI,CAAA;IACf,EAAE,EAAE,WAAW,SAAS,YAAY,GAAG,qBAAqB,GAAG,SAAS,CAAA;CACzE,CACJ,CAAA;AAaD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,oBAAoB,CAAC,WAAW,SAAS,YAAY,GAAG,QAAQ,EACpF,IAAI,EAAE,IAAI,CAAC,WAAW,CAAC,GACtB,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"getEntityPermissions.d.ts","sourceRoot":"","sources":["../../../src/utilities/getEntityPermissions/getEntityPermissions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,gBAAgB,EAChB,oBAAoB,EAEpB,gBAAgB,EAEjB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,KAAK,EAAE,yBAAyB,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAA;AAC9F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAA;AAC1E,OAAO,KAAK,EAAE,SAAS,EAAE,qBAAqB,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
|
41
|
-
const { id,
|
|
41
|
+
const { id, data: _data, entity, entityType, fetchData, operations, req } = args;
|
|
42
42
|
const { locale: _locale, user } = req;
|
|
43
43
|
const locale = _locale ? _locale : undefined;
|
|
44
44
|
if (fetchData && entityType === 'collection' && !id) {
|
|
@@ -71,6 +71,9 @@ const topLevelGlobalPermissions = [
|
|
|
71
71
|
})() : undefined;
|
|
72
72
|
const isLoggedIn = !!user;
|
|
73
73
|
const fieldsPermissions = {};
|
|
74
|
+
// A permission tree is reusable only within this entity calculation. The caller's
|
|
75
|
+
// cache can be shared across collections and globals with different access rules.
|
|
76
|
+
const blockPermissionCache = new WeakMap();
|
|
74
77
|
const entityPermissions = {
|
|
75
78
|
fields: fieldsPermissions
|
|
76
79
|
};
|
|
@@ -134,7 +137,7 @@ const topLevelGlobalPermissions = [
|
|
|
134
137
|
await Promise.all(wherePromises);
|
|
135
138
|
populateFieldPermissions({
|
|
136
139
|
id,
|
|
137
|
-
|
|
140
|
+
blockPermissionCache,
|
|
138
141
|
collection: entityType === 'collection' ? entity : null,
|
|
139
142
|
data,
|
|
140
143
|
fields: entity.fields,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utilities/getEntityPermissions/getEntityPermissions.ts"],"sourcesContent":["import { isDeepStrictEqual } from 'util'\n\nimport type {\n BlockPermissions,\n CollectionPermission,\n FieldsPermissions,\n GlobalPermission,\n Permission,\n} from '../../auth/types.js'\nimport type { SanitizedCollectionConfig, TypeWithID } from '../../collections/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type { BlockSlug, DefaultDocumentIDType } from '../../index.js'\nimport type { AllOperations, JsonObject, PayloadRequest, Where } from '../../types/index.js'\n\nimport { getAccessOperationRequest } from '../getAccessOperationRequest.js'\nimport { entityDocExists } from './entityDocExists.js'\nimport { populateFieldPermissions } from './populateFieldPermissions.js'\n\ntype WhereQueryCache = { result: Promise<boolean>; where: Where }[]\n\nexport type BlockReferencesPermissions = Record<\n BlockSlug,\n BlockPermissions | Promise<BlockPermissions>\n>\n\nexport type EntityDoc = JsonObject | TypeWithID\n\ntype ReturnType<TEntityType extends 'collection' | 'global'> = TEntityType extends 'global'\n ? GlobalPermission\n : CollectionPermission\n\ntype Args<TEntityType extends 'collection' | 'global'> = {\n blockReferencesPermissions: BlockReferencesPermissions\n /**\n * If the document data is passed, it will be used to check access instead of fetching the document from the database.\n */\n data?: JsonObject\n entity: TEntityType extends 'collection' ? SanitizedCollectionConfig : SanitizedGlobalConfig\n entityType: TEntityType\n /**\n * Operations to check access for\n */\n operations: AllOperations[]\n req: PayloadRequest\n} & (\n | {\n fetchData: false\n id?: never\n }\n | {\n fetchData: true\n id: TEntityType extends 'collection' ? DefaultDocumentIDType : undefined\n }\n)\n\nconst topLevelCollectionPermissions = [\n 'create',\n 'delete',\n 'read',\n 'readVersions',\n 'update',\n 'validate',\n 'unlock',\n]\nconst topLevelGlobalPermissions = ['read', 'readVersions', 'update', 'validate']\n\n/**\n * Build up permissions object for an entity (collection or global).\n * This is not run during any update and reflects the current state of the entity data => doc and data is the same.\n *\n * When `fetchData` is false:\n * - returned `Where` are not run and evaluated as \"does not have permission\".\n * - If req.data is passed: `data` and `doc` is passed to access functions.\n * - If req.data is not passed: `data` and `doc` is not passed to access functions.\n *\n * When `fetchData` is true:\n * - `Where` are run and evaluated as \"has permission\" or \"does not have permission\".\n * - `data` and `doc` are always passed to access functions.\n * - Error is thrown if `entityType` is 'collection' and `id` is not passed.\n *\n * In both cases:\n * We cannot include siblingData or blockData here, as we do not have siblingData available once we reach block or array\n * rows, as we're calculating schema permissions, which do not include individual rows.\n * For consistency, it's thus better to never include the siblingData and blockData\n *\n * @internal\n */\nexport async function getEntityPermissions<TEntityType extends 'collection' | 'global'>(\n args: Args<TEntityType>,\n): Promise<ReturnType<TEntityType>> {\n const {\n id,\n blockReferencesPermissions,\n data: _data,\n entity,\n entityType,\n fetchData,\n operations,\n req,\n } = args\n const { locale: _locale, user } = req\n\n const locale = _locale ? _locale : undefined\n\n if (fetchData && entityType === 'collection' && !id) {\n throw new Error('ID is required when fetching data for a collection')\n }\n\n const hasData = _data && Object.keys(_data).length > 0\n const data: JsonObject | undefined = hasData\n ? _data\n : fetchData\n ? await (async () => {\n if (entityType === 'global') {\n return req.payload.findGlobal({\n slug: entity.slug,\n depth: 0,\n fallbackLocale: null,\n locale,\n overrideAccess: true,\n req,\n })\n }\n\n if (entityType === 'collection') {\n return req.payload.findByID({\n id: id!,\n collection: entity.slug,\n depth: 0,\n fallbackLocale: null,\n locale,\n overrideAccess: true,\n req,\n trash: true,\n })\n }\n })()\n : undefined\n\n const isLoggedIn = !!user\n\n const fieldsPermissions: FieldsPermissions = {}\n\n const entityPermissions: ReturnType<TEntityType> = {\n fields: fieldsPermissions,\n }\n\n const promises: Promise<void>[] = []\n\n // Phase 1: Resolve all access functions to get where queries\n const accessResults: {\n operation: keyof typeof entity.access\n result: Promise<boolean | Where>\n }[] = []\n\n for (const _operation of operations) {\n const operation = _operation as keyof typeof entity.access\n const accessFunction = entity.access[operation]\n\n if (\n (entityType === 'collection' && topLevelCollectionPermissions.includes(operation)) ||\n (entityType === 'global' && topLevelGlobalPermissions.includes(operation))\n ) {\n if (typeof accessFunction === 'function') {\n accessResults.push({\n operation,\n result: Promise.resolve(\n accessFunction({\n id,\n slug: entity.slug,\n data,\n req:\n _operation === 'readVersions' || _operation === 'unlock'\n ? req\n : getAccessOperationRequest({\n operation: _operation,\n req,\n }),\n }),\n ),\n })\n } else {\n entityPermissions[operation] = {\n permission: isLoggedIn,\n }\n }\n }\n }\n\n // Await all access functions in parallel\n const resolvedAccessResults = await Promise.all(\n accessResults.map(async (item) => ({\n operation: item.operation,\n result: await item.result,\n })),\n )\n\n // Phase 2: Process where queries with cache and resolve in parallel\n const whereQueryCache: WhereQueryCache = []\n const wherePromises: Promise<void>[] = []\n\n for (const { operation, result: accessResult } of resolvedAccessResults) {\n if (typeof accessResult === 'object') {\n processWhereQuery({\n id,\n slug: entity.slug,\n accessResult,\n entityPermissions,\n entityType,\n fetchData,\n locale,\n operation,\n req,\n wherePromises,\n whereQueryCache,\n })\n } else if (entityPermissions[operation]?.permission !== false) {\n entityPermissions[operation] = { permission: !!accessResult }\n }\n }\n\n // Await all where query DB calls in parallel\n await Promise.all(wherePromises)\n\n populateFieldPermissions({\n id,\n blockReferencesPermissions,\n collection: entityType === 'collection' ? (entity as SanitizedCollectionConfig) : null,\n data,\n fields: entity.fields,\n global: entityType === 'global' ? (entity as SanitizedGlobalConfig) : null,\n operations,\n parentPermissionsObject: entityPermissions,\n permissionsObject: fieldsPermissions,\n promises,\n req,\n })\n\n /**\n * Await all promises in parallel.\n * A promise can add more promises to the promises array (group of fields calls populateFieldPermissions again in their own promise), which will not be\n * awaited in the first run.\n * This is why we need to loop again to process the new promises, until there are no more promises left.\n */\n let iterations = 0\n while (promises.length > 0) {\n const currentPromises = promises.splice(0, promises.length)\n\n await Promise.all(currentPromises)\n\n iterations++\n if (iterations >= 100) {\n throw new Error('Infinite getEntityPermissions promise loop detected.')\n }\n }\n\n return entityPermissions\n}\n\nconst processWhereQuery = ({\n id,\n slug,\n accessResult,\n entityPermissions,\n entityType,\n fetchData,\n locale,\n operation,\n req,\n wherePromises,\n whereQueryCache,\n}: {\n accessResult: Where\n entityPermissions: CollectionPermission | GlobalPermission\n entityType: 'collection' | 'global'\n fetchData: boolean\n id?: DefaultDocumentIDType\n locale?: string\n operation: Extract<keyof (CollectionPermission | GlobalPermission), AllOperations>\n req: PayloadRequest\n slug: string\n wherePromises: Promise<void>[]\n whereQueryCache: WhereQueryCache\n}): void => {\n if (fetchData) {\n // Check cache for identical where query using deep comparison\n let cached = whereQueryCache.find((entry) => isDeepStrictEqual(entry.where, accessResult))\n\n if (!cached) {\n // Cache miss - start DB query (don't await)\n cached = {\n result: entityDocExists({\n id,\n slug,\n entityType,\n locale,\n operation,\n req,\n where: accessResult,\n }),\n where: accessResult,\n }\n whereQueryCache.push(cached)\n }\n\n // Defer resolution to Promise.all (cache hits reuse same promise)\n wherePromises.push(\n cached.result.then((hasPermission) => {\n entityPermissions[operation] = {\n permission: hasPermission,\n where: accessResult,\n }\n }),\n )\n } else {\n // TODO: 4.0: Investigate defaulting to `false` here, if where query is returned but ignored as we don't\n // have the document data available. This seems more secure.\n // Alternatively, we could set permission to a third state, like 'unknown'.\n // Even after calling sanitizePermissions, the permissions will still be true if the where query is returned but ignored as we don't have the document data available.\n entityPermissions[operation] = { permission: true, where: accessResult }\n }\n}\n"],"names":["isDeepStrictEqual","getAccessOperationRequest","entityDocExists","populateFieldPermissions","topLevelCollectionPermissions","topLevelGlobalPermissions","getEntityPermissions","args","id","blockReferencesPermissions","data","_data","entity","entityType","fetchData","operations","req","locale","_locale","user","undefined","Error","hasData","Object","keys","length","payload","findGlobal","slug","depth","fallbackLocale","overrideAccess","findByID","collection","trash","isLoggedIn","fieldsPermissions","entityPermissions","fields","promises","accessResults","_operation","operation","accessFunction","access","includes","push","result","Promise","resolve","permission","resolvedAccessResults","all","map","item","whereQueryCache","wherePromises","accessResult","processWhereQuery","global","parentPermissionsObject","permissionsObject","iterations","currentPromises","splice","cached","find","entry","where","then","hasPermission"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,OAAM;AAcxC,SAASC,yBAAyB,QAAQ,kCAAiC;AAC3E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,wBAAwB,QAAQ,gCAA+B;AAuCxE,MAAMC,gCAAgC;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AACD,MAAMC,4BAA4B;IAAC;IAAQ;IAAgB;IAAU;CAAW;AAEhF;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,eAAeC,qBACpBC,IAAuB;IAEvB,MAAM,EACJC,EAAE,EACFC,0BAA0B,EAC1BC,MAAMC,KAAK,EACXC,MAAM,EACNC,UAAU,EACVC,SAAS,EACTC,UAAU,EACVC,GAAG,EACJ,GAAGT;IACJ,MAAM,EAAEU,QAAQC,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AAG,CAACW;QAElBD;QACA,IAAIA,cAAc,KAAK;YACrB,MAAM,IAAIzC,MAAM;QAClB;IACF;IAEA,OAAOgB;AACT;AAEA,MAAMqB,oBAAoB,CAAC,EACzBlD,EAAE,EACFoB,IAAI,EACJ6B,YAAY,EACZpB,iBAAiB,EACjBxB,UAAU,EACVC,SAAS,EACTG,MAAM,EACNyB,SAAS,EACT1B,GAAG,EACHwC,aAAa,EACbD,eAAe,EAahB;IACC,IAAIzC,WAAW;QACb,8DAA8D;QAC9D,IAAImD,SAASV,gBAAgBW,IAAI,CAAC,CAACC,QAAUnE,kBAAkBmE,MAAMC,KAAK,EAAEX;QAE5E,IAAI,CAACQ,QAAQ;YACX,4CAA4C;YAC5CA,SAAS;gBACPlB,QAAQ7C,gBAAgB;oBACtBM;oBACAoB;oBACAf;oBACAI;oBACAyB;oBACA1B;oBACAoD,OAAOX;gBACT;gBACAW,OAAOX;YACT;YACAF,gBAAgBT,IAAI,CAACmB;QACvB;QAEA,kEAAkE;QAClET,cAAcV,IAAI,CAChBmB,OAAOlB,MAAM,CAACsB,IAAI,CAAC,CAACC;YAClBjC,iBAAiB,CAACK,UAAU,GAAG;gBAC7BQ,YAAYoB;gBACZF,OAAOX;YACT;QACF;IAEJ,OAAO;QACL,wGAAwG;QACxG,4DAA4D;QAC5D,2EAA2E;QAC3E,sKAAsK;QACtKpB,iBAAiB,CAACK,UAAU,GAAG;YAAEQ,YAAY;YAAMkB,OAAOX;QAAa;IACzE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/utilities/getEntityPermissions/getEntityPermissions.ts"],"sourcesContent":["import { isDeepStrictEqual } from 'util'\n\nimport type {\n BlockPermissions,\n CollectionPermission,\n FieldsPermissions,\n GlobalPermission,\n Permission,\n} from '../../auth/types.js'\nimport type { SanitizedCollectionConfig, TypeWithID } from '../../collections/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type { BlockSlug, DefaultDocumentIDType } from '../../index.js'\nimport type { AllOperations, JsonObject, PayloadRequest, Where } from '../../types/index.js'\n\nimport { getAccessOperationRequest } from '../getAccessOperationRequest.js'\nimport { entityDocExists } from './entityDocExists.js'\nimport { populateFieldPermissions } from './populateFieldPermissions.js'\n\ntype WhereQueryCache = { result: Promise<boolean>; where: Where }[]\n\nexport type BlockReferencesPermissions = Record<\n BlockSlug,\n BlockPermissions | Promise<BlockPermissions>\n>\n\nexport type EntityDoc = JsonObject | TypeWithID\n\ntype ReturnType<TEntityType extends 'collection' | 'global'> = TEntityType extends 'global'\n ? GlobalPermission\n : CollectionPermission\n\ntype Args<TEntityType extends 'collection' | 'global'> = {\n blockReferencesPermissions: BlockReferencesPermissions\n /**\n * If the document data is passed, it will be used to check access instead of fetching the document from the database.\n */\n data?: JsonObject\n entity: TEntityType extends 'collection' ? SanitizedCollectionConfig : SanitizedGlobalConfig\n entityType: TEntityType\n /**\n * Operations to check access for\n */\n operations: AllOperations[]\n req: PayloadRequest\n} & (\n | {\n fetchData: false\n id?: never\n }\n | {\n fetchData: true\n id: TEntityType extends 'collection' ? DefaultDocumentIDType : undefined\n }\n)\n\nconst topLevelCollectionPermissions = [\n 'create',\n 'delete',\n 'read',\n 'readVersions',\n 'update',\n 'validate',\n 'unlock',\n]\nconst topLevelGlobalPermissions = ['read', 'readVersions', 'update', 'validate']\n\n/**\n * Build up permissions object for an entity (collection or global).\n * This is not run during any update and reflects the current state of the entity data => doc and data is the same.\n *\n * When `fetchData` is false:\n * - returned `Where` are not run and evaluated as \"does not have permission\".\n * - If req.data is passed: `data` and `doc` is passed to access functions.\n * - If req.data is not passed: `data` and `doc` is not passed to access functions.\n *\n * When `fetchData` is true:\n * - `Where` are run and evaluated as \"has permission\" or \"does not have permission\".\n * - `data` and `doc` are always passed to access functions.\n * - Error is thrown if `entityType` is 'collection' and `id` is not passed.\n *\n * In both cases:\n * We cannot include siblingData or blockData here, as we do not have siblingData available once we reach block or array\n * rows, as we're calculating schema permissions, which do not include individual rows.\n * For consistency, it's thus better to never include the siblingData and blockData\n *\n * @internal\n */\nexport async function getEntityPermissions<TEntityType extends 'collection' | 'global'>(\n args: Args<TEntityType>,\n): Promise<ReturnType<TEntityType>> {\n const { id, data: _data, entity, entityType, fetchData, operations, req } = args\n const { locale: _locale, user } = req\n\n const locale = _locale ? _locale : undefined\n\n if (fetchData && entityType === 'collection' && !id) {\n throw new Error('ID is required when fetching data for a collection')\n }\n\n const hasData = _data && Object.keys(_data).length > 0\n const data: JsonObject | undefined = hasData\n ? _data\n : fetchData\n ? await (async () => {\n if (entityType === 'global') {\n return req.payload.findGlobal({\n slug: entity.slug,\n depth: 0,\n fallbackLocale: null,\n locale,\n overrideAccess: true,\n req,\n })\n }\n\n if (entityType === 'collection') {\n return req.payload.findByID({\n id: id!,\n collection: entity.slug,\n depth: 0,\n fallbackLocale: null,\n locale,\n overrideAccess: true,\n req,\n trash: true,\n })\n }\n })()\n : undefined\n\n const isLoggedIn = !!user\n\n const fieldsPermissions: FieldsPermissions = {}\n // A permission tree is reusable only within this entity calculation. The caller's\n // cache can be shared across collections and globals with different access rules.\n const blockPermissionCache = new WeakMap<object, Map<string, BlockPermissions>>()\n\n const entityPermissions: ReturnType<TEntityType> = {\n fields: fieldsPermissions,\n }\n\n const promises: Promise<void>[] = []\n\n // Phase 1: Resolve all access functions to get where queries\n const accessResults: {\n operation: keyof typeof entity.access\n result: Promise<boolean | Where>\n }[] = []\n\n for (const _operation of operations) {\n const operation = _operation as keyof typeof entity.access\n const accessFunction = entity.access[operation]\n\n if (\n (entityType === 'collection' && topLevelCollectionPermissions.includes(operation)) ||\n (entityType === 'global' && topLevelGlobalPermissions.includes(operation))\n ) {\n if (typeof accessFunction === 'function') {\n accessResults.push({\n operation,\n result: Promise.resolve(\n accessFunction({\n id,\n slug: entity.slug,\n data,\n req:\n _operation === 'readVersions' || _operation === 'unlock'\n ? req\n : getAccessOperationRequest({\n operation: _operation,\n req,\n }),\n }),\n ),\n })\n } else {\n entityPermissions[operation] = {\n permission: isLoggedIn,\n }\n }\n }\n }\n\n // Await all access functions in parallel\n const resolvedAccessResults = await Promise.all(\n accessResults.map(async (item) => ({\n operation: item.operation,\n result: await item.result,\n })),\n )\n\n // Phase 2: Process where queries with cache and resolve in parallel\n const whereQueryCache: WhereQueryCache = []\n const wherePromises: Promise<void>[] = []\n\n for (const { operation, result: accessResult } of resolvedAccessResults) {\n if (typeof accessResult === 'object') {\n processWhereQuery({\n id,\n slug: entity.slug,\n accessResult,\n entityPermissions,\n entityType,\n fetchData,\n locale,\n operation,\n req,\n wherePromises,\n whereQueryCache,\n })\n } else if (entityPermissions[operation]?.permission !== false) {\n entityPermissions[operation] = { permission: !!accessResult }\n }\n }\n\n // Await all where query DB calls in parallel\n await Promise.all(wherePromises)\n\n populateFieldPermissions({\n id,\n blockPermissionCache,\n collection: entityType === 'collection' ? (entity as SanitizedCollectionConfig) : null,\n data,\n fields: entity.fields,\n global: entityType === 'global' ? (entity as SanitizedGlobalConfig) : null,\n operations,\n parentPermissionsObject: entityPermissions,\n permissionsObject: fieldsPermissions,\n promises,\n req,\n })\n\n /**\n * Await all promises in parallel.\n * A promise can add more promises to the promises array (group of fields calls populateFieldPermissions again in their own promise), which will not be\n * awaited in the first run.\n * This is why we need to loop again to process the new promises, until there are no more promises left.\n */\n let iterations = 0\n while (promises.length > 0) {\n const currentPromises = promises.splice(0, promises.length)\n\n await Promise.all(currentPromises)\n\n iterations++\n if (iterations >= 100) {\n throw new Error('Infinite getEntityPermissions promise loop detected.')\n }\n }\n\n return entityPermissions\n}\n\nconst processWhereQuery = ({\n id,\n slug,\n accessResult,\n entityPermissions,\n entityType,\n fetchData,\n locale,\n operation,\n req,\n wherePromises,\n whereQueryCache,\n}: {\n accessResult: Where\n entityPermissions: CollectionPermission | GlobalPermission\n entityType: 'collection' | 'global'\n fetchData: boolean\n id?: DefaultDocumentIDType\n locale?: string\n operation: Extract<keyof (CollectionPermission | GlobalPermission), AllOperations>\n req: PayloadRequest\n slug: string\n wherePromises: Promise<void>[]\n whereQueryCache: WhereQueryCache\n}): void => {\n if (fetchData) {\n // Check cache for identical where query using deep comparison\n let cached = whereQueryCache.find((entry) => isDeepStrictEqual(entry.where, accessResult))\n\n if (!cached) {\n // Cache miss - start DB query (don't await)\n cached = {\n result: entityDocExists({\n id,\n slug,\n entityType,\n locale,\n operation,\n req,\n where: accessResult,\n }),\n where: accessResult,\n }\n whereQueryCache.push(cached)\n }\n\n // Defer resolution to Promise.all (cache hits reuse same promise)\n wherePromises.push(\n cached.result.then((hasPermission) => {\n entityPermissions[operation] = {\n permission: hasPermission,\n where: accessResult,\n }\n }),\n )\n } else {\n // TODO: 4.0: Investigate defaulting to `false` here, if where query is returned but ignored as we don't\n // have the document data available. This seems more secure.\n // Alternatively, we could set permission to a third state, like 'unknown'.\n // Even after calling sanitizePermissions, the permissions will still be true if the where query is returned but ignored as we don't have the document data available.\n entityPermissions[operation] = { permission: true, where: accessResult }\n }\n}\n"],"names":["isDeepStrictEqual","getAccessOperationRequest","entityDocExists","populateFieldPermissions","topLevelCollectionPermissions","topLevelGlobalPermissions","getEntityPermissions","args","id","data","_data","entity","entityType","fetchData","operations","req","locale","_locale","user","undefined","Error","hasData","Object","keys","length","payload","findGlobal","slug","depth","fallbackLocale","overrideAccess","findByID","collection","trash","isLoggedIn","fieldsPermissions","blockPermissionCache","WeakMap","entityPermissions","fields","promises","accessResults","_operation","operation","accessFunction","access","includes","push","result","Promise","resolve","permission","resolvedAccessResults","all","map","item","whereQueryCache","wherePromises","accessResult","processWhereQuery","global","parentPermissionsObject","permissionsObject","iterations","currentPromises","splice","cached","find","entry","where","then","hasPermission"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,OAAM;AAcxC,SAASC,yBAAyB,QAAQ,kCAAiC;AAC3E,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,wBAAwB,QAAQ,gCAA+B;AAuCxE,MAAMC,gCAAgC;IACpC;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AACD,MAAMC,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AOX;QAAa;IACzE;AACF"}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import type { CollectionPermission, FieldPermissions, FieldsPermissions, GlobalPermission } from '../../auth/types.js';
|
|
1
|
+
import type { BlockPermissions, CollectionPermission, FieldPermissions, FieldsPermissions, GlobalPermission } from '../../auth/types.js';
|
|
2
2
|
import type { SanitizedCollectionConfig } from '../../collections/config/types.js';
|
|
3
3
|
import type { SanitizedGlobalConfig } from '../../globals/config/types.js';
|
|
4
4
|
import type { DefaultDocumentIDType } from '../../index.js';
|
|
5
5
|
import type { AllOperations, JsonObject, PayloadRequest } from '../../types/index.js';
|
|
6
|
-
import type { BlockReferencesPermissions } from './getEntityPermissions.js';
|
|
7
6
|
import { type Field } from '../../fields/config/types.js';
|
|
8
7
|
/**
|
|
9
8
|
* Build up permissions object and run access functions for each field of an entity
|
|
10
9
|
* This function is synchronous and collects all async work into the promises array
|
|
11
10
|
*/
|
|
12
|
-
export declare const populateFieldPermissions: ({ id,
|
|
13
|
-
|
|
11
|
+
export declare const populateFieldPermissions: ({ id, activeBlocks, blockPermissionCache, collection, data, fields, global, operations, parentPermissionsObject, permissionsObject, promises, req, }: {
|
|
12
|
+
activeBlocks?: Set<object>;
|
|
13
|
+
blockPermissionCache: WeakMap<object, Map<string, BlockPermissions>>;
|
|
14
14
|
/** The collection which the fields belong to. If the fields belong to a global, this will be null. */
|
|
15
15
|
collection: null | SanitizedCollectionConfig;
|
|
16
16
|
data: JsonObject | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"populateFieldPermissions.d.ts","sourceRoot":"","sources":["../../../src/utilities/getEntityPermissions/populateFieldPermissions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"populateFieldPermissions.d.ts","sourceRoot":"","sources":["../../../src/utilities/getEntityPermissions/populateFieldPermissions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,oBAAoB,EACpB,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAEjB,MAAM,qBAAqB,CAAA;AAC5B,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAA;AAClF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAA;AAC1E,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAA;AAC3D,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAErF,OAAO,EAAE,KAAK,KAAK,EAAc,MAAM,8BAA8B,CAAA;AAqCrE;;;GAGG;AACH,eAAO,MAAM,wBAAwB,yJAalC;IACD,YAAY,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IAC1B,oBAAoB,EAAE,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAA;IACpE,sGAAsG;IACtG,UAAU,EAAE,IAAI,GAAG,yBAAyB,CAAA;IAC5C,IAAI,EAAE,UAAU,GAAG,SAAS,CAAA;IAC5B,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,sGAAsG;IACtG,MAAM,EAAE,IAAI,GAAG,qBAAqB,CAAA;IACpC,EAAE,CAAC,EAAE,qBAAqB,CAAA;IAC1B;;OAEG;IACH,UAAU,EAAE,aAAa,EAAE,CAAA;IAC3B,uBAAuB,EAAE,oBAAoB,GAAG,gBAAgB,GAAG,gBAAgB,CAAA;IACnF,iBAAiB,EAAE,iBAAiB,CAAA;IACpC,QAAQ,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,CAAA;IACzB,GAAG,EAAE,cAAc,CAAA;CACpB,KAAG,IA4TH,CAAA"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { tabHasName } from '../../fields/config/types.js';
|
|
2
|
+
import { deepCopyObject } from '../deepCopyObject.js';
|
|
2
3
|
import { getAccessOperationRequest } from '../getAccessOperationRequest.js';
|
|
4
|
+
import { markRecursiveBlockBoundary } from '../sanitizePermissions.js';
|
|
3
5
|
const isThenable = (value)=>value != null && typeof value.then === 'function';
|
|
4
6
|
/**
|
|
5
7
|
* Helper to set a permission value that might be a promise.
|
|
@@ -28,7 +30,7 @@ target, operation, value, promises)=>{
|
|
|
28
30
|
/**
|
|
29
31
|
* Build up permissions object and run access functions for each field of an entity
|
|
30
32
|
* This function is synchronous and collects all async work into the promises array
|
|
31
|
-
*/ export const populateFieldPermissions = ({ id,
|
|
33
|
+
*/ export const populateFieldPermissions = ({ id, activeBlocks = new Set(), blockPermissionCache, collection, data, fields, global, operations, parentPermissionsObject, permissionsObject, promises, req })=>{
|
|
32
34
|
for (const field of fields){
|
|
33
35
|
// Set up permissions for all operations
|
|
34
36
|
for (const operation of operations){
|
|
@@ -84,7 +86,8 @@ target, operation, value, promises)=>{
|
|
|
84
86
|
}
|
|
85
87
|
populateFieldPermissions({
|
|
86
88
|
id,
|
|
87
|
-
|
|
89
|
+
activeBlocks,
|
|
90
|
+
blockPermissionCache,
|
|
88
91
|
collection,
|
|
89
92
|
data,
|
|
90
93
|
fields: field.fields,
|
|
@@ -114,15 +117,7 @@ target, operation, value, promises)=>{
|
|
|
114
117
|
if (!block) {
|
|
115
118
|
continue;
|
|
116
119
|
}
|
|
117
|
-
//
|
|
118
|
-
if (typeof _block === 'string') {
|
|
119
|
-
const blockReferencePermissions = blockReferencesPermissions[_block];
|
|
120
|
-
if (blockReferencePermissions) {
|
|
121
|
-
// Reference the cached permissions (may be a promise or resolved object)
|
|
122
|
-
blocksPermissions[block.slug] = blockReferencePermissions;
|
|
123
|
-
continue;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
120
|
+
// Reference permissions belong to this usage: callbacks and inheritance depend on context.
|
|
126
121
|
// Initialize block permissions object if needed
|
|
127
122
|
if (!blocksPermissions[block.slug]) {
|
|
128
123
|
blocksPermissions[block.slug] = {};
|
|
@@ -152,25 +147,58 @@ target, operation, value, promises)=>{
|
|
|
152
147
|
if (!blockPermission.fields) {
|
|
153
148
|
blockPermission.fields = {};
|
|
154
149
|
}
|
|
155
|
-
//
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
150
|
+
// A recursive reference has no finite permission subtree. Deny this occurrence
|
|
151
|
+
// explicitly so sanitization cannot mistake its absent descendants for full access.
|
|
152
|
+
if (activeBlocks.has(block)) {
|
|
153
|
+
for (const operation of operations){
|
|
154
|
+
if (operation === 'create' || operation === 'read' || operation === 'update' || operation === 'validate') {
|
|
155
|
+
setPermission(blockPermission, operation, false, promises);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
markRecursiveBlockBoundary({
|
|
159
|
+
fields: blockPermission.fields
|
|
160
|
+
});
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
// Nested occurrences depend on the active ancestor path. At the root,
|
|
164
|
+
// identical inherited permissions have the same finite subtree.
|
|
165
|
+
const inherited = operations.map((operation)=>blockPermission[operation]?.permission);
|
|
166
|
+
const cacheKey = inherited.some(isThenable) ? undefined : operations.map((operation, index)=>`${operation}:${inherited[index]}`).join('|');
|
|
167
|
+
const cached = cacheKey === undefined ? undefined : blockPermissionCache.get(block)?.get(cacheKey);
|
|
168
|
+
if (activeBlocks.size === 0 && cached) {
|
|
169
|
+
// Sanitization mutates permissions, so occurrences cannot share an object.
|
|
170
|
+
blocksPermissions[block.slug] = deepCopyObject(cached);
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
const pendingPromises = promises.length;
|
|
174
|
+
activeBlocks.add(block);
|
|
175
|
+
try {
|
|
176
|
+
populateFieldPermissions({
|
|
177
|
+
id,
|
|
178
|
+
activeBlocks,
|
|
179
|
+
blockPermissionCache,
|
|
180
|
+
collection,
|
|
181
|
+
data,
|
|
182
|
+
fields: block.fields,
|
|
183
|
+
global,
|
|
184
|
+
operations,
|
|
185
|
+
parentPermissionsObject: blockPermission,
|
|
186
|
+
permissionsObject: blockPermission.fields,
|
|
187
|
+
promises,
|
|
188
|
+
req
|
|
189
|
+
});
|
|
190
|
+
} finally{
|
|
191
|
+
activeBlocks.delete(block);
|
|
192
|
+
}
|
|
193
|
+
// Do not clone trees whose access results are still resolving.
|
|
194
|
+
if (activeBlocks.size === 0 && cacheKey !== undefined && promises.length === pendingPromises) {
|
|
195
|
+
let byAccess = blockPermissionCache.get(block);
|
|
196
|
+
if (!byAccess) {
|
|
197
|
+
byAccess = new Map();
|
|
198
|
+
blockPermissionCache.set(block, byAccess);
|
|
199
|
+
}
|
|
200
|
+
byAccess.set(cacheKey, blockPermission);
|
|
159
201
|
}
|
|
160
|
-
// Recursively process block fields synchronously
|
|
161
|
-
populateFieldPermissions({
|
|
162
|
-
id,
|
|
163
|
-
blockReferencesPermissions,
|
|
164
|
-
collection,
|
|
165
|
-
data,
|
|
166
|
-
fields: block.fields,
|
|
167
|
-
global,
|
|
168
|
-
operations,
|
|
169
|
-
parentPermissionsObject: blockPermission,
|
|
170
|
-
permissionsObject: blockPermission.fields,
|
|
171
|
-
promises,
|
|
172
|
-
req
|
|
173
|
-
});
|
|
174
202
|
}
|
|
175
203
|
}
|
|
176
204
|
}
|
|
@@ -179,13 +207,14 @@ target, operation, value, promises)=>{
|
|
|
179
207
|
// Field does not have a name => same parentPermissionsObject
|
|
180
208
|
populateFieldPermissions({
|
|
181
209
|
id,
|
|
210
|
+
activeBlocks,
|
|
182
211
|
collection,
|
|
183
212
|
data,
|
|
184
213
|
fields: field.fields,
|
|
185
214
|
global,
|
|
186
215
|
operations,
|
|
187
216
|
// Field does not have a name here => use parent permissions object
|
|
188
|
-
|
|
217
|
+
blockPermissionCache,
|
|
189
218
|
parentPermissionsObject,
|
|
190
219
|
permissionsObject,
|
|
191
220
|
promises,
|
|
@@ -224,7 +253,8 @@ target, operation, value, promises)=>{
|
|
|
224
253
|
}
|
|
225
254
|
populateFieldPermissions({
|
|
226
255
|
id,
|
|
227
|
-
|
|
256
|
+
activeBlocks,
|
|
257
|
+
blockPermissionCache,
|
|
228
258
|
collection,
|
|
229
259
|
data,
|
|
230
260
|
fields: tab.fields,
|
|
@@ -239,13 +269,14 @@ target, operation, value, promises)=>{
|
|
|
239
269
|
// Tab does not have a name => same parentPermissionsObject
|
|
240
270
|
populateFieldPermissions({
|
|
241
271
|
id,
|
|
272
|
+
activeBlocks,
|
|
242
273
|
collection,
|
|
243
274
|
data,
|
|
244
275
|
fields: tab.fields,
|
|
245
276
|
global,
|
|
246
277
|
operations,
|
|
247
278
|
// Tab does not have a name here => use parent permissions object
|
|
248
|
-
|
|
279
|
+
blockPermissionCache,
|
|
249
280
|
parentPermissionsObject,
|
|
250
281
|
permissionsObject,
|
|
251
282
|
promises,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utilities/getEntityPermissions/populateFieldPermissions.ts"],"sourcesContent":["import type {\n BlockPermissions,\n BlocksPermissions,\n CollectionPermission,\n FieldPermissions,\n FieldsPermissions,\n GlobalPermission,\n Permission,\n} from '../../auth/types.js'\nimport type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type { DefaultDocumentIDType } from '../../index.js'\nimport type { AllOperations, JsonObject, PayloadRequest } from '../../types/index.js'\nimport type { BlockReferencesPermissions } from './getEntityPermissions.js'\n\nimport { type Field, tabHasName } from '../../fields/config/types.js'\nimport { getAccessOperationRequest } from '../getAccessOperationRequest.js'\n\nconst isThenable = (value: unknown): value is Promise<unknown> =>\n value != null && typeof (value as { then?: unknown }).then === 'function'\n\n/**\n * Helper to set a permission value that might be a promise.\n * If it's a promise, creates a chained promise that resolves to update the target,\n * stores the promise temporarily, and adds it to the promises array for later resolution.\n */\nconst setPermission = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n target: any,\n operation: AllOperations,\n value: boolean | Promise<boolean> | undefined,\n promises: Promise<void>[],\n): void => {\n if (isThenable(value)) {\n // Create a single permission object that will be mutated in place\n // This ensures all references (including cached blocks) see the resolved value\n const permissionObj = { permission: value as any }\n target[operation] = permissionObj\n\n const permissionPromise = value.then((result) => {\n // Mutate the permission property in place so all references see the update\n permissionObj.permission = result\n })\n\n promises.push(permissionPromise)\n } else {\n target[operation] = { permission: value }\n }\n}\n\n/**\n * Build up permissions object and run access functions for each field of an entity\n * This function is synchronous and collects all async work into the promises array\n */\nexport const populateFieldPermissions = ({\n id,\n blockReferencesPermissions,\n collection,\n data,\n fields,\n global,\n operations,\n parentPermissionsObject,\n permissionsObject,\n promises,\n req,\n}: {\n blockReferencesPermissions: BlockReferencesPermissions\n /** The collection which the fields belong to. If the fields belong to a global, this will be null. */\n collection: null | SanitizedCollectionConfig\n data: JsonObject | undefined\n fields: Field[]\n /** The global which the fields belong to. If the fields belong to a collection, this will be null. */\n global: null | SanitizedGlobalConfig\n id?: DefaultDocumentIDType\n /**\n * Operations to check access for\n */\n operations: AllOperations[]\n parentPermissionsObject: CollectionPermission | FieldPermissions | GlobalPermission\n permissionsObject: FieldsPermissions\n promises: Promise<void>[]\n req: PayloadRequest\n}): void => {\n for (const field of fields) {\n // Set up permissions for all operations\n for (const operation of operations) {\n const parentPermissionForOperation = (\n parentPermissionsObject[operation as keyof typeof parentPermissionsObject] as Permission\n )?.permission\n\n // Fields don't have all operations of a collection\n if (operation === 'delete' || operation === 'readVersions' || operation === 'unlock') {\n continue\n }\n\n if ('name' in field && field.name) {\n if (!permissionsObject[field.name]) {\n permissionsObject[field.name] = {}\n }\n const fieldPermissions: FieldPermissions = permissionsObject[field.name]!\n\n if ('access' in field && field.access && typeof field.access[operation] === 'function') {\n const accessResult = field.access[operation](\n collection\n ? {\n id,\n collection,\n data,\n doc: data,\n req: getAccessOperationRequest({\n operation,\n req,\n }),\n // We cannot include siblingData or blockData here, as we do not have siblingData/blockData available once we reach block or array\n // rows, as we're calculating schema permissions, which do not include individual rows.\n // For consistency, it's thus better to never include the siblingData and blockData\n }\n : {\n id,\n data,\n doc: data,\n global: global!,\n req: getAccessOperationRequest({\n operation,\n req,\n }),\n // We cannot include siblingData or blockData here, as we do not have siblingData/blockData available once we reach block or array\n // rows, as we're calculating schema permissions, which do not include individual rows.\n // For consistency, it's thus better to never include the siblingData and blockData\n },\n )\n\n // Handle both sync and async access results\n if (isThenable(accessResult)) {\n const booleanPromise = accessResult.then((result) => Boolean(result))\n setPermission(fieldPermissions, operation, booleanPromise, promises)\n } else {\n setPermission(fieldPermissions, operation, Boolean(accessResult), promises)\n }\n } else {\n // Inherit from parent (which might be a promise)\n setPermission(fieldPermissions, operation, parentPermissionForOperation, promises)\n }\n }\n }\n\n // Handle named fields with nested content\n if ('name' in field && field.name) {\n const fieldPermissions: FieldPermissions = permissionsObject[field.name]!\n\n if ('fields' in field && field.fields) {\n if (!fieldPermissions.fields) {\n fieldPermissions.fields = {}\n }\n\n populateFieldPermissions({\n id,\n blockReferencesPermissions,\n collection,\n data,\n fields: field.fields,\n global,\n operations,\n parentPermissionsObject: fieldPermissions,\n permissionsObject: fieldPermissions.fields,\n promises,\n req,\n })\n }\n\n if ('blocks' in field && field.blocks?.length) {\n if (!fieldPermissions.blocks) {\n fieldPermissions.blocks = {}\n }\n const blocksPermissions: BlocksPermissions = fieldPermissions.blocks\n\n // Set up permissions for all operations for all blocks\n for (const operation of operations) {\n // Fields don't have all operations of a collection\n if (operation === 'delete' || operation === 'readVersions' || operation === 'unlock') {\n continue\n }\n\n const parentPermissionForOperation = (\n parentPermissionsObject[operation as keyof typeof parentPermissionsObject] as Permission\n )?.permission\n\n for (const _block of field.blocks) {\n const block = typeof _block === 'string' ? req.payload.blocks[_block] : _block\n\n // Skip if block doesn't exist (invalid block reference)\n if (!block) {\n continue\n }\n\n // Handle block references - check if we've seen this block before\n if (typeof _block === 'string') {\n const blockReferencePermissions = blockReferencesPermissions[_block]\n if (blockReferencePermissions) {\n // Reference the cached permissions (may be a promise or resolved object)\n blocksPermissions[block.slug] = blockReferencePermissions as BlockPermissions\n continue\n }\n }\n\n // Initialize block permissions object if needed\n if (!blocksPermissions[block.slug]) {\n blocksPermissions[block.slug] = {} as BlockPermissions\n }\n\n const blockPermission = blocksPermissions[block.slug]!\n\n // Set permission for this operation\n if (!blockPermission[operation]) {\n const fieldPermission =\n fieldPermissions[operation]?.permission ?? parentPermissionForOperation\n\n // Inherit from field permission (which might be a promise)\n setPermission(blockPermission, operation, fieldPermission, promises)\n }\n }\n }\n\n // Process nested content for each unique block (once per block, not once per operation)\n const processedBlocks = new Set<string>()\n for (const _block of field.blocks) {\n const block = typeof _block === 'string' ? req.payload.blocks[_block] : _block\n\n // Skip if block doesn't exist (invalid block reference)\n if (!block || processedBlocks.has(block.slug)) {\n continue\n }\n processedBlocks.add(block.slug)\n\n const blockPermission = blocksPermissions[block.slug]\n if (!blockPermission) {\n continue\n }\n\n if (!blockPermission.fields) {\n blockPermission.fields = {}\n }\n\n // Handle block references with caching - store as promise that will be resolved later\n if (typeof _block === 'string' && !blockReferencesPermissions[_block]) {\n // Mark this block as being processed by storing a reference\n blockReferencesPermissions[_block] = blockPermission\n }\n\n // Recursively process block fields synchronously\n populateFieldPermissions({\n id,\n blockReferencesPermissions,\n collection,\n data,\n fields: block.fields,\n global,\n operations,\n parentPermissionsObject: blockPermission,\n permissionsObject: blockPermission.fields,\n promises,\n req,\n })\n }\n }\n }\n\n // Handle unnamed group fields\n if ('fields' in field && field.fields && !('name' in field && field.name)) {\n // Field does not have a name => same parentPermissionsObject\n populateFieldPermissions({\n id,\n collection,\n data,\n fields: field.fields,\n global,\n operations,\n // Field does not have a name here => use parent permissions object\n blockReferencesPermissions,\n parentPermissionsObject,\n permissionsObject,\n promises,\n req,\n })\n }\n\n // Handle tabs fields\n if (field.type === 'tabs') {\n // Process tabs for all operations\n for (const operation of operations) {\n // Fields don't have all operations of a collection\n if (operation === 'delete' || operation === 'readVersions' || operation === 'unlock') {\n continue\n }\n\n const parentPermissionForOperation = (\n parentPermissionsObject[operation as keyof typeof parentPermissionsObject] as Permission\n )?.permission\n\n for (const tab of field.tabs) {\n if (tabHasName(tab)) {\n if (!permissionsObject[tab.name]) {\n permissionsObject[tab.name] = { fields: {} }\n }\n\n const tabPermissions = permissionsObject[tab.name]!\n if (!tabPermissions[operation]) {\n // Inherit from parent (which might be a promise)\n setPermission(tabPermissions, operation, parentPermissionForOperation, promises)\n }\n }\n }\n }\n\n for (const tab of field.tabs) {\n if (tabHasName(tab)) {\n const tabPermissions: FieldPermissions = permissionsObject[tab.name]!\n\n if (!tabPermissions.fields) {\n tabPermissions.fields = {}\n }\n\n populateFieldPermissions({\n id,\n blockReferencesPermissions,\n collection,\n data,\n fields: tab.fields,\n global,\n operations,\n parentPermissionsObject: tabPermissions,\n permissionsObject: tabPermissions.fields,\n promises,\n req,\n })\n } else {\n // Tab does not have a name => same parentPermissionsObject\n populateFieldPermissions({\n id,\n collection,\n data,\n fields: tab.fields,\n global,\n operations,\n // Tab does not have a name here => use parent permissions object\n blockReferencesPermissions,\n parentPermissionsObject,\n permissionsObject,\n promises,\n req,\n })\n }\n }\n }\n }\n}\n"],"names":["tabHasName","getAccessOperationRequest","isThenable","value","then","setPermission","target","operation","promises","permissionObj","permission","permissionPromise","result","push","populateFieldPermissions","id","blockReferencesPermissions","collection","data","fields","global","operations","parentPermissionsObject","permissionsObject","req","field","parentPermissionForOperation","name","fieldPermissions","access","accessResult","doc","booleanPromise","Boolean","blocks","length","blocksPermissions","_block","block","payload","blockReferencePermissions","slug","blockPermission","fieldPermission","processedBlocks","Set","has","add","type","tab","tabs","tabPermissions"],"mappings":"AAeA,SAAqBA,UAAU,QAAQ,+BAA8B;AACrE,SAASC,yBAAyB,QAAQ,kCAAiC;AAE3E,MAAMC,aAAa,CAACC,QAClBA,SAAS,QAAQ,OAAO,AAACA,MAA6BC,IAAI,KAAK;AAEjE;;;;CAIC,GACD,MAAMC,gBAAgB,CACpB,8DAA8D;AAC9DC,QACAC,WACAJ,OACAK;IAEA,IAAIN,WAAWC,QAAQ;QACrB,kEAAkE;QAClE,+EAA+E;QAC/E,MAAMM,gBAAgB;Y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gBACF;YACF;YAEA,KAAK,MAAMyC,OAAOxB,MAAMyB,IAAI,CAAE;gBAC5B,IAAIlD,WAAWiD,MAAM;oBACnB,MAAME,iBAAmC5B,iBAAiB,CAAC0B,IAAItB,IAAI,CAAC;oBAEpE,IAAI,CAACwB,eAAehC,MAAM,EAAE;wBAC1BgC,eAAehC,MAAM,GAAG,CAAC;oBAC3B;oBAEAL,yBAAyB;wBACvBC;wBACAC;wBACAC;wBACAC;wBACAC,QAAQ8B,IAAI9B,MAAM;wBAClBC;wBACAC;wBACAC,yBAAyB6B;wBACzB5B,mBAAmB4B,eAAehC,MAAM;wBACxCX;wBACAgB;oBACF;gBACF,OAAO;oBACL,2DAA2D;oBAC3DV,yBAAyB;wBACvBC;wBACAE;wBACAC;wBACAC,QAAQ8B,IAAI9B,MAAM;wBAClBC;wBACAC;wBACA,iEAAiE;wBACjEL;wBACAM;wBACAC;wBACAf;wBACAgB;oBACF;gBACF;YACF;QACF;IACF;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../src/utilities/getEntityPermissions/populateFieldPermissions.ts"],"sourcesContent":["import type {\n BlockPermissions,\n BlocksPermissions,\n CollectionPermission,\n FieldPermissions,\n FieldsPermissions,\n GlobalPermission,\n Permission,\n} from '../../auth/types.js'\nimport type { SanitizedCollectionConfig } from '../../collections/config/types.js'\nimport type { SanitizedGlobalConfig } from '../../globals/config/types.js'\nimport type { DefaultDocumentIDType } from '../../index.js'\nimport type { AllOperations, JsonObject, PayloadRequest } from '../../types/index.js'\n\nimport { type Field, tabHasName } from '../../fields/config/types.js'\nimport { deepCopyObject } from '../deepCopyObject.js'\nimport { getAccessOperationRequest } from '../getAccessOperationRequest.js'\nimport { markRecursiveBlockBoundary } from '../sanitizePermissions.js'\n\nconst isThenable = (value: unknown): value is Promise<unknown> =>\n value != null && typeof (value as { then?: unknown }).then === 'function'\n\n/**\n * Helper to set a permission value that might be a promise.\n * If it's a promise, creates a chained promise that resolves to update the target,\n * stores the promise temporarily, and adds it to the promises array for later resolution.\n */\nconst setPermission = (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n target: any,\n operation: AllOperations,\n value: boolean | Promise<boolean> | undefined,\n promises: Promise<void>[],\n): void => {\n if (isThenable(value)) {\n // Create a single permission object that will be mutated in place\n // This ensures all references (including cached blocks) see the resolved value\n const permissionObj = { permission: value as any }\n target[operation] = permissionObj\n\n const permissionPromise = value.then((result) => {\n // Mutate the permission property in place so all references see the update\n permissionObj.permission = result\n })\n\n promises.push(permissionPromise)\n } else {\n target[operation] = { permission: value }\n }\n}\n\n/**\n * Build up permissions object and run access functions for each field of an entity\n * This function is synchronous and collects all async work into the promises array\n */\nexport const populateFieldPermissions = ({\n id,\n activeBlocks = new Set<object>(),\n blockPermissionCache,\n collection,\n data,\n fields,\n global,\n operations,\n parentPermissionsObject,\n permissionsObject,\n promises,\n req,\n}: {\n activeBlocks?: Set<object>\n blockPermissionCache: WeakMap<object, Map<string, BlockPermissions>>\n /** The collection which the fields belong to. If the fields belong to a global, this will be null. */\n collection: null | SanitizedCollectionConfig\n data: JsonObject | undefined\n fields: Field[]\n /** The global which the fields belong to. If the fields belong to a collection, this will be null. */\n global: null | SanitizedGlobalConfig\n id?: DefaultDocumentIDType\n /**\n * Operations to check access for\n */\n operations: AllOperations[]\n parentPermissionsObject: CollectionPermission | FieldPermissions | GlobalPermission\n permissionsObject: FieldsPermissions\n promises: Promise<void>[]\n req: PayloadRequest\n}): void => {\n for (const field of fields) {\n // Set up permissions for all operations\n for (const operation of operations) {\n const parentPermissionForOperation = (\n parentPermissionsObject[operation as keyof typeof parentPermissionsObject] as Permission\n )?.permission\n\n // Fields don't have all operations of a collection\n if (operation === 'delete' || operation === 'readVersions' || operation === 'unlock') {\n continue\n }\n\n if ('name' in field && field.name) {\n if (!permissionsObject[field.name]) {\n permissionsObject[field.name] = {}\n }\n const fieldPermissions: FieldPermissions = permissionsObject[field.name]!\n\n if ('access' in field && field.access && typeof field.access[operation] === 'function') {\n const accessResult = field.access[operation](\n collection\n ? {\n id,\n collection,\n data,\n doc: data,\n req: getAccessOperationRequest({\n operation,\n req,\n }),\n // We cannot include siblingData or blockData here, as we do not have siblingData/blockData available once we reach block or array\n // rows, as we're calculating schema permissions, which do not include individual rows.\n // For consistency, it's thus better to never include the siblingData and blockData\n }\n : {\n id,\n data,\n doc: data,\n global: global!,\n req: getAccessOperationRequest({\n operation,\n req,\n }),\n // We cannot include siblingData or blockData here, as we do not have siblingData/blockData available once we reach block or array\n // rows, as we're calculating schema permissions, which do not include individual rows.\n // For consistency, it's thus better to never include the siblingData and blockData\n },\n )\n\n // Handle both sync and async access results\n if (isThenable(accessResult)) {\n const booleanPromise = accessResult.then((result) => Boolean(result))\n setPermission(fieldPermissions, operation, booleanPromise, promises)\n } else {\n setPermission(fieldPermissions, operation, Boolean(accessResult), promises)\n }\n } else {\n // Inherit from parent (which might be a promise)\n setPermission(fieldPermissions, operation, parentPermissionForOperation, promises)\n }\n }\n }\n\n // Handle named fields with nested content\n if ('name' in field && field.name) {\n const fieldPermissions: FieldPermissions = permissionsObject[field.name]!\n\n if ('fields' in field && field.fields) {\n if (!fieldPermissions.fields) {\n fieldPermissions.fields = {}\n }\n\n populateFieldPermissions({\n id,\n activeBlocks,\n blockPermissionCache,\n collection,\n data,\n fields: field.fields,\n global,\n operations,\n parentPermissionsObject: fieldPermissions,\n permissionsObject: fieldPermissions.fields,\n promises,\n req,\n })\n }\n\n if ('blocks' in field && field.blocks?.length) {\n if (!fieldPermissions.blocks) {\n fieldPermissions.blocks = {}\n }\n const blocksPermissions: BlocksPermissions = fieldPermissions.blocks\n\n // Set up permissions for all operations for all blocks\n for (const operation of operations) {\n // Fields don't have all operations of a collection\n if (operation === 'delete' || operation === 'readVersions' || operation === 'unlock') {\n continue\n }\n\n const parentPermissionForOperation = (\n parentPermissionsObject[operation as keyof typeof parentPermissionsObject] as Permission\n )?.permission\n\n for (const _block of field.blocks) {\n const block = typeof _block === 'string' ? req.payload.blocks[_block] : _block\n\n // Skip if block doesn't exist (invalid block reference)\n if (!block) {\n continue\n }\n\n // Reference permissions belong to this usage: callbacks and inheritance depend on context.\n // Initialize block permissions object if needed\n if (!blocksPermissions[block.slug]) {\n blocksPermissions[block.slug] = {} as BlockPermissions\n }\n\n const blockPermission = blocksPermissions[block.slug]!\n\n // Set permission for this operation\n if (!blockPermission[operation]) {\n const fieldPermission =\n fieldPermissions[operation]?.permission ?? parentPermissionForOperation\n\n // Inherit from field permission (which might be a promise)\n setPermission(blockPermission, operation, fieldPermission, promises)\n }\n }\n }\n\n // Process nested content for each unique block (once per block, not once per operation)\n const processedBlocks = new Set<string>()\n for (const _block of field.blocks) {\n const block = typeof _block === 'string' ? req.payload.blocks[_block] : _block\n\n // Skip if block doesn't exist (invalid block reference)\n if (!block || processedBlocks.has(block.slug)) {\n continue\n }\n processedBlocks.add(block.slug)\n\n const blockPermission = blocksPermissions[block.slug]\n if (!blockPermission) {\n continue\n }\n\n if (!blockPermission.fields) {\n blockPermission.fields = {}\n }\n\n // A recursive reference has no finite permission subtree. Deny this occurrence\n // explicitly so sanitization cannot mistake its absent descendants for full access.\n if (activeBlocks.has(block)) {\n for (const operation of operations) {\n if (\n operation === 'create' ||\n operation === 'read' ||\n operation === 'update' ||\n operation === 'validate'\n ) {\n setPermission(blockPermission, operation, false, promises)\n }\n }\n markRecursiveBlockBoundary({ fields: blockPermission.fields })\n continue\n }\n\n // Nested occurrences depend on the active ancestor path. At the root,\n // identical inherited permissions have the same finite subtree.\n const inherited = operations.map(\n (operation) =>\n (blockPermission[operation as keyof BlockPermissions] as Permission | undefined)\n ?.permission,\n )\n const cacheKey = inherited.some(isThenable)\n ? undefined\n : operations.map((operation, index) => `${operation}:${inherited[index]}`).join('|')\n const cached =\n cacheKey === undefined ? undefined : blockPermissionCache.get(block)?.get(cacheKey)\n if (activeBlocks.size === 0 && cached) {\n // Sanitization mutates permissions, so occurrences cannot share an object.\n blocksPermissions[block.slug] = deepCopyObject(cached)\n continue\n }\n\n const pendingPromises = promises.length\n activeBlocks.add(block)\n try {\n populateFieldPermissions({\n id,\n activeBlocks,\n blockPermissionCache,\n collection,\n data,\n fields: block.fields,\n global,\n operations,\n parentPermissionsObject: blockPermission,\n permissionsObject: blockPermission.fields,\n promises,\n req,\n })\n } finally {\n activeBlocks.delete(block)\n }\n // Do not clone trees whose access results are still resolving.\n if (\n activeBlocks.size === 0 &&\n cacheKey !== undefined &&\n promises.length === pendingPromises\n ) {\n let byAccess = blockPermissionCache.get(block)\n if (!byAccess) {\n byAccess = new Map()\n blockPermissionCache.set(block, byAccess)\n }\n byAccess.set(cacheKey, blockPermission)\n }\n }\n }\n }\n\n // Handle unnamed group fields\n if ('fields' in field && field.fields && !('name' in field && field.name)) {\n // Field does not have a name => same parentPermissionsObject\n populateFieldPermissions({\n id,\n activeBlocks,\n collection,\n data,\n fields: field.fields,\n global,\n operations,\n // Field does not have a name here => use parent permissions object\n blockPermissionCache,\n parentPermissionsObject,\n permissionsObject,\n promises,\n req,\n })\n }\n\n // Handle tabs fields\n if (field.type === 'tabs') {\n // Process tabs for all operations\n for (const operation of operations) {\n // Fields don't have all operations of a collection\n if (operation === 'delete' || operation === 'readVersions' || operation === 'unlock') {\n continue\n }\n\n const parentPermissionForOperation = (\n parentPermissionsObject[operation as keyof typeof parentPermissionsObject] as Permission\n )?.permission\n\n for (const tab of field.tabs) {\n if (tabHasName(tab)) {\n if (!permissionsObject[tab.name]) {\n permissionsObject[tab.name] = { fields: {} }\n }\n\n const tabPermissions = permissionsObject[tab.name]!\n if (!tabPermissions[operation]) {\n // Inherit from parent (which might be a promise)\n setPermission(tabPermissions, operation, parentPermissionForOperation, promises)\n }\n }\n }\n }\n\n for (const tab of field.tabs) {\n if (tabHasName(tab)) {\n const tabPermissions: FieldPermissions = permissionsObject[tab.name]!\n\n if (!tabPermissions.fields) {\n tabPermissions.fields = {}\n }\n\n populateFieldPermissions({\n id,\n activeBlocks,\n blockPermissionCache,\n collection,\n data,\n fields: tab.fields,\n global,\n operations,\n parentPermissionsObject: tabPermissions,\n permissionsObject: tabPermissions.fields,\n promises,\n req,\n })\n } else {\n // Tab does not have a name => same parentPermissionsObject\n populateFieldPermissions({\n id,\n activeBlocks,\n collection,\n data,\n fields: tab.fields,\n global,\n operations,\n // Tab does not have a name here => use parent permissions object\n blockPermissionCache,\n parentPermissionsObject,\n permissionsObject,\n promises,\n req,\n })\n }\n }\n }\n }\n}\n"],"names":["tabHasName","deepCopyObject","getAccessOperationRequest","markRecursiveBlockBoundary","isThenable","value","then","setPermission","target","operation","promises","permissionObj","permission","permissionPromise","result","push","populateFieldPermissions","id","activeBlocks","Set","blockPermissionCache","collection","data","fields","global","operations","parentPermissionsObject","permissionsObject","req","field","parentPermissionForOperation","name","fieldPermissions","access","accessResult","doc","booleanPromise","Boolean","blocks","length","blocksPermissions","_block","block","payload","slug","blockPermission","fieldPermission","processedBlocks","has","add","inherited","map","cacheKey","some","undefined","index","join","cached","get","size","pendingPromises","delete","byAccess","Map","set","type","tab","tabs","tabPermissions"],"mappings":"AAcA,SAAqBA,UAAU,QAAQ,+BAA8B;AACrE,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,yBAAyB,QAAQ,kCAAiC;AAC3E,SAASC,0BAA0B,QAAQ,4BAA2B;AAEtE,MAAMC,aAAa,CAACC,QAClBA,SAAS,QAAQ,OAAO,AAACA,MAA6BC,IAAI,KAAK;AAEjE;;;;CAIC,GACD,MAAMC,gBAAgB,CACpB,8DAA8D;AAC9DC,QACAC,WACAJ,OACAK;IAEA,IAAIN,WAAWC,QAAQ;QACrB,kEAAkE;QAClE,+EAA+E;QAC/E,MAAMM,gBAAgB;YAAEC,YAAYP;QAAa;QACjDG,MAAM,CAACC,UAAU,GAAGE;QAEpB,MAAME,oBAAoBR,MAAMC,IAAI,CAAC,CAACQ;YACpC,2EAA2E;YAC3EH,cAAcC,UAAU,GAAGE;QAC7B;QAEAJ,SAASK,IAAI,CAACF;IAChB,OAAO;QACLL,MAAM,C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AAI3C,MAAM;wBAClBC;wBACAC;wBACA,iEAAiE;wBACjEL;wBACAM;wBACAC;wBACAjB;wBACAkB;oBACF;gBACF;YACF;QACF;IACF;AACF,EAAC"}
|
|
@@ -22,7 +22,7 @@ type MergeLocalizedDataArgs = {
|
|
|
22
22
|
* Merges data from dataWithLocales onto docWithLocales for specified locales.
|
|
23
23
|
* For localized fields, merges only the specified locales while preserving others
|
|
24
24
|
* (or only `localesToPreserve` if supplied).
|
|
25
|
-
* For non-localized fields,
|
|
25
|
+
* For non-localized fields, uses incoming values while preserving existing values when omitted.
|
|
26
26
|
* Returns a new object without mutating the original.
|
|
27
27
|
*/
|
|
28
28
|
export declare function mergeLocalizedData({ configBlockReferences, dataWithLocales, docWithLocales, fields, localesToPreserve, localesToUpdate, parentIsLocalized, }: MergeLocalizedDataArgs): JsonObject;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mergeLocalizedData.d.ts","sourceRoot":"","sources":["../../src/utilities/mergeLocalizedData.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAS,KAAK,EAAkB,MAAM,2BAA2B,CAAA;AAC7E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAsDnD,KAAK,sBAAsB,GAAG;IAC5B,qBAAqB,EAAE,eAAe,CAAC,QAAQ,CAAC,CAAA;IAChD,eAAe,EAAE,UAAU,CAAA;IAC3B,cAAc,EAAE,UAAU,CAAA;IAC1B,MAAM,EAAE,KAAK,EAAE,CAAA;IACf;;;;;;;OAOG;IACH,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAA;IAC5B,eAAe,EAAE,MAAM,EAAE,CAAA;IACzB,iBAAiB,CAAC,EAAE,OAAO,CAAA;CAC5B,CAAA;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,EACjC,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,MAAM,EACN,iBAAiB,EACjB,eAAe,EACf,iBAAyB,GAC1B,EAAE,sBAAsB,GAAG,UAAU,
|
|
1
|
+
{"version":3,"file":"mergeLocalizedData.d.ts","sourceRoot":"","sources":["../../src/utilities/mergeLocalizedData.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAS,KAAK,EAAkB,MAAM,2BAA2B,CAAA;AAC7E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAsDnD,KAAK,sBAAsB,GAAG;IAC5B,qBAAqB,EAAE,eAAe,CAAC,QAAQ,CAAC,CAAA;IAChD,eAAe,EAAE,UAAU,CAAA;IAC3B,cAAc,EAAE,UAAU,CAAA;IAC1B,MAAM,EAAE,KAAK,EAAE,CAAA;IACf;;;;;;;OAOG;IACH,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAA;IAC5B,eAAe,EAAE,MAAM,EAAE,CAAA;IACzB,iBAAiB,CAAC,EAAE,OAAO,CAAA;CAC5B,CAAA;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,EACjC,qBAAqB,EACrB,eAAe,EACf,cAAc,EACd,MAAM,EACN,iBAAiB,EACjB,eAAe,EACf,iBAAyB,GAC1B,EAAE,sBAAsB,GAAG,UAAU,CAuSrC"}
|
|
@@ -48,7 +48,7 @@ import { fieldAffectsData, fieldShouldBeLocalized, tabHasName } from '../fields/
|
|
|
48
48
|
* Merges data from dataWithLocales onto docWithLocales for specified locales.
|
|
49
49
|
* For localized fields, merges only the specified locales while preserving others
|
|
50
50
|
* (or only `localesToPreserve` if supplied).
|
|
51
|
-
* For non-localized fields,
|
|
51
|
+
* For non-localized fields, uses incoming values while preserving existing values when omitted.
|
|
52
52
|
* Returns a new object without mutating the original.
|
|
53
53
|
*/ export function mergeLocalizedData({ configBlockReferences, dataWithLocales, docWithLocales, fields, localesToPreserve, localesToUpdate, parentIsLocalized = false }) {
|
|
54
54
|
if (!docWithLocales || typeof docWithLocales !== 'object') {
|
|
@@ -88,6 +88,8 @@ import { fieldAffectsData, fieldShouldBeLocalized, tabHasName } from '../fields/
|
|
|
88
88
|
// Preserve existing value if new value is not a valid object
|
|
89
89
|
result[field.name] = existingValue;
|
|
90
90
|
}
|
|
91
|
+
} else if (newValue === null) {
|
|
92
|
+
result[field.name] = null;
|
|
91
93
|
} else if (Array.isArray(newValue)) {
|
|
92
94
|
// Non-localized array - still process children for any localized fields
|
|
93
95
|
result[field.name] = newValue.map((newItem, index)=>{
|
|
@@ -125,6 +127,8 @@ import { fieldAffectsData, fieldShouldBeLocalized, tabHasName } from '../fields/
|
|
|
125
127
|
// Preserve existing value if new value is not a valid object
|
|
126
128
|
result[field.name] = existingValue;
|
|
127
129
|
}
|
|
130
|
+
} else if (newValue === null) {
|
|
131
|
+
result[field.name] = null;
|
|
128
132
|
} else if (Array.isArray(newValue)) {
|
|
129
133
|
// Non-localized blocks - still process children for any localized fields
|
|
130
134
|
result[field.name] = newValue.map((newBlockData, index)=>{
|
|
@@ -220,7 +224,7 @@ import { fieldAffectsData, fieldShouldBeLocalized, tabHasName } from '../fields/
|
|
|
220
224
|
} else if (parentIsLocalized) {
|
|
221
225
|
result[field.name] = dataWithLocales[field.name];
|
|
222
226
|
} else {
|
|
223
|
-
result[field.name] = field.name
|
|
227
|
+
result[field.name] = typeof dataWithLocales[field.name] !== 'undefined' ? dataWithLocales[field.name] : docWithLocales[field.name];
|
|
224
228
|
}
|
|
225
229
|
break;
|
|
226
230
|
}
|