payload 3.0.0-beta.34 → 3.0.0-beta.36
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/sendVerificationEmail.js +1 -1
- package/dist/auth/sendVerificationEmail.js.map +1 -1
- package/dist/collections/operations/create.d.ts.map +1 -1
- package/dist/collections/operations/create.js +1 -0
- package/dist/collections/operations/create.js.map +1 -1
- package/dist/collections/operations/update.d.ts.map +1 -1
- package/dist/collections/operations/update.js +1 -0
- package/dist/collections/operations/update.js.map +1 -1
- package/dist/collections/operations/updateByID.d.ts.map +1 -1
- package/dist/collections/operations/updateByID.js +1 -0
- package/dist/collections/operations/updateByID.js.map +1 -1
- package/dist/config/types.d.ts +1 -0
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/exports/utilities.d.ts +1 -1
- package/dist/exports/utilities.d.ts.map +1 -1
- package/dist/exports/utilities.js +1 -1
- package/dist/exports/utilities.js.map +1 -1
- package/dist/types/index.d.ts +0 -12
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/uploads/canResizeImage.d.ts +1 -1
- package/dist/uploads/canResizeImage.d.ts.map +1 -1
- package/dist/uploads/canResizeImage.js +1 -1
- package/dist/uploads/canResizeImage.js.map +1 -1
- package/dist/uploads/cropImage.d.ts +1 -1
- package/dist/uploads/cropImage.d.ts.map +1 -1
- package/dist/uploads/cropImage.js +1 -1
- package/dist/uploads/cropImage.js.map +1 -1
- package/dist/uploads/generateFileData.d.ts +3 -1
- package/dist/uploads/generateFileData.d.ts.map +1 -1
- package/dist/uploads/generateFileData.js +50 -12
- package/dist/uploads/generateFileData.js.map +1 -1
- package/dist/uploads/getBaseFields.d.ts.map +1 -1
- package/dist/uploads/getBaseFields.js +15 -0
- package/dist/uploads/getBaseFields.js.map +1 -1
- package/dist/uploads/getSafeFilename.d.ts +2 -2
- package/dist/uploads/getSafeFilename.d.ts.map +1 -1
- package/dist/uploads/getSafeFilename.js +1 -2
- package/dist/uploads/getSafeFilename.js.map +1 -1
- package/dist/uploads/imageResizer.d.ts +7 -9
- package/dist/uploads/imageResizer.d.ts.map +1 -1
- package/dist/uploads/imageResizer.js +42 -24
- package/dist/uploads/imageResizer.js.map +1 -1
- package/dist/uploads/isImage.d.ts +1 -1
- package/dist/uploads/isImage.d.ts.map +1 -1
- package/dist/uploads/isImage.js +1 -1
- package/dist/uploads/isImage.js.map +1 -1
- package/dist/uploads/types.d.ts +14 -0
- package/dist/uploads/types.d.ts.map +1 -1
- package/dist/uploads/types.js.map +1 -1
- package/package.json +2 -2
package/dist/config/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/config/types.ts"],"sourcesContent":["import type {\n DefaultTranslationsObject,\n I18nClient,\n I18nOptions,\n TFunction,\n} from '@payloadcms/translations'\nimport type { Options as ExpressFileUploadOptions } from 'express-fileupload'\nimport type GraphQL from 'graphql'\nimport type { Metadata as NextMetadata } from 'next'\nimport type { DestinationStream, LoggerOptions } from 'pino'\nimport type React from 'react'\nimport type { default as sharp } from 'sharp'\nimport type { DeepRequired } from 'ts-essentials'\n\nimport type { RichTextAdapterProvider } from '../admin/RichText.js'\nimport type { DocumentTab, RichTextAdapter } from '../admin/types.js'\nimport type { AdminView, ServerSideEditViewProps } from '../admin/views/types.js'\nimport type { Permissions } from '../auth/index.js'\nimport type {\n AfterErrorHook,\n Collection,\n CollectionConfig,\n SanitizedCollectionConfig,\n} from '../collections/config/types.js'\nimport type { DatabaseAdapterResult } from '../database/types.js'\nimport type { EmailAdapter, SendEmailOptions } from '../email/types.js'\nimport type { GlobalConfig, Globals, SanitizedGlobalConfig } from '../globals/config/types.js'\nimport type { GeneratedTypes, Payload } from '../index.js'\nimport type { PayloadRequest, PayloadRequestWithData, Where } from '../types/index.js'\nimport type { PayloadLogger } from '../utilities/logger.js'\n\nexport type BinScriptConfig = {\n key: string\n scriptPath: string\n}\n\nexport type BinScript = (config: SanitizedConfig) => Promise<void> | void\n\ntype Prettify<T> = {\n [K in keyof T]: T[K]\n} & NonNullable<unknown>\n\n// eslint-disable-next-line no-use-before-define\nexport type Plugin = (config: Config) => Config | Promise<Config>\n\nexport type LivePreviewConfig = {\n /**\n Device breakpoints to use for the `iframe` of the Live Preview window.\n Options are displayed in the Live Preview toolbar.\n The `responsive` breakpoint is included by default.\n */\n breakpoints?: {\n height: number | string\n label: string\n name: string\n width: number | string\n }[]\n /**\n The URL of the frontend application. This will be rendered within an `iframe` as its `src`.\n Payload will send a `window.postMessage()` to this URL with the document data in real-time.\n The frontend application is responsible for receiving the message and updating the UI accordingly.\n Use the `useLivePreview` hook to get started in React applications.\n */\n url?:\n | ((args: {\n collectionConfig?: SanitizedCollectionConfig\n data: Record<string, any>\n globalConfig?: SanitizedGlobalConfig\n locale: Locale\n payload: Payload\n }) => Promise<string> | string)\n | string\n}\n\nexport type OGImageConfig = {\n alt?: string\n height?: number | string\n type?: string\n url: string\n width?: number | string\n}\n\nexport type OpenGraphConfig = {\n description?: string\n images?: OGImageConfig | OGImageConfig[]\n siteName?: string\n title?: string\n}\n\nexport type IconConfig = {\n color?: string\n /**\n * @see https://developer.mozilla.org/docs/Web/API/HTMLImageElement/fetchPriority\n */\n fetchPriority?: 'auto' | 'high' | 'low'\n media?: string\n /** defaults to rel=\"icon\" */\n rel?: string\n sizes?: string\n type?: string\n url: string\n}\n\nexport type MetaConfig = {\n /**\n * When `static`, a pre-made image will be used for all pages.\n * When `dynamic`, a unique image will be generated for each page based on page content and given overrides.\n * When `off`, no Open Graph images will be generated and the `/api/og` endpoint will be disabled. You can still provide custom images using the `openGraph.images` property.\n * @default 'dynamic'\n */\n defaultOGImageType?: 'dynamic' | 'off' | 'static'\n /**\n * Overrides the auto-generated <meta name=\"description\"> of admin pages\n * @example `\"This is my custom CMS built with Payload.\"`\n */\n description?: string\n /**\n * Icons to be rendered by devices and browsers.\n *\n * For example browser tabs, phone home screens, and search engine results.\n */\n icons?: IconConfig\n /**\n * Overrides the auto-generated <meta name=\"keywords\"> of admin pages\n * @example `\"CMS, Payload, Custom\"`\n */\n keywords?: string\n /**\n * Metadata to be rendered as `og` meta tags in the head of the Admin Panel.\n *\n * For example when sharing the Admin Panel on social media or through messaging services.\n */\n openGraph?: OpenGraphConfig\n /**\n * Overrides the auto-generated <title> of admin pages\n * @example `\"My Admin Panel\"`\n */\n title?: string\n /**\n * String to append to the auto-generated <title> of admin pages\n * @example `\" - Custom CMS\"`\n */\n titleSuffix?: string\n}\n\nexport type ServerOnlyLivePreviewProperties = keyof Pick<LivePreviewConfig, 'url'>\n\ntype GeneratePreviewURLOptions = {\n locale: string\n req: PayloadRequestWithData\n token: null | string\n}\n\nexport type GeneratePreviewURL = (\n doc: Record<string, unknown>,\n options: GeneratePreviewURLOptions,\n) => Promise<null | string> | null | string\n\nexport type GraphQLInfo = {\n Mutation: {\n fields: Record<string, any>\n name: string\n }\n Query: {\n fields: Record<string, any>\n name: string\n }\n collections: {\n [slug: number | string | symbol]: Collection\n }\n globals: Globals\n types: {\n arrayTypes: Record<string, GraphQL.GraphQLType>\n blockInputTypes: Record<string, GraphQL.GraphQLInputObjectType>\n blockTypes: Record<string, GraphQL.GraphQLObjectType>\n fallbackLocaleInputType?: GraphQL.GraphQLEnumType | GraphQL.GraphQLScalarType\n groupTypes: Record<string, GraphQL.GraphQLObjectType>\n localeInputType?: GraphQL.GraphQLEnumType | GraphQL.GraphQLScalarType\n tabTypes: Record<string, GraphQL.GraphQLObjectType>\n }\n}\nexport type GraphQLExtension = (\n graphQL: typeof GraphQL,\n context: {\n config: SanitizedConfig\n } & GraphQLInfo,\n) => Record<string, unknown>\n\nexport type InitOptions = {\n /**\n * Sometimes, with the local API, you might need to pass a config file directly, for example, serverless on Vercel\n * The passed config should match the config file, and if it doesn't, there could be mismatches between the admin UI\n * and the backend functionality\n */\n config: Promise<SanitizedConfig> | SanitizedConfig\n /**\n * Disable connect to the database on init\n */\n disableDBConnect?: boolean\n\n /**\n * Disable running of the `onInit` function\n */\n disableOnInit?: boolean\n\n /**\n * A previously instantiated logger instance. Must conform to the PayloadLogger interface which uses Pino\n * This allows you to bring your own logger instance and let payload use it\n */\n logger?: PayloadLogger\n\n loggerDestination?: DestinationStream\n\n /**\n * Specify options for the built-in Pino logger that Payload uses for internal logging.\n *\n * See Pino Docs for options: https://getpino.io/#/docs/api?id=options\n */\n loggerOptions?: LoggerOptions\n /**\n * A function that is called immediately following startup that receives the Payload instance as it's only argument.\n */\n onInit?: (payload: Payload) => Promise<void> | void\n}\n\n/**\n * This result is calculated on the server\n * and then sent to the client allowing the dashboard to show accessible data and actions.\n *\n * If the result is `true`, the user has access.\n * If the result is an object, it is interpreted as a MongoDB query.\n *\n * @example `{ createdBy: { equals: id } }`\n *\n * @example `{ tenant: { in: tenantIds } }`\n *\n * @see https://payloadcms.com/docs/access-control/overview\n */\nexport type AccessResult = Where | boolean\n\nexport type AccessArgs<TData = any> = {\n /**\n * The relevant resource that is being accessed.\n *\n * `data` is null when a list is requested\n */\n data?: TData\n /** ID of the resource being accessed */\n id?: number | string\n /** If true, the request is for a static file */\n isReadingStaticFile?: boolean\n /** The original request that requires an access check */\n req: PayloadRequestWithData\n}\n\n/**\n * Access function runs on the server\n * and is sent to the client allowing the dashboard to show accessible data and actions.\n *\n * @see https://payloadcms.com/docs/access-control/overview\n */\nexport type Access<TData = any> = (args: AccessArgs<TData>) => AccessResult | Promise<AccessResult>\n\n/** Web Request/Response model, but the req has more payload specific properties added to it. */\nexport type PayloadHandler = (req: PayloadRequest) => Promise<Response> | Response\n\n/**\n * Docs: https://payloadcms.com/docs/rest-api/overview#custom-endpoints\n */\nexport type Endpoint = {\n /** Extension point to add your custom data. */\n custom?: Record<string, any>\n\n /**\n * Middleware that will be called when the path/method matches\n *\n * Compatible with Web Request/Response Model\n */\n handler: PayloadHandler\n /** HTTP method (or \"all\") */\n method: 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put'\n /**\n * Pattern that should match the path of the incoming request\n *\n * Compatible with the Express router\n */\n path: string\n /**\n * Please add \"root\" routes under the /api folder in the Payload Project.\n * https://nextjs.org/docs/app/api-reference/file-conventions/route\n *\n * @deprecated in 3.0\n */\n root?: never\n}\n\nexport type EditViewComponent = React.ComponentType<ServerSideEditViewProps>\n\nexport type EditViewConfig =\n | {\n /**\n * Add a new Edit view to the admin panel\n * i.e. you can render a custom view that has no tab, if desired\n * Or override a specific properties of an existing one\n * i.e. you can customize the `Default` view tab label, if desired\n */\n Tab?: DocumentTab\n path?: string\n }\n | {\n Component: EditViewComponent\n path: string\n }\n | {\n actions?: CustomComponent[]\n }\n\n/**\n * Override existing views\n * i.e. Dashboard, Account, API, LivePreview, etc.\n * Path is not available here\n * All Tab properties become optional\n * i.e. you can change just the label, if desired\n */\nexport type EditView = EditViewComponent | EditViewConfig\n\nexport type ServerProps = {\n [key: string]: unknown\n i18n: I18nClient\n locale?: Locale\n params?: { [key: string]: string | string[] | undefined }\n payload: Payload\n permissions?: Permissions\n searchParams?: { [key: string]: string | string[] | undefined }\n user?: GeneratedTypes['user']\n}\n\nexport const serverProps: (keyof ServerProps)[] = [\n 'payload',\n 'i18n',\n 'locale',\n 'params',\n 'permissions',\n 'searchParams',\n 'permissions',\n]\n\nexport type CustomComponent<TAdditionalProps extends any = any> = React.ComponentType<\n TAdditionalProps & Partial<ServerProps>\n>\n\nexport type Locale = {\n /**\n * value of supported locale\n * @example \"en\"\n */\n code: string\n /**\n * Code of another locale to use when reading documents with fallback, if not specified defaultLocale is used\n */\n fallbackLocale?: string\n /**\n * label of supported locale\n * @example \"English\"\n */\n label: Record<string, string> | string\n /**\n * if true, defaults textAligmnent on text fields to RTL\n */\n rtl?: boolean\n}\n\nexport type BaseLocalizationConfig = {\n /**\n * Locale for users that have not expressed their preference for a specific locale\n * @example `\"en\"`\n */\n defaultLocale: string\n /** Set to `true` to let missing values in localised fields fall back to the values in `defaultLocale` */\n fallback?: boolean\n}\n\nexport type LocalizationConfigWithNoLabels = Prettify<\n BaseLocalizationConfig & {\n /**\n * List of supported locales\n * @example `[\"en\", \"es\", \"fr\", \"nl\", \"de\", \"jp\"]`\n */\n locales: string[]\n }\n>\n\nexport type LocalizationConfigWithLabels = Prettify<\n BaseLocalizationConfig & {\n /**\n * List of supported locales with labels\n * @example {\n * label: 'English',\n * value: 'en',\n * rtl: false\n * }\n */\n locales: Locale[]\n }\n>\n\nexport type SanitizedLocalizationConfig = Prettify<\n LocalizationConfigWithLabels & {\n /**\n * List of supported locales\n * @example `[\"en\", \"es\", \"fr\", \"nl\", \"de\", \"jp\"]`\n */\n localeCodes: string[]\n }\n>\n\n/**\n * @see https://payloadcms.com/docs/configuration/localization#localization\n */\nexport type LocalizationConfig = Prettify<\n LocalizationConfigWithLabels | LocalizationConfigWithNoLabels\n>\n\nexport type LabelFunction = ({ t }: { t: TFunction }) => string\n\nexport type SharpDependency = (\n input?:\n | ArrayBuffer\n | Buffer\n | Float32Array\n | Float64Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array\n | string,\n options?: sharp.SharpOptions,\n) => sharp.Sharp\n\n/**\n * This is the central configuration\n *\n * @see https://payloadcms.com/docs/configuration/overview\n */\nexport type Config = {\n /** Configure admin dashboard */\n admin?: {\n /** Automatically log in as a user when visiting the admin dashboard. */\n autoLogin?:\n | {\n /**\n * The email address of the user to login as\n *\n */\n email: string\n /** The password of the user to login as */\n password: string\n /**\n * If set to true, the login credentials will be prefilled but the user will still need to click the login button.\n *\n * @default false\n */\n prefillOnly?: boolean\n }\n | false\n /** Set account profile picture. Options: gravatar, default or a custom React component. */\n avatar?: 'default' | 'gravatar' | React.ComponentType<any>\n\n /**\n * Add extra and/or replace built-in components with custom components\n *\n * @see https://payloadcms.com/docs/admin/components\n */\n components?: {\n /**\n * Replace the navigation with a custom component\n */\n Nav?: CustomComponent\n /**\n * Add custom components to the top right of the Admin Panel\n */\n actions?: CustomComponent[]\n /**\n * Add custom components after the collection overview\n */\n afterDashboard?: CustomComponent[]\n /**\n * Add custom components after the email/password field\n */\n afterLogin?: CustomComponent[]\n /**\n * Add custom components after the navigation links\n */\n afterNavLinks?: CustomComponent[]\n /**\n * Add custom components before the collection overview\n */\n beforeDashboard?: CustomComponent[]\n /**\n * Add custom components before the email/password field\n */\n beforeLogin?: CustomComponent[]\n /**\n * Add custom components before the navigation links\n */\n beforeNavLinks?: CustomComponent[]\n /** Replace graphical components */\n graphics?: {\n /** Replace the icon in the navigation */\n Icon?: CustomComponent\n /** Replace the logo on the login page */\n Logo?: CustomComponent\n }\n /** Replace logout related components */\n logout?: {\n /** Replace the logout button */\n Button?: CustomComponent\n }\n /**\n * Wrap the admin dashboard in custom context providers\n */\n providers?: React.ComponentType<{ children?: React.ReactNode }>[]\n /**\n * Replace or modify top-level admin routes, or add new ones:\n * + `Account` - `/admin/account`\n * + `Dashboard` - `/admin`\n * + `:path` - `/admin/:path`\n */\n views?: {\n /** Add custom admin views */\n [key: string]: AdminView\n /** Replace the account screen */\n Account?: AdminView\n /** Replace the admin homepage */\n Dashboard?: AdminView\n }\n }\n /** Extension point to add your custom data. Available in server and client. */\n custom?: Record<string, any>\n /** Global date format that will be used for all dates in the Admin panel. Any valid date-fns format pattern can be used. */\n dateFormat?: string\n /** If set to true, the entire Admin panel will be disabled. */\n disable?: boolean\n livePreview?: LivePreviewConfig & {\n collections?: string[]\n globals?: string[]\n }\n /** Base meta data to use for the Admin Panel. Included properties are titleSuffix, ogImage, and favicon. */\n meta?: MetaConfig\n routes?: {\n /** The route for the account page. */\n account?: string\n /** The route for the create first user page. */\n createFirstUser?: string\n /** The route for the forgot password page. */\n forgot?: string\n /** The route the user will be redirected to after being inactive for too long. */\n inactivity?: string\n /** The route for the login page. */\n login?: string\n /** The route for the logout page. */\n logout?: string\n /** The route for the unauthorized page. */\n unauthorized?: string\n }\n /** The slug of a Collection that you want to be used to log in to the Admin dashboard. */\n user?: string\n }\n /** Custom Payload bin scripts can be injected via the config. */\n bin?: BinScriptConfig[]\n /**\n * Manage the datamodel of your application\n *\n * @see https://payloadcms.com/docs/configuration/collections#collection-configs\n */\n collections?: CollectionConfig[]\n /**\n * Replace the built-in components with custom ones\n */\n components?: { [key: string]: (() => JSX.Element) | JSX.Element }\n /**\n * Prefix a string to all cookies that Payload sets.\n *\n * @default \"payload\"\n */\n cookiePrefix?: string\n /** Either a whitelist array of URLS to allow CORS requests from, or a wildcard string ('*') to accept incoming requests from any domain. */\n cors?: '*' | string[]\n /** A whitelist array of URLs to allow Payload cookies to be accepted from as a form of CSRF protection. */\n csrf?: string[]\n\n /** Extension point to add your custom data. Server only. */\n custom?: Record<string, any>\n\n /** Pass in a database adapter for use on this project. */\n db: DatabaseAdapterResult\n /** Enable to expose more detailed error information. */\n debug?: boolean\n /**\n * If a user does not specify `depth` while requesting a resource, this depth will be used.\n *\n * @see https://payloadcms.com/docs/getting-started/concepts#depth\n *\n * @default 2\n */\n defaultDepth?: number\n /**\n * The maximum allowed depth to be permitted application-wide. This setting helps prevent against malicious queries.\n *\n * @default 40000\n */\n defaultMaxTextLength?: number\n /** Default richtext editor to use for richText fields */\n editor: RichTextAdapterProvider<any, any, any>\n /**\n * Email Adapter\n *\n * @see https://payloadcms.com/docs/email/overview\n */\n email?: EmailAdapter | Promise<EmailAdapter>\n /** Custom REST endpoints */\n endpoints?: Endpoint[]\n /**\n * @see https://payloadcms.com/docs/configuration/globals#global-configs\n */\n globals?: GlobalConfig[]\n /**\n * Manage the GraphQL API\n *\n * You can add your own GraphQL queries and mutations to Payload, making use of all the types that Payload has defined for you.\n *\n * @see https://payloadcms.com/docs/graphql/overview\n */\n graphQL?: {\n disable?: boolean\n disablePlaygroundInProduction?: boolean\n maxComplexity?: number\n /**\n * Function that returns an object containing keys to custom GraphQL mutations\n *\n * @see https://payloadcms.com/docs/graphql/extending\n */\n mutations?: GraphQLExtension\n /**\n * Function that returns an object containing keys to custom GraphQL queries\n *\n * @see https://payloadcms.com/docs/graphql/extending\n */\n queries?: GraphQLExtension\n /**\n * Filepath to write the generated schema to\n */\n schemaOutputFile?: string\n }\n /**\n * Tap into Payload-wide hooks.\n *\n * @see https://payloadcms.com/docs/hooks/overview\n */\n hooks?: {\n afterError?: AfterErrorHook\n }\n /** i18n config settings */\n i18n?: I18nOptions<{} | DefaultTranslationsObject> // loosen the type here to allow for custom translations\n /** Automatically index all sortable top-level fields in the database to improve sort performance and add database compatibility for Azure Cosmos and similar. */\n indexSortableFields?: boolean\n /**\n * Translate your content to different languages/locales.\n *\n * @default false // disable localization\n */\n localization?: LocalizationConfig | false\n /**\n * The maximum allowed depth to be permitted application-wide. This setting helps prevent against malicious queries.\n *\n * @see https://payloadcms.com/docs/getting-started/concepts#depth\n *\n * @default 10\n */\n maxDepth?: number\n /** A function that is called immediately following startup that receives the Payload instance as its only argument. */\n onInit?: (payload: Payload) => Promise<void> | void\n /**\n * An array of Payload plugins.\n *\n * @see https://payloadcms.com/docs/plugins/overview\n */\n plugins?: Plugin[]\n /** Control the routing structure that Payload binds itself to. */\n routes?: {\n /** @default \"/admin\" */\n admin?: string\n /** @default \"/api\" */\n api?: string\n /** @default \"/graphql\" */\n graphQL?: string\n /** @default \"/graphql-playground\" */\n graphQLPlayground?: string\n }\n /** Secure string that Payload will use for any encryption workflows */\n secret: string\n /**\n * Define the absolute URL of your app including the protocol, for example `https://example.org`.\n * No paths allowed, only protocol, domain and (optionally) port.\n *\n * @see https://payloadcms.com/docs/configuration/overview#options\n */\n serverURL?: string\n /**\n * Pass in a local copy of Sharp if you'd like to use it.\n *\n */\n sharp?: SharpDependency\n /** Send anonymous telemetry data about general usage. */\n telemetry?: boolean\n /** Control how typescript interfaces are generated from your collections. */\n typescript?: {\n /** Disable declare block in generated types file */\n declare?:\n | {\n /**\n * @internal internal use only to allow for multiple declarations within a monorepo and suppress the \"Duplicate identifier GeneratedTypes\" error\n *\n * Adds a @ts-ignore flag above the GeneratedTypes interface declaration\n *\n * @default false\n */\n ignoreTSError?: boolean\n }\n | false\n /** Filename to write the generated types to */\n outputFile?: string\n }\n /**\n * Customize the handling of incoming file uploads for collections that have uploads enabled.\n */\n upload?: ExpressFileUploadOptions\n}\n\nexport type SanitizedConfig = Omit<\n DeepRequired<Config>,\n 'collections' | 'editor' | 'endpoint' | 'globals' | 'i18n' | 'localization' | 'upload'\n> & {\n collections: SanitizedCollectionConfig[]\n /** Default richtext editor to use for richText fields */\n editor: RichTextAdapter<any, any, any>\n endpoints: Endpoint[]\n globals: SanitizedGlobalConfig[]\n i18n: Required<I18nOptions>\n localization: SanitizedLocalizationConfig | false\n paths: {\n config: string\n configDir: string\n rawConfig: string\n }\n upload: ExpressFileUploadOptions & {\n /**\n * Deduped list of adapters used in the project\n */\n adapters: string[]\n }\n}\n\nexport type EditConfig =\n | (\n | {\n /**\n * Replace or modify individual nested routes, or add new ones:\n * + `Default` - `/admin/collections/:collection/:id`\n * + `API` - `/admin/collections/:collection/:id/api`\n * + `LivePreview` - `/admin/collections/:collection/:id/preview`\n * + `References` - `/admin/collections/:collection/:id/references`\n * + `Relationships` - `/admin/collections/:collection/:id/relationships`\n * + `Versions` - `/admin/collections/:collection/:id/versions`\n * + `Version` - `/admin/collections/:collection/:id/versions/:version`\n * + `CustomView` - `/admin/collections/:collection/:id/:path`\n */\n API?: EditViewComponent | Partial<EditViewConfig>\n Default?: EditViewComponent | Partial<EditViewConfig>\n LivePreview?: EditViewComponent | Partial<EditViewConfig>\n Version?: EditViewComponent | Partial<EditViewConfig>\n Versions?: EditViewComponent | Partial<EditViewConfig>\n // TODO: uncomment these as they are built\n // References?: EditView\n // Relationships?: EditView\n }\n | {\n [key: string]: EditViewConfig\n }\n )\n | EditViewComponent\n\nexport type EntityDescriptionComponent = CustomComponent\n\nexport type EntityDescriptionFunction = ({ t }: { t: TFunction }) => string\n\nexport type EntityDescription = EntityDescriptionFunction | Record<string, string> | string\n\nexport type { EmailAdapter, SendEmailOptions }\n"],"names":["serverProps"],"rangeMappings":";;;;;;;;","mappings":"AAiVA,OAAO,MAAMA,cAAqC;IAChD;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA"}
|
|
1
|
+
{"version":3,"sources":["../../src/config/types.ts"],"sourcesContent":["import type {\n DefaultTranslationsObject,\n I18nClient,\n I18nOptions,\n TFunction,\n} from '@payloadcms/translations'\nimport type { Options as ExpressFileUploadOptions } from 'express-fileupload'\nimport type GraphQL from 'graphql'\nimport type { Metadata as NextMetadata } from 'next'\nimport type { DestinationStream, LoggerOptions } from 'pino'\nimport type React from 'react'\nimport type { JSX } from 'react'\nimport type { default as sharp } from 'sharp'\nimport type { DeepRequired } from 'ts-essentials'\n\nimport type { RichTextAdapterProvider } from '../admin/RichText.js'\nimport type { DocumentTab, RichTextAdapter } from '../admin/types.js'\nimport type { AdminView, ServerSideEditViewProps } from '../admin/views/types.js'\nimport type { Permissions } from '../auth/index.js'\nimport type {\n AfterErrorHook,\n Collection,\n CollectionConfig,\n SanitizedCollectionConfig,\n} from '../collections/config/types.js'\nimport type { DatabaseAdapterResult } from '../database/types.js'\nimport type { EmailAdapter, SendEmailOptions } from '../email/types.js'\nimport type { GlobalConfig, Globals, SanitizedGlobalConfig } from '../globals/config/types.js'\nimport type { GeneratedTypes, Payload } from '../index.js'\nimport type { PayloadRequest, PayloadRequestWithData, Where } from '../types/index.js'\nimport type { PayloadLogger } from '../utilities/logger.js'\n\nexport type BinScriptConfig = {\n key: string\n scriptPath: string\n}\n\nexport type BinScript = (config: SanitizedConfig) => Promise<void> | void\n\ntype Prettify<T> = {\n [K in keyof T]: T[K]\n} & NonNullable<unknown>\n\n// eslint-disable-next-line no-use-before-define\nexport type Plugin = (config: Config) => Config | Promise<Config>\n\nexport type LivePreviewConfig = {\n /**\n Device breakpoints to use for the `iframe` of the Live Preview window.\n Options are displayed in the Live Preview toolbar.\n The `responsive` breakpoint is included by default.\n */\n breakpoints?: {\n height: number | string\n label: string\n name: string\n width: number | string\n }[]\n /**\n The URL of the frontend application. This will be rendered within an `iframe` as its `src`.\n Payload will send a `window.postMessage()` to this URL with the document data in real-time.\n The frontend application is responsible for receiving the message and updating the UI accordingly.\n Use the `useLivePreview` hook to get started in React applications.\n */\n url?:\n | ((args: {\n collectionConfig?: SanitizedCollectionConfig\n data: Record<string, any>\n globalConfig?: SanitizedGlobalConfig\n locale: Locale\n payload: Payload\n }) => Promise<string> | string)\n | string\n}\n\nexport type OGImageConfig = {\n alt?: string\n height?: number | string\n type?: string\n url: string\n width?: number | string\n}\n\nexport type OpenGraphConfig = {\n description?: string\n images?: OGImageConfig | OGImageConfig[]\n siteName?: string\n title?: string\n}\n\nexport type IconConfig = {\n color?: string\n /**\n * @see https://developer.mozilla.org/docs/Web/API/HTMLImageElement/fetchPriority\n */\n fetchPriority?: 'auto' | 'high' | 'low'\n media?: string\n /** defaults to rel=\"icon\" */\n rel?: string\n sizes?: string\n type?: string\n url: string\n}\n\nexport type MetaConfig = {\n /**\n * When `static`, a pre-made image will be used for all pages.\n * When `dynamic`, a unique image will be generated for each page based on page content and given overrides.\n * When `off`, no Open Graph images will be generated and the `/api/og` endpoint will be disabled. You can still provide custom images using the `openGraph.images` property.\n * @default 'dynamic'\n */\n defaultOGImageType?: 'dynamic' | 'off' | 'static'\n /**\n * Overrides the auto-generated <meta name=\"description\"> of admin pages\n * @example `\"This is my custom CMS built with Payload.\"`\n */\n description?: string\n /**\n * Icons to be rendered by devices and browsers.\n *\n * For example browser tabs, phone home screens, and search engine results.\n */\n icons?: IconConfig\n /**\n * Overrides the auto-generated <meta name=\"keywords\"> of admin pages\n * @example `\"CMS, Payload, Custom\"`\n */\n keywords?: string\n /**\n * Metadata to be rendered as `og` meta tags in the head of the Admin Panel.\n *\n * For example when sharing the Admin Panel on social media or through messaging services.\n */\n openGraph?: OpenGraphConfig\n /**\n * Overrides the auto-generated <title> of admin pages\n * @example `\"My Admin Panel\"`\n */\n title?: string\n /**\n * String to append to the auto-generated <title> of admin pages\n * @example `\" - Custom CMS\"`\n */\n titleSuffix?: string\n}\n\nexport type ServerOnlyLivePreviewProperties = keyof Pick<LivePreviewConfig, 'url'>\n\ntype GeneratePreviewURLOptions = {\n locale: string\n req: PayloadRequestWithData\n token: null | string\n}\n\nexport type GeneratePreviewURL = (\n doc: Record<string, unknown>,\n options: GeneratePreviewURLOptions,\n) => Promise<null | string> | null | string\n\nexport type GraphQLInfo = {\n Mutation: {\n fields: Record<string, any>\n name: string\n }\n Query: {\n fields: Record<string, any>\n name: string\n }\n collections: {\n [slug: number | string | symbol]: Collection\n }\n globals: Globals\n types: {\n arrayTypes: Record<string, GraphQL.GraphQLType>\n blockInputTypes: Record<string, GraphQL.GraphQLInputObjectType>\n blockTypes: Record<string, GraphQL.GraphQLObjectType>\n fallbackLocaleInputType?: GraphQL.GraphQLEnumType | GraphQL.GraphQLScalarType\n groupTypes: Record<string, GraphQL.GraphQLObjectType>\n localeInputType?: GraphQL.GraphQLEnumType | GraphQL.GraphQLScalarType\n tabTypes: Record<string, GraphQL.GraphQLObjectType>\n }\n}\nexport type GraphQLExtension = (\n graphQL: typeof GraphQL,\n context: {\n config: SanitizedConfig\n } & GraphQLInfo,\n) => Record<string, unknown>\n\nexport type InitOptions = {\n /**\n * Sometimes, with the local API, you might need to pass a config file directly, for example, serverless on Vercel\n * The passed config should match the config file, and if it doesn't, there could be mismatches between the admin UI\n * and the backend functionality\n */\n config: Promise<SanitizedConfig> | SanitizedConfig\n /**\n * Disable connect to the database on init\n */\n disableDBConnect?: boolean\n\n /**\n * Disable running of the `onInit` function\n */\n disableOnInit?: boolean\n\n /**\n * A previously instantiated logger instance. Must conform to the PayloadLogger interface which uses Pino\n * This allows you to bring your own logger instance and let payload use it\n */\n logger?: PayloadLogger\n\n loggerDestination?: DestinationStream\n\n /**\n * Specify options for the built-in Pino logger that Payload uses for internal logging.\n *\n * See Pino Docs for options: https://getpino.io/#/docs/api?id=options\n */\n loggerOptions?: LoggerOptions\n /**\n * A function that is called immediately following startup that receives the Payload instance as it's only argument.\n */\n onInit?: (payload: Payload) => Promise<void> | void\n}\n\n/**\n * This result is calculated on the server\n * and then sent to the client allowing the dashboard to show accessible data and actions.\n *\n * If the result is `true`, the user has access.\n * If the result is an object, it is interpreted as a MongoDB query.\n *\n * @example `{ createdBy: { equals: id } }`\n *\n * @example `{ tenant: { in: tenantIds } }`\n *\n * @see https://payloadcms.com/docs/access-control/overview\n */\nexport type AccessResult = Where | boolean\n\nexport type AccessArgs<TData = any> = {\n /**\n * The relevant resource that is being accessed.\n *\n * `data` is null when a list is requested\n */\n data?: TData\n /** ID of the resource being accessed */\n id?: number | string\n /** If true, the request is for a static file */\n isReadingStaticFile?: boolean\n /** The original request that requires an access check */\n req: PayloadRequestWithData\n}\n\n/**\n * Access function runs on the server\n * and is sent to the client allowing the dashboard to show accessible data and actions.\n *\n * @see https://payloadcms.com/docs/access-control/overview\n */\nexport type Access<TData = any> = (args: AccessArgs<TData>) => AccessResult | Promise<AccessResult>\n\n/** Web Request/Response model, but the req has more payload specific properties added to it. */\nexport type PayloadHandler = (req: PayloadRequest) => Promise<Response> | Response\n\n/**\n * Docs: https://payloadcms.com/docs/rest-api/overview#custom-endpoints\n */\nexport type Endpoint = {\n /** Extension point to add your custom data. */\n custom?: Record<string, any>\n\n /**\n * Middleware that will be called when the path/method matches\n *\n * Compatible with Web Request/Response Model\n */\n handler: PayloadHandler\n /** HTTP method (or \"all\") */\n method: 'connect' | 'delete' | 'get' | 'head' | 'options' | 'patch' | 'post' | 'put'\n /**\n * Pattern that should match the path of the incoming request\n *\n * Compatible with the Express router\n */\n path: string\n /**\n * Please add \"root\" routes under the /api folder in the Payload Project.\n * https://nextjs.org/docs/app/api-reference/file-conventions/route\n *\n * @deprecated in 3.0\n */\n root?: never\n}\n\nexport type EditViewComponent = React.ComponentType<ServerSideEditViewProps>\n\nexport type EditViewConfig =\n | {\n /**\n * Add a new Edit view to the admin panel\n * i.e. you can render a custom view that has no tab, if desired\n * Or override a specific properties of an existing one\n * i.e. you can customize the `Default` view tab label, if desired\n */\n Tab?: DocumentTab\n path?: string\n }\n | {\n Component: EditViewComponent\n path: string\n }\n | {\n actions?: CustomComponent[]\n }\n\n/**\n * Override existing views\n * i.e. Dashboard, Account, API, LivePreview, etc.\n * Path is not available here\n * All Tab properties become optional\n * i.e. you can change just the label, if desired\n */\nexport type EditView = EditViewComponent | EditViewConfig\n\nexport type ServerProps = {\n [key: string]: unknown\n i18n: I18nClient\n locale?: Locale\n params?: { [key: string]: string | string[] | undefined }\n payload: Payload\n permissions?: Permissions\n searchParams?: { [key: string]: string | string[] | undefined }\n user?: GeneratedTypes['user']\n}\n\nexport const serverProps: (keyof ServerProps)[] = [\n 'payload',\n 'i18n',\n 'locale',\n 'params',\n 'permissions',\n 'searchParams',\n 'permissions',\n]\n\nexport type CustomComponent<TAdditionalProps extends any = any> = React.ComponentType<\n TAdditionalProps & Partial<ServerProps>\n>\n\nexport type Locale = {\n /**\n * value of supported locale\n * @example \"en\"\n */\n code: string\n /**\n * Code of another locale to use when reading documents with fallback, if not specified defaultLocale is used\n */\n fallbackLocale?: string\n /**\n * label of supported locale\n * @example \"English\"\n */\n label: Record<string, string> | string\n /**\n * if true, defaults textAligmnent on text fields to RTL\n */\n rtl?: boolean\n}\n\nexport type BaseLocalizationConfig = {\n /**\n * Locale for users that have not expressed their preference for a specific locale\n * @example `\"en\"`\n */\n defaultLocale: string\n /** Set to `true` to let missing values in localised fields fall back to the values in `defaultLocale` */\n fallback?: boolean\n}\n\nexport type LocalizationConfigWithNoLabels = Prettify<\n BaseLocalizationConfig & {\n /**\n * List of supported locales\n * @example `[\"en\", \"es\", \"fr\", \"nl\", \"de\", \"jp\"]`\n */\n locales: string[]\n }\n>\n\nexport type LocalizationConfigWithLabels = Prettify<\n BaseLocalizationConfig & {\n /**\n * List of supported locales with labels\n * @example {\n * label: 'English',\n * value: 'en',\n * rtl: false\n * }\n */\n locales: Locale[]\n }\n>\n\nexport type SanitizedLocalizationConfig = Prettify<\n LocalizationConfigWithLabels & {\n /**\n * List of supported locales\n * @example `[\"en\", \"es\", \"fr\", \"nl\", \"de\", \"jp\"]`\n */\n localeCodes: string[]\n }\n>\n\n/**\n * @see https://payloadcms.com/docs/configuration/localization#localization\n */\nexport type LocalizationConfig = Prettify<\n LocalizationConfigWithLabels | LocalizationConfigWithNoLabels\n>\n\nexport type LabelFunction = ({ t }: { t: TFunction }) => string\n\nexport type SharpDependency = (\n input?:\n | ArrayBuffer\n | Buffer\n | Float32Array\n | Float64Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Uint8Array\n | Uint8ClampedArray\n | Uint16Array\n | Uint32Array\n | string,\n options?: sharp.SharpOptions,\n) => sharp.Sharp\n\n/**\n * This is the central configuration\n *\n * @see https://payloadcms.com/docs/configuration/overview\n */\nexport type Config = {\n /** Configure admin dashboard */\n admin?: {\n /** Automatically log in as a user when visiting the admin dashboard. */\n autoLogin?:\n | {\n /**\n * The email address of the user to login as\n *\n */\n email: string\n /** The password of the user to login as */\n password: string\n /**\n * If set to true, the login credentials will be prefilled but the user will still need to click the login button.\n *\n * @default false\n */\n prefillOnly?: boolean\n }\n | false\n /** Set account profile picture. Options: gravatar, default or a custom React component. */\n avatar?: 'default' | 'gravatar' | React.ComponentType<any>\n\n /**\n * Add extra and/or replace built-in components with custom components\n *\n * @see https://payloadcms.com/docs/admin/components\n */\n components?: {\n /**\n * Replace the navigation with a custom component\n */\n Nav?: CustomComponent\n /**\n * Add custom components to the top right of the Admin Panel\n */\n actions?: CustomComponent[]\n /**\n * Add custom components after the collection overview\n */\n afterDashboard?: CustomComponent[]\n /**\n * Add custom components after the email/password field\n */\n afterLogin?: CustomComponent[]\n /**\n * Add custom components after the navigation links\n */\n afterNavLinks?: CustomComponent[]\n /**\n * Add custom components before the collection overview\n */\n beforeDashboard?: CustomComponent[]\n /**\n * Add custom components before the email/password field\n */\n beforeLogin?: CustomComponent[]\n /**\n * Add custom components before the navigation links\n */\n beforeNavLinks?: CustomComponent[]\n /** Replace graphical components */\n graphics?: {\n /** Replace the icon in the navigation */\n Icon?: CustomComponent\n /** Replace the logo on the login page */\n Logo?: CustomComponent\n }\n /** Replace logout related components */\n logout?: {\n /** Replace the logout button */\n Button?: CustomComponent\n }\n /**\n * Wrap the admin dashboard in custom context providers\n */\n providers?: React.ComponentType<{ children?: React.ReactNode }>[]\n /**\n * Replace or modify top-level admin routes, or add new ones:\n * + `Account` - `/admin/account`\n * + `Dashboard` - `/admin`\n * + `:path` - `/admin/:path`\n */\n views?: {\n /** Add custom admin views */\n [key: string]: AdminView\n /** Replace the account screen */\n Account?: AdminView\n /** Replace the admin homepage */\n Dashboard?: AdminView\n }\n }\n /** Extension point to add your custom data. Available in server and client. */\n custom?: Record<string, any>\n /** Global date format that will be used for all dates in the Admin panel. Any valid date-fns format pattern can be used. */\n dateFormat?: string\n /** If set to true, the entire Admin panel will be disabled. */\n disable?: boolean\n livePreview?: LivePreviewConfig & {\n collections?: string[]\n globals?: string[]\n }\n /** Base meta data to use for the Admin Panel. Included properties are titleSuffix, ogImage, and favicon. */\n meta?: MetaConfig\n routes?: {\n /** The route for the account page. */\n account?: string\n /** The route for the create first user page. */\n createFirstUser?: string\n /** The route for the forgot password page. */\n forgot?: string\n /** The route the user will be redirected to after being inactive for too long. */\n inactivity?: string\n /** The route for the login page. */\n login?: string\n /** The route for the logout page. */\n logout?: string\n /** The route for the unauthorized page. */\n unauthorized?: string\n }\n /** The slug of a Collection that you want to be used to log in to the Admin dashboard. */\n user?: string\n }\n /** Custom Payload bin scripts can be injected via the config. */\n bin?: BinScriptConfig[]\n /**\n * Manage the datamodel of your application\n *\n * @see https://payloadcms.com/docs/configuration/collections#collection-configs\n */\n collections?: CollectionConfig[]\n /**\n * Replace the built-in components with custom ones\n */\n components?: { [key: string]: (() => JSX.Element) | JSX.Element }\n /**\n * Prefix a string to all cookies that Payload sets.\n *\n * @default \"payload\"\n */\n cookiePrefix?: string\n /** Either a whitelist array of URLS to allow CORS requests from, or a wildcard string ('*') to accept incoming requests from any domain. */\n cors?: '*' | string[]\n /** A whitelist array of URLs to allow Payload cookies to be accepted from as a form of CSRF protection. */\n csrf?: string[]\n\n /** Extension point to add your custom data. Server only. */\n custom?: Record<string, any>\n\n /** Pass in a database adapter for use on this project. */\n db: DatabaseAdapterResult\n /** Enable to expose more detailed error information. */\n debug?: boolean\n /**\n * If a user does not specify `depth` while requesting a resource, this depth will be used.\n *\n * @see https://payloadcms.com/docs/getting-started/concepts#depth\n *\n * @default 2\n */\n defaultDepth?: number\n /**\n * The maximum allowed depth to be permitted application-wide. This setting helps prevent against malicious queries.\n *\n * @default 40000\n */\n defaultMaxTextLength?: number\n /** Default richtext editor to use for richText fields */\n editor: RichTextAdapterProvider<any, any, any>\n /**\n * Email Adapter\n *\n * @see https://payloadcms.com/docs/email/overview\n */\n email?: EmailAdapter | Promise<EmailAdapter>\n /** Custom REST endpoints */\n endpoints?: Endpoint[]\n /**\n * @see https://payloadcms.com/docs/configuration/globals#global-configs\n */\n globals?: GlobalConfig[]\n /**\n * Manage the GraphQL API\n *\n * You can add your own GraphQL queries and mutations to Payload, making use of all the types that Payload has defined for you.\n *\n * @see https://payloadcms.com/docs/graphql/overview\n */\n graphQL?: {\n disable?: boolean\n disablePlaygroundInProduction?: boolean\n maxComplexity?: number\n /**\n * Function that returns an object containing keys to custom GraphQL mutations\n *\n * @see https://payloadcms.com/docs/graphql/extending\n */\n mutations?: GraphQLExtension\n /**\n * Function that returns an object containing keys to custom GraphQL queries\n *\n * @see https://payloadcms.com/docs/graphql/extending\n */\n queries?: GraphQLExtension\n /**\n * Filepath to write the generated schema to\n */\n schemaOutputFile?: string\n }\n /**\n * Tap into Payload-wide hooks.\n *\n * @see https://payloadcms.com/docs/hooks/overview\n */\n hooks?: {\n afterError?: AfterErrorHook\n }\n /** i18n config settings */\n i18n?: I18nOptions<{} | DefaultTranslationsObject> // loosen the type here to allow for custom translations\n /** Automatically index all sortable top-level fields in the database to improve sort performance and add database compatibility for Azure Cosmos and similar. */\n indexSortableFields?: boolean\n /**\n * Translate your content to different languages/locales.\n *\n * @default false // disable localization\n */\n localization?: LocalizationConfig | false\n /**\n * The maximum allowed depth to be permitted application-wide. This setting helps prevent against malicious queries.\n *\n * @see https://payloadcms.com/docs/getting-started/concepts#depth\n *\n * @default 10\n */\n maxDepth?: number\n /** A function that is called immediately following startup that receives the Payload instance as its only argument. */\n onInit?: (payload: Payload) => Promise<void> | void\n /**\n * An array of Payload plugins.\n *\n * @see https://payloadcms.com/docs/plugins/overview\n */\n plugins?: Plugin[]\n /** Control the routing structure that Payload binds itself to. */\n routes?: {\n /** @default \"/admin\" */\n admin?: string\n /** @default \"/api\" */\n api?: string\n /** @default \"/graphql\" */\n graphQL?: string\n /** @default \"/graphql-playground\" */\n graphQLPlayground?: string\n }\n /** Secure string that Payload will use for any encryption workflows */\n secret: string\n /**\n * Define the absolute URL of your app including the protocol, for example `https://example.org`.\n * No paths allowed, only protocol, domain and (optionally) port.\n *\n * @see https://payloadcms.com/docs/configuration/overview#options\n */\n serverURL?: string\n /**\n * Pass in a local copy of Sharp if you'd like to use it.\n *\n */\n sharp?: SharpDependency\n /** Send anonymous telemetry data about general usage. */\n telemetry?: boolean\n /** Control how typescript interfaces are generated from your collections. */\n typescript?: {\n /** Disable declare block in generated types file */\n declare?:\n | {\n /**\n * @internal internal use only to allow for multiple declarations within a monorepo and suppress the \"Duplicate identifier GeneratedTypes\" error\n *\n * Adds a @ts-ignore flag above the GeneratedTypes interface declaration\n *\n * @default false\n */\n ignoreTSError?: boolean\n }\n | false\n /** Filename to write the generated types to */\n outputFile?: string\n }\n /**\n * Customize the handling of incoming file uploads for collections that have uploads enabled.\n */\n upload?: ExpressFileUploadOptions\n}\n\nexport type SanitizedConfig = Omit<\n DeepRequired<Config>,\n 'collections' | 'editor' | 'endpoint' | 'globals' | 'i18n' | 'localization' | 'upload'\n> & {\n collections: SanitizedCollectionConfig[]\n /** Default richtext editor to use for richText fields */\n editor: RichTextAdapter<any, any, any>\n endpoints: Endpoint[]\n globals: SanitizedGlobalConfig[]\n i18n: Required<I18nOptions>\n localization: SanitizedLocalizationConfig | false\n paths: {\n config: string\n configDir: string\n rawConfig: string\n }\n upload: ExpressFileUploadOptions & {\n /**\n * Deduped list of adapters used in the project\n */\n adapters: string[]\n }\n}\n\nexport type EditConfig =\n | (\n | {\n /**\n * Replace or modify individual nested routes, or add new ones:\n * + `Default` - `/admin/collections/:collection/:id`\n * + `API` - `/admin/collections/:collection/:id/api`\n * + `LivePreview` - `/admin/collections/:collection/:id/preview`\n * + `References` - `/admin/collections/:collection/:id/references`\n * + `Relationships` - `/admin/collections/:collection/:id/relationships`\n * + `Versions` - `/admin/collections/:collection/:id/versions`\n * + `Version` - `/admin/collections/:collection/:id/versions/:version`\n * + `CustomView` - `/admin/collections/:collection/:id/:path`\n */\n API?: EditViewComponent | Partial<EditViewConfig>\n Default?: EditViewComponent | Partial<EditViewConfig>\n LivePreview?: EditViewComponent | Partial<EditViewConfig>\n Version?: EditViewComponent | Partial<EditViewConfig>\n Versions?: EditViewComponent | Partial<EditViewConfig>\n // TODO: uncomment these as they are built\n // References?: EditView\n // Relationships?: EditView\n }\n | {\n [key: string]: EditViewConfig\n }\n )\n | EditViewComponent\n\nexport type EntityDescriptionComponent = CustomComponent\n\nexport type EntityDescriptionFunction = ({ t }: { t: TFunction }) => string\n\nexport type EntityDescription = EntityDescriptionFunction | Record<string, string> | string\n\nexport type { EmailAdapter, SendEmailOptions }\n"],"names":["serverProps"],"rangeMappings":";;;;;;;;","mappings":"AAkVA,OAAO,MAAMA,cAAqC;IAChD;IACA;IACA;IACA;IACA;IACA;IACA;CACD,CAAA"}
|
|
@@ -9,7 +9,7 @@ export { traverseFields as afterReadTraverseFields } from '../fields/hooks/after
|
|
|
9
9
|
export { traverseFields as beforeChangeTraverseFields } from '../fields/hooks/beforeChange/traverseFields.js';
|
|
10
10
|
export { traverseFields as beforeValidateTraverseFields } from '../fields/hooks/beforeValidate/traverseFields.js';
|
|
11
11
|
export { formatFilesize } from '../uploads/formatFilesize.js';
|
|
12
|
-
export {
|
|
12
|
+
export { isImage } from '../uploads/isImage.js';
|
|
13
13
|
export { combineMerge } from '../utilities/combineMerge.js';
|
|
14
14
|
export { configToJSONSchema, entityToJSONSchema, fieldsToJSONSchema, withNullableJSONSchemaType, } from '../utilities/configToJSONSchema.js';
|
|
15
15
|
export { createArrayFromCommaDelineated } from '../utilities/createArrayFromCommaDelineated.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../../src/exports/utilities.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAA;AACtF,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,8BAA8B,CAAA;AACzE,OAAO,EAAE,cAAc,IAAI,yBAAyB,EAAE,MAAM,+CAA+C,CAAA;AAC3G,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,sCAAsC,CAAA;AAClF,OAAO,EAAE,cAAc,IAAI,uBAAuB,EAAE,MAAM,6CAA6C,CAAA;AACvG,OAAO,EAAE,cAAc,IAAI,0BAA0B,EAAE,MAAM,gDAAgD,CAAA;AAC7G,OAAO,EAAE,cAAc,IAAI,4BAA4B,EAAE,MAAM,kDAAkD,CAAA;AAEjH,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAA;AAE7D,OAAO,EAAE,OAAO,
|
|
1
|
+
{"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../../src/exports/utilities.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,wBAAwB,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAA;AACtF,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,8BAA8B,CAAA;AACzE,OAAO,EAAE,cAAc,IAAI,yBAAyB,EAAE,MAAM,+CAA+C,CAAA;AAC3G,OAAO,EAAE,O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AO,EACL,sBAAsB,EACtB,0BAA0B,EAC1B,gCAAgC,GACjC,MAAM,kCAAkC,CAAA;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAA;AAErD,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,uCAAuC,CAAA;AACxF,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAA;AACnD,OAAO,EAAE,uBAAuB,EAAE,MAAM,yCAAyC,CAAA;AACjF,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAA;AAC3D,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,6BAA6B,CAAA;AACpE,OAAO,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAA;AAC3C,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,MAAM,qCAAqC,CAAA"}
|
|
@@ -8,7 +8,7 @@ export { traverseFields as afterReadTraverseFields } from '../fields/hooks/after
|
|
|
8
8
|
export { traverseFields as beforeChangeTraverseFields } from '../fields/hooks/beforeChange/traverseFields.js';
|
|
9
9
|
export { traverseFields as beforeValidateTraverseFields } from '../fields/hooks/beforeValidate/traverseFields.js';
|
|
10
10
|
export { formatFilesize } from '../uploads/formatFilesize.js';
|
|
11
|
-
export {
|
|
11
|
+
export { isImage } from '../uploads/isImage.js';
|
|
12
12
|
export { combineMerge } from '../utilities/combineMerge.js';
|
|
13
13
|
export { configToJSONSchema, entityToJSONSchema, fieldsToJSONSchema, withNullableJSONSchemaType } from '../utilities/configToJSONSchema.js';
|
|
14
14
|
export { createArrayFromCommaDelineated } from '../utilities/createArrayFromCommaDelineated.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/utilities.ts"],"sourcesContent":["/**\n * WARNING: This file contains exports that can only be safely used on the front-end\n */\n\nexport { createDataloaderCacheKey, getDataLoader } from '../collections/dataloader.js'\nexport { default as getDefaultValue } from '../fields/getDefaultValue.js'\nexport { traverseFields as afterChangeTraverseFields } from '../fields/hooks/afterChange/traverseFields.js'\nexport { promise as afterReadPromise } from '../fields/hooks/afterRead/promise.js'\nexport { traverseFields as afterReadTraverseFields } from '../fields/hooks/afterRead/traverseFields.js'\nexport { traverseFields as beforeChangeTraverseFields } from '../fields/hooks/beforeChange/traverseFields.js'\nexport { traverseFields as beforeValidateTraverseFields } from '../fields/hooks/beforeValidate/traverseFields.js'\n\nexport { formatFilesize } from '../uploads/formatFilesize.js'\n\nexport {
|
|
1
|
+
{"version":3,"sources":["../../src/exports/utilities.ts"],"sourcesContent":["/**\n * WARNING: This file contains exports that can only be safely used on the front-end\n */\n\nexport { createDataloaderCacheKey, getDataLoader } from '../collections/dataloader.js'\nexport { default as getDefaultValue } from '../fields/getDefaultValue.js'\nexport { traverseFields as afterChangeTraverseFields } from '../fields/hooks/afterChange/traverseFields.js'\nexport { promise as afterReadPromise } from '../fields/hooks/afterRead/promise.js'\nexport { traverseFields as afterReadTraverseFields } from '../fields/hooks/afterRead/traverseFields.js'\nexport { traverseFields as beforeChangeTraverseFields } from '../fields/hooks/beforeChange/traverseFields.js'\nexport { traverseFields as beforeValidateTraverseFields } from '../fields/hooks/beforeValidate/traverseFields.js'\n\nexport { formatFilesize } from '../uploads/formatFilesize.js'\n\nexport { isImage } from '../uploads/isImage.js'\n\nexport { combineMerge } from '../utilities/combineMerge.js'\nexport {\n configToJSONSchema,\n entityToJSONSchema,\n fieldsToJSONSchema,\n withNullableJSONSchemaType,\n} from '../utilities/configToJSONSchema.js'\n\nexport { createArrayFromCommaDelineated } from '../utilities/createArrayFromCommaDelineated.js'\nexport { createLocalReq } from '../utilities/createLocalReq.js'\nexport { deepCopyObject } from '../utilities/deepCopyObject.js'\n\nexport { deepMerge } from '../utilities/deepMerge.js'\nexport { fieldSchemaToJSON } from '../utilities/fieldSchemaToJSON.js'\n\nexport { default as flattenTopLevelFields } from '../utilities/flattenTopLevelFields.js'\n\nexport { formatLabels, formatNames, toWords } from '../utilities/formatLabels.js'\nexport { getCollectionIDFieldTypes } from '../utilities/getCollectionIDFieldTypes.js'\nexport { getObjectDotNotation } from '../utilities/getObjectDotNotation.js'\n\nexport { default as getUniqueListBy } from '../utilities/getUniqueListBy.js'\n\nexport { isEntityHidden } from '../utilities/isEntityHidden.js'\nexport { isNumber } from '../utilities/isNumber.js'\n\nexport { isPlainObject } from '../utilities/isPlainObject.js'\nexport {\n isReactClientComponent,\n isReactComponentOrFunction,\n isReactServerComponentOrFunction,\n} from '../utilities/isReactComponent.js'\nexport { isValidID } from '../utilities/isValidID.js'\n\nexport { default as isolateObjectProperty } from '../utilities/isolateObjectProperty.js'\nexport { mapAsync } from '../utilities/mapAsync.js'\nexport { mergeListSearchAndWhere } from '../utilities/mergeListSearchAndWhere.js'\nexport { setsAreEqual } from '../utilities/setsAreEqual.js'\nexport { default as toKebabCase } from '../utilities/toKebabCase.js'\nexport { wait } from '../utilities/wait.js'\nexport { default as wordBoundariesRegex } from '../utilities/wordBoundariesRegex.js'\n"],"names":["createDataloaderCacheKey","getDataLoader","default","getDefaultValue","traverseFields","afterChangeTraverseFields","promise","afterReadPromise","afterReadTraverseFields","beforeChangeTraverseFields","beforeValidateTraverseFields","formatFilesize","isImage","combineMerge","configToJSONSchema","entityToJSONSchema","fieldsToJSONSchema","withNullableJSONSchemaType","createArrayFromCommaDelineated","createLocalReq","deepCopyObject","deepMerge","fieldSchemaToJSON","flattenTopLevelFields","formatLabels","formatNames","toWords","getCollectionIDFieldTypes","getObjectDotNotation","getUniqueListBy","isEntityHidden","isNumber","isPlainObject","isReactClientComponent","isReactComponentOrFunction","isReactServerComponentOrFunction","isValidID","isolateObjectProperty","mapAsync","mergeListSearchAndWhere","setsAreEqual","toKebabCase","wait","wordBoundariesRegex"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA;;CAEC,GAED,SAASA,wBAAwB,EAAEC,aAAa,QAAQ,+BAA8B;AACtF,SAASC,WAAWC,eAAe,QAAQ,+BAA8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SAASC,IAAI,QAAQ,uBAAsB;AAC3C,SAASxC,WAAWyC,mBAAmB,QAAQ,sCAAqC"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -6,18 +6,6 @@ import type payload from '../index.js';
|
|
|
6
6
|
import type { GeneratedTypes } from '../index.js';
|
|
7
7
|
import type { validOperators } from './constants.js';
|
|
8
8
|
export type { Payload as Payload } from '../index.js';
|
|
9
|
-
export type UploadEdits = {
|
|
10
|
-
crop?: {
|
|
11
|
-
height?: number;
|
|
12
|
-
width?: number;
|
|
13
|
-
x?: number;
|
|
14
|
-
y?: number;
|
|
15
|
-
};
|
|
16
|
-
focalPoint?: {
|
|
17
|
-
x?: number;
|
|
18
|
-
y?: number;
|
|
19
|
-
};
|
|
20
|
-
};
|
|
21
9
|
export type CustomPayloadRequestProperties = {
|
|
22
10
|
context: RequestContext;
|
|
23
11
|
/** The locale that should be used for a field when it is not translated to the requested locale */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AAC/D,OAAO,KAAK,UAAU,MAAM,YAAY,CAAA;AAExC,OAAO,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAA;AACpF,OAAO,KAAK,OAAO,MAAM,aAAa,CAAA;AACtC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AACpD,YAAY,EAAE,OAAO,IAAI,OAAO,EAAE,MAAM,aAAa,CAAA;AAErD,MAAM,MAAM,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/types/index.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AAC/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AA;AAC/D,MAAM,MAAM,iBAAiB,GAAG,cAAc,CAAA;AAC9C,MAAM,MAAM,cAAc,GAAG,QAAQ,CAAA;AACrC,MAAM,MAAM,aAAa,GAAG,cAAc,GAAG,SAAS,GAAG,iBAAiB,CAAA;AAE1E,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,IAAI,kBAAkB,CAEpE;AAED,MAAM,MAAM,KAAK,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;AACpD,MAAM,MAAM,KAAK,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;AAC5C,MAAM,MAAM,UAAU,CAAC,CAAC,EAAE,WAAW,IAAI,KAAK,CAAC,CAAC,CAAC,SAAS,IAAI,GAAG,WAAW,GAAG,CAAC,CAAA"}
|
package/dist/types/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["import type { I18n, TFunction } from '@payloadcms/translations'\nimport type DataLoader from 'dataloader'\n\nimport type { TypeWithID, TypeWithTimestamps } from '../collections/config/types.js'\nimport type payload from '../index.js'\nimport type { GeneratedTypes } from '../index.js'\nimport type { validOperators } from './constants.js'\nexport type { Payload as Payload } from '../index.js'\n\nexport type
|
|
1
|
+
{"version":3,"sources":["../../src/types/index.ts"],"sourcesContent":["import type { I18n, TFunction } from '@payloadcms/translations'\nimport type DataLoader from 'dataloader'\n\nimport type { TypeWithID, TypeWithTimestamps } from '../collections/config/types.js'\nimport type payload from '../index.js'\nimport type { GeneratedTypes } from '../index.js'\nimport type { validOperators } from './constants.js'\nexport type { Payload as Payload } from '../index.js'\n\nexport type CustomPayloadRequestProperties = {\n context: RequestContext\n /** The locale that should be used for a field when it is not translated to the requested locale */\n fallbackLocale?: string\n i18n: I18n\n /**\n * The requested locale if specified\n * Only available for localized collections\n */\n locale?: GeneratedTypes['locale']\n /**\n * The payload object\n */\n payload: typeof payload\n /**\n * The context in which the request is being made\n */\n payloadAPI: 'GraphQL' | 'REST' | 'local'\n /** Optimized document loader */\n payloadDataLoader?: DataLoader<string, TypeWithID>\n /** Resized versions of the image that was uploaded during this request */\n payloadUploadSizes?: Record<string, Buffer>\n /** Query params on the request */\n query: Record<string, unknown>\n /** The route parameters\n * @example\n * /:collection/:id -> /posts/123\n * { collection: 'posts', id: '123' }\n */\n routeParams?: Record<string, unknown>\n /** Translate function - duplicate of i18n.t */\n t: TFunction\n /**\n * Identifier for the database transaction for interactions in a single, all-or-nothing operation.\n */\n transactionID?: number | string\n /**\n * Used to ensure consistency when multiple operations try to create a transaction concurrently on the same request\n */\n transactionIDPromise?: Promise<void>\n /** The signed-in user */\n user: GeneratedTypes['user'] | null\n} & Pick<\n URL,\n 'hash' | 'host' | 'href' | 'origin' | 'pathname' | 'port' | 'protocol' | 'search' | 'searchParams'\n>\nexport type PayloadRequestData = {\n /** Data from the request body */\n data?: Record<string, unknown>\n /** The locale that should be used for a field when it is not translated to the requested locale */\n file?: {\n data: Buffer\n mimetype: string\n name: string\n size: number\n tempFilePath?: string\n }\n}\nexport type PayloadRequest = Partial<Request> &\n Required<Pick<Request, 'headers'>> &\n CustomPayloadRequestProperties\nexport type PayloadRequestWithData = PayloadRequest & PayloadRequestData\nexport interface RequestContext {\n [key: string]: unknown\n}\n\nexport type Operator = (typeof validOperators)[number]\n\nexport type WhereField = {\n [key in Operator]?: unknown\n}\n\nexport type Where = {\n [key: string]: Where[] | WhereField\n and?: Where[]\n or?: Where[]\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Document = any\n\nexport type Operation = 'create' | 'delete' | 'read' | 'update'\nexport type VersionOperations = 'readVersions'\nexport type AuthOperations = 'unlock'\nexport type AllOperations = AuthOperations | Operation | VersionOperations\n\nexport function docHasTimestamps(doc: any): doc is TypeWithTimestamps {\n return doc?.createdAt && doc?.updatedAt\n}\n\nexport type IfAny<T, Y, N> = 0 extends 1 & T ? Y : N // This is a commonly used trick to detect 'any'\nexport type IsAny<T> = IfAny<T, true, false>\nexport type ReplaceAny<T, DefaultType> = IsAny<T> extends true ? DefaultType : T\n"],"names":["docHasTimestamps","doc","createdAt","updatedAt"],"rangeMappings":";;","mappings":"AA+FA,OAAO,SAASA,iBAAiBC,GAAQ;IACvC,OAAOA,KAAKC,aAAaD,KAAKE;AAChC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export
|
|
1
|
+
export declare function canResizeImage(mimeType: string): boolean;
|
|
2
2
|
//# sourceMappingURL=canResizeImage.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"canResizeImage.d.ts","sourceRoot":"","sources":["../../src/uploads/canResizeImage.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"canResizeImage.d.ts","sourceRoot":"","sources":["../../src/uploads/canResizeImage.ts"],"names":[],"mappings":"AAAA,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAExD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/canResizeImage.ts"],"sourcesContent":["export
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/canResizeImage.ts"],"sourcesContent":["export function canResizeImage(mimeType: string): boolean {\n return ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/tiff'].indexOf(mimeType) > -1\n}\n"],"names":["canResizeImage","mimeType","indexOf"],"rangeMappings":";;;;;;;;","mappings":"AAAA,OAAO,SAASA,eAAeC,QAAgB;IAC7C,OAAO;QAAC;QAAc;QAAa;QAAa;QAAc;KAAa,CAACC,OAAO,CAACD,YAAY,CAAC;AACnG"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export declare const percentToPixel: (value: any, dimension: any) => number;
|
|
2
|
-
export
|
|
2
|
+
export declare function cropImage({ cropData, dimensions, file, sharp }: {
|
|
3
3
|
cropData: any;
|
|
4
4
|
dimensions: any;
|
|
5
5
|
file: any;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cropImage.d.ts","sourceRoot":"","sources":["../../src/uploads/cropImage.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,cAAc,wCAE1B,CAAA;AAED,
|
|
1
|
+
{"version":3,"file":"cropImage.d.ts","sourceRoot":"","sources":["../../src/uploads/cropImage.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,cAAc,wCAE1B,CAAA;AAED,wBAAsB,SAAS,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE;;;;;CAAA,gBAoBpE"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export const percentToPixel = (value, dimension)=>{
|
|
2
2
|
return Math.floor(parseFloat(value) / 100 * dimension);
|
|
3
3
|
};
|
|
4
|
-
export
|
|
4
|
+
export async function cropImage({ cropData, dimensions, file, sharp }) {
|
|
5
5
|
try {
|
|
6
6
|
const { height, width, x, y } = cropData;
|
|
7
7
|
const formattedCropData = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/cropImage.ts"],"sourcesContent":["export const percentToPixel = (value, dimension) => {\n return Math.floor((parseFloat(value) / 100) * dimension)\n}\n\nexport
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/cropImage.ts"],"sourcesContent":["export const percentToPixel = (value, dimension) => {\n return Math.floor((parseFloat(value) / 100) * dimension)\n}\n\nexport async function cropImage({ cropData, dimensions, file, sharp }) {\n try {\n const { height, width, x, y } = cropData\n\n const formattedCropData = {\n height: percentToPixel(height, dimensions.height),\n left: percentToPixel(x, dimensions.width),\n top: percentToPixel(y, dimensions.height),\n width: percentToPixel(width, dimensions.width),\n }\n\n const cropped = sharp(file.tempFilePath || file.data).extract(formattedCropData)\n\n return await cropped.toBuffer({\n resolveWithObject: true,\n })\n } catch (error) {\n console.error(`Error cropping image:`, error)\n throw error\n }\n}\n"],"names":["percentToPixel","value","dimension","Math","floor","parseFloat","cropImage","cropData","dimensions","file","sharp","height","width","x","y","formattedCropData","left","top","cropped","tempFilePath","data","extract","toBuffer","resolveWithObject","error","console"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;","mappings":"AAAA,OAAO,MAAMA,iBAAiB,CAACC,OAAOC;IACpC,OAAOC,KAAKC,KAAK,CAAC,AAACC,WAAWJ,SAAS,MAAOC;AAChD,EAAC;AAED,OAAO,eAAeI,UAAU,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,IAAI,EAAEC,KAAK,EAAE;IACnE,IAAI;QACF,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAEC,CAAC,EAAEC,CAAC,EAAE,GAAGP;QAEhC,MAAMQ,oBAAoB;YACxBJ,QAAQX,eAAeW,QAAQH,WAAWG,MAAM;YAChDK,MAAMhB,eAAea,GAAGL,WAAWI,KAAK;YACxCK,KAAKjB,eAAec,GAAGN,WAAWG,MAAM;YACxCC,OAAOZ,eAAeY,OAAOJ,WAAWI,KAAK;QAC/C;QAEA,MAAMM,UAAUR,MAAMD,KAAKU,YAAY,IAAIV,KAAKW,IAAI,EAAEC,OAAO,CAACN;QAE9D,OAAO,MAAMG,QAAQI,QAAQ,CAAC;YAC5BC,mBAAmB;QACrB;IACF,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,CAAC,qBAAqB,CAAC,EAAEA;QACvC,MAAMA;IACR;AACF"}
|
|
@@ -6,6 +6,8 @@ type Args<T> = {
|
|
|
6
6
|
collection: Collection;
|
|
7
7
|
config: SanitizedConfig;
|
|
8
8
|
data: T;
|
|
9
|
+
operation: 'create' | 'update';
|
|
10
|
+
originalDoc?: T;
|
|
9
11
|
overwriteExistingFiles?: boolean;
|
|
10
12
|
req: PayloadRequestWithData;
|
|
11
13
|
throwOnMissingFile?: boolean;
|
|
@@ -14,6 +16,6 @@ type Result<T> = Promise<{
|
|
|
14
16
|
data: T;
|
|
15
17
|
files: FileToSave[];
|
|
16
18
|
}>;
|
|
17
|
-
export declare const generateFileData: <T>({ collection: { config: collectionConfig }, data, overwriteExistingFiles, req, throwOnMissingFile, }: Args<T>) => Result<T>;
|
|
19
|
+
export declare const generateFileData: <T>({ collection: { config: collectionConfig }, data, operation, originalDoc, overwriteExistingFiles, req, throwOnMissingFile, }: Args<T>) => Result<T>;
|
|
18
20
|
export {};
|
|
19
21
|
//# sourceMappingURL=generateFileData.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateFileData.d.ts","sourceRoot":"","sources":["../../src/uploads/generateFileData.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAA;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AAC/D,OAAO,KAAK,EAAY,UAAU,
|
|
1
|
+
{"version":3,"file":"generateFileData.d.ts","sourceRoot":"","sources":["../../src/uploads/generateFileData.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAA;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AACzD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AAC/D,OAAO,KAAK,EAAY,UAAU,EAAgC,MAAM,YAAY,CAAA;AAYpF,KAAK,IAAI,CAAC,CAAC,IAAI;IACb,UAAU,EAAE,UAAU,CAAA;IACtB,MAAM,EAAE,eAAe,CAAA;IACvB,IAAI,EAAE,CAAC,CAAA;IACP,SAAS,EAAE,QAAQ,GAAG,QAAQ,CAAA;IAC9B,WAAW,CAAC,EAAE,CAAC,CAAA;IACf,sBAAsB,CAAC,EAAE,OAAO,CAAA;IAChC,GAAG,EAAE,sBAAsB,CAAA;IAC3B,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAC7B,CAAA;AAED,KAAK,MAAM,CAAC,CAAC,IAAI,OAAO,CAAC;IACvB,IAAI,EAAE,CAAC,CAAA;IACP,KAAK,EAAE,UAAU,EAAE,CAAA;CACpB,CAAC,CAAA;AAEF,eAAO,MAAM,gBAAgB,oIAQ1B,KAAK,CAAC,CAAC,KAAG,OAAO,CAAC,CA8OpB,CAAA"}
|
|
@@ -4,15 +4,15 @@ import fs from 'fs';
|
|
|
4
4
|
import mkdirp from 'mkdirp';
|
|
5
5
|
import sanitize from 'sanitize-filename';
|
|
6
6
|
import { FileRetrievalError, FileUploadError, MissingFile } from '../errors/index.js';
|
|
7
|
-
import canResizeImage from './canResizeImage.js';
|
|
8
|
-
import cropImage from './cropImage.js';
|
|
7
|
+
import { canResizeImage } from './canResizeImage.js';
|
|
8
|
+
import { cropImage } from './cropImage.js';
|
|
9
9
|
import { getExternalFile } from './getExternalFile.js';
|
|
10
10
|
import { getFileByPath } from './getFileByPath.js';
|
|
11
11
|
import { getImageSize } from './getImageSize.js';
|
|
12
|
-
import getSafeFileName from './getSafeFilename.js';
|
|
13
|
-
import resizeAndTransformImageSizes from './imageResizer.js';
|
|
14
|
-
import isImage from './isImage.js';
|
|
15
|
-
export const generateFileData = async ({ collection: { config: collectionConfig }, data, overwriteExistingFiles, req, throwOnMissingFile })=>{
|
|
12
|
+
import { getSafeFileName } from './getSafeFilename.js';
|
|
13
|
+
import { resizeAndTransformImageSizes } from './imageResizer.js';
|
|
14
|
+
import { isImage } from './isImage.js';
|
|
15
|
+
export const generateFileData = async ({ collection: { config: collectionConfig }, data, operation, originalDoc, overwriteExistingFiles, req, throwOnMissingFile })=>{
|
|
16
16
|
if (!collectionConfig.upload) {
|
|
17
17
|
return {
|
|
18
18
|
data,
|
|
@@ -21,8 +21,13 @@ export const generateFileData = async ({ collection: { config: collectionConfig
|
|
|
21
21
|
}
|
|
22
22
|
const { sharp } = req.payload.config;
|
|
23
23
|
let file = req.file;
|
|
24
|
-
const uploadEdits =
|
|
25
|
-
|
|
24
|
+
const uploadEdits = parseUploadEditsFromReqOrIncomingData({
|
|
25
|
+
data,
|
|
26
|
+
operation,
|
|
27
|
+
originalDoc,
|
|
28
|
+
req
|
|
29
|
+
});
|
|
30
|
+
const { disableLocalStorage, focalPoint: focalPointEnabled = true, formatOptions, imageSizes, resizeOptions, staticDir, trimOptions } = collectionConfig.upload;
|
|
26
31
|
const staticPath = staticDir;
|
|
27
32
|
if (!file && uploadEdits && data) {
|
|
28
33
|
const { filename, url } = data;
|
|
@@ -177,9 +182,9 @@ export const generateFileData = async ({ collection: { config: collectionConfig
|
|
|
177
182
|
}
|
|
178
183
|
}
|
|
179
184
|
}
|
|
180
|
-
if (Array.isArray(imageSizes)
|
|
185
|
+
if (fileSupportsResize && (Array.isArray(imageSizes) || focalPointEnabled !== false)) {
|
|
181
186
|
req.payloadUploadSizes = {};
|
|
182
|
-
const { sizeData, sizesToSave } = await resizeAndTransformImageSizes({
|
|
187
|
+
const { focalPoint, sizeData, sizesToSave } = await resizeAndTransformImageSizes({
|
|
183
188
|
config: collectionConfig,
|
|
184
189
|
dimensions: !cropData ? dimensions : {
|
|
185
190
|
...dimensions,
|
|
@@ -191,13 +196,16 @@ export const generateFileData = async ({ collection: { config: collectionConfig
|
|
|
191
196
|
req,
|
|
192
197
|
savedFilename: fsSafeName || file.name,
|
|
193
198
|
sharp,
|
|
194
|
-
staticPath
|
|
199
|
+
staticPath,
|
|
200
|
+
uploadEdits
|
|
195
201
|
});
|
|
196
202
|
fileData.sizes = sizeData;
|
|
203
|
+
fileData.focalX = focalPoint?.x;
|
|
204
|
+
fileData.focalY = focalPoint?.y;
|
|
197
205
|
filesToSave.push(...sizesToSave);
|
|
198
206
|
}
|
|
199
207
|
} catch (err) {
|
|
200
|
-
|
|
208
|
+
req.payload.logger.error(err);
|
|
201
209
|
throw new FileUploadError(req.t);
|
|
202
210
|
}
|
|
203
211
|
newData = {
|
|
@@ -209,5 +217,35 @@ export const generateFileData = async ({ collection: { config: collectionConfig
|
|
|
209
217
|
files: filesToSave
|
|
210
218
|
};
|
|
211
219
|
};
|
|
220
|
+
/**
|
|
221
|
+
* Parse upload edits from req or incoming data
|
|
222
|
+
*/ function parseUploadEditsFromReqOrIncomingData(args) {
|
|
223
|
+
const { data, operation, originalDoc, req } = args;
|
|
224
|
+
// Get intended focal point change from query string or incoming data
|
|
225
|
+
const { uploadEdits = {} } = req.query || {};
|
|
226
|
+
if (uploadEdits.focalPoint) return uploadEdits;
|
|
227
|
+
const incomingData = data;
|
|
228
|
+
const origDoc = originalDoc;
|
|
229
|
+
// If no change in focal point, return undefined.
|
|
230
|
+
// This prevents a refocal operation triggered from admin, because it always sends the focal point.
|
|
231
|
+
if (origDoc && incomingData.focalX === origDoc.focalX && incomingData.focalY === origDoc.focalY) {
|
|
232
|
+
return undefined;
|
|
233
|
+
}
|
|
234
|
+
if (incomingData?.focalX && incomingData?.focalY) {
|
|
235
|
+
uploadEdits.focalPoint = {
|
|
236
|
+
x: incomingData.focalX,
|
|
237
|
+
y: incomingData.focalY
|
|
238
|
+
};
|
|
239
|
+
return uploadEdits;
|
|
240
|
+
}
|
|
241
|
+
// If no focal point is set, default to center
|
|
242
|
+
if (operation === 'create') {
|
|
243
|
+
uploadEdits.focalPoint = {
|
|
244
|
+
x: 50,
|
|
245
|
+
y: 50
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
return uploadEdits;
|
|
249
|
+
}
|
|
212
250
|
|
|
213
251
|
//# sourceMappingURL=generateFileData.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/uploads/generateFileData.ts"],"sourcesContent":["import type { OutputInfo, Sharp, SharpOptions } from 'sharp'\n\nimport fileType from 'file-type'\nconst { fromBuffer } = fileType\nimport fs from 'fs'\nimport mkdirp from 'mkdirp'\nimport sanitize from 'sanitize-filename'\n\nimport type { Collection } from '../collections/config/types.js'\nimport type { SanitizedConfig } from '../config/types.js'\nimport type { PayloadRequestWithData } from '../types/index.js'\nimport type { FileData, FileToSave, ProbedImageSize } from './types.js'\n\nimport { FileRetrievalError, FileUploadError, MissingFile } from '../errors/index.js'\nimport canResizeImage from './canResizeImage.js'\nimport cropImage from './cropImage.js'\nimport { getExternalFile } from './getExternalFile.js'\nimport { getFileByPath } from './getFileByPath.js'\nimport { getImageSize } from './getImageSize.js'\nimport getSafeFileName from './getSafeFilename.js'\nimport resizeAndTransformImageSizes from './imageResizer.js'\nimport isImage from './isImage.js'\n\ntype Args<T> = {\n collection: Collection\n config: SanitizedConfig\n data: T\n overwriteExistingFiles?: boolean\n req: PayloadRequestWithData\n throwOnMissingFile?: boolean\n}\n\ntype Result<T> = Promise<{\n data: T\n files: FileToSave[]\n}>\n\nexport const generateFileData = async <T>({\n collection: { config: collectionConfig },\n data,\n overwriteExistingFiles,\n req,\n throwOnMissingFile,\n}: Args<T>): Result<T> => {\n if (!collectionConfig.upload) {\n return {\n data,\n files: [],\n }\n }\n\n const { sharp } = req.payload.config\n\n let file = req.file\n\n const uploadEdits = req.query['uploadEdits'] || {}\n\n const { disableLocalStorage, formatOptions, imageSizes, resizeOptions, staticDir, trimOptions } =\n collectionConfig.upload\n\n const staticPath = staticDir\n\n if (!file && uploadEdits && data) {\n const { filename, url } = data as FileData\n\n try {\n if (url && url.startsWith('/') && !disableLocalStorage) {\n const filePath = `${staticPath}/${filename}`\n const response = await getFileByPath(filePath)\n file = response\n overwriteExistingFiles = true\n } else if (filename && url) {\n file = await getExternalFile({\n data: data as FileData,\n req,\n uploadConfig: collectionConfig.upload,\n })\n overwriteExistingFiles = true\n }\n } catch (err: unknown) {\n throw new FileRetrievalError(req.t, err instanceof Error ? err.message : undefined)\n }\n }\n\n if (!file) {\n if (throwOnMissingFile) throw new MissingFile(req.t)\n\n return {\n data,\n files: [],\n }\n }\n\n if (!disableLocalStorage) {\n mkdirp.sync(staticPath)\n }\n\n let newData = data\n const filesToSave: FileToSave[] = []\n const fileData: Partial<FileData> = {}\n const fileIsAnimated = file.mimetype === 'image/gif' || file.mimetype === 'image/webp'\n const cropData =\n typeof uploadEdits === 'object' && 'crop' in uploadEdits ? uploadEdits.crop : undefined\n\n try {\n const fileSupportsResize = canResizeImage(file.mimetype)\n let fsSafeName: string\n let sharpFile: Sharp | undefined\n let dimensions: ProbedImageSize | undefined\n let fileBuffer: { data: Buffer; info: OutputInfo }\n let ext\n let mime: string\n const fileHasAdjustments =\n fileSupportsResize &&\n Boolean(resizeOptions || formatOptions || trimOptions || file.tempFilePath)\n\n const sharpOptions: SharpOptions = {}\n\n if (fileIsAnimated) sharpOptions.animated = true\n\n if (fileHasAdjustments && sharp) {\n if (file.tempFilePath) {\n sharpFile = sharp(file.tempFilePath, sharpOptions).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081\n } else {\n sharpFile = sharp(file.data, sharpOptions).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081\n }\n\n if (resizeOptions) {\n sharpFile = sharpFile.resize(resizeOptions)\n }\n if (formatOptions) {\n sharpFile = sharpFile.toFormat(formatOptions.format, formatOptions.options)\n }\n if (trimOptions) {\n sharpFile = sharpFile.trim(trimOptions)\n }\n }\n\n if (fileSupportsResize || isImage(file.mimetype)) {\n dimensions = await getImageSize(file)\n fileData.width = dimensions.width\n fileData.height = dimensions.height\n }\n\n if (sharpFile) {\n const metadata = await sharpFile.metadata()\n fileBuffer = await sharpFile.toBuffer({ resolveWithObject: true })\n ;({ ext, mime } = await fromBuffer(fileBuffer.data)) // This is getting an incorrect gif height back.\n fileData.width = fileBuffer.info.width\n fileData.height = fileBuffer.info.height\n fileData.filesize = fileBuffer.info.size\n\n // Animated GIFs + WebP aggregate the height from every frame, so we need to use divide by number of pages\n if (metadata.pages) {\n fileData.height = fileBuffer.info.height / metadata.pages\n fileData.filesize = fileBuffer.data.length\n }\n } else {\n mime = file.mimetype\n fileData.filesize = file.size\n\n if (file.name.includes('.')) {\n ext = file.name.split('.').pop()\n } else {\n ext = ''\n }\n }\n\n // Adust SVG mime type. fromBuffer modifies it.\n if (mime === 'application/xml' && ext === 'svg') mime = 'image/svg+xml'\n fileData.mimeType = mime\n\n const baseFilename = sanitize(file.name.substring(0, file.name.lastIndexOf('.')) || file.name)\n fsSafeName = `${baseFilename}${ext ? `.${ext}` : ''}`\n\n if (!overwriteExistingFiles) {\n fsSafeName = await getSafeFileName({\n collectionSlug: collectionConfig.slug,\n desiredFilename: fsSafeName,\n req,\n staticPath,\n })\n }\n\n fileData.filename = fsSafeName\n let fileForResize = file\n\n if (cropData && sharp) {\n const { data: croppedImage, info } = await cropImage({ cropData, dimensions, file, sharp })\n\n filesToSave.push({\n buffer: croppedImage,\n path: `${staticPath}/${fsSafeName}`,\n })\n\n fileForResize = {\n ...file,\n data: croppedImage,\n size: info.size,\n }\n fileData.width = info.width\n fileData.height = info.height\n fileData.filesize = info.size\n\n if (file.tempFilePath) {\n await fs.promises.writeFile(file.tempFilePath, croppedImage) // write fileBuffer to the temp path\n } else {\n req.file = fileForResize\n }\n } else {\n filesToSave.push({\n buffer: fileBuffer?.data || file.data,\n path: `${staticPath}/${fsSafeName}`,\n })\n\n // If using temp files and the image is being resized, write the file to the temp path\n if (fileBuffer?.data || file.data.length > 0) {\n if (file.tempFilePath) {\n await fs.promises.writeFile(file.tempFilePath, fileBuffer?.data || file.data) // write fileBuffer to the temp path\n } else {\n // Assign the _possibly modified_ file to the request object\n req.file = {\n ...file,\n data: fileBuffer?.data || file.data,\n size: fileBuffer?.info.size,\n }\n }\n }\n }\n\n if (Array.isArray(imageSizes) && fileSupportsResize && sharp) {\n req.payloadUploadSizes = {}\n const { sizeData, sizesToSave } = await resizeAndTransformImageSizes({\n config: collectionConfig,\n dimensions: !cropData\n ? dimensions\n : {\n ...dimensions,\n height: fileData.height,\n width: fileData.width,\n },\n file: fileForResize,\n mimeType: fileData.mimeType,\n req,\n savedFilename: fsSafeName || file.name,\n sharp,\n staticPath,\n })\n\n fileData.sizes = sizeData\n filesToSave.push(...sizesToSave)\n }\n } catch (err) {\n console.error(err)\n throw new FileUploadError(req.t)\n }\n\n newData = {\n ...newData,\n ...fileData,\n }\n\n return {\n data: newData,\n files: filesToSave,\n }\n}\n"],"names":["fileType","fromBuffer","fs","mkdirp","sanitize","FileRetrievalError","FileUploadError","MissingFile","canResizeImage","cropImage","getExternalFile","getFileByPath","getImageSize","getSafeFileName","resizeAndTransformImageSizes","isImage","generateFileData","collection","config","collectionConfig","data","overwriteExistingFiles","req","throwOnMissingFile","upload","files","sharp","payload","file","uploadEdits","query","disableLocalStorage","formatOptions","imageSizes","resizeOptions","staticDir","trimOptions","staticPath","filename","url","startsWith","filePath","response","uploadConfig","err","t","Error","message","undefined","sync","newData","filesToSave","fileData","fileIsAnimated","mimetype","cropData","crop","fileSupportsResize","fsSafeName","sharpFile","dimensions","fileBuffer","ext","mime","fileHasAdjustments","Boolean","tempFilePath","sharpOptions","animated","rotate","resize","toFormat","format","options","trim","width","height","metadata","toBuffer","resolveWithObject","info","filesize","size","pages","length","name","includes","split","pop","mimeType","baseFilename","substring","lastIndexOf","collectionSlug","slug","desiredFilename","fileForResize","croppedImage","push","buffer","path","promises","writeFile","Array","isArray","payloadUploadSizes","sizeData","sizesToSave","savedFilename","sizes","console","error"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAEA,OAAOA,cAAc,YAAW;AAChC,MAAM,EAAEC,UAAU,EAAE,GAAGD;AACvB,OAAOE,QAAQ,KAAI;AACnB,OAAOC,YAAY,SAAQ;AAC3B,OAAOC,cAAc,oBAAmB;AAOxC,S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,sFAAsF;YACtF,IAAIG,YAAYzC,QAAQQ,KAAKR,IAAI,CAACgE,MAAM,GAAG,GAAG;gBAC5C,IAAIxD,KAAKsC,YAAY,EAAE;oBACrB,MAAMhE,GAAGmG,QAAQ,CAACC,SAAS,CAAC1E,KAAKsC,YAAY,EAAEL,YAAYzC,QAAQQ,KAAKR,IAAI,EAAE,oCAAoC;;gBACpH,OAAO;oBACL,4DAA4D;oBAC5DE,IAAIM,IAAI,GAAG;wBACT,GAAGA,IAAI;wBACPR,MAAMyC,YAAYzC,QAAQQ,KAAKR,IAAI;wBACnC8D,MAAMrB,YAAYmB,KAAKE;oBACzB;gBACF;YACF;QACF;QAEA,IAAIqB,MAAMC,OAAO,CAACvE,eAAewB,sBAAsB/B,OAAO;YAC5DJ,IAAImF,kBAAkB,GAAG,CAAC;YAC1B,MAAM,EAAEC,QAAQ,EAAEC,WAAW,EAAE,GAAG,MAAM7F,6BAA6B;gBACnEI,QAAQC;gBACRyC,YAAY,CAACL,WACTK,aACA;oBACE,GAAGA,UAAU;oBACbgB,QAAQxB,SAASwB,MAAM;oBACvBD,OAAOvB,SAASuB,KAAK;gBACvB;gBACJ/C,MAAMoE;gBACNP,UAAUrC,SAASqC,QAAQ;gBAC3BnE;gBACAsF,eAAelD,cAAc9B,KAAKyD,IAAI;gBACtC3D;gBACAW;YACF;YAEAe,SAASyD,KAAK,GAAGH;YACjBvD,YAAY+C,IAAI,IAAIS;QACtB;IACF,EAAE,OAAO/D,KAAK;QACZkE,QAAQC,KAAK,CAACnE;QACd,MAAM,IAAItC,gBAAgBgB,IAAIuB,CAAC;IACjC;IAEAK,UAAU;QACR,GAAGA,OAAO;QACV,GAAGE,QAAQ;IACb;IAEA,OAAO;QACLhC,MAAM8B;QACNzB,OAAO0B;IACT;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/uploads/generateFileData.ts"],"sourcesContent":["import type { OutputInfo, Sharp, SharpOptions } from 'sharp'\n\nimport fileType from 'file-type'\nconst { fromBuffer } = fileType\nimport fs from 'fs'\nimport mkdirp from 'mkdirp'\nimport sanitize from 'sanitize-filename'\n\nimport type { Collection } from '../collections/config/types.js'\nimport type { SanitizedConfig } from '../config/types.js'\nimport type { PayloadRequestWithData } from '../types/index.js'\nimport type { FileData, FileToSave, ProbedImageSize, UploadEdits } from './types.js'\n\nimport { FileRetrievalError, FileUploadError, MissingFile } from '../errors/index.js'\nimport { canResizeImage } from './canResizeImage.js'\nimport { cropImage } from './cropImage.js'\nimport { getExternalFile } from './getExternalFile.js'\nimport { getFileByPath } from './getFileByPath.js'\nimport { getImageSize } from './getImageSize.js'\nimport { getSafeFileName } from './getSafeFilename.js'\nimport { resizeAndTransformImageSizes } from './imageResizer.js'\nimport { isImage } from './isImage.js'\n\ntype Args<T> = {\n collection: Collection\n config: SanitizedConfig\n data: T\n operation: 'create' | 'update'\n originalDoc?: T\n overwriteExistingFiles?: boolean\n req: PayloadRequestWithData\n throwOnMissingFile?: boolean\n}\n\ntype Result<T> = Promise<{\n data: T\n files: FileToSave[]\n}>\n\nexport const generateFileData = async <T>({\n collection: { config: collectionConfig },\n data,\n operation,\n originalDoc,\n overwriteExistingFiles,\n req,\n throwOnMissingFile,\n}: Args<T>): Result<T> => {\n if (!collectionConfig.upload) {\n return {\n data,\n files: [],\n }\n }\n\n const { sharp } = req.payload.config\n\n let file = req.file\n\n const uploadEdits = parseUploadEditsFromReqOrIncomingData({\n data,\n operation,\n originalDoc,\n req,\n })\n\n const {\n disableLocalStorage,\n focalPoint: focalPointEnabled = true,\n formatOptions,\n imageSizes,\n resizeOptions,\n staticDir,\n trimOptions,\n } = collectionConfig.upload\n\n const staticPath = staticDir\n\n if (!file && uploadEdits && data) {\n const { filename, url } = data as FileData\n\n try {\n if (url && url.startsWith('/') && !disableLocalStorage) {\n const filePath = `${staticPath}/${filename}`\n const response = await getFileByPath(filePath)\n file = response\n overwriteExistingFiles = true\n } else if (filename && url) {\n file = await getExternalFile({\n data: data as FileData,\n req,\n uploadConfig: collectionConfig.upload,\n })\n overwriteExistingFiles = true\n }\n } catch (err: unknown) {\n throw new FileRetrievalError(req.t, err instanceof Error ? err.message : undefined)\n }\n }\n\n if (!file) {\n if (throwOnMissingFile) throw new MissingFile(req.t)\n\n return {\n data,\n files: [],\n }\n }\n\n if (!disableLocalStorage) {\n mkdirp.sync(staticPath)\n }\n\n let newData = data\n const filesToSave: FileToSave[] = []\n const fileData: Partial<FileData> = {}\n const fileIsAnimated = file.mimetype === 'image/gif' || file.mimetype === 'image/webp'\n const cropData =\n typeof uploadEdits === 'object' && 'crop' in uploadEdits ? uploadEdits.crop : undefined\n\n try {\n const fileSupportsResize = canResizeImage(file.mimetype)\n let fsSafeName: string\n let sharpFile: Sharp | undefined\n let dimensions: ProbedImageSize | undefined\n let fileBuffer: { data: Buffer; info: OutputInfo }\n let ext\n let mime: string\n const fileHasAdjustments =\n fileSupportsResize &&\n Boolean(resizeOptions || formatOptions || trimOptions || file.tempFilePath)\n\n const sharpOptions: SharpOptions = {}\n\n if (fileIsAnimated) sharpOptions.animated = true\n\n if (fileHasAdjustments && sharp) {\n if (file.tempFilePath) {\n sharpFile = sharp(file.tempFilePath, sharpOptions).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081\n } else {\n sharpFile = sharp(file.data, sharpOptions).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081\n }\n\n if (resizeOptions) {\n sharpFile = sharpFile.resize(resizeOptions)\n }\n if (formatOptions) {\n sharpFile = sharpFile.toFormat(formatOptions.format, formatOptions.options)\n }\n if (trimOptions) {\n sharpFile = sharpFile.trim(trimOptions)\n }\n }\n\n if (fileSupportsResize || isImage(file.mimetype)) {\n dimensions = await getImageSize(file)\n fileData.width = dimensions.width\n fileData.height = dimensions.height\n }\n\n if (sharpFile) {\n const metadata = await sharpFile.metadata()\n fileBuffer = await sharpFile.toBuffer({ resolveWithObject: true })\n ;({ ext, mime } = await fromBuffer(fileBuffer.data)) // This is getting an incorrect gif height back.\n fileData.width = fileBuffer.info.width\n fileData.height = fileBuffer.info.height\n fileData.filesize = fileBuffer.info.size\n\n // Animated GIFs + WebP aggregate the height from every frame, so we need to use divide by number of pages\n if (metadata.pages) {\n fileData.height = fileBuffer.info.height / metadata.pages\n fileData.filesize = fileBuffer.data.length\n }\n } else {\n mime = file.mimetype\n fileData.filesize = file.size\n\n if (file.name.includes('.')) {\n ext = file.name.split('.').pop()\n } else {\n ext = ''\n }\n }\n\n // Adust SVG mime type. fromBuffer modifies it.\n if (mime === 'application/xml' && ext === 'svg') mime = 'image/svg+xml'\n fileData.mimeType = mime\n\n const baseFilename = sanitize(file.name.substring(0, file.name.lastIndexOf('.')) || file.name)\n fsSafeName = `${baseFilename}${ext ? `.${ext}` : ''}`\n\n if (!overwriteExistingFiles) {\n fsSafeName = await getSafeFileName({\n collectionSlug: collectionConfig.slug,\n desiredFilename: fsSafeName,\n req,\n staticPath,\n })\n }\n\n fileData.filename = fsSafeName\n let fileForResize = file\n\n if (cropData && sharp) {\n const { data: croppedImage, info } = await cropImage({ cropData, dimensions, file, sharp })\n\n filesToSave.push({\n buffer: croppedImage,\n path: `${staticPath}/${fsSafeName}`,\n })\n\n fileForResize = {\n ...file,\n data: croppedImage,\n size: info.size,\n }\n fileData.width = info.width\n fileData.height = info.height\n fileData.filesize = info.size\n\n if (file.tempFilePath) {\n await fs.promises.writeFile(file.tempFilePath, croppedImage) // write fileBuffer to the temp path\n } else {\n req.file = fileForResize\n }\n } else {\n filesToSave.push({\n buffer: fileBuffer?.data || file.data,\n path: `${staticPath}/${fsSafeName}`,\n })\n\n // If using temp files and the image is being resized, write the file to the temp path\n if (fileBuffer?.data || file.data.length > 0) {\n if (file.tempFilePath) {\n await fs.promises.writeFile(file.tempFilePath, fileBuffer?.data || file.data) // write fileBuffer to the temp path\n } else {\n // Assign the _possibly modified_ file to the request object\n req.file = {\n ...file,\n data: fileBuffer?.data || file.data,\n size: fileBuffer?.info.size,\n }\n }\n }\n }\n\n if (fileSupportsResize && (Array.isArray(imageSizes) || focalPointEnabled !== false)) {\n req.payloadUploadSizes = {}\n const { focalPoint, sizeData, sizesToSave } = await resizeAndTransformImageSizes({\n config: collectionConfig,\n dimensions: !cropData\n ? dimensions\n : {\n ...dimensions,\n height: fileData.height,\n width: fileData.width,\n },\n file: fileForResize,\n mimeType: fileData.mimeType,\n req,\n savedFilename: fsSafeName || file.name,\n sharp,\n staticPath,\n uploadEdits,\n })\n\n fileData.sizes = sizeData\n fileData.focalX = focalPoint?.x\n fileData.focalY = focalPoint?.y\n filesToSave.push(...sizesToSave)\n }\n } catch (err) {\n req.payload.logger.error(err)\n throw new FileUploadError(req.t)\n }\n\n newData = {\n ...newData,\n ...fileData,\n }\n\n return {\n data: newData,\n files: filesToSave,\n }\n}\n\n/**\n * Parse upload edits from req or incoming data\n */\nfunction parseUploadEditsFromReqOrIncomingData(args: {\n data: unknown\n operation: 'create' | 'update'\n originalDoc: unknown\n req: PayloadRequestWithData\n}): UploadEdits {\n const { data, operation, originalDoc, req } = args\n\n // Get intended focal point change from query string or incoming data\n const {\n uploadEdits = {},\n }: {\n uploadEdits?: UploadEdits\n } = req.query || {}\n\n if (uploadEdits.focalPoint) return uploadEdits\n\n const incomingData = data as FileData\n const origDoc = originalDoc as FileData\n\n // If no change in focal point, return undefined.\n // This prevents a refocal operation triggered from admin, because it always sends the focal point.\n if (origDoc && incomingData.focalX === origDoc.focalX && incomingData.focalY === origDoc.focalY) {\n return undefined\n }\n\n if (incomingData?.focalX && incomingData?.focalY) {\n uploadEdits.focalPoint = {\n x: incomingData.focalX,\n y: incomingData.focalY,\n }\n return uploadEdits\n }\n\n // If no focal point is set, default to center\n if (operation === 'create') {\n uploadEdits.focalPoint = {\n x: 50,\n y: 50,\n }\n }\n return uploadEdits\n}\n"],"names":["fileType","fromBuffer","fs","mkdirp","sanitize","FileRetrievalError","FileUploadError","MissingFile","canResizeImage","cropImage","getExternalFile","getFileByPath","getImageSize","getSafeFileName","resizeAndTransformImageSizes","isImage","generateFileData","collection","config","collectionConfig","data","operation","originalDoc","overwriteExistingFiles","req","throwOnMissingFile","upload","files","sharp","payload","file","uploadEdits","parseUploadEditsFromReqOrIncomingData","disableLocalStorage","focalPoint","focalPointEnabled","formatOptions","imageSizes","resizeOptions","staticDir","trimOptions","staticPath","filename","url","startsWith","filePath","response","uploadConfig","err","t","Error","message","undefined","sync","newData","filesToSave","fileData","fileIsAnimated","mimetype","cropData","crop","fileSupportsResize","fsSafeName","sharpFile","dimensions","fileBuffer","ext","mime","fileHasAdjustments","Boolean","tempFilePath","sharpOptions","animated","rotate","resize","toFormat","format","options","trim","width","height","metadata","toBuffer","resolveWithObject","info","filesize","size","pages","length","name","includes","split","pop","mimeType","baseFilename","substring","lastIndexOf","collectionSlug","slug","desiredFilename","fileForResize","croppedImage","push","buffer","path","promises","writeFile","Array","isArray","payloadUploadSizes","sizeData","sizesToSave","savedFilename","sizes","focalX","x","focalY","y","logger","error","args","query","incomingData","origDoc"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAEA,OAAOA,cAAc,YAAW;AAChC,MAAM,EAAEC,UAAU,EAAE,GAAGD;AACvB,OAAOE,QAAQ,KAAI;AACnB,OAAOC,YAAY,SAAQ;AAC3B,OAAOC,cAAc,oBAAmB;AAOxC,SAASC,kBAAkB,EAAEC,eAAe,EAAEC,WAAW,QAAQ,qBAAoB;AACrF,SAASC,cAAc,QAAQ,sBAAqB;AACpD,SAASC,SAAS,QAAQ,iBAAgB;AAC1C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CAAsCwF,IAK9C;IACC,MAAM,EAAEpG,IAAI,EAAEC,SAAS,EAAEC,WAAW,EAAEE,GAAG,EAAE,GAAGgG;IAE9C,qEAAqE;IACrE,MAAM,EACJzF,cAAc,CAAC,CAAC,EACjB,GAEGP,IAAIiG,KAAK,IAAI,CAAC;IAElB,IAAI1F,YAAYG,UAAU,EAAE,OAAOH;IAEnC,MAAM2F,eAAetG;IACrB,MAAMuG,UAAUrG;IAEhB,iDAAiD;IACjD,mGAAmG;IACnG,IAAIqG,WAAWD,aAAaR,MAAM,KAAKS,QAAQT,MAAM,IAAIQ,aAAaN,MAAM,KAAKO,QAAQP,MAAM,EAAE;QAC/F,OAAOhE;IACT;IAEA,IAAIsE,cAAcR,UAAUQ,cAAcN,QAAQ;QAChDrF,YAAYG,UAAU,GAAG;YACvBiF,GAAGO,aAAaR,MAAM;YACtBG,GAAGK,aAAaN,MAAM;QACxB;QACA,OAAOrF;IACT;IAEA,8CAA8C;IAC9C,IAAIV,cAAc,UAAU;QAC1BU,YAAYG,UAAU,GAAG;YACvBiF,GAAG;YACHE,GAAG;QACL;IACF;IACA,OAAOtF;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getBaseFields.d.ts","sourceRoot":"","sources":["../../src/uploads/getBaseFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAA;AACtE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAChD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAA;AAiBtD,KAAK,OAAO,GAAG;IACb,UAAU,EAAE,gBAAgB,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAA;CACf,CAAA;AAED,eAAO,MAAM,mBAAmB,2BAA4B,OAAO,KAAG,KAAK,
|
|
1
|
+
{"version":3,"file":"getBaseFields.d.ts","sourceRoot":"","sources":["../../src/uploads/getBaseFields.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gCAAgC,CAAA;AACtE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAChD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,2BAA2B,CAAA;AAiBtD,KAAK,OAAO,GAAG;IACb,UAAU,EAAE,gBAAgB,CAAA;IAC5B,MAAM,EAAE,MAAM,CAAA;CACf,CAAA;AAED,eAAO,MAAM,mBAAmB,2BAA4B,OAAO,KAAG,KAAK,EAuM1E,CAAA"}
|
|
@@ -116,6 +116,21 @@ export const getBaseUploadFields = ({ collection, config })=>{
|
|
|
116
116
|
width,
|
|
117
117
|
height
|
|
118
118
|
];
|
|
119
|
+
// Add focal point fields if not disabled
|
|
120
|
+
if (uploadOptions.focalPoint !== false || uploadOptions.imageSizes || uploadOptions.resizeOptions) {
|
|
121
|
+
uploadFields = uploadFields.concat([
|
|
122
|
+
'focalX',
|
|
123
|
+
'focalY'
|
|
124
|
+
].map((name)=>{
|
|
125
|
+
return {
|
|
126
|
+
name,
|
|
127
|
+
type: 'number',
|
|
128
|
+
admin: {
|
|
129
|
+
hidden: true
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}));
|
|
133
|
+
}
|
|
119
134
|
if (uploadOptions.mimeTypes) {
|
|
120
135
|
mimeType.validate = mimeTypeValidator(uploadOptions.mimeTypes);
|
|
121
136
|
}
|