payload 3.0.0-beta.46 → 3.0.0-beta.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/admin/views/types.d.ts +1 -1
  2. package/dist/admin/views/types.d.ts.map +1 -1
  3. package/dist/admin/views/types.js.map +1 -1
  4. package/dist/auth/operations/local/login.d.ts +1 -2
  5. package/dist/auth/operations/local/login.d.ts.map +1 -1
  6. package/dist/auth/operations/local/login.js.map +1 -1
  7. package/dist/auth/operations/local/resetPassword.d.ts +1 -2
  8. package/dist/auth/operations/local/resetPassword.d.ts.map +1 -1
  9. package/dist/auth/operations/local/resetPassword.js.map +1 -1
  10. package/dist/auth/operations/local/unlock.d.ts +1 -2
  11. package/dist/auth/operations/local/unlock.d.ts.map +1 -1
  12. package/dist/auth/operations/local/unlock.js.map +1 -1
  13. package/dist/auth/operations/local/verifyEmail.d.ts +1 -2
  14. package/dist/auth/operations/local/verifyEmail.d.ts.map +1 -1
  15. package/dist/auth/operations/local/verifyEmail.js.map +1 -1
  16. package/dist/auth/operations/refresh.d.ts +1 -2
  17. package/dist/auth/operations/refresh.d.ts.map +1 -1
  18. package/dist/auth/operations/refresh.js.map +1 -1
  19. package/dist/collections/operations/local/create.d.ts +1 -2
  20. package/dist/collections/operations/local/create.d.ts.map +1 -1
  21. package/dist/collections/operations/local/create.js.map +1 -1
  22. package/dist/collections/operations/local/delete.d.ts +2 -4
  23. package/dist/collections/operations/local/delete.d.ts.map +1 -1
  24. package/dist/collections/operations/local/delete.js.map +1 -1
  25. package/dist/config/defaults.js +1 -1
  26. package/dist/config/defaults.js.map +1 -1
  27. package/dist/config/schema.d.ts.map +1 -1
  28. package/dist/config/schema.js +9 -1
  29. package/dist/config/schema.js.map +1 -1
  30. package/dist/config/shared/openGraphSchema.js +2 -2
  31. package/dist/config/shared/openGraphSchema.js.map +1 -1
  32. package/dist/config/types.d.ts +1 -1
  33. package/dist/config/types.d.ts.map +1 -1
  34. package/dist/config/types.js.map +1 -1
  35. package/dist/globals/config/types.d.ts +1 -2
  36. package/dist/globals/config/types.d.ts.map +1 -1
  37. package/dist/globals/config/types.js.map +1 -1
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +4 -0
  40. package/dist/index.js.map +1 -1
  41. package/dist/uploads/cropImage.js +2 -2
  42. package/dist/uploads/cropImage.js.map +1 -1
  43. package/dist/uploads/generateFileData.js +4 -4
  44. package/dist/uploads/generateFileData.js.map +1 -1
  45. package/dist/uploads/getBaseFields.js +1 -1
  46. package/dist/uploads/getBaseFields.js.map +1 -1
  47. package/dist/uploads/imageResizer.d.ts.map +1 -1
  48. package/dist/uploads/imageResizer.js +21 -11
  49. package/dist/uploads/imageResizer.js.map +1 -1
  50. package/package.json +2 -2
@@ -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 { 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 /**\n * Automatically generate types during development\n * @default true\n */\n autoGenerate?: boolean\n\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\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"}
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 /**\n * Automatically generate types during development\n * @default true\n */\n autoGenerate?: boolean\n\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\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"}
@@ -4,8 +4,7 @@ import type { CustomPreviewButton, CustomPublishButton, CustomSaveButton, Custom
4
4
  import type { Access, EditConfig, Endpoint, EntityDescription, EntityDescriptionComponent, GeneratePreviewURL, LivePreviewConfig, OpenGraphConfig } from '../../config/types.js';
5
5
  import type { DBIdentifierName } from '../../database/types.js';
6
6
  import type { Field } from '../../fields/config/types.js';
7
- import type { PayloadRequestWithData, RequestContext } from '../../types/index.js';
8
- import type { Where } from '../../types/index.js';
7
+ import type { PayloadRequestWithData, RequestContext, Where } from '../../types/index.js';
9
8
  import type { IncomingGlobalVersions, SanitizedGlobalVersions } from '../../versions/types.js';
10
9
  export type TypeWithID = {
11
10
  id: number | string;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/globals/config/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAA;AAChE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAA;AAEjD,OAAO,KAAK,EACV,mBAAmB,EACnB,mBAAmB,EACnB,gBAAgB,EAChB,qBAAqB,EACtB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,KAAK,EACV,MAAM,EACN,UAAU,EACV,QAAQ,EACR,iBAAiB,EACjB,0BAA0B,EAC1B,kBAAkB,EAClB,iBAAiB,EACjB,eAAe,EAChB,MAAM,uBAAuB,CAAA;AAC9B,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAA;AAC/D,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAA;AACzD,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AAClF,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAA;AACjD,OAAO,KAAK,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAA;AAE9F,MAAM,MAAM,UAAU,GAAG;IACvB,EAAE,EAAE,MAAM,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Ac,CAAC,GAAG,CAAC,CAAA;YACtC,IAAI,EAAE,iBAAiB,CAAA;YACvB,WAAW,CAAC,EAAE,iBAAiB,CAAA;SAChC,CAAA;KACF,GACD,KAAK,CAAA;CACV,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/globals/config/types.ts"],"sourcesContent":["import type { GraphQLNonNull, GraphQLObjectType } from 'graphql'\nimport type { DeepRequired } from 'ts-essentials'\n\nimport type {\n CustomPreviewButton,\n CustomPublishButton,\n CustomSaveButton,\n CustomSaveDraftButton,\n} from '../../admin/types.js'\nimport type {\n Access,\n EditConfig,\n Endpoint,\n EntityDescription,\n EntityDescriptionComponent,\n GeneratePreviewURL,\n LivePreviewConfig,\n OpenGraphConfig,\n} from '../../config/types.js'\nimport type { DBIdentifierName } from '../../database/types.js'\nimport type { Field } from '../../fields/config/types.js'\nimport type { PayloadRequestWithData, RequestContext } from '../../types/index.js'\nimport type { Where } from '../../types/index.js'\nimport type { IncomingGlobalVersions, SanitizedGlobalVersions } from '../../versions/types.js'\n\nexport type TypeWithID = {\n id: number | string\n}\n\nexport type BeforeValidateHook = (args: {\n context: RequestContext\n data?: any\n /** The global which this hook is being run on */\n global: SanitizedGlobalConfig\n originalDoc?: any\n req: PayloadRequestWithData\n}) => any\n\nexport type BeforeChangeHook = (args: {\n context: RequestContext\n data: any\n /** The global which this hook is being run on */\n global: SanitizedGlobalConfig\n originalDoc?: any\n req: PayloadRequestWithData\n}) => any\n\nexport type AfterChangeHook = (args: {\n context: RequestContext\n doc: any\n /** The global which this hook is being run on */\n global: SanitizedGlobalConfig\n previousDoc: any\n req: PayloadRequestWithData\n}) => any\n\nexport type BeforeReadHook = (args: {\n context: RequestContext\n doc: any\n /** The global which this hook is being run on */\n global: SanitizedGlobalConfig\n req: PayloadRequestWithData\n}) => any\n\nexport type AfterReadHook = (args: {\n context: RequestContext\n doc: any\n findMany?: boolean\n /** The global which this hook is being run on */\n global: SanitizedGlobalConfig\n query?: Where\n req: PayloadRequestWithData\n}) => any\n\nexport type GlobalAdminOptions = {\n /**\n * Custom admin components\n */\n components?: {\n elements?: {\n Description?: EntityDescriptionComponent\n /**\n * Replaces the \"Preview\" button\n */\n PreviewButton?: CustomPreviewButton\n /**\n * Replaces the \"Publish\" button\n * + drafts must be enabled\n */\n PublishButton?: CustomPublishButton\n /**\n * Replaces the \"Save\" button\n * + drafts must be disabled\n */\n SaveButton?: CustomSaveButton\n /**\n * Replaces the \"Save Draft\" button\n * + drafts must be enabled\n * + autosave must be disabled\n */\n SaveDraftButton?: CustomSaveDraftButton\n }\n views?: {\n /**\n * Set to a React component to replace the entire \"Edit\" view, including all nested routes.\n * Set to an object to replace or modify individual nested routes, or to add new ones.\n */\n Edit?: EditConfig\n }\n }\n /** Extension point to add your custom data. Available in server and client. */\n custom?: Record<string, any>\n /**\n * Custom description for collection\n */\n description?: EntityDescription\n /**\n * Place globals into a navigational group\n * */\n group?: Record<string, string> | string\n /**\n * Exclude the global from the admin nav and routes\n */\n hidden?: ((args: { user: PayloadRequestWithData['user'] }) => boolean) | boolean\n /**\n * Hide the API URL within the Edit view\n */\n hideAPIURL?: boolean\n /**\n * Live preview options\n */\n livePreview?: LivePreviewConfig\n meta?: {\n description?: string\n openGraph?: OpenGraphConfig\n }\n /**\n * Function to generate custom preview URL\n */\n preview?: GeneratePreviewURL\n}\n\nexport type GlobalConfig = {\n access?: {\n read?: Access\n readDrafts?: Access\n readVersions?: Access\n update?: Access\n }\n admin?: GlobalAdminOptions\n /** Extension point to add your custom data. Server only. */\n custom?: Record<string, any>\n /**\n * Customize the SQL table name\n */\n dbName?: DBIdentifierName\n endpoints?: Omit<Endpoint, 'root'>[] | false\n fields: Field[]\n graphQL?:\n | {\n name?: string\n }\n | false\n hooks?: {\n afterChange?: AfterChangeHook[]\n afterRead?: AfterReadHook[]\n beforeChange?: BeforeChangeHook[]\n beforeRead?: BeforeReadHook[]\n beforeValidate?: BeforeValidateHook[]\n }\n label?: Record<string, string> | string\n slug: string\n /**\n * Options used in typescript generation\n */\n typescript?: {\n /**\n * Typescript generation name given to the interface type\n */\n interface?: string\n }\n versions?: IncomingGlobalVersions | boolean\n}\n\nexport interface SanitizedGlobalConfig\n extends Omit<DeepRequired<GlobalConfig>, 'endpoints' | 'fields' | 'versions'> {\n endpoints: Endpoint[] | false\n fields: Field[]\n versions: SanitizedGlobalVersions\n}\n\nexport type Globals = {\n config: SanitizedGlobalConfig[]\n graphQL?:\n | {\n [slug: string]: {\n mutationInputType: GraphQLNonNull<any>\n type: GraphQLObjectType\n versionType?: GraphQLObjectType\n }\n }\n | false\n}\n"],"names":[],"rangeMappings":"","mappings":"AA+LA,WAWC"}
1
+ {"version":3,"sources":["../../../src/globals/config/types.ts"],"sourcesContent":["import type { GraphQLNonNull, GraphQLObjectType } from 'graphql'\nimport type { DeepRequired } from 'ts-essentials'\n\nimport type {\n CustomPreviewButton,\n CustomPublishButton,\n CustomSaveButton,\n CustomSaveDraftButton,\n} from '../../admin/types.js'\nimport type {\n Access,\n EditConfig,\n Endpoint,\n EntityDescription,\n EntityDescriptionComponent,\n GeneratePreviewURL,\n LivePreviewConfig,\n OpenGraphConfig,\n} from '../../config/types.js'\nimport type { DBIdentifierName } from '../../database/types.js'\nimport type { Field } from '../../fields/config/types.js'\nimport type { PayloadRequestWithData, RequestContext , Where } from '../../types/index.js'\nimport type { IncomingGlobalVersions, SanitizedGlobalVersions } from '../../versions/types.js'\n\nexport type TypeWithID = {\n id: number | string\n}\n\nexport type BeforeValidateHook = (args: {\n context: RequestContext\n data?: any\n /** The global which this hook is being run on */\n global: SanitizedGlobalConfig\n originalDoc?: any\n req: PayloadRequestWithData\n}) => any\n\nexport type BeforeChangeHook = (args: {\n context: RequestContext\n data: any\n /** The global which this hook is being run on */\n global: SanitizedGlobalConfig\n originalDoc?: any\n req: PayloadRequestWithData\n}) => any\n\nexport type AfterChangeHook = (args: {\n context: RequestContext\n doc: any\n /** The global which this hook is being run on */\n global: SanitizedGlobalConfig\n previousDoc: any\n req: PayloadRequestWithData\n}) => any\n\nexport type BeforeReadHook = (args: {\n context: RequestContext\n doc: any\n /** The global which this hook is being run on */\n global: SanitizedGlobalConfig\n req: PayloadRequestWithData\n}) => any\n\nexport type AfterReadHook = (args: {\n context: RequestContext\n doc: any\n findMany?: boolean\n /** The global which this hook is being run on */\n global: SanitizedGlobalConfig\n query?: Where\n req: PayloadRequestWithData\n}) => any\n\nexport type GlobalAdminOptions = {\n /**\n * Custom admin components\n */\n components?: {\n elements?: {\n Description?: EntityDescriptionComponent\n /**\n * Replaces the \"Preview\" button\n */\n PreviewButton?: CustomPreviewButton\n /**\n * Replaces the \"Publish\" button\n * + drafts must be enabled\n */\n PublishButton?: CustomPublishButton\n /**\n * Replaces the \"Save\" button\n * + drafts must be disabled\n */\n SaveButton?: CustomSaveButton\n /**\n * Replaces the \"Save Draft\" button\n * + drafts must be enabled\n * + autosave must be disabled\n */\n SaveDraftButton?: CustomSaveDraftButton\n }\n views?: {\n /**\n * Set to a React component to replace the entire \"Edit\" view, including all nested routes.\n * Set to an object to replace or modify individual nested routes, or to add new ones.\n */\n Edit?: EditConfig\n }\n }\n /** Extension point to add your custom data. Available in server and client. */\n custom?: Record<string, any>\n /**\n * Custom description for collection\n */\n description?: EntityDescription\n /**\n * Place globals into a navigational group\n * */\n group?: Record<string, string> | string\n /**\n * Exclude the global from the admin nav and routes\n */\n hidden?: ((args: { user: PayloadRequestWithData['user'] }) => boolean) | boolean\n /**\n * Hide the API URL within the Edit view\n */\n hideAPIURL?: boolean\n /**\n * Live preview options\n */\n livePreview?: LivePreviewConfig\n meta?: {\n description?: string\n openGraph?: OpenGraphConfig\n }\n /**\n * Function to generate custom preview URL\n */\n preview?: GeneratePreviewURL\n}\n\nexport type GlobalConfig = {\n access?: {\n read?: Access\n readDrafts?: Access\n readVersions?: Access\n update?: Access\n }\n admin?: GlobalAdminOptions\n /** Extension point to add your custom data. Server only. */\n custom?: Record<string, any>\n /**\n * Customize the SQL table name\n */\n dbName?: DBIdentifierName\n endpoints?: Omit<Endpoint, 'root'>[] | false\n fields: Field[]\n graphQL?:\n | {\n name?: string\n }\n | false\n hooks?: {\n afterChange?: AfterChangeHook[]\n afterRead?: AfterReadHook[]\n beforeChange?: BeforeChangeHook[]\n beforeRead?: BeforeReadHook[]\n beforeValidate?: BeforeValidateHook[]\n }\n label?: Record<string, string> | string\n slug: string\n /**\n * Options used in typescript generation\n */\n typescript?: {\n /**\n * Typescript generation name given to the interface type\n */\n interface?: string\n }\n versions?: IncomingGlobalVersions | boolean\n}\n\nexport interface SanitizedGlobalConfig\n extends Omit<DeepRequired<GlobalConfig>, 'endpoints' | 'fields' | 'versions'> {\n endpoints: Endpoint[] | false\n fields: Field[]\n versions: SanitizedGlobalVersions\n}\n\nexport type Globals = {\n config: SanitizedGlobalConfig[]\n graphQL?:\n | {\n [slug: string]: {\n mutationInputType: GraphQLNonNull<any>\n type: GraphQLObjectType\n versionType?: GraphQLObjectType\n }\n }\n | false\n}\n"],"names":[],"rangeMappings":"","mappings":"AA8LA,WAWC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,SAAS,CAAA;AAC7E,OAAO,KAAK,EAAE,aAAa,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,cAAc,CAAA;AAC5E,OAAO,KAAK,IAAI,MAAM,MAAM,CAAA;AAO5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAA;AACzD,OAAO,KAAK,EAAE,MAAM,IAAI,oBAAoB,EAAE,MAAM,qCAAqC,CAAA;AACzF,OAAO,KAAK,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,2CAA2C,CAAA;AACjG,OAAO,KAAK,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,kCAAkC,CAAA;AAC/E,OAAO,KAAK,EAAE,OAAO,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,6 +247,10 @@ const dirname = path.dirname(filename);
247
247
  payload: this
248
248
  });
249
249
  }
250
+ // Warn if image resizing is enabled but sharp is not installed
251
+ if (!this.config.sharp && this.config.collections.some((c)=>c.upload.imageSizes || c.upload.formatOptions)) {
252
+ this.logger.warn(`Image resizing is enabled for one or more collections, but sharp not installed. Please install 'sharp' and pass into the config.`);
253
+ }
250
254
  this.sendEmail = this.email['sendEmail'];
251
255
  serverInitTelemetry(this);
252
256
  // 1. loop over collections, if collection has auth strategy, initialize and push to array
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { ExecutionResult, GraphQLSchema, ValidationRule } from 'graphql'\nimport type { OperationArgs, Request as graphQLRequest } from 'graphql-http'\nimport type pino from 'pino'\n\nimport { spawn } from 'child_process'\nimport crypto from 'crypto'\nimport { fileURLToPath } from 'node:url'\nimport path from 'path'\n\nimport type { AuthArgs } from './auth/operations/auth.js'\nimport type { Result as ForgotPasswordResult } from './auth/operations/forgotPassword.js'\nimport type { Options as ForgotPasswordOptions } from './auth/operations/local/forgotPassword.js'\nimport type { Options as LoginOptions } from './auth/operations/local/login.js'\nimport type { Options as ResetPasswordOptions } from './auth/operations/local/resetPassword.js'\nimport type { Options as UnlockOptions } from './auth/operations/local/unlock.js'\nimport type { Options as VerifyEmailOptions } from './auth/operations/local/verifyEmail.js'\nimport type { Result as LoginResult } from './auth/operations/login.js'\nimport type { Result as ResetPasswordResult } from './auth/operations/resetPassword.js'\nimport type { AuthStrategy, User } from './auth/types.js'\nimport type { BulkOperationResult, Collection, TypeWithID } from './collections/config/types.js'\nimport type { Options as CountOptions } from './collections/operations/local/count.js'\nimport type { Options as CreateOptions } from './collections/operations/local/create.js'\nimport type {\n ByIDOptions as DeleteByIDOptions,\n ManyOptions as DeleteManyOptions,\n Options as DeleteOptions,\n} from './collections/operations/local/delete.js'\nimport type { Options as DuplicateOptions } from './collections/operations/local/duplicate.js'\nimport type { Options as FindOptions } from './collections/operations/local/find.js'\nimport type { Options as FindByIDOptions } from './collections/operations/local/findByID.js'\nimport type { Options as FindVersionByIDOptions } from './collections/operations/local/findVersionByID.js'\nimport type { Options as FindVersionsOptions } from './collections/operations/local/findVersions.js'\nimport type { Options as RestoreVersionOptions } from './collections/operations/local/restoreVersion.js'\nimport type {\n ByIDOptions as UpdateByIDOptions,\n ManyOptions as UpdateManyOptions,\n Options as UpdateOptions,\n} from './collections/operations/local/update.js'\nimport type { InitOptions, SanitizedConfig } from './config/types.js'\nimport type { BaseDatabaseAdapter, PaginatedDocs } from './database/types.js'\nimport type { InitializedEmailAdapter } from './email/types.js'\nimport type { TypeWithID as GlobalTypeWithID, Globals } from './globals/config/types.js'\nimport type { Options as FindGlobalOptions } from './globals/operations/local/findOne.js'\nimport type { Options as FindGlobalVersionByIDOptions } from './globals/operations/local/findVersionByID.js'\nimport type { Options as FindGlobalVersionsOptions } from './globals/operations/local/findVersions.js'\nimport type { Options as RestoreGlobalVersionOptions } from './globals/operations/local/restoreVersion.js'\nimport type { Options as UpdateGlobalOptions } from './globals/operations/local/update.js'\nimport type { TypeWithVersion } from './versions/types.js'\n\nimport { decrypt, encrypt } from './auth/crypto.js'\nimport { APIKeyAuthentication } from './auth/strategies/apiKey.js'\nimport { JWTAuthentication } from './auth/strategies/jwt.js'\nimport localOperations from './collections/operations/local/index.js'\nimport { validateSchema } from './config/validate.js'\nimport { consoleEmailAdapter } from './email/consoleEmailAdapter.js'\nimport { fieldAffectsData } from './fields/config/types.js'\nimport localGlobalOperations from './globals/operations/local/index.js'\nimport flattenFields from './utilities/flattenTopLevelFields.js'\nimport Logger from './utilities/logger.js'\nimport { serverInit as serverInitTelemetry } from './utilities/telemetry/events/serverInit.js'\n\nconst filename = fileURLToPath(import.meta.url)\nconst dirname = path.dirname(filename)\n\n/**\n * @description Payload\n */\nexport class BasePayload<TGeneratedTypes extends GeneratedTypes> {\n /**\n * @description Authorization and Authentication using headers and cookies to run auth user strategies\n * @returns cookies: Map<string, string>\n * @returns permissions: Permissions\n * @returns user: User\n */\n auth = async (options: AuthArgs) => {\n const { auth } = localOperations.auth\n return auth(this, options)\n }\n\n authStrategies: AuthStrategy[]\n\n collections: {\n [slug: number | string | symbol]: Collection\n } = {}\n\n config: SanitizedConfig\n\n /**\n * @description Performs count operation\n * @param options\n * @returns count of documents satisfying query\n */\n count = async <T extends keyof TGeneratedTypes['collections']>(\n options: CountOptions<T>,\n ): Promise<{ totalDocs: number }> => {\n const { count } = localOperations\n return count(this, options)\n }\n\n /**\n * @description Performs create operation\n * @param options\n * @returns created document\n */\n create = async <T extends keyof TGeneratedTypes['collections']>(\n options: CreateOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]> => {\n const { create } = localOperations\n return create<T>(this, options)\n }\n db: DatabaseAdapter\n\n decrypt = decrypt\n\n duplicate = async <T extends keyof TGeneratedTypes['collections']>(\n options: DuplicateOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]> => {\n const { duplicate } = localOperations\n return duplicate<T>(this, options)\n }\n\n email: InitializedEmailAdapter\n\n // TODO: re-implement or remove?\n // errorHandler: ErrorHandler\n\n encrypt = encrypt\n\n extensions: (args: {\n args: OperationArgs<any>\n req: graphQLRequest<unknown, unknown>\n result: ExecutionResult\n }) => Promise<any>\n\n /**\n * @description Find documents with criteria\n * @param options\n * @returns documents satisfying query\n */\n find = async <T extends keyof TGeneratedTypes['collections']>(\n options: FindOptions<T>,\n ): Promise<PaginatedDocs<TGeneratedTypes['collections'][T]>> => {\n const { find } = localOperations\n return find<T>(this, options)\n }\n\n /**\n * @description Find document by ID\n * @param options\n * @returns document with specified ID\n */\n findByID = async <T extends keyof TGeneratedTypes['collections']>(\n options: FindByIDOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]> => {\n const { findByID } = localOperations\n return findByID<T>(this, options)\n }\n\n findGlobal = async <T extends keyof TGeneratedTypes['globals']>(\n options: FindGlobalOptions<T>,\n ): Promise<TGeneratedTypes['globals'][T]> => {\n const { findOne } = localGlobalOperations\n return findOne<T>(this, options)\n }\n\n /**\n * @description Find global version by ID\n * @param options\n * @returns global version with specified ID\n */\n findGlobalVersionByID = async <T extends keyof TGeneratedTypes['globals']>(\n options: FindGlobalVersionByIDOptions<T>,\n ): Promise<TypeWithVersion<TGeneratedTypes['globals'][T]>> => {\n const { findVersionByID } = localGlobalOperations\n return findVersionByID<T>(this, options)\n }\n\n /**\n * @description Find global versions with criteria\n * @param options\n * @returns versions satisfying query\n */\n findGlobalVersions = async <T extends keyof TGeneratedTypes['globals']>(\n options: FindGlobalVersionsOptions<T>,\n ): Promise<PaginatedDocs<TypeWithVersion<TGeneratedTypes['globals'][T]>>> => {\n const { findVersions } = localGlobalOperations\n return findVersions<T>(this, options)\n }\n\n /**\n * @description Find version by ID\n * @param options\n * @returns version with specified ID\n */\n findVersionByID = async <T extends keyof TGeneratedTypes['collections']>(\n options: FindVersionByIDOptions<T>,\n ): Promise<TypeWithVersion<TGeneratedTypes['collections'][T]>> => {\n const { findVersionByID } = localOperations\n return findVersionByID<T>(this, options)\n }\n\n /**\n * @description Find versions with criteria\n * @param options\n * @returns versions satisfying query\n */\n findVersions = async <T extends keyof TGeneratedTypes['collections']>(\n options: FindVersionsOptions<T>,\n ): Promise<PaginatedDocs<TypeWithVersion<TGeneratedTypes['collections'][T]>>> => {\n const { findVersions } = localOperations\n return findVersions<T>(this, options)\n }\n\n forgotPassword = async <T extends keyof TGeneratedTypes['collections']>(\n options: ForgotPasswordOptions<T>,\n ): Promise<ForgotPasswordResult> => {\n const { forgotPassword } = localOperations.auth\n return forgotPassword<T>(this, options)\n }\n\n getAPIURL = (): string => `${this.config.serverURL}${this.config.routes.api}`\n\n getAdminURL = (): string => `${this.config.serverURL}${this.config.routes.admin}`\n\n globals: Globals\n\n logger: pino.Logger\n\n login = async <T extends keyof TGeneratedTypes['collections']>(\n options: LoginOptions<T>,\n ): Promise<LoginResult & { user: TGeneratedTypes['collections'][T] }> => {\n const { login } = localOperations.auth\n return login<T>(this, options)\n }\n\n resetPassword = async <T extends keyof TGeneratedTypes['collections']>(\n options: ResetPasswordOptions<T>,\n ): Promise<ResetPasswordResult> => {\n const { resetPassword } = localOperations.auth\n return resetPassword<T>(this, options)\n }\n\n /**\n * @description Restore global version by ID\n * @param options\n * @returns version with specified ID\n */\n restoreGlobalVersion = async <T extends keyof TGeneratedTypes['globals']>(\n options: RestoreGlobalVersionOptions<T>,\n ): Promise<TGeneratedTypes['globals'][T]> => {\n const { restoreVersion } = localGlobalOperations\n return restoreVersion<T>(this, options)\n }\n\n /**\n * @description Restore version by ID\n * @param options\n * @returns version with specified ID\n */\n restoreVersion = async <T extends keyof TGeneratedTypes['collections']>(\n options: RestoreVersionOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]> => {\n const { restoreVersion } = localOperations\n return restoreVersion<T>(this, options)\n }\n\n schema: GraphQLSchema\n\n secret: string\n\n sendEmail: InitializedEmailAdapter['sendEmail']\n\n types: {\n arrayTypes: any\n blockInputTypes: any\n blockTypes: any\n fallbackLocaleInputType?: any\n groupTypes: any\n localeInputType?: any\n tabTypes: any\n }\n\n unlock = async <T extends keyof TGeneratedTypes['collections']>(\n options: UnlockOptions<T>,\n ): Promise<boolean> => {\n const { unlock } = localOperations.auth\n return unlock(this, options)\n }\n\n updateGlobal = async <T extends keyof TGeneratedTypes['globals']>(\n options: UpdateGlobalOptions<T>,\n ): Promise<TGeneratedTypes['globals'][T]> => {\n const { update } = localGlobalOperations\n return update<T>(this, options)\n }\n\n validationRules: (args: OperationArgs<any>) => ValidationRule[]\n\n verifyEmail = async <T extends keyof TGeneratedTypes['collections']>(\n options: VerifyEmailOptions<T>,\n ): Promise<boolean> => {\n const { verifyEmail } = localOperations.auth\n return verifyEmail(this, options)\n }\n\n versions: {\n [slug: string]: any // TODO: Type this\n } = {}\n\n async bin({\n args,\n cwd,\n log,\n }: {\n args: string[]\n cwd?: string\n log?: boolean\n }): Promise<{ code: number }> {\n return new Promise((resolve, reject) => {\n const spawned = spawn('node', [path.resolve(dirname, '../bin.js'), ...args], {\n cwd,\n stdio: log || log === undefined ? 'inherit' : 'ignore',\n })\n\n spawned.on('exit', (code) => {\n resolve({ code })\n })\n\n spawned.on('error', (error) => {\n reject(error)\n })\n })\n }\n\n /**\n * @description delete one or more documents\n * @param options\n * @returns Updated document(s)\n */\n delete<T extends keyof TGeneratedTypes['collections']>(\n options: DeleteByIDOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]>\n\n delete<T extends keyof TGeneratedTypes['collections']>(\n options: DeleteManyOptions<T>,\n ): Promise<BulkOperationResult<T>>\n\n delete<T extends keyof TGeneratedTypes['collections']>(\n options: DeleteOptions<T>,\n ): Promise<BulkOperationResult<T> | TGeneratedTypes['collections'][T]> {\n const { deleteLocal } = localOperations\n return deleteLocal<T>(this, options)\n }\n\n /**\n * @description Initializes Payload\n * @param options\n */\n async init(options: InitOptions): Promise<Payload> {\n if (!options?.config) {\n throw new Error('Error: the payload config is required to initialize payload.')\n }\n\n this.logger = Logger('payload', options.loggerOptions, options.loggerDestination)\n\n this.config = await options.config\n\n if (process.env.NODE_ENV !== 'production') {\n validateSchema(this.config, this.logger)\n }\n\n if (!this.config.secret) {\n throw new Error('Error: missing secret key. A secret key is needed to secure Payload.')\n }\n\n this.secret = crypto.createHash('sha256').update(this.config.secret).digest('hex').slice(0, 32)\n\n this.globals = {\n config: this.config.globals,\n }\n\n this.config.collections.forEach((collection) => {\n const customID = flattenFields(collection.fields).find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n )\n\n let customIDType\n\n if (customID?.type === 'number' || customID?.type === 'text') customIDType = customID.type\n\n this.collections[collection.slug] = {\n config: collection,\n customIDType,\n }\n })\n\n // Generate types on startup\n if (process.env.NODE_ENV !== 'production' && this.config.typescript.autoGenerate !== false) {\n // We cannot run it directly here, as generate-types imports json-schema-to-typescript, which breaks on turbopack.\n // see: https://github.com/vercel/next.js/issues/66723\n void this.bin({\n args: ['generate:types'],\n log: false,\n })\n }\n\n this.db = this.config.db.init({ payload: this })\n this.db.payload = this\n\n if (this.db?.init) {\n await this.db.init()\n }\n\n if (!options.disableDBConnect && this.db.connect) {\n await this.db.connect()\n }\n\n // Load email adapter\n if (this.config.email instanceof Promise) {\n const awaitedAdapter = await this.config.email\n this.email = awaitedAdapter({ payload: this })\n } else if (this.config.email) {\n this.email = this.config.email({ payload: this })\n } else {\n this.logger.warn(\n `No email adapter provided. Email will be written to console. More info at https://payloadcms.com/docs/email/overview.`,\n )\n\n this.email = consoleEmailAdapter({ payload: this })\n }\n\n this.sendEmail = this.email['sendEmail']\n\n serverInitTelemetry(this)\n\n // 1. loop over collections, if collection has auth strategy, initialize and push to array\n let jwtStrategyEnabled = false\n this.authStrategies = this.config.collections.reduce((authStrategies, collection) => {\n if (collection?.auth) {\n if (collection.auth.strategies.length > 0) {\n authStrategies.push(...collection.auth.strategies)\n }\n\n // 2. if api key enabled, push api key strategy into the array\n if (collection.auth?.useAPIKey) {\n authStrategies.push({\n name: `${collection.slug}-api-key`,\n authenticate: APIKeyAuthentication(collection),\n })\n }\n\n // 3. if localStrategy flag is true\n if (!collection.auth.disableLocalStrategy && !jwtStrategyEnabled) {\n jwtStrategyEnabled = true\n }\n }\n\n return authStrategies\n }, [] as AuthStrategy[])\n\n // 4. if enabled, push jwt strategy into authStrategies last\n if (jwtStrategyEnabled) {\n this.authStrategies.push({\n name: 'local-jwt',\n authenticate: JWTAuthentication,\n })\n }\n\n if (!options.disableOnInit) {\n if (typeof options.onInit === 'function') await options.onInit(this)\n if (typeof this.config.onInit === 'function') await this.config.onInit(this)\n }\n\n return this\n }\n\n update<T extends keyof TGeneratedTypes['collections']>(\n options: UpdateManyOptions<T>,\n ): Promise<BulkOperationResult<T>>\n\n /**\n * @description Update one or more documents\n * @param options\n * @returns Updated document(s)\n */\n update<T extends keyof TGeneratedTypes['collections']>(\n options: UpdateByIDOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]>\n\n update<T extends keyof TGeneratedTypes['collections']>(\n options: UpdateOptions<T>,\n ): Promise<BulkOperationResult<T> | TGeneratedTypes['collections'][T]> {\n const { update } = localOperations\n return update<T>(this, options)\n }\n}\n\nconst initialized = new BasePayload()\n\nexport default initialized\n\nlet cached = global._payload\n\nif (!cached) {\n // eslint-disable-next-line no-multi-assign\n cached = global._payload = { payload: null, promise: null }\n}\n\nexport const getPayload = async (options: InitOptions): Promise<BasePayload<GeneratedTypes>> => {\n if (!options?.config) {\n throw new Error('Error: the payload config is required for getPayload to work.')\n }\n\n if (cached.payload) {\n return cached.payload\n }\n\n if (!cached.promise) {\n cached.promise = new BasePayload<GeneratedTypes>().init(options)\n }\n\n try {\n cached.payload = await cached.promise\n } catch (e) {\n cached.promise = null\n throw e\n }\n\n return cached.payload\n}\n\ntype GeneratedTypes = {\n collections: {\n [slug: number | string | symbol]: TypeWithID & Record<string, unknown>\n }\n globals: {\n [slug: number | string | symbol]: GlobalTypeWithID & Record<string, unknown>\n }\n locale: null | string\n user: User\n}\n\ntype Payload = BasePayload<GeneratedTypes>\n\ninterface RequestContext {\n [key: string]: unknown\n}\n\ntype DatabaseAdapter = BaseDatabaseAdapter\n\nexport type { DatabaseAdapter, GeneratedTypes, Payload, RequestContext }\n"],"names":["spawn","crypto","fileURLToPath","path","decrypt","encrypt","APIKeyAuthentication","JWTAuthentication","localOperations","validateSchema","consoleEmailAdapter","fieldAffectsData","localGlobalOperations","flattenFields","Logger","serverInit","serverInitTelemetry","filename","url","dirname","BasePayload","auth","options","authStrategies","collections","config","count","create","db","duplicate","email","extensions","find","findByID","findGlobal","findOne","findGlobalVersionByID","findVersionByID","findGlobalVersions","findVersions","forgotPassword","getAPIURL","serverURL","routes","api","getAdminURL","admin","globals","logger","login","resetPassword","restoreGlobalVersion","restoreVersion","schema","secret","sendEmail","types","unlock","updateGlobal","update","validationRules","verifyEmail","versions","bin","args","cwd","log","Promise","resolve","reject","spawned","stdio","undefined","on","code","error","delete","deleteLocal","init","Error","loggerOptions","loggerDestination","process","env","NODE_ENV","createHash","digest","slice","forEach","collection","customID","fields","field","name","customIDType","type","slug","typescript","autoGenerate","payload","disableDBConnect","connect","awaitedAdapter","warn","jwtStrategyEnabled","reduce","strategies","length","push","useAPIKey","authenticate","disableLocalStrategy","disableOnInit","onInit","initialized","cached","global","_payload","promise","getPayload","e"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAIA,SAASA,KAAK,QAAQ,gBAAe;AACrC,OAAOC,YAAY,SAAQ;AAC3B,SAASC,aAAa,QAAQ,WAAU;AACxC,OAAOC,UAAU,OAAM;AA0CvB,SAASC,OAAO,EAAEC,OAAO,QAAQ,mBAAkB;AACnD,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,OAAOC,qBAAqB,0CAAyC;AACrE,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SAASC,gBAAgB,QAAQ,2BAA0B;AAC3D,OAAOC,2BAA2B,sCAAqC;AACvE,OAAOC,mBAAmB,uCAAsC;AAChE,OAAOC,YAAY,wBAAuB;AAC1C,SAASC,cAAcC,mBAAmB,QAAQ,6CAA4C;AAE9F,MAAMC,WAAWf,cAAc,YAAYgB,GAAG;AAC9C,MAAMC,UAAUhB,KAAKgB,OAAO,CAACF;AAE7B;;CAEC,GACD,OAAO,MAAMG;IACX;;;;;GAK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OAAOG,OAAO;IACvC,EAAE,OAAOE,GAAG;QACVL,OAAOG,OAAO,GAAG;QACjB,MAAME;IACR;IAEA,OAAOL,OAAOhB,OAAO;AACvB,EAAC"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { ExecutionResult, GraphQLSchema, ValidationRule } from 'graphql'\nimport type { OperationArgs, Request as graphQLRequest } from 'graphql-http'\nimport type pino from 'pino'\n\nimport { spawn } from 'child_process'\nimport crypto from 'crypto'\nimport { fileURLToPath } from 'node:url'\nimport path from 'path'\n\nimport type { AuthArgs } from './auth/operations/auth.js'\nimport type { Result as ForgotPasswordResult } from './auth/operations/forgotPassword.js'\nimport type { Options as ForgotPasswordOptions } from './auth/operations/local/forgotPassword.js'\nimport type { Options as LoginOptions } from './auth/operations/local/login.js'\nimport type { Options as ResetPasswordOptions } from './auth/operations/local/resetPassword.js'\nimport type { Options as UnlockOptions } from './auth/operations/local/unlock.js'\nimport type { Options as VerifyEmailOptions } from './auth/operations/local/verifyEmail.js'\nimport type { Result as LoginResult } from './auth/operations/login.js'\nimport type { Result as ResetPasswordResult } from './auth/operations/resetPassword.js'\nimport type { AuthStrategy, User } from './auth/types.js'\nimport type { BulkOperationResult, Collection, TypeWithID } from './collections/config/types.js'\nimport type { Options as CountOptions } from './collections/operations/local/count.js'\nimport type { Options as CreateOptions } from './collections/operations/local/create.js'\nimport type {\n ByIDOptions as DeleteByIDOptions,\n ManyOptions as DeleteManyOptions,\n Options as DeleteOptions,\n} from './collections/operations/local/delete.js'\nimport type { Options as DuplicateOptions } from './collections/operations/local/duplicate.js'\nimport type { Options as FindOptions } from './collections/operations/local/find.js'\nimport type { Options as FindByIDOptions } from './collections/operations/local/findByID.js'\nimport type { Options as FindVersionByIDOptions } from './collections/operations/local/findVersionByID.js'\nimport type { Options as FindVersionsOptions } from './collections/operations/local/findVersions.js'\nimport type { Options as RestoreVersionOptions } from './collections/operations/local/restoreVersion.js'\nimport type {\n ByIDOptions as UpdateByIDOptions,\n ManyOptions as UpdateManyOptions,\n Options as UpdateOptions,\n} from './collections/operations/local/update.js'\nimport type { InitOptions, SanitizedConfig } from './config/types.js'\nimport type { BaseDatabaseAdapter, PaginatedDocs } from './database/types.js'\nimport type { InitializedEmailAdapter } from './email/types.js'\nimport type { TypeWithID as GlobalTypeWithID, Globals } from './globals/config/types.js'\nimport type { Options as FindGlobalOptions } from './globals/operations/local/findOne.js'\nimport type { Options as FindGlobalVersionByIDOptions } from './globals/operations/local/findVersionByID.js'\nimport type { Options as FindGlobalVersionsOptions } from './globals/operations/local/findVersions.js'\nimport type { Options as RestoreGlobalVersionOptions } from './globals/operations/local/restoreVersion.js'\nimport type { Options as UpdateGlobalOptions } from './globals/operations/local/update.js'\nimport type { TypeWithVersion } from './versions/types.js'\n\nimport { decrypt, encrypt } from './auth/crypto.js'\nimport { APIKeyAuthentication } from './auth/strategies/apiKey.js'\nimport { JWTAuthentication } from './auth/strategies/jwt.js'\nimport localOperations from './collections/operations/local/index.js'\nimport { validateSchema } from './config/validate.js'\nimport { consoleEmailAdapter } from './email/consoleEmailAdapter.js'\nimport { fieldAffectsData } from './fields/config/types.js'\nimport localGlobalOperations from './globals/operations/local/index.js'\nimport flattenFields from './utilities/flattenTopLevelFields.js'\nimport Logger from './utilities/logger.js'\nimport { serverInit as serverInitTelemetry } from './utilities/telemetry/events/serverInit.js'\n\nconst filename = fileURLToPath(import.meta.url)\nconst dirname = path.dirname(filename)\n\n/**\n * @description Payload\n */\nexport class BasePayload<TGeneratedTypes extends GeneratedTypes> {\n /**\n * @description Authorization and Authentication using headers and cookies to run auth user strategies\n * @returns cookies: Map<string, string>\n * @returns permissions: Permissions\n * @returns user: User\n */\n auth = async (options: AuthArgs) => {\n const { auth } = localOperations.auth\n return auth(this, options)\n }\n\n authStrategies: AuthStrategy[]\n\n collections: {\n [slug: number | string | symbol]: Collection\n } = {}\n\n config: SanitizedConfig\n\n /**\n * @description Performs count operation\n * @param options\n * @returns count of documents satisfying query\n */\n count = async <T extends keyof TGeneratedTypes['collections']>(\n options: CountOptions<T>,\n ): Promise<{ totalDocs: number }> => {\n const { count } = localOperations\n return count(this, options)\n }\n\n /**\n * @description Performs create operation\n * @param options\n * @returns created document\n */\n create = async <T extends keyof TGeneratedTypes['collections']>(\n options: CreateOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]> => {\n const { create } = localOperations\n return create<T>(this, options)\n }\n db: DatabaseAdapter\n\n decrypt = decrypt\n\n duplicate = async <T extends keyof TGeneratedTypes['collections']>(\n options: DuplicateOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]> => {\n const { duplicate } = localOperations\n return duplicate<T>(this, options)\n }\n\n email: InitializedEmailAdapter\n\n // TODO: re-implement or remove?\n // errorHandler: ErrorHandler\n\n encrypt = encrypt\n\n extensions: (args: {\n args: OperationArgs<any>\n req: graphQLRequest<unknown, unknown>\n result: ExecutionResult\n }) => Promise<any>\n\n /**\n * @description Find documents with criteria\n * @param options\n * @returns documents satisfying query\n */\n find = async <T extends keyof TGeneratedTypes['collections']>(\n options: FindOptions<T>,\n ): Promise<PaginatedDocs<TGeneratedTypes['collections'][T]>> => {\n const { find } = localOperations\n return find<T>(this, options)\n }\n\n /**\n * @description Find document by ID\n * @param options\n * @returns document with specified ID\n */\n findByID = async <T extends keyof TGeneratedTypes['collections']>(\n options: FindByIDOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]> => {\n const { findByID } = localOperations\n return findByID<T>(this, options)\n }\n\n findGlobal = async <T extends keyof TGeneratedTypes['globals']>(\n options: FindGlobalOptions<T>,\n ): Promise<TGeneratedTypes['globals'][T]> => {\n const { findOne } = localGlobalOperations\n return findOne<T>(this, options)\n }\n\n /**\n * @description Find global version by ID\n * @param options\n * @returns global version with specified ID\n */\n findGlobalVersionByID = async <T extends keyof TGeneratedTypes['globals']>(\n options: FindGlobalVersionByIDOptions<T>,\n ): Promise<TypeWithVersion<TGeneratedTypes['globals'][T]>> => {\n const { findVersionByID } = localGlobalOperations\n return findVersionByID<T>(this, options)\n }\n\n /**\n * @description Find global versions with criteria\n * @param options\n * @returns versions satisfying query\n */\n findGlobalVersions = async <T extends keyof TGeneratedTypes['globals']>(\n options: FindGlobalVersionsOptions<T>,\n ): Promise<PaginatedDocs<TypeWithVersion<TGeneratedTypes['globals'][T]>>> => {\n const { findVersions } = localGlobalOperations\n return findVersions<T>(this, options)\n }\n\n /**\n * @description Find version by ID\n * @param options\n * @returns version with specified ID\n */\n findVersionByID = async <T extends keyof TGeneratedTypes['collections']>(\n options: FindVersionByIDOptions<T>,\n ): Promise<TypeWithVersion<TGeneratedTypes['collections'][T]>> => {\n const { findVersionByID } = localOperations\n return findVersionByID<T>(this, options)\n }\n\n /**\n * @description Find versions with criteria\n * @param options\n * @returns versions satisfying query\n */\n findVersions = async <T extends keyof TGeneratedTypes['collections']>(\n options: FindVersionsOptions<T>,\n ): Promise<PaginatedDocs<TypeWithVersion<TGeneratedTypes['collections'][T]>>> => {\n const { findVersions } = localOperations\n return findVersions<T>(this, options)\n }\n\n forgotPassword = async <T extends keyof TGeneratedTypes['collections']>(\n options: ForgotPasswordOptions<T>,\n ): Promise<ForgotPasswordResult> => {\n const { forgotPassword } = localOperations.auth\n return forgotPassword<T>(this, options)\n }\n\n getAPIURL = (): string => `${this.config.serverURL}${this.config.routes.api}`\n\n getAdminURL = (): string => `${this.config.serverURL}${this.config.routes.admin}`\n\n globals: Globals\n\n logger: pino.Logger\n\n login = async <T extends keyof TGeneratedTypes['collections']>(\n options: LoginOptions<T>,\n ): Promise<LoginResult & { user: TGeneratedTypes['collections'][T] }> => {\n const { login } = localOperations.auth\n return login<T>(this, options)\n }\n\n resetPassword = async <T extends keyof TGeneratedTypes['collections']>(\n options: ResetPasswordOptions<T>,\n ): Promise<ResetPasswordResult> => {\n const { resetPassword } = localOperations.auth\n return resetPassword<T>(this, options)\n }\n\n /**\n * @description Restore global version by ID\n * @param options\n * @returns version with specified ID\n */\n restoreGlobalVersion = async <T extends keyof TGeneratedTypes['globals']>(\n options: RestoreGlobalVersionOptions<T>,\n ): Promise<TGeneratedTypes['globals'][T]> => {\n const { restoreVersion } = localGlobalOperations\n return restoreVersion<T>(this, options)\n }\n\n /**\n * @description Restore version by ID\n * @param options\n * @returns version with specified ID\n */\n restoreVersion = async <T extends keyof TGeneratedTypes['collections']>(\n options: RestoreVersionOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]> => {\n const { restoreVersion } = localOperations\n return restoreVersion<T>(this, options)\n }\n\n schema: GraphQLSchema\n\n secret: string\n\n sendEmail: InitializedEmailAdapter['sendEmail']\n\n types: {\n arrayTypes: any\n blockInputTypes: any\n blockTypes: any\n fallbackLocaleInputType?: any\n groupTypes: any\n localeInputType?: any\n tabTypes: any\n }\n\n unlock = async <T extends keyof TGeneratedTypes['collections']>(\n options: UnlockOptions<T>,\n ): Promise<boolean> => {\n const { unlock } = localOperations.auth\n return unlock(this, options)\n }\n\n updateGlobal = async <T extends keyof TGeneratedTypes['globals']>(\n options: UpdateGlobalOptions<T>,\n ): Promise<TGeneratedTypes['globals'][T]> => {\n const { update } = localGlobalOperations\n return update<T>(this, options)\n }\n\n validationRules: (args: OperationArgs<any>) => ValidationRule[]\n\n verifyEmail = async <T extends keyof TGeneratedTypes['collections']>(\n options: VerifyEmailOptions<T>,\n ): Promise<boolean> => {\n const { verifyEmail } = localOperations.auth\n return verifyEmail(this, options)\n }\n\n versions: {\n [slug: string]: any // TODO: Type this\n } = {}\n\n async bin({\n args,\n cwd,\n log,\n }: {\n args: string[]\n cwd?: string\n log?: boolean\n }): Promise<{ code: number }> {\n return new Promise((resolve, reject) => {\n const spawned = spawn('node', [path.resolve(dirname, '../bin.js'), ...args], {\n cwd,\n stdio: log || log === undefined ? 'inherit' : 'ignore',\n })\n\n spawned.on('exit', (code) => {\n resolve({ code })\n })\n\n spawned.on('error', (error) => {\n reject(error)\n })\n })\n }\n\n /**\n * @description delete one or more documents\n * @param options\n * @returns Updated document(s)\n */\n delete<T extends keyof TGeneratedTypes['collections']>(\n options: DeleteByIDOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]>\n\n delete<T extends keyof TGeneratedTypes['collections']>(\n options: DeleteManyOptions<T>,\n ): Promise<BulkOperationResult<T>>\n\n delete<T extends keyof TGeneratedTypes['collections']>(\n options: DeleteOptions<T>,\n ): Promise<BulkOperationResult<T> | TGeneratedTypes['collections'][T]> {\n const { deleteLocal } = localOperations\n return deleteLocal<T>(this, options)\n }\n\n /**\n * @description Initializes Payload\n * @param options\n */\n async init(options: InitOptions): Promise<Payload> {\n if (!options?.config) {\n throw new Error('Error: the payload config is required to initialize payload.')\n }\n\n this.logger = Logger('payload', options.loggerOptions, options.loggerDestination)\n\n this.config = await options.config\n\n if (process.env.NODE_ENV !== 'production') {\n validateSchema(this.config, this.logger)\n }\n\n if (!this.config.secret) {\n throw new Error('Error: missing secret key. A secret key is needed to secure Payload.')\n }\n\n this.secret = crypto.createHash('sha256').update(this.config.secret).digest('hex').slice(0, 32)\n\n this.globals = {\n config: this.config.globals,\n }\n\n this.config.collections.forEach((collection) => {\n const customID = flattenFields(collection.fields).find(\n (field) => fieldAffectsData(field) && field.name === 'id',\n )\n\n let customIDType\n\n if (customID?.type === 'number' || customID?.type === 'text') customIDType = customID.type\n\n this.collections[collection.slug] = {\n config: collection,\n customIDType,\n }\n })\n\n // Generate types on startup\n if (process.env.NODE_ENV !== 'production' && this.config.typescript.autoGenerate !== false) {\n // We cannot run it directly here, as generate-types imports json-schema-to-typescript, which breaks on turbopack.\n // see: https://github.com/vercel/next.js/issues/66723\n void this.bin({\n args: ['generate:types'],\n log: false,\n })\n }\n\n this.db = this.config.db.init({ payload: this })\n this.db.payload = this\n\n if (this.db?.init) {\n await this.db.init()\n }\n\n if (!options.disableDBConnect && this.db.connect) {\n await this.db.connect()\n }\n\n // Load email adapter\n if (this.config.email instanceof Promise) {\n const awaitedAdapter = await this.config.email\n this.email = awaitedAdapter({ payload: this })\n } else if (this.config.email) {\n this.email = this.config.email({ payload: this })\n } else {\n this.logger.warn(\n `No email adapter provided. Email will be written to console. More info at https://payloadcms.com/docs/email/overview.`,\n )\n\n this.email = consoleEmailAdapter({ payload: this })\n }\n\n // Warn if image resizing is enabled but sharp is not installed\n if (\n !this.config.sharp &&\n this.config.collections.some((c) => c.upload.imageSizes || c.upload.formatOptions)\n ) {\n this.logger.warn(\n `Image resizing is enabled for one or more collections, but sharp not installed. Please install 'sharp' and pass into the config.`,\n )\n }\n\n this.sendEmail = this.email['sendEmail']\n\n serverInitTelemetry(this)\n\n // 1. loop over collections, if collection has auth strategy, initialize and push to array\n let jwtStrategyEnabled = false\n this.authStrategies = this.config.collections.reduce((authStrategies, collection) => {\n if (collection?.auth) {\n if (collection.auth.strategies.length > 0) {\n authStrategies.push(...collection.auth.strategies)\n }\n\n // 2. if api key enabled, push api key strategy into the array\n if (collection.auth?.useAPIKey) {\n authStrategies.push({\n name: `${collection.slug}-api-key`,\n authenticate: APIKeyAuthentication(collection),\n })\n }\n\n // 3. if localStrategy flag is true\n if (!collection.auth.disableLocalStrategy && !jwtStrategyEnabled) {\n jwtStrategyEnabled = true\n }\n }\n\n return authStrategies\n }, [] as AuthStrategy[])\n\n // 4. if enabled, push jwt strategy into authStrategies last\n if (jwtStrategyEnabled) {\n this.authStrategies.push({\n name: 'local-jwt',\n authenticate: JWTAuthentication,\n })\n }\n\n if (!options.disableOnInit) {\n if (typeof options.onInit === 'function') await options.onInit(this)\n if (typeof this.config.onInit === 'function') await this.config.onInit(this)\n }\n\n return this\n }\n\n update<T extends keyof TGeneratedTypes['collections']>(\n options: UpdateManyOptions<T>,\n ): Promise<BulkOperationResult<T>>\n\n /**\n * @description Update one or more documents\n * @param options\n * @returns Updated document(s)\n */\n update<T extends keyof TGeneratedTypes['collections']>(\n options: UpdateByIDOptions<T>,\n ): Promise<TGeneratedTypes['collections'][T]>\n\n update<T extends keyof TGeneratedTypes['collections']>(\n options: UpdateOptions<T>,\n ): Promise<BulkOperationResult<T> | TGeneratedTypes['collections'][T]> {\n const { update } = localOperations\n return update<T>(this, options)\n }\n}\n\nconst initialized = new BasePayload()\n\nexport default initialized\n\nlet cached = global._payload\n\nif (!cached) {\n // eslint-disable-next-line no-multi-assign\n cached = global._payload = { payload: null, promise: null }\n}\n\nexport const getPayload = async (options: InitOptions): Promise<BasePayload<GeneratedTypes>> => {\n if (!options?.config) {\n throw new Error('Error: the payload config is required for getPayload to work.')\n }\n\n if (cached.payload) {\n return cached.payload\n }\n\n if (!cached.promise) {\n cached.promise = new BasePayload<GeneratedTypes>().init(options)\n }\n\n try {\n cached.payload = await cached.promise\n } catch (e) {\n cached.promise = null\n throw e\n }\n\n return cached.payload\n}\n\ntype GeneratedTypes = {\n collections: {\n [slug: number | string | symbol]: TypeWithID & Record<string, unknown>\n }\n globals: {\n [slug: number | string | symbol]: GlobalTypeWithID & Record<string, unknown>\n }\n locale: null | string\n user: User\n}\n\ntype Payload = BasePayload<GeneratedTypes>\n\ninterface RequestContext {\n [key: string]: unknown\n}\n\ntype DatabaseAdapter = BaseDatabaseAdapter\n\nexport type { DatabaseAdapter, GeneratedTypes, Payload, RequestContext }\n"],"names":["spawn","crypto","fileURLToPath","path","decrypt","encrypt","APIKeyAuthentication","JWTAuthentication","localOperations","validateSchema","consoleEmailAdapter","fieldAffectsData","localGlobalOperations","flattenFields","Logger","serverInit","serverInitTelemetry","filename","url","dirname","BasePayload","auth","options","authStrategies","collections","config","count","create","db","duplicate","email","extensions","find","findByID","findGlobal","findOne","findGlobalVersionByID","findVersionByID","findGlobalVersions","findVersions","forgotPassword","getAPIURL","serverURL","routes","api","getAdminURL","admin","globals","logger","login","resetPassword","restoreGlobalVersion","restoreVersion","schema","secret","sendEmail","types","unlock","updateGlobal","update","validationRules","verifyEmail","versions","bin","args","cwd","log","Promise","resolve","reject","spawned","stdio","undefined","on","code","error","delete","deleteLocal","init","Error","loggerOptions","loggerDestination","process","env","NODE_ENV","createHash","digest","slice","forEach","collection","customID","fields","field","name","customIDType","type","slug","typescript","autoGenerate","payload","disableDBConnect","connect","awaitedAdapter","warn","sharp","some","c","upload","imageSizes","formatOptions","jwtStrategyEnabled","reduce","strategies","length","push","useAPIKey","authenticate","disableLocalStrategy","disableOnInit","onInit","initialized","cached","global","_payload","promise","getPayload","e"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAIA,SAASA,KAAK,QAAQ,gBAAe;AACrC,OAAOC,YAAY,SAAQ;AAC3B,SAASC,aAAa,QAAQ,WAAU;AACxC,OAAOC,UAAU,OAAM;AA0CvB,SAASC,OAAO,EAAEC,OAAO,QAAQ,mBAAkB;AACnD,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,OAAOC,qBAAqB,0CAAyC;AACrE,SAASC,cAAc,QAAQ,uBAAsB;AACrD,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SAASC,gBAAgB,QAAQ,2BAA0B;AAC3D,OAAOC,2BAA2B,sCAAqC;AACvE,OAAOC,mBAAmB,uCAAsC;AAChE,OAAOC,YAAY,wBAAuB;AAC1C,SAASC,cAAcC,mBAAmB,QAAQ,6CAA4C;AAE9F,MAAMC,WAAWf,cAAc,YAAYgB,GAAG;AAC9C,MAAMC,UAAUhB,KAAKgB,OAAO,CAACF;AAE7B;;CAEC,GACD,OAAO,MAAMG;IACX;;;;;GAKC,GACDC,OAAO,OAAOC;QACZ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QACpB,MAAM,IAAIsD,MAAM;IAClB;IAEA,IAAI0C,OAAOtB,OAAO,EAAE;QAClB,OAAOsB,OAAOtB,OAAO;IACvB;IAEA,IAAI,CAACsB,OAAOG,OAAO,EAAE;QACnBH,OAAOG,OAAO,GAAG,IAAIxG,cAA8B0D,IAAI,CAACxD;IAC1D;IAEA,IAAI;QACFmG,OAAOtB,OAAO,GAAG,MAAMsB,OAAOG,OAAO;IACvC,EAAE,OAAOE,GAAG;QACVL,OAAOG,OAAO,GAAG;QACjB,MAAME;IACR;IAEA,OAAOL,OAAOtB,OAAO;AACvB,EAAC"}
@@ -4,13 +4,13 @@ export const percentToPixel = (value, dimension)=>{
4
4
  export async function cropImage({ cropData, dimensions, file, sharp }) {
5
5
  try {
6
6
  const { height, width, x, y } = cropData;
7
- const fileIsAnimated = [
7
+ const fileIsAnimatedType = [
8
8
  'image/avif',
9
9
  'image/gif',
10
10
  'image/webp'
11
11
  ].includes(file.mimetype);
12
12
  const sharpOptions = {};
13
- if (fileIsAnimated) sharpOptions.animated = true;
13
+ if (fileIsAnimatedType) sharpOptions.animated = true;
14
14
  const formattedCropData = {
15
15
  height: percentToPixel(height, dimensions.height),
16
16
  left: percentToPixel(x, dimensions.width),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/uploads/cropImage.ts"],"sourcesContent":["import type { SharpOptions } from 'sharp'\n\nexport 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 fileIsAnimated = ['image/avif', 'image/gif', 'image/webp'].includes(file.mimetype)\n\n const sharpOptions: SharpOptions = {}\n\n if (fileIsAnimated) sharpOptions.animated = true\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, sharpOptions).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","fileIsAnimated","includes","mimetype","sharpOptions","animated","formattedCropData","left","top","cropped","tempFilePath","data","extract","toBuffer","resolveWithObject","error","console"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAEA,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,iBAAiB;YAAC;YAAc;YAAa;SAAa,CAACC,QAAQ,CAACP,KAAKQ,QAAQ;QAEvF,MAAMC,eAA6B,CAAC;QAEpC,IAAIH,gBAAgBG,aAAaC,QAAQ,GAAG;QAE5C,MAAMC,oBAAoB;YACxBT,QAAQX,eAAeW,QAAQH,WAAWG,MAAM;YAChDU,MAAMrB,eAAea,GAAGL,WAAWI,KAAK;YACxCU,KAAKtB,eAAec,GAAGN,WAAWG,MAAM;YACxCC,OAAOZ,eAAeY,OAAOJ,WAAWI,KAAK;QAC/C;QAEA,MAAMW,UAAUb,MAAMD,KAAKe,YAAY,IAAIf,KAAKgB,IAAI,EAAEP,cAAcQ,OAAO,CAACN;QAE5E,OAAO,MAAMG,QAAQI,QAAQ,CAAC;YAC5BC,mBAAmB;QACrB;IACF,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,CAAC,qBAAqB,CAAC,EAAEA;QACvC,MAAMA;IACR;AACF"}
1
+ {"version":3,"sources":["../../src/uploads/cropImage.ts"],"sourcesContent":["import type { SharpOptions } from 'sharp'\n\nexport 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 fileIsAnimatedType = ['image/avif', 'image/gif', 'image/webp'].includes(file.mimetype)\n\n const sharpOptions: SharpOptions = {}\n\n if (fileIsAnimatedType) sharpOptions.animated = true\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, sharpOptions).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","fileIsAnimatedType","includes","mimetype","sharpOptions","animated","formattedCropData","left","top","cropped","tempFilePath","data","extract","toBuffer","resolveWithObject","error","console"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAEA,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,qBAAqB;YAAC;YAAc;YAAa;SAAa,CAACC,QAAQ,CAACP,KAAKQ,QAAQ;QAE3F,MAAMC,eAA6B,CAAC;QAEpC,IAAIH,oBAAoBG,aAAaC,QAAQ,GAAG;QAEhD,MAAMC,oBAAoB;YACxBT,QAAQX,eAAeW,QAAQH,WAAWG,MAAM;YAChDU,MAAMrB,eAAea,GAAGL,WAAWI,KAAK;YACxCU,KAAKtB,eAAec,GAAGN,WAAWG,MAAM;YACxCC,OAAOZ,eAAeY,OAAOJ,WAAWI,KAAK;QAC/C;QAEA,MAAMW,UAAUb,MAAMD,KAAKe,YAAY,IAAIf,KAAKgB,IAAI,EAAEP,cAAcQ,OAAO,CAACN;QAE5E,OAAO,MAAMG,QAAQI,QAAQ,CAAC;YAC5BC,mBAAmB;QACrB;IACF,EAAE,OAAOC,OAAO;QACdC,QAAQD,KAAK,CAAC,CAAC,qBAAqB,CAAC,EAAEA;QACvC,MAAMA;IACR;AACF"}
@@ -61,7 +61,7 @@ export const generateFileData = async ({ collection: { config: collectionConfig
61
61
  let newData = data;
62
62
  const filesToSave = [];
63
63
  const fileData = {};
64
- const fileIsAnimated = [
64
+ const fileIsAnimatedType = [
65
65
  'image/avif',
66
66
  'image/gif',
67
67
  'image/webp'
@@ -77,8 +77,8 @@ export const generateFileData = async ({ collection: { config: collectionConfig
77
77
  let mime;
78
78
  const fileHasAdjustments = fileSupportsResize && Boolean(resizeOptions || formatOptions || imageSizes || trimOptions || file.tempFilePath);
79
79
  const sharpOptions = {};
80
- if (fileIsAnimated) sharpOptions.animated = true;
81
- if (sharp && (fileIsAnimated || fileHasAdjustments)) {
80
+ if (fileIsAnimatedType) sharpOptions.animated = true;
81
+ if (sharp && (fileIsAnimatedType || fileHasAdjustments)) {
82
82
  if (file.tempFilePath) {
83
83
  sharpFile = sharp(file.tempFilePath, sharpOptions).rotate() // pass rotate() to auto-rotate based on EXIF data. https://github.com/payloadcms/payload/pull/3081
84
84
  ;
@@ -160,7 +160,7 @@ export const generateFileData = async ({ collection: { config: collectionConfig
160
160
  };
161
161
  fileData.width = info.width;
162
162
  fileData.height = info.height;
163
- if (fileIsAnimated) {
163
+ if (fileIsAnimatedType) {
164
164
  const metadata = await sharpFile.metadata();
165
165
  fileData.height = metadata.pages ? info.height / metadata.pages : info.height;
166
166
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/uploads/generateFileData.ts"],"sourcesContent":["import type { OutputInfo, Sharp, SharpOptions } from 'sharp'\n\nimport { fileTypeFromBuffer } from 'file-type'\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 = ['image/avif', 'image/gif', 'image/webp'].includes(file.mimetype)\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 || imageSizes || trimOptions || file.tempFilePath)\n\n const sharpOptions: SharpOptions = {}\n\n if (fileIsAnimated) sharpOptions.animated = true\n\n if (sharp && (fileIsAnimated || fileHasAdjustments)) {\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 (fileHasAdjustments) {\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\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 fileTypeFromBuffer(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 if (fileIsAnimated) {\n const metadata = await sharpFile.metadata()\n fileData.height = metadata.pages ? info.height / metadata.pages : info.height\n }\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":["fileTypeFromBuffer","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","includes","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","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,SAASA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ploads/generateFileData.ts"],"sourcesContent":["import type { OutputInfo, Sharp, SharpOptions } from 'sharp'\n\nimport { fileTypeFromBuffer } from 'file-type'\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 fileIsAnimatedType = ['image/avif', 'image/gif', 'image/webp'].includes(file.mimetype)\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 || imageSizes || trimOptions || file.tempFilePath)\n\n const sharpOptions: SharpOptions = {}\n\n if (fileIsAnimatedType) sharpOptions.animated = true\n\n if (sharp && (fileIsAnimatedType || fileHasAdjustments)) {\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 (fileHasAdjustments) {\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\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 fileTypeFromBuffer(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 if (fileIsAnimatedType) {\n const metadata = await sharpFile.metadata()\n fileData.height = metadata.pages ? info.height / metadata.pages : info.height\n }\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":["fileTypeFromBuffer","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","fileIsAnimatedType","includes","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","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,SAASA,kBAAkB,QAAQ,YAAW;AAC9C,OAAOC,Q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155
155
  afterRead: [
156
156
  ({ data, value })=>{
157
- if (value) return value;
157
+ if (value && size.height && size.width) return value;
158
158
  const sizeFilename = data?.sizes?.[size.name]?.filename;
159
159
  if (sizeFilename) {
160
160
  return `${config.serverURL}${config.routes.api}/${collection.slug}/file/${sizeFilename}`;