Compare commits

..

1 Commits

Author SHA1 Message Date
Jarrod Flesch
1b0afee70e fix: cascade draft arg when querying globals with graphql 2024-06-06 10:35:23 -04:00
430 changed files with 1811 additions and 6606 deletions

7
.vscode/launch.json vendored
View File

@@ -111,13 +111,6 @@
"request": "launch",
"type": "node-terminal"
},
{
"command": "node --no-deprecation test/dev.js field-error-states",
"cwd": "${workspaceFolder}",
"name": "Run Dev Field Error States",
"request": "launch",
"type": "node-terminal"
},
{
"command": "pnpm run test:int live-preview",
"cwd": "${workspaceFolder}",

View File

@@ -42,8 +42,5 @@
}
},
"files.insertFinalNewline": true,
"jestrunner.jestCommand": "pnpm exec cross-env NODE_OPTIONS=\"--experimental-vm-modules --no-deprecation\" node 'node_modules/jest/bin/jest.js'",
"jestrunner.debugOptions": {
"runtimeArgs": ["--experimental-vm-modules", "--no-deprecation"]
}
"jestrunner.jestCommand": "pnpm exec cross-env NODE_OPTIONS=\"--experimental-vm-modules --no-deprecation\" node 'node_modules/jest/bin/jest.js'"
}

View File

@@ -282,11 +282,3 @@ const { data } = useLivePreview<PageType>({
depth: 1, // Ensure this matches the depth of your initial request
})
```
### Iframe refuses to connect
If your front-end application has set a [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) (CSP) that blocks the Admin Panel from loading your front-end application, the iframe will not be able to load your site. To resolve this, you can whitelist the Admin Panel's domain in your CSP by setting the `frame-ancestors` directive:
```plaintext
frame-ancestors: "self" localhost:* https://your-site.com;
```

View File

@@ -173,11 +173,3 @@ If you are noticing that updates feel less snappy than client-side Live Preview
},
}
```
### Iframe refuses to connect
If your front-end application has set a [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP) (CSP) that blocks the Admin Panel from loading your front-end application, the iframe will not be able to load your site. To resolve this, you can whitelist the Admin Panel's domain in your CSP by setting the `frame-ancestors` directive:
```plaintext
frame-ancestors: "self" localhost:* https://your-site.com;
```

View File

@@ -1,804 +0,0 @@
# 🚧 **DRAFT:** 3.0 Migration Guide / Breaking Changes
> [!IMPORTANT]
> This document will continue to be updated and cleaned up until the 3.0 release.
## What has changed?
The core logic and principles of Payload remain the same for 3.0. The brunt of the changes are at the HTTP layer and the Admin Panel. These aspects were moved to be based upon Next.js.
## To migrate from Payload 2.0 to 3.0:
1. Delete the `admin.bundler` property from your Payload config:
Payload no longer bundles the admin panel. Instead, we rely directly on Next.js for bundling. This also means that the `@payloadcms/bundler-webpack` and `@payloadcms/bundler-vite` packages have been deprecated. You can completely uninstall those from your project by removing them from your `package.json` file and re-running your package managers installation process, i.e. `pnpm i`.
2. Add the `secret` property to your Payload config. This used to be set in the `payload.init()` function of your `server.ts` file. Move it to `payload.config.ts` instead:
```tsx
// payload.config.ts
buildConfig({
// ...
secret: process.env.PAYLOAD_SECRET
})
```
3. The `admin.css` and `admin.scss` properties in the Payload config have been removed:
Instead for any global styles you can:
- use `(payload)/custom.scss` to import or add your own styles, eg. for tailwind
- plugins that need to inject global styles should do so via the provider config at `admin.components.providers` :
```tsx
// payload.config.js
//...
admin: {
components: {
providers: [
MyProvider
]
}
},
//...
// MyProvider.tsx
import React from 'react'
import './globals.css'
const MyProvider: React.FC<{children?: any}= ({ children }) ={
return (
<React.fragment>
{children}
</React.fragment>
)
}
export default Provider
```
4. The `admin.indexHTML` property has been removed.
5. The `collection.admin.hooks` property has been removed.
Instead, use the new `beforeDuplicate` field-level hook which take the usual field hook arguments.
```tsx
// TODO: add snippet here of old vs new
```
6. Import all Payload React components via the `@payloadcms/ui` package instead of `payload`:
If you were previously importing components into your app from the `payload` package, for example to create a custom component, you will need to:
- Change your import paths (see below)
- Migrate your component (if necessary, see next bullet)
```tsx
import { Button } from '@payloadcms/ui/elements/Button'
// TODO: Add new full list of exports
```
7. Migrate all Custom Components to Server Components.
All Custom Components are now server-rendered, and therefore, cannot use state or hooks directly. If youre using Custom Components in your app that requires state or hooks, define your component in a separate file with the `'use client'` directive at the top, then render *that* client component within your server component. Remember you can only pass serializable props to this component, so props cannot be blindly spread.
```tsx
import React from 'react'
import type { ServerOnlyProps } from './types.ts'
import MyClientComponent from './client.tsx'
export const MyServerComponent: React.FC<ServerOnlyProps= (serverOnlyProps) ={
const clientOnlyProps = {
// ... sanitize server-only props here as needed
}
return (
<MyClientComponent {...clientOnlyProps} />
)
}
```
8. The `custom` property in the Payload config, i.e. collections, globals, blocks, and fields are now ***server only***.
Use `admin.custom` properties will be available in both server and client bundles.
```tsx
// payload.config.ts
buildConfig({
// Server Only
custom: {
someProperty: 'value'
},
admin: {
custom: {
name: 'Customer portal' // Available in server and client
}
},
})
```
9. The `admin.description` property on field configs no longer attaches `data` to its args:
This is because we cannot pass your `description` function to the client for execution (functions are not serializable, and state is held on the client). To display dynamic descriptions that use current `data` or `path`, you must now pass a custom component and subscribe to the fields state yourself using Payloads React hooks:
```tsx
// TODO: add config snippet for total clarity
import React from 'react'
// TODO: get rest of imports
export const CustomFieldDescriptionComponent: DescriptionComponent = () ={
const { path } = useFieldProps()
const { value } = useFormFields(([fields]) =fields[path])
return (
<div>
{`Component description: ${path} - ${value}`}
</div>
)
}
```
10. The `admin.label` property on the `collapsible` field no longer attaches `data` to its args.
This is because we cannot pass your `label` function to the client for execution (functions are not serializable, and state is held on the client). To display dynamic labels that use current `data` or `path`, you must now pass a custom component and subscribe to the fields state yourself using Payloads React hooks:
```tsx
// TODO: add config snippet for total clarity
import React from 'react'
// TODO: get rest of imports
export const CustomFieldLabelComponent: LabelComponent = () => {
const { path } = useFieldProps()
const { value } = useFormFields(([fields]) =fields[path])
return (
<div>
{`Component label: ${path} - ${value}`}
</div>
)
}
```
11. The `admin.components.Cell` no longer receives `rowData` or `cellData`.
If using a custom component, you must now get the data yourself via the `useTableCell` hook, i.e. `const { cellData, rowData } = useTableCell()`.
```tsx
// TODO: add config snippet for total clarity
import React from 'react'
// TODO: get rest of imports
export const CustomCellComponent: CellComponent = () ={
const { cellData, rowData } = useTableCell()
return (
<div>
{`Component cell: ${cellData}`}
</div>
)
}
```
12. `admin.components.RowLabel` no longer accepts a function, instead use a custom component and make use of the `useRowLabel` hook:
```tsx
// ❌ Before
// Field config
{
type: 'array',
admin: {
components: {
RowLabel: ({ data }) ={
console.log(data)
return data?.title || 'Untitled'
},
}
}
}
```
```tsx
// ✅ After
// Field config
{
type: 'array',
admin: {
components: {
RowLabel: ArrayRowLabel
}
}
}
// Custom Component
'use client'
import type { RowLabelComponent } from 'payload/types'
import { useRowLabel } from '@payloadcms/ui/forms/RowLabel/Context'
import React from 'react'
export const ArrayRowLabel: RowLabelComponent = () ={
const { data } = useRowLabel<{ title: string }>()
return (
<div>{data.title || 'Untitled'}</div>
)
}
```
13. The `admin.components.views[].Tab.pillLabel` has been replaced with `admin.components.views[].Tab.Pill`
```tsx
// Collection.ts
// ❌ Before
{
admin: {
components: {
views: {
Edit: {
Tab: {
pillLabel: '',
},
},
},
},
},
}
// ✅ After
{
admin: {
components: {
views: {
Edit: {
Tab: {
Pill: MyPill,
},
},
},
},
},
}
```
14. The `useTitle` hook has been absorbed by the `useDocumentInfo` hook.
Now, you can get title directly from document info context, i.e. `const { title } = useDocumentInfo()`.
15. The `Fields` type was renamed to `FormState`:
This was changed for improved semantics. If you were previously importing this type in your own application, simply change the import name:
```tsx
// ❌ Before
import type { Fields } from 'payload/types'
// ✅ After
import type { FormState } from 'payload/types'
```
16. The `useDocumentInfo` hook no longer returns a `SanizitedCollectionConfig` or `SanitizedGlobalConfig`:
This is because the configs themselves are not serializable and so they cannot be thread through to the client, i.e. the `DocumentInfoContext`. Instead, various properties of the config are passed instead, like `collectionSlug` and `globalSlug`. You can use these to access a client-side config, if needed, through the `useConfig` hook (see next bullet).
17. The `useConfig` hook now returns a `ClientConfig` and not a `SanizitedConfig`.
This is because the config itself is not serializable and so it is not able to be thread through to the client, i.e. the `ConfigContext`.
18. `DocumentTabProps` no longer contains `id` or `isEditing`.
Instead you can use the `useDocumentInfo` hook to get this information (see above).
19. The args of the `livePreview.url` function have changed.
It no longer receives `documentInfo` as an arg, and instead, now has `collectionConfig` and `globalConfig`.
20. The `href` and `isActive` functions in the view tab config no longer sends the `match` or `location` arguments.
This is is a property specific to React Router, not Next.js. If you need to do fancy matching similar to this, use a custom tab that fires of some hooks, i.e. `usePathname()` and run it through your own utility functions.
21. The `views.Edit` or `views.Edit.Default` or `views.Edit.Default.Component` properties are no longer of type `AdminViewComponent` like the other views.
Instead, their new type is `React.FC<EditViewProps>` where you now only receive the config slug. This is because of how custom edit views need to be rendered server-side, then returned by a client-component (i.e. the document drawer). Theres an example of this adapter pattern in the first sections of this page.
22. `beforeDuplicate` field hooks have been added to `unique` fields to automatically add “- Copy” to the end.
23. The `useCollapsible` hook has had slight changes to its property names:
`collapsed` is now `isCollapsed` and `withinCollapsible` is now `isWithinCollapsible`.
24. Components that return a function have webpack errors.
Will need to document the following (if intended as a breaking change)
![Untitled](https://prod-files-secure.s3.us-west-2.amazonaws.com/0fcec415-321b-48ca-a915-504d61c448b3/94156826-74ee-4708-aa73-1beb11ad0306/Untitled.png)
25. The `admin.favicon` property is now `admin.icons` and the types have changed
Reference: https://github.com/payloadcms/payload/pull/6347
```tsx
// payload.config.ts
// ❌ Before
{
// ...
admin: {
favicon: 'path-to-favicon.svg'
}
}
// ✅ After
{
// ...
admin: {
icons: [{
path: 'path-to-favicon.svg',
sizes: '32x32'
}]
}
}
```
See also: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#icons
26. The `admin.meta.ogImage` property has been replaced by `admin.meta.openGraph.images`
Reference: https://github.com/payloadcms/payload/pull/6227
```tsx
// payload.config.ts
// ❌ Before
{
admin: {
meta: {
ogImage: ''
}
}
}
```
```tsx
// ✅ After
{
admin: {
meta: {
openGraph: {
images: []
}
}
}
}
```
See also : https://nextjs.org/docs/app/api-reference/functions/generate-metadata#opengraph
27. The `admin.logoutRoute` and `admin.inactivityRoute` properties have been consolidated into a single `admin.routes` property
Reference: https://github.com/payloadcms/payload/pull/6354
To migrate, simply move those two keys as follows:
```tsx
// payload.config.ts
// ❌ Before
{
// ...
admin: {
logoutRoute: '/custom-logout',
inactivityRoute: '/custom-inactivity'
}
}
// ✅ After
{
// ...
admin: {
routes: {
logout: '/custom-logout',
inactivity: '/custom-inactivity'
}
}
}
```
## Environment variables
- Environment variables prefixed with `PAYLOAD_PUBLIC` will no longer be available on the client. In order to access them on the client, those will now have to be prefixed with `NEXT_PUBLIC` instead
## i18n
- `useTranslation()` hook no longer takes any options, any translations using shorthand accessors will need to use the entire `group:key`
```tsx
// ❌ Before
const { i18n, t } = useTranslation('general')
return <p>{t('cancel')}</p>
// ✅ After
const { i18n, t } = useTranslation()
return <p>{t('general:cancel')}</p>
```
- `react-i18n` was removed, the `Trans` component from react-i18n has been replaced with a payload provided solution. You can instead `import { Translation } from "@payloadcms/ui"`
```tsx
// Translation string example
// "loggedInChangePassword": "To change your password, go to your <0>account</0> and edit your password there."
// ❌ Before
<Trans i18nKey="loggedInChangePassword" t={t}>
<Link to={`${admin}/account`}>account</Link>
</Trans>
// ✅ After
<Translation
t={t}
i18nKey="authentication:loggedInChangePassword"
elements={{
'0': ({ children }) => <Link href={`${admin}/account`} children={children} />,
}}
/>
```
## Description and Label handling
https://github.com/payloadcms/payload/pull/6264
- Globals config: `admin.description` no longer accepts a custom component. You will have to move it to `admin.components.elements.Description`
- Collections config: `admin.description` no longer accepts a custom component. You will have to move it to `admin.components.edit.Description`
- All Fields: `field.admin.description` no longer accepts a custom component. You will have to move it to `field.admin.components.Description`
- Collapsible Field: `field.label` no longer accepts a custom component. You will have to move it to `field.admin.components.RowLabel`
- Array Field: `field.admin.components.RowLabel` no longer accepts strings or records
- If you are using our exported field components in your own app, their `labelProps` property has been stripped down and no longer contains the `label` and `required` prop. Those can now only be configured at the top-level.
## Custom Endpoints
- `root` endpoints no longer exist on the config. If you want to create a “root” endpoint, you can add them to the api folder within your Payload application. See Next docs: https://nextjs.org/docs/app/api-reference/file-conventions/route
- Endpoint handlers
- arguments
- ❌ Before: `(req, res, next)`
- ✅ After: `(req)`
- return
- ❌ Before: `res.json`, `res.send`, etc.
- ✅ After: a valid HTTP [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response)
```tsx
// ❌ Before
{
path: '/whoami/:parameter',
method: 'post',
handler: (req, res) => {
res.json({
parameter: req.params.parameter,
name: req.body.name,
age: req.body.age,
})
}
}
// ✅ After
{
path: '/whoami/:parameter',
method: 'post',
handler: (req) => {
return Response.json({
parameter: req.routeParams.parameter,
// ^^ `params` is now `routeParams`
name: req.data.name,
age: req.data.age,
})
}
}
```
- Handlers no longer resolve `data` for you on the request, use `req.json()` or you can use our utilities
```tsx
// ❌ Before
{
path: '/whoami/:parameter',
method: 'post',
handler: async (req) => {
return Response.json({
name: req.data.name, // data will be undefined
})
}
}
// ✅ After
import { addDataAndFileToRequest } from '@payloadcms/next/utilities'
{
path: '/whoami/:parameter',
method: 'post',
handler: async (req) => {
// mutates req, must be awaited
await addDataAndFileToRequest(req)
return Response.json({
name: req.data.name, // data is now available
})
}
}
```
- Handlers no longer resolve `locale` and `fallbackLocale` for you
```tsx
// ❌ Before
{
path: '/whoami/:parameter',
method: 'post',
handler: async (req) => {
return Response.json({
// will be undefined
fallbackLocale: req.fallbackLocale,
locale: req.locale,
})
}
}
// ✅ After
import { addLocalesToRequest } from '@payloadcms/next/utilities'
{
path: '/whoami/:parameter',
method: 'post',
handler: async (req) => {
// mutates req
addLocalesToRequest(req)
return Response.json({
fallbackLocale: req.fallbackLocale,
locale: req.locale,
})
}
}
```
## Req (Hooks, Access-control, etc)
- The `req` used to extend the Express Request, now it extends the [Web Request](https://developer.mozilla.org/en-US/docs/Web/API/Request). So you may need to change things in your code, for example if you are relying on `req.headers['content-type']` you will now need to to use `req.headers.get('content-type')`
## Uploads
- `staticDir` must now be an absolute path. Before it would attempt to use the location of the payload config and merge the relative path set for staticDir.
- `staticURL` has been removed. If you were using this format URLs when using an external provider, you can leverage the `generateFileURL` functions in order to do the same.
## Email Adapters
Email functionality has been abstracted out into email adapters.
- All existing nodemailer functionality was abstracted into the `@payloadcms/email-nodemailer` package
- No longer configured with ethereal.email by default.
- Ability to pass email into the `init` function has been removed.
- Warning will be given on startup if email not configured. Any `sendEmail` call will simply log the To address and subject.
- A Resend adapter is now also available via the `@payloadcms/email-resend` package.
### If you used the default email configuration in 2.0 (nodemailer):
```tsx
// ❌ Before
// via payload.init
payload.init({
email: {
transport: someNodemailerTransport
fromName: 'hello',
fromAddress: 'hello@example.com',
},
})
// or via email in payload.config.ts
export default buildConfig({
email: {
transport: someNodemailerTransport
fromName: 'hello',
fromAddress: 'hello@example.com',
},
})
// ✅ After
// Using new nodemailer adapter package
import { nodemailerAdapter } from '@payloadcms/email-nodemailer'
export default buildConfig({
email: nodemailerAdapter() // This will be the old ethereal.email functionality
})
// or pass in transport
export default buildConfig({
email: nodemailerAdapter({
defaultFromAddress: 'info@payloadcms.com',
defaultFromName: 'Payload',
transport: await nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: 587,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
})
})
})
```
### Removal of rate-limiting
- Now only available if using custom server and using express or similar
# Plugins
- *All* plugins have been standardized to use *named exports* (as opposed to default exports). Most also have a suffix of `Plugin` to make it clear what is being imported.
```tsx
// ❌ Before
import seo from '@payloadcms/plugin-seo'
import stripePlugin from '@payloadcms/plugin-stripe'
// ✅ After
import { seoPlugin } from '@payloadcms/plugin-seo'
import { stripePlugin } from '@payloadcms/plugin-stripe'
// etc.
```
## `@payloadcms/plugin-cloud-storage`
- The adapters that are exported from `@payloadcms/plugin-cloud-storage` (ie. `@payloadcms/plugin-cloud-storage/s3`) package have been removed.
- New *standalone* packages have been created for each of the existing adapters. Please see the documentation for the one that you use.
- `@payloadcms/plugin-cloud-storage` is still fully supported but should only to be used if you are providing a custom adapter that does not have a dedicated package.
- If you have created a custom adapter, the type must now provide a `name` property.
| Service | Package |
| -------------------- | ---------------------------------------------------------------------------- |
| Vercel Blob | https://github.com/payloadcms/payload/tree/beta/packages/storage-vercel-blob |
| AWS S3 | https://github.com/payloadcms/payload/tree/beta/packages/storage-s3 |
| Azure | https://github.com/payloadcms/payload/tree/beta/packages/storage-azure |
| Google Cloud Storage | https://github.com/payloadcms/payload/tree/beta/packages/storage-gcs |
```tsx
// ❌ Before (required peer dependencies depending on adapter)
import { cloudStorage } from '@payloadcms/plugin-cloud-storage'
import { s3Adapter } from '@payloadcms/plugin-cloud-storage/s3'
plugins: [
cloudStorage({
collections: {
[mediaSlug]: {
adapter: s3Adapter({
bucket: process.env.S3_BUCKET,
config: {
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
},
region: process.env.S3_REGION,
},
}),
},
},
}),
],
// ✅ After
import { s3Storage } from '@payloadcms/storage-s3'
plugins: [
s3Storage({
collections: {
[mediaSlug]: true,
},
bucket: process.env.S3_BUCKET,
config: {
credentials: {
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
},
region: process.env.S3_REGION,
},
}),
],
```
## `@payloadcms/plugin-form-builder`
- Field overrides for form and form submission collections now accept a function with a `defaultFields` inside the args instead of an array of config
```tsx
// ❌ Before
fields: [
{
name: 'custom',
type: 'text',
}
]
// ✅ After
fields: ({ defaultFields }) => {
return [
...defaultFields,
{
name: 'custom',
type: 'text',
},
]
}
```
## `@payloadcms/plugin-redirects`
- Field overrides for the redirects collection now accepts a function with a `defaultFields` inside the args instead of an array of config
```tsx
// ❌ Before
fields: [
{
name: 'custom',
type: 'text',
}
]
// ✅ After
fields: ({ defaultFields }) => {
return [
...defaultFields,
{
name: 'custom',
type: 'text',
},
]
}
```
## `@payloadcms/richtext-lexical`
// TODO: Needs comprehensive breaking changes / migration steps
### Custom Features
- Previously, a Feature would contain both server code (e.g. population promises) and client code (e.g. toolbar items). Now, they have been split up into server features and client features

View File

@@ -618,45 +618,3 @@ export const Orders: CollectionConfig = {
**req** will have the **payload** object and can be used inside your endpoint handlers for making
calls like req.payload.find() that will make use of access control and hooks.
</Banner>
## Method Override for GET Requests
Payload supports a method override feature that allows you to send GET requests using the HTTP POST method. This can be particularly useful in scenarios when the query string in a regular GET request is too long.
### How to Use
To use this feature, include the `X-HTTP-Method-Override` header set to `GET` in your POST request. The parameters should be sent in the body of the request with the `Content-Type` set to `application/x-www-form-urlencoded`.
### Example
Here is an example of how to use the method override to perform a GET request:
#### Using Method Override (POST)
```ts
const res = await fetch(`${api}/${collectionSlug}`, {
method: 'POST',
credentials: 'include',
headers: {
'Accept-Language': i18n.language,
'Content-Type': 'application/x-www-form-urlencoded',
'X-HTTP-Method-Override': 'GET',
},
body: qs.stringify({
depth: 1,
locale: 'en',
}),
})
```
#### Equivalent Regular GET Request
```ts
const res = await fetch(`${api}/${collectionSlug}?depth=1&locale=en`, {
method: 'GET',
credentials: 'include',
headers: {
'Accept-Language': i18n.language,
},
})
```

View File

@@ -22,7 +22,6 @@ Collections and Globals both support the same options for configuring drafts. Yo
| Draft Option | Description |
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `autosave` | Enable `autosave` to automatically save progress while documents are edited. To enable, set to `true` or pass an object with [options](/docs/versions/autosave). |
| `validate` | Set `validate` to `true` to validate draft documents when saved. Default is `false`. |
## Database changes

View File

@@ -33,7 +33,6 @@ export default withBundleAnalyzer(
'.js': ['.ts', '.tsx', '.js', '.jsx'],
'.mjs': ['.mts', '.mjs'],
}
return webpackConfig
},
}),

View File

@@ -1,6 +1,6 @@
{
"name": "payload-monorepo",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"private": true,
"type": "module",
"scripts": {
@@ -9,7 +9,6 @@
"build:app": "next build",
"build:app:analyze": "cross-env ANALYZE=true next build",
"build:core": "turbo build --filter \"!@payloadcms/plugin-*\"",
"build:core:force": "pnpm clean:build && turbo build --filter \"!@payloadcms/plugin-*\" --no-cache --force",
"build:create-payload-app": "turbo build --filter create-payload-app",
"build:db-mongodb": "turbo build --filter db-mongodb",
"build:db-postgres": "turbo build --filter db-postgres",
@@ -43,21 +42,21 @@
"build:translations": "turbo build --filter translations",
"build:ui": "turbo build --filter ui",
"clean": "turbo clean",
"clean:all": "node ./scripts/delete-recursively.js '@node_modules' 'media' '**/dist' '**/.cache' '**/.next' '**/.turbo' '**/tsconfig.tsbuildinfo' '**/payload*.tgz'",
"clean:build": "node ./scripts/delete-recursively.js 'media' '**/dist' '**/.cache' '**/.next' '**/.turbo' '**/tsconfig.tsbuildinfo' '**/payload*.tgz'",
"clean:cache": "node ./scripts/delete-recursively.js node_modules/.cache! packages/payload/node_modules/.cache! .next",
"clean:all": "find . \\( -type d \\( -name node_modules -o -name dist -o -name .cache -o -name .next -o -name .turbo \\) -o -type f -name tsconfig.tsbuildinfo \\) -exec rm -rf {} +",
"clean:build": "find . \\( -type d \\( -name dist -o -name .cache -o -name .next -o -name .turbo \\) -o -type f -name tsconfig.tsbuildinfo \\) -not -path '*/node_modules/*' -exec rm -rf {} +",
"clean:cache": "rimraf node_modules/.cache && rimraf packages/payload/node_modules/.cache && rimraf .next",
"dev": "cross-env NODE_OPTIONS=--no-deprecation node ./test/dev.js",
"dev:generate-graphql-schema": "cross-env NODE_OPTIONS=--no-deprecation tsx ./test/generateGraphQLSchema.ts",
"dev:generate-types": "cross-env NODE_OPTIONS=--no-deprecation tsx ./test/generateTypes.ts",
"dev:postgres": "cross-env NODE_OPTIONS=--no-deprecation PAYLOAD_DATABASE=postgres node ./test/dev.js",
"devsafe": "node ./scripts/delete-recursively.js '**/.next' && pnpm dev",
"devsafe": "rimraf .next && pnpm dev",
"docker:restart": "pnpm docker:stop --remove-orphans && pnpm docker:start",
"docker:start": "docker compose -f packages/plugin-cloud-storage/docker-compose.yml up -d",
"docker:stop": "docker compose -f packages/plugin-cloud-storage/docker-compose.yml down",
"fix": "eslint \"packages/**/*.ts\" --fix",
"lint": "eslint \"packages/**/*.ts\"",
"lint-staged": "lint-staged",
"obliterate-playwright-cache-macos": "rm -rf ~/Library/Caches/ms-playwright && find /System/Volumes/Data/private/var/folders -type d -name 'playwright*' -exec rm -rf {} +",
"obliterate-playwright-cache": "rm -rf ~/Library/Caches/ms-playwright && find /System/Volumes/Data/private/var/folders -type d -name 'playwright*' -exec rm -rf {} +",
"prepare": "husky install",
"reinstall": "pnpm clean:all && pnpm install",
"release:alpha": "tsx ./scripts/release.ts --bump prerelease --tag alpha",
@@ -124,7 +123,6 @@
"husky": "^8.0.3",
"jest": "29.7.0",
"jest-environment-jsdom": "29.7.0",
"json-schema-to-typescript": "11.0.3",
"lint-staged": "^14.0.1",
"minimist": "1.2.8",
"mongodb-memory-server": "^9.0",
@@ -160,7 +158,7 @@
"react-dom": "^19.0.0 || ^19.0.0-rc-f994737d14-20240522"
},
"engines": {
"node": "^18.20.2 || >=20.9.0",
"node": ">=18.20.2",
"pnpm": "^8.15.7"
},
"pnpm": {

View File

@@ -1,6 +1,6 @@
{
"name": "create-payload-app",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",

View File

@@ -5,7 +5,7 @@ import path from 'path'
import type { DbType, StorageAdapterType } from '../types.js'
import { warning } from '../utils/log.js'
import { dbReplacements, storageReplacements } from './replacements.js'
import { configReplacements, dbReplacements, storageReplacements } from './replacements.js'
/** Update payload config with necessary imports and adapters */
export async function configurePayloadConfig(args: {
@@ -15,8 +15,8 @@ export async function configurePayloadConfig(args: {
}
packageJsonName?: string
projectDirOrConfigPath: { payloadConfigPath: string } | { projectDir: string }
sharp?: boolean
storageAdapter?: StorageAdapterType
sharp?: boolean
}): Promise<void> {
if (!args.dbType) {
return
@@ -93,32 +93,32 @@ export async function configurePayloadConfig(args: {
const dbReplacement = dbReplacements[args.dbType]
configLines = replaceInConfigLines({
endMatch: `// database-adapter-config-end`,
lines: configLines,
replacement: dbReplacement.configReplacement(args.envNames?.dbUri),
startMatch: `// database-adapter-config-start`,
endMatch: `// database-adapter-config-end`,
lines: configLines,
})
configLines = replaceInConfigLines({
lines: configLines,
replacement: [dbReplacement.importReplacement],
startMatch: '// database-adapter-import',
lines: configLines,
})
// Storage Adapter Replacement
if (args.storageAdapter) {
const replacement = storageReplacements[args.storageAdapter]
configLines = replaceInConfigLines({
lines: configLines,
replacement: replacement.configReplacement,
startMatch: '// storage-adapter-placeholder',
lines: configLines,
})
if (replacement?.importReplacement) {
configLines = replaceInConfigLines({
lines: configLines,
replacement: [replacement.importReplacement],
startMatch: '// storage-adapter-import-placeholder',
lines: configLines,
})
}
}
@@ -126,14 +126,14 @@ export async function configurePayloadConfig(args: {
// Sharp Replacement (provided by default, only remove if explicitly set to false)
if (args.sharp === false) {
configLines = replaceInConfigLines({
lines: configLines,
replacement: [],
startMatch: 'sharp,',
lines: configLines,
})
configLines = replaceInConfigLines({
lines: configLines,
replacement: [],
startMatch: "import sharp from 'sharp'",
lines: configLines,
})
}
@@ -146,16 +146,16 @@ export async function configurePayloadConfig(args: {
}
function replaceInConfigLines({
endMatch,
lines,
replacement,
startMatch,
endMatch,
lines,
}: {
replacement: string[]
startMatch: string
/** Optional endMatch to replace multiple lines */
endMatch?: string
lines: string[]
replacement: string[]
startMatch: string
}) {
if (!replacement) {
return lines

View File

@@ -66,9 +66,9 @@ const diskReplacement: StorageAdapterReplacement = {
}
export const storageReplacements: Record<StorageAdapterType, StorageAdapterReplacement> = {
localDisk: diskReplacement,
payloadCloud: payloadCloudReplacement,
vercelBlobStorage: vercelBlobStorageReplacement,
localDisk: diskReplacement,
}
/**

View File

@@ -4,7 +4,8 @@ import chalk from 'chalk'
import { Syntax, parseModule } from 'esprima-next'
import fs from 'fs'
import { log , warning } from '../utils/log.js'
import { warning } from '../utils/log.js'
import { log } from '../utils/log.js'
export const withPayloadStatement = {
cjs: `const { withPayload } = require('@payloadcms/next/withPayload')\n`,

View File

@@ -77,4 +77,4 @@ export type NextAppDetails = {
export type NextConfigType = 'cjs' | 'esm'
export type StorageAdapterType = 'localDisk' | 'payloadCloud' | 'vercelBlobStorage'
export type StorageAdapterType = 'payloadCloud' | 'vercelBlobStorage' | 'localDisk'

View File

@@ -3,7 +3,8 @@ import chalk from 'chalk'
import path from 'path'
import terminalLink from 'terminal-link'
import type { PackageManager , ProjectTemplate } from '../types.js'
import type { ProjectTemplate } from '../types.js'
import type { PackageManager } from '../types.js'
import { getValidTemplates } from '../lib/templates.js'

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/db-mongodb",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"description": "The officially supported MongoDB database adapter for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,5 +1,6 @@
import type { CreateGlobalVersion } from 'payload/database'
import type { Document , PayloadRequestWithData } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Document } from 'payload/types'
import type { MongooseAdapter } from './index.js'

View File

@@ -1,5 +1,6 @@
import type { CreateVersion } from 'payload/database'
import type { Document , PayloadRequestWithData } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Document } from 'payload/types'
import type { MongooseAdapter } from './index.js'

View File

@@ -1,5 +1,6 @@
import type { DeleteOne } from 'payload/database'
import type { Document , PayloadRequestWithData } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Document } from 'payload/types'
import type { MongooseAdapter } from './index.js'

View File

@@ -1,6 +1,7 @@
import type { MongooseQueryOptions } from 'mongoose'
import type { FindOne } from 'payload/database'
import type { Document , PayloadRequestWithData } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Document } from 'payload/types'
import type { MongooseAdapter } from './index.js'

View File

@@ -1,11 +1,13 @@
import type { Payload } from 'payload'
import type { PathToQuery } from 'payload/database'
import type { Field , Operator } from 'payload/types'
import type { Field } from 'payload/types'
import type { Operator } from 'payload/types'
import ObjectIdImport from 'bson-objectid'
import mongoose from 'mongoose'
import { getLocalizedPaths } from 'payload/database'
import { fieldAffectsData , validOperators } from 'payload/types'
import { fieldAffectsData } from 'payload/types'
import { validOperators } from 'payload/types'
import type { MongooseAdapter } from '../index.js'

View File

@@ -2,7 +2,8 @@
/* eslint-disable no-await-in-loop */
import type { FilterQuery } from 'mongoose'
import type { Payload } from 'payload'
import type { Field, Operator , Where } from 'payload/types'
import type { Operator, Where } from 'payload/types'
import type { Field } from 'payload/types'
import deepmerge from 'deepmerge'
import { validOperators } from 'payload/types'

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/db-postgres",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"description": "The officially supported Postgres database adapter for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/email-nodemailer",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"description": "Payload Nodemailer Email Adapter",
"homepage": "https://payloadcms.com",
"repository": {
@@ -42,7 +42,7 @@
"payload": "workspace:*"
},
"engines": {
"node": "^18.20.2 || >=20.9.0"
"node": ">=18.20.2"
},
"publishConfig": {
"exports": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/email-resend",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"description": "Payload Resend Email Adapter",
"homepage": "https://payloadcms.com",
"repository": {
@@ -40,7 +40,7 @@
"payload": "workspace:*"
},
"engines": {
"node": "^18.20.2 || >=20.9.0"
"node": ">=18.20.2"
},
"publishConfig": {
"exports": {

View File

@@ -10,7 +10,6 @@ const baseRules = {
'no-use-before-define': 'off',
'object-shorthand': 'warn',
'no-useless-escape': 'warn',
'import/no-duplicates': 'warn',
'perfectionist/sort-objects': [
'error',
{
@@ -124,7 +123,7 @@ module.exports = {
ecmaVersion: 'latest',
sourceType: 'module',
},
plugins: ['import'], // Plugins are defined in the overrides to be more specific and only target the files they are meant for.
plugins: [], // Plugins are defined in the overrides to be more specific and only target the files they are meant for.
overrides: [
{
files: ['**/*.ts'],

View File

@@ -21,7 +21,6 @@
"@typescript-eslint/parser": "7.3.1",
"eslint": "8.57.0",
"eslint-config-prettier": "9.1.0",
"eslint-plugin-import": "2.25.2",
"eslint-plugin-jest": "27.9.0",
"eslint-plugin-jest-dom": "5.1.0",
"eslint-plugin-jsx-a11y": "6.8.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/graphql",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",

View File

@@ -1 +0,0 @@
export { GraphQLJSON, GraphQLJSONObject } from '../packages/graphql-type-json/index.js'

View File

@@ -1,2 +1 @@
export { generateSchema } from '../bin/generateSchema.js'
export { buildObjectType } from '../schema/buildObjectType.js'

View File

@@ -1,4 +1,5 @@
import type { Collection, PayloadRequestWithData , Where } from 'payload/types'
import type { PayloadRequestWithData, Where } from 'payload/types'
import type { Collection } from 'payload/types'
import { countOperation } from 'payload/operations'
import { isolateObjectProperty } from 'payload/utilities'

View File

@@ -1,5 +1,6 @@
import type { GeneratedTypes } from 'payload'
import type { Collection , PayloadRequestWithData } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Collection } from 'payload/types'
import type { MarkOptional } from 'ts-essentials'
import { createOperation } from 'payload/operations'

View File

@@ -1,5 +1,6 @@
import type { GeneratedTypes } from 'payload'
import type { Collection , PayloadRequestWithData } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Collection } from 'payload/types'
import { deleteByIDOperation } from 'payload/operations'
import { isolateObjectProperty } from 'payload/utilities'

View File

@@ -1,5 +1,6 @@
import type { GeneratedTypes } from 'payload'
import type { Collection , PayloadRequestWithData } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Collection } from 'payload/types'
import { duplicateOperation } from 'payload/operations'
import { isolateObjectProperty } from 'payload/utilities'

View File

@@ -1,5 +1,6 @@
import type { PaginatedDocs } from 'payload/database'
import type { Collection, PayloadRequestWithData , Where } from 'payload/types'
import type { PayloadRequestWithData, Where } from 'payload/types'
import type { Collection } from 'payload/types'
import { findOperation } from 'payload/operations'
import { isolateObjectProperty } from 'payload/utilities'

View File

@@ -1,5 +1,6 @@
import type { GeneratedTypes } from 'payload'
import type { Collection , PayloadRequestWithData } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Collection } from 'payload/types'
import { findByIDOperation } from 'payload/operations'
import { isolateObjectProperty } from 'payload/utilities'

View File

@@ -1,4 +1,5 @@
import type { Collection , PayloadRequestWithData, TypeWithID } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Collection, TypeWithID } from 'payload/types'
import type { TypeWithVersion } from 'payload/versions'
import { findVersionByIDOperation } from 'payload/operations'

View File

@@ -1,5 +1,6 @@
import type { PaginatedDocs } from 'payload/database'
import type { Collection, PayloadRequestWithData , Where } from 'payload/types'
import type { PayloadRequestWithData, Where } from 'payload/types'
import type { Collection } from 'payload/types'
import { findVersionsOperation } from 'payload/operations'
import { isolateObjectProperty } from 'payload/utilities'

View File

@@ -1,4 +1,5 @@
import type { Collection , PayloadRequestWithData } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Collection } from 'payload/types'
import { restoreVersionOperation } from 'payload/operations'
import { isolateObjectProperty } from 'payload/utilities'

View File

@@ -1,5 +1,6 @@
import type { GeneratedTypes } from 'payload'
import type { Collection , PayloadRequestWithData } from 'payload/types'
import type { PayloadRequestWithData } from 'payload/types'
import type { Collection } from 'payload/types'
import { updateByIDOperation } from 'payload/operations'
import { isolateObjectProperty } from 'payload/utilities'

View File

@@ -1,23 +1,39 @@
import type { Document, SanitizedGlobalConfig } from 'payload/types'
import type { PayloadRequest } from 'payload/types'
import { findOneOperation } from 'payload/operations'
import { type Document, type SanitizedGlobalConfig } from 'payload/types'
import { isolateObjectProperty } from 'payload/utilities'
import type { Context } from '../types.js'
export default function findOneResolver(globalConfig: SanitizedGlobalConfig): Document {
return async function resolver(_, args, context: Context) {
if (args.locale) context.req.locale = args.locale
if (args.fallbackLocale) context.req.fallbackLocale = args.fallbackLocale
let { req } = context
const locale = req.locale
const fallbackLocale = req.fallbackLocale
req = isolateObjectProperty<PayloadRequest>(req, 'locale')
req = isolateObjectProperty<PayloadRequest>(req, 'fallbackLocale')
req.locale = args.locale || locale
req.fallbackLocale = args.fallbackLocale || fallbackLocale
const { slug } = globalConfig
if (!req.query) req.query = {}
const draft: boolean =
args.draft ?? req.query?.draft === 'false'
? false
: req.query?.draft === 'true'
? true
: undefined
if (typeof draft === 'boolean') req.query.draft = String(draft)
context.req = req
const options = {
slug,
slug: globalConfig.slug,
depth: 0,
draft: args.draft,
globalConfig,
req: isolateObjectProperty(context.req, 'transactionID'),
req: isolateObjectProperty<PayloadRequest>(req, 'transactionID'),
}
const result = await findOneOperation(options)

View File

@@ -1,6 +1,11 @@
import type { Document, PayloadRequestWithData, SanitizedGlobalConfig } from 'payload/types'
import type { PayloadRequest } from 'payload/types'
import { findVersionByIDOperationGlobal } from 'payload/operations'
import {
type Document,
type PayloadRequestWithData,
type SanitizedGlobalConfig,
} from 'payload/types'
import { isolateObjectProperty } from 'payload/utilities'
import type { Context } from '../types.js'
@@ -20,15 +25,21 @@ export type Resolver = (
export default function findVersionByIDResolver(globalConfig: SanitizedGlobalConfig): Resolver {
return async function resolver(_, args, context: Context) {
if (args.locale) context.req.locale = args.locale
if (args.fallbackLocale) context.req.fallbackLocale = args.fallbackLocale
let { req } = context
const locale = req.locale
const fallbackLocale = req.fallbackLocale
req = isolateObjectProperty<PayloadRequest>(req, 'locale')
req = isolateObjectProperty<PayloadRequest>(req, 'fallbackLocale')
req.locale = args.locale || locale
req.fallbackLocale = args.fallbackLocale || fallbackLocale
context.req = req
const options = {
id: args.id,
depth: 0,
draft: args.draft,
globalConfig,
req: isolateObjectProperty(context.req, 'transactionID'),
req: isolateObjectProperty<PayloadRequest>(req, 'transactionID'),
}
const result = await findVersionByIDOperationGlobal(options)

View File

@@ -1,4 +1,9 @@
import type { Document, PayloadRequestWithData, SanitizedGlobalConfig } from 'payload/types'
import type {
Document,
PayloadRequest,
PayloadRequestWithData,
SanitizedGlobalConfig,
} from 'payload/types'
import { restoreVersionOperationGlobal } from 'payload/operations'
import { isolateObjectProperty } from 'payload/utilities'
@@ -20,7 +25,7 @@ export default function restoreVersionResolver(globalConfig: SanitizedGlobalConf
id: args.id,
depth: 0,
globalConfig,
req: isolateObjectProperty(context.req, 'transactionID'),
req: isolateObjectProperty<PayloadRequest>(context.req, 'transactionID'),
}
const result = await restoreVersionOperationGlobal(options)

View File

@@ -1,5 +1,5 @@
import type { GeneratedTypes } from 'payload'
import type { PayloadRequestWithData, SanitizedGlobalConfig } from 'payload/types'
import type { PayloadRequest, PayloadRequestWithData, SanitizedGlobalConfig } from 'payload/types'
import type { DeepPartial } from 'ts-essentials'
import { updateOperationGlobal } from 'payload/operations'
@@ -24,18 +24,32 @@ export default function updateResolver<TSlug extends keyof GeneratedTypes['globa
globalConfig: SanitizedGlobalConfig,
): Resolver<TSlug> {
return async function resolver(_, args, context: Context) {
if (args.locale) context.req.locale = args.locale
if (args.fallbackLocale) context.req.fallbackLocale = args.fallbackLocale
let { req } = context
const locale = req.locale
const fallbackLocale = req.fallbackLocale
req = isolateObjectProperty<PayloadRequest>(req, 'locale')
req = isolateObjectProperty<PayloadRequest>(req, 'fallbackLocale')
req.locale = args.locale || locale
req.fallbackLocale = args.fallbackLocale || fallbackLocale
if (!req.query) req.query = {}
const { slug } = globalConfig
const draft: boolean =
args.draft ?? req.query?.draft === 'false'
? false
: req.query?.draft === 'true'
? true
: undefined
if (typeof draft === 'boolean') req.query.draft = String(draft)
context.req = req
const options = {
slug,
slug: globalConfig.slug,
data: args.data,
depth: 0,
draft: args.draft,
globalConfig,
req: isolateObjectProperty(context.req, 'transactionID'),
req: isolateObjectProperty<PayloadRequest>(req, 'transactionID'),
}
const result = await updateOperationGlobal<TSlug>(options)

View File

@@ -37,7 +37,8 @@ import {
GraphQLString,
} from 'graphql'
import { fieldAffectsData, optionIsObject, tabHasName } from 'payload/types'
import { flattenTopLevelFields , toWords } from 'payload/utilities'
import { toWords } from 'payload/utilities'
import { flattenTopLevelFields } from 'payload/utilities'
import { GraphQLJSON } from '../packages/graphql-type-json/index.js'
import combineParentName from '../utilities/combineParentName.js'

View File

@@ -41,7 +41,6 @@ import {
GraphQLUnionType,
} from 'graphql'
import { DateTimeResolver, EmailAddressResolver } from 'graphql-scalars'
import { MissingEditorProp } from 'payload/errors'
import { tabHasName } from 'payload/types'
import { createDataloaderCacheKey, toWords } from 'payload/utilities'
@@ -81,7 +80,7 @@ type Args = {
parentName: string
}
export function buildObjectType({
function buildObjectType({
name,
baseFields = {},
config,
@@ -477,10 +476,6 @@ export function buildObjectType({
async resolve(parent, args, context: Context) {
let depth = config.defaultDepth
if (typeof args.depth !== 'undefined') depth = args.depth
if (!field?.editor) {
throw new MissingEditorProp(field) // while we allow disabling editor functionality, you should not have any richText fields defined if you do not have an editor
}
if (typeof field?.editor === 'function') {
throw new Error('Attempted to access unsanitized rich text editor.')
}
@@ -492,13 +487,13 @@ export function buildObjectType({
// is run here again, with the provided depth.
// In the graphql find.ts resolver, the depth is then hard-coded to 0.
// Effectively, this means that the populationPromise for GraphQL is only run here, and not in the find.ts resolver / normal population promise.
if (editor?.graphQLPopulationPromises) {
if (editor?.populationPromises) {
const fieldPromises = []
const populationPromises = []
const populateDepth =
field?.maxDepth !== undefined && field?.maxDepth < depth ? field?.maxDepth : depth
editor?.graphQLPopulationPromises({
editor?.populationPromises({
context,
depth: populateDepth,
draft: args.draft,
@@ -698,3 +693,5 @@ export function buildObjectType({
return newlyCreatedBlockType
}
export default buildObjectType

View File

@@ -37,7 +37,7 @@ import restoreVersionResolver from '../resolvers/collections/restoreVersion.js'
import { updateResolver } from '../resolvers/collections/update.js'
import formatName from '../utilities/formatName.js'
import { buildMutationInputType, getCollectionIDType } from './buildMutationInputType.js'
import { buildObjectType } from './buildObjectType.js'
import buildObjectType from './buildObjectType.js'
import buildPaginatedListType from './buildPaginatedListType.js'
import { buildPolicyType } from './buildPoliciesType.js'
import buildWhereInputType from './buildWhereInputType.js'

View File

@@ -17,7 +17,7 @@ import restoreVersionResolver from '../resolvers/globals/restoreVersion.js'
import updateResolver from '../resolvers/globals/update.js'
import formatName from '../utilities/formatName.js'
import { buildMutationInputType } from './buildMutationInputType.js'
import { buildObjectType } from './buildObjectType.js'
import buildObjectType from './buildObjectType.js'
import buildPaginatedListType from './buildPaginatedListType.js'
import { buildPolicyType } from './buildPoliciesType.js'
import buildWhereInputType from './buildWhereInputType.js'

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/live-preview-react",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"description": "The official live preview React SDK for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/live-preview",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"description": "The official live preview JavaScript SDK for Payload",
"homepage": "https://payloadcms.com",
"repository": {

View File

@@ -1,6 +1,6 @@
{
"name": "@payloadcms/next",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"homepage": "https://payloadcms.com",
"repository": {
"type": "git",
@@ -54,8 +54,8 @@
"path-to-regexp": "^6.2.1",
"qs": "6.11.2",
"react-diff-viewer-continued": "3.2.6",
"react-toastify": "10.0.5",
"sass": "1.77.4",
"sonner": "^1.5.0",
"ws": "^8.16.0"
},
"devDependencies": {
@@ -84,7 +84,7 @@
"payload": "workspace:*"
},
"engines": {
"node": "^18.20.2 || >=20.9.0"
"node": ">=18.20.2"
},
"publishConfig": {
"exports": {

View File

@@ -11,6 +11,7 @@ import { headers as getHeaders, cookies as nextCookies } from 'next/headers.js'
import { parseCookies } from 'payload/auth'
import { createClientConfig } from 'payload/config'
import React from 'react'
import 'react-toastify/dist/ReactToastify.css'
import { getPayloadHMR } from '../../utilities/getPayloadHMR.js'
import { getRequestLanguage } from '../../utilities/getRequestLanguage.js'

View File

@@ -1,5 +1,6 @@
import httpStatus from 'http-status'
import { extractJWT , generatePayloadCookie } from 'payload/auth'
import { extractJWT } from 'payload/auth'
import { generatePayloadCookie } from 'payload/auth'
import { refreshOperation } from 'payload/operations'
import type { CollectionRouteHandler } from '../types.js'

View File

@@ -407,11 +407,6 @@ export const POST =
let res: Response
let collection: Collection
const overrideHttpMethod = request.headers.get('X-HTTP-Method-Override')
if (overrideHttpMethod === 'GET') {
return await GET(config)(request, { params: { slug } })
}
try {
req = await createPayloadRequest({
config,

View File

@@ -1,5 +1,5 @@
@import './styles.scss';
@import './toasts.scss';
@import './toastify.scss';
@import './colors.scss';
:root {

View File

@@ -0,0 +1,58 @@
@import 'vars';
.Toastify {
.Toastify__toast-container {
left: base(5);
transform: none;
right: base(5);
width: auto;
}
.Toastify__toast {
padding: base(0.5);
border-radius: $style-radius-m;
font-weight: 600;
}
.Toastify__close-button {
align-self: center;
opacity: 0.7;
&:hover {
opacity: 1;
}
}
.Toastify__toast--success {
color: var(--color-success-900);
background: var(--color-success-500);
.Toastify__progress-bar {
background-color: var(--color-success-900);
}
}
.Toastify__close-button--success {
color: var(--color-success-900);
}
.Toastify__toast--error {
background: var(--theme-error-500);
color: #fff;
.Toastify__progress-bar {
background-color: #fff;
}
}
.Toastify__close-button--light {
color: inherit;
}
@include mid-break {
.Toastify__toast-container {
left: $baseline;
right: $baseline;
}
}
}

View File

@@ -1,111 +0,0 @@
.payload-toast-container {
.payload-toast-close-button {
left: unset;
right: 0.5rem;
top: 1.55rem;
color: var(--theme-elevation-400);
background: unset;
border: none;
display: flex;
width: 1.25rem;
height: 1.25rem;
justify-content: center;
align-items: center;
&:hover {
background: none;
}
svg {
width: 2rem;
height: 2rem;
}
[dir='RTL'] & {
right: unset;
left: 0.5rem;
}
}
.payload-toast-item {
padding: 1rem 2.5rem 1rem 1rem;
color: var(--theme-text);
font-style: normal;
font-weight: 600;
display: flex;
gap: 1rem;
align-items: center;
width: 100%;
border-radius: 0.15rem;
border: 1px solid var(--theme-border-color);
background: var(--theme-input-bg);
box-shadow:
0px 10px 4px -8px rgba(0, 2, 4, 0.02),
0px 2px 3px 0px rgba(0, 2, 4, 0.05);
.toast-content {
transition: opacity 100ms cubic-bezier(0.55, 0.055, 0.675, 0.19);
}
&[data-front='false'] {
.toast-content {
opacity: 0;
}
}
&[data-expanded='true'] {
.toast-content {
opacity: 1;
}
}
.toast-icon {
svg {
width: 2.4rem;
height: 2.4rem;
}
}
&.toast-warning {
border-color: var(--theme-warning-200);
background-color: var(--theme-warning-100);
}
&.toast-error {
border-color: var(--theme-error-300);
background-color: var(--theme-error-150);
}
&.toast-success {
border-color: var(--theme-success-200);
background-color: var(--theme-success-100);
}
&.toast-info {
border-color: var(--theme-elevation-250);
background-color: var(--theme-elevation-100);
}
[data-theme='light'] & {
&.toast-warning {
border-color: var(--theme-warning-550);
background-color: var(--theme-warning-100);
}
&.toast-error {
border-color: var(--theme-error-200);
background-color: var(--theme-error-50);
}
&.toast-success {
border-color: var(--theme-success-550);
background-color: var(--theme-success-50);
}
&.toast-info {
border-color: var(--theme-border-color);
background-color: var(--theme-elevation-50);
}
}
}
}

View File

@@ -1,7 +1,8 @@
import type { CustomPayloadRequestProperties, PayloadRequest, SanitizedConfig } from 'payload/types'
import { initI18n } from '@payloadcms/translations'
import { executeAuthStrategies , parseCookies } from 'payload/auth'
import { executeAuthStrategies } from 'payload/auth'
import { parseCookies } from 'payload/auth'
import { getDataLoader } from 'payload/utilities'
import qs from 'qs'
import { URL } from 'url'
@@ -58,17 +59,6 @@ export const createPayloadRequest = async ({
fallbackLocale = locales.fallbackLocale
}
const overrideHttpMethod = request.headers.get('X-HTTP-Method-Override')
const queryToParse = overrideHttpMethod === 'GET' ? await request.text() : urlProperties.search
const query = queryToParse
? qs.parse(queryToParse, {
arrayLimit: 1000,
depth: 10,
ignoreQueryPrefix: true,
})
: {}
const customRequest: CustomPayloadRequestProperties = {
context: {},
fallbackLocale,
@@ -85,7 +75,13 @@ export const createPayloadRequest = async ({
payloadUploadSizes: {},
port: urlProperties.port,
protocol: urlProperties.protocol,
query,
query: urlProperties.search
? qs.parse(urlProperties.search, {
arrayLimit: 1000,
depth: 10,
ignoreQueryPrefix: true,
})
: {},
routeParams: params || {},
search: urlProperties.search,
searchParams: urlProperties.searchParams,

View File

@@ -36,16 +36,6 @@ export const reload = async (config: SanitizedConfig, payload: Payload): Promise
// TODO: support HMR for other props in the future (see payload/src/index init()) hat may change on Payload singleton
// Generate types
if (config.typescript.autoGenerate !== false) {
// We cannot run it directly here, as generate-types imports json-schema-to-typescript, which breaks on turbopack.
// see: https://github.com/vercel/next.js/issues/66723
void payload.bin({
args: ['generate:types'],
log: false,
})
}
await payload.db.init()
if (payload.db.connect) {
await payload.db.connect({ hotReload: true })

View File

@@ -1,5 +1,4 @@
import type { I18nClient } from '@payloadcms/translations'
import type { Locale } from 'payload/config'
import type { InitPageResult, PayloadRequestWithData, VisibleEntities } from 'payload/types'
import { initI18n } from '@payloadcms/translations'
@@ -23,6 +22,7 @@ export const initPage = async ({
searchParams,
}: Args): Promise<InitPageResult> => {
const headers = getHeaders()
const localeParam = searchParams?.locale as string
const payload = await getPayloadHMR({ config: configPromise })
const {
@@ -34,6 +34,10 @@ export const initPage = async ({
} = payload.config
const queryString = `${qs.stringify(searchParams ?? {}, { addQueryPrefix: true })}`
const defaultLocale =
localization && localization.defaultLocale ? localization.defaultLocale : 'en'
const localeCode = localeParam || defaultLocale
const locale = localization && findLocaleFromCode(localization, localeCode)
const cookies = parseCookies(headers)
const language = getRequestLanguage({ config: payload.config, cookies, headers })
@@ -60,6 +64,7 @@ export const initPage = async ({
const req = await createLocalReq(
{
fallbackLocale: null,
locale: locale.code,
req: {
host: headers.get('host'),
i18n,
@@ -74,53 +79,9 @@ export const initPage = async ({
)
const { permissions, user } = await payload.auth({ headers, req })
req.user = user
const localeParam = searchParams?.locale as string
let locale: Locale
if (localization) {
const defaultLocaleCode = localization.defaultLocale ? localization.defaultLocale : 'en'
let localeCode: string = localeParam
if (!localeCode) {
try {
localeCode = await payload
.find({
collection: 'payload-preferences',
depth: 0,
limit: 1,
user,
where: {
and: [
{
'user.relationTo': {
equals: payload.config.admin.user,
},
},
{
'user.value': {
equals: user.id,
},
},
{
key: {
equals: 'locale',
},
},
],
},
})
?.then((res) => res.docs?.[0]?.value as string)
} catch (error) {} // eslint-disable-line no-empty
}
locale = findLocaleFromCode(localization, localeCode)
if (!locale) locale = findLocaleFromCode(localization, defaultLocaleCode)
req.locale = locale.code
}
const visibleEntities: VisibleEntities = {
collections: collections
.map(({ slug, admin: { hidden } }) => (!isEntityHidden({ hidden, user }) ? slug : null))

View File

@@ -2,7 +2,8 @@ import type { Metadata } from 'next'
import type { Icon } from 'next/dist/lib/metadata/types/metadata-types.js'
import type { MetaConfig } from 'payload/config'
import { payloadFaviconDark , payloadFaviconLight, staticOGImage } from '@payloadcms/ui/assets'
import { staticOGImage } from '@payloadcms/ui/assets'
import { payloadFaviconDark, payloadFaviconLight } from '@payloadcms/ui/assets'
import QueryString from 'qs'
const defaultOpenGraph = {

View File

@@ -15,7 +15,7 @@ import { useTranslation } from '@payloadcms/ui/providers/Translation'
import { useSearchParams } from 'next/navigation.js'
import qs from 'qs'
import * as React from 'react'
import { toast } from 'sonner'
import { toast } from 'react-toastify'
import { SetDocumentStepNav } from '../Edit/Default/SetDocumentStepNav/index.js'
import { LocaleSelector } from './LocaleSelector/index.js'

View File

@@ -91,7 +91,7 @@ export const Account: React.FC<AdminViewProps> = async ({
initialParams={{
depth: 0,
'fallback-locale': 'null',
locale: locale?.code,
locale: locale.code,
uploadEdits: undefined,
}}
>

View File

@@ -26,7 +26,7 @@ export const getDocumentData = async (args: {
id,
collectionSlug: collectionConfig?.slug,
globalSlug: globalConfig?.slug,
locale: locale?.code,
locale: locale.code,
operation: (collectionConfig && id) || globalConfig ? 'update' : 'create',
schemaPath: collectionConfig?.slug || globalConfig?.slug,
},

View File

@@ -10,7 +10,6 @@ import { EditDepthProvider } from '@payloadcms/ui/providers/EditDepth'
import { FormQueryParamsProvider } from '@payloadcms/ui/providers/FormQueryParams'
import { isEditing as getIsEditing } from '@payloadcms/ui/utilities/isEditing'
import { notFound, redirect } from 'next/navigation.js'
import QueryString from 'qs'
import React from 'react'
import type { GenerateEditViewMetadata } from './getMetaBySegment.js'
@@ -86,14 +85,10 @@ export const Document: React.FC<AdminViewProps> = async ({
}
action = `${serverURL}${apiRoute}/${collectionSlug}${isEditing ? `/${id}` : ''}`
const apiQueryParams = QueryString.stringify(
{
draft: collectionConfig.versions?.drafts ? 'true' : undefined,
locale: locale?.code,
},
{ addQueryPrefix: true },
)
apiURL = `${serverURL}${apiRoute}/${collectionSlug}/${id}${apiQueryParams}`
apiURL = `${serverURL}${apiRoute}/${collectionSlug}/${id}?locale=${locale.code}${
collectionConfig.versions?.drafts ? '&draft=true' : ''
}`
const editConfig = collectionConfig?.admin?.components?.views?.Edit
ViewOverride = typeof editConfig === 'function' ? editConfig : null
@@ -123,14 +118,9 @@ export const Document: React.FC<AdminViewProps> = async ({
action = `${serverURL}${apiRoute}/globals/${globalSlug}`
const apiQueryParams = QueryString.stringify(
{
draft: globalConfig.versions?.drafts ? 'true' : undefined,
locale: locale?.code,
},
{ addQueryPrefix: true },
)
apiURL = `${serverURL}${apiRoute}/${globalSlug}${apiQueryParams}`
apiURL = `${serverURL}${apiRoute}/${globalSlug}?locale=${locale.code}${
globalConfig.versions?.drafts ? '&draft=true' : ''
}`
const editConfig = globalConfig?.admin?.components?.views?.Edit
ViewOverride = typeof editConfig === 'function' ? editConfig : null
@@ -161,17 +151,15 @@ export const Document: React.FC<AdminViewProps> = async ({
hasSavePermission &&
((collectionConfig?.versions?.drafts && collectionConfig?.versions?.drafts?.autosave) ||
(globalConfig?.versions?.drafts && globalConfig?.versions?.drafts?.autosave))
const validateDraftData =
collectionConfig?.versions?.drafts && collectionConfig?.versions?.drafts?.validate
if (shouldAutosave && !validateDraftData && !id && collectionSlug) {
if (shouldAutosave && !id && collectionSlug) {
const doc = await payload.create({
collection: collectionSlug,
data: {},
depth: 0,
draft: true,
fallbackLocale: null,
locale: locale?.code,
locale: locale.code,
req,
user,
})
@@ -216,15 +204,12 @@ export const Document: React.FC<AdminViewProps> = async ({
/>
)}
<HydrateClientUser permissions={permissions} user={user} />
<EditDepthProvider
depth={1}
key={`${collectionSlug || globalSlug}${locale?.code ? `-${locale?.code}` : ''}`}
>
<EditDepthProvider depth={1} key={`${collectionSlug || globalSlug}-${locale.code}`}>
<FormQueryParamsProvider
initialParams={{
depth: 0,
'fallback-locale': 'null',
locale: locale?.code,
locale: locale.code,
uploadEdits: undefined,
}}
>

View File

@@ -10,7 +10,7 @@ import { useConfig } from '@payloadcms/ui/providers/Config'
import { useDocumentInfo } from '@payloadcms/ui/providers/DocumentInfo'
import { useTranslation } from '@payloadcms/ui/providers/Translation'
import React, { useCallback, useEffect, useState } from 'react'
import { toast } from 'sonner'
import { toast } from 'react-toastify'
import type { Props } from './types.js'
@@ -71,7 +71,7 @@ export const Auth: React.FC<Props> = (props) => {
})
if (response.status === 200) {
toast.success(t('authentication:successfullyUnlocked'))
toast.success(t('authentication:successfullyUnlocked'), { autoClose: 3000 })
} else {
toast.error(t('authentication:failedToUnlock'))
}

View File

@@ -9,7 +9,7 @@ import { useConfig } from '@payloadcms/ui/providers/Config'
import { useTranslation } from '@payloadcms/ui/providers/Translation'
import { email } from 'payload/fields/validations'
import React, { Fragment, useState } from 'react'
import { toast } from 'sonner'
import { toast } from 'react-toastify'
export const ForgotPasswordForm: React.FC = () => {
const config = useConfig()

View File

@@ -97,7 +97,7 @@ export const ListView: React.FC<AdminViewProps> = async ({
const sort =
query?.sort && typeof query.sort === 'string'
? query.sort
: listPreferences?.sort || collectionConfig.defaultSort || undefined
: listPreferences?.sort || undefined
const data = await payload.find({
collection: collectionSlug,

View File

@@ -10,20 +10,16 @@ export const DeviceContainer: React.FC<{
const { children } = props
const deviceFrameRef = React.useRef<HTMLDivElement>(null)
const outerFrameRef = React.useRef<HTMLDivElement>(null)
const { breakpoint, setMeasuredDeviceSize, size: desiredSize, zoom } = useLivePreviewContext()
const { breakpoint, setMeasuredDeviceSize, size, zoom } = useLivePreviewContext()
// Keep an accurate measurement of the actual device size as it is truly rendered
// This is helpful when `sizes` are non-number units like percentages, etc.
const { size: measuredDeviceSize } = useResize(deviceFrameRef.current)
const { size: outerFrameSize } = useResize(outerFrameRef.current)
let deviceIsLargerThanFrame: boolean = false
const { size: measuredDeviceSize } = useResize(deviceFrameRef)
// Sync the measured device size with the context so that other components can use it
// This happens from the bottom up so that as this component mounts and unmounts,
// its size is freshly populated again upon re-mounting, i.e. going from iframe->popup->iframe
// Its size is freshly populated again upon re-mounting, i.e. going from iframe->popup->iframe
useEffect(() => {
if (measuredDeviceSize) {
setMeasuredDeviceSize(measuredDeviceSize)
@@ -38,34 +34,13 @@ export const DeviceContainer: React.FC<{
if (
typeof zoom === 'number' &&
typeof desiredSize.width === 'number' &&
typeof desiredSize.height === 'number' &&
typeof measuredDeviceSize.width === 'number' &&
typeof measuredDeviceSize.height === 'number'
typeof size.width === 'number' &&
typeof size.height === 'number'
) {
const scaledWidth = size.width / zoom
const difference = scaledWidth - size.width
x = `${difference / 2}px`
margin = '0 auto'
const scaledDesiredWidth = desiredSize.width / zoom
const scaledDeviceWidth = measuredDeviceSize.width * zoom
const scaledDeviceDifferencePixels = scaledDesiredWidth - desiredSize.width
deviceIsLargerThanFrame = scaledDeviceWidth > outerFrameSize.width
if (deviceIsLargerThanFrame) {
if (zoom > 1) {
const differenceFromDeviceToFrame = measuredDeviceSize.width - outerFrameSize.width
if (differenceFromDeviceToFrame < 0) x = `${differenceFromDeviceToFrame / 2}px`
else x = '0'
} else {
x = '0'
}
} else {
if (zoom >= 1) {
x = `${scaledDeviceDifferencePixels / 2}px`
} else {
const differenceFromDeviceToFrame = outerFrameSize.width - scaledDeviceWidth
x = `${differenceFromDeviceToFrame / 2}px`
margin = '0'
}
}
}
}
@@ -73,29 +48,21 @@ export const DeviceContainer: React.FC<{
let height = zoom ? `${100 / zoom}%` : '100%'
if (breakpoint !== 'responsive') {
width = `${desiredSize?.width / (typeof zoom === 'number' ? zoom : 1)}px`
height = `${desiredSize?.height / (typeof zoom === 'number' ? zoom : 1)}px`
width = `${size?.width / (typeof zoom === 'number' ? zoom : 1)}px`
height = `${size?.height / (typeof zoom === 'number' ? zoom : 1)}px`
}
return (
<div
ref={outerFrameRef}
ref={deviceFrameRef}
style={{
height: '100%',
width: '100%',
height,
margin,
transform: `translate3d(${x}, 0, 0)`,
width,
}}
>
<div
ref={deviceFrameRef}
style={{
height,
margin,
transform: `translate3d(${x}, 0, 0)`,
width,
}}
>
{children}
</div>
{children}
</div>
)
}

View File

@@ -11,7 +11,7 @@ import { useConfig } from '@payloadcms/ui/providers/Config'
import { useTranslation } from '@payloadcms/ui/providers/Translation'
import { useRouter } from 'next/navigation.js'
import React from 'react'
import { toast } from 'sonner'
import { toast } from 'react-toastify'
type Args = {
token: string
@@ -49,7 +49,7 @@ export const ResetPasswordClient: React.FC<Args> = ({ token }) => {
history.push(`${admin}`)
} else {
history.push(`${admin}/login`)
toast.success(i18n.t('general:updatedSuccessfully'))
toast.success(i18n.t('general:updatedSuccessfully'), { autoClose: 3000 })
}
},
[fetchFullUser, history, admin, i18n],

View File

@@ -1,5 +1,6 @@
import type { CollectionPermission, GlobalPermission } from 'payload/auth'
import type { Document , OptionObject } from 'payload/types'
import type { OptionObject } from 'payload/types'
import type { Document } from 'payload/types'
export type CompareOption = {
label: string

View File

@@ -9,7 +9,7 @@ import { MinimalTemplate } from '@payloadcms/ui/templates/Minimal'
import { requests } from '@payloadcms/ui/utilities/api'
import { useRouter } from 'next/navigation.js'
import React, { Fragment, useCallback, useState } from 'react'
import { toast } from 'sonner'
import { toast } from 'react-toastify'
import type { Props } from './types.js'

View File

@@ -28,13 +28,6 @@ export const withPayload = (nextConfig = {}) => {
'libsql',
],
},
turbo: {
...(nextConfig?.experimental?.turbo || {}),
resolveAlias: {
...(nextConfig?.experimental?.turbo?.resolveAlias || {}),
'payload-mock-package': 'payload-mock-package',
},
},
},
headers: async () => {
const headersFromConfig = 'headers' in nextConfig ? await nextConfig.headers() : []

View File

@@ -4,6 +4,8 @@ import { register } from 'node:module'
import path from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { bin } from './dist/bin/index.js'
// Allow disabling SWC for debugging
if (process.env.DISABLE_SWC !== 'true') {
const filename = fileURLToPath(import.meta.url)
@@ -13,9 +15,4 @@ if (process.env.DISABLE_SWC !== 'true') {
register('./dist/bin/loader/index.js', url)
}
const start = async () => {
const { bin } = await import('./dist/bin/index.js')
bin()
}
void start()
bin()

View File

@@ -1,6 +1,6 @@
{
"name": "payload",
"version": "3.0.0-beta.47",
"version": "3.0.0-beta.41",
"description": "Node, React, Headless CMS and Application Framework built on Next.js",
"keywords": [
"admin panel",
@@ -137,7 +137,7 @@
}
},
"engines": {
"node": "^18.20.2 || >=20.9.0"
"node": "^18.20.2 || >=20.6.0"
},
"publishConfig": {
"exports": {

View File

@@ -2,10 +2,8 @@ import type { GenericLanguages, I18n, I18nClient } from '@payloadcms/translation
import type { JSONSchema4 } from 'json-schema'
import type React from 'react'
import type { SanitizedCollectionConfig, TypeWithID } from '../collections/config/types.js'
import type { SanitizedConfig } from '../config/types.js'
import type { Field, FieldAffectingData, RichTextField, Validate } from '../fields/config/types.js'
import type { SanitizedGlobalConfig } from '../globals/config/types.js'
import type { Field, FieldBase, RichTextField, Validate } from '../fields/config/types.js'
import type { PayloadRequestWithData, RequestContext } from '../types/index.js'
import type { WithServerSidePropsComponentProps } from './elements/WithServerSideProps.js'
@@ -17,173 +15,6 @@ export type RichTextFieldProps<
path?: string
}
export type AfterReadRichTextHookArgs<
TData extends TypeWithID = any,
TValue = any,
TSiblingData = any,
> = {
currentDepth?: number
depth?: number
draft?: boolean
fallbackLocale?: string
fieldPromises?: Promise<void>[]
/** Boolean to denote if this hook is running against finding one, or finding many within the afterRead hook. */
findMany?: boolean
flattenLocales?: boolean
locale?: string
/** A string relating to which operation the field type is currently executing within. */
operation?: 'create' | 'delete' | 'read' | 'update'
overrideAccess?: boolean
populationPromises?: Promise<void>[]
showHiddenFields?: boolean
triggerAccessControl?: boolean
triggerHooks?: boolean
}
export type AfterChangeRichTextHookArgs<
TData extends TypeWithID = any,
TValue = any,
TSiblingData = any,
> = {
/** A string relating to which operation the field type is currently executing within. */
operation: 'create' | 'update'
/** The document before changes were applied. */
previousDoc?: TData
/** The sibling data of the document before changes being applied. */
previousSiblingDoc?: TData
/** The previous value of the field, before changes */
previousValue?: TValue
}
export type BeforeValidateRichTextHookArgs<
TData extends TypeWithID = any,
TValue = any,
TSiblingData = any,
> = {
/** A string relating to which operation the field type is currently executing within. */
operation: 'create' | 'update'
overrideAccess?: boolean
/** The sibling data of the document before changes being applied. */
previousSiblingDoc?: TData
/** The previous value of the field, before changes */
previousValue?: TValue
}
export type BeforeChangeRichTextHookArgs<
TData extends TypeWithID = any,
TValue = any,
TSiblingData = any,
> = {
/**
* The original data with locales (not modified by any hooks). Only available in `beforeChange` and `beforeDuplicate` field hooks.
*/
docWithLocales?: Record<string, unknown>
duplicate?: boolean
errors?: { field: string; message: string }[]
/** Only available in `beforeChange` field hooks */
mergeLocaleActions?: (() => Promise<void>)[]
/** A string relating to which operation the field type is currently executing within. */
operation?: 'create' | 'delete' | 'read' | 'update'
/** The sibling data of the document before changes being applied. */
previousSiblingDoc?: TData
/** The previous value of the field, before changes */
previousValue?: TValue
/**
* The original siblingData with locales (not modified by any hooks).
*/
siblingDocWithLocales?: Record<string, unknown>
skipValidation?: boolean
}
export type BaseRichTextHookArgs<
TData extends TypeWithID = any,
TValue = any,
TSiblingData = any,
> = {
/** The collection which the field belongs to. If the field belongs to a global, this will be null. */
collection: SanitizedCollectionConfig | null
context: RequestContext
/** The data passed to update the document within create and update operations, and the full document itself in the afterRead hook. */
data?: Partial<TData>
/** The field which the hook is running against. */
field: FieldAffectingData
/** The global which the field belongs to. If the field belongs to a collection, this will be null. */
global: SanitizedGlobalConfig | null
/** The full original document in `update` operations. In the `afterChange` hook, this is the resulting document of the operation. */
originalDoc?: TData
/**
* The path of the field, e.g. ["group", "myArray", 1, "textField"]. The path is the schemaPath but with indexes and would be used in the context of field data, not field schemas.
*/
path: (number | string)[]
/** The Express request object. It is mocked for Local API operations. */
req: PayloadRequestWithData
/**
* The schemaPath of the field, e.g. ["group", "myArray", "textField"]. The schemaPath is the path but without indexes and would be used in the context of field schemas, not field data.
*/
schemaPath: string[]
/** The sibling data passed to a field that the hook is running against. */
siblingData: Partial<TSiblingData>
/** The value of the field. */
value?: TValue
}
export type AfterReadRichTextHook<
TData extends TypeWithID = any,
TValue = any,
TSiblingData = any,
> = (
args: BaseRichTextHookArgs<TData, TValue, TSiblingData> &
AfterReadRichTextHookArgs<TData, TValue, TSiblingData>,
) => Promise<TValue> | TValue
export type AfterChangeRichTextHook<
TData extends TypeWithID = any,
TValue = any,
TSiblingData = any,
> = (
args: BaseRichTextHookArgs<TData, TValue, TSiblingData> &
AfterChangeRichTextHookArgs<TData, TValue, TSiblingData>,
) => Promise<TValue> | TValue
export type BeforeChangeRichTextHook<
TData extends TypeWithID = any,
TValue = any,
TSiblingData = any,
> = (
args: BaseRichTextHookArgs<TData, TValue, TSiblingData> &
BeforeChangeRichTextHookArgs<TData, TValue, TSiblingData>,
) => Promise<TValue> | TValue
export type BeforeValidateRichTextHook<
TData extends TypeWithID = any,
TValue = any,
TSiblingData = any,
> = (
args: BaseRichTextHookArgs<TData, TValue, TSiblingData> &
BeforeValidateRichTextHookArgs<TData, TValue, TSiblingData>,
) => Promise<TValue> | TValue
export type RichTextHooks = {
afterChange?: AfterChangeRichTextHook[]
afterRead?: AfterReadRichTextHook[]
beforeChange?: BeforeChangeRichTextHook[]
beforeValidate?: BeforeValidateRichTextHook[]
}
type RichTextAdapterBase<
Value extends object = object,
AdapterProps = any,
@@ -201,28 +32,7 @@ type RichTextAdapterBase<
schemaMap: Map<string, Field[]>
schemaPath: string
}) => Map<string, Field[]>
/**
* Like an afterRead hook, but runs only for the GraphQL resolver. For populating data, this should be used, as afterRead hooks do not have a depth in graphQL.
*
* To populate stuff / resolve field hooks, mutate the incoming populationPromises or fieldPromises array. They will then be awaited in the correct order within payload itself.
* @param data
*/
graphQLPopulationPromises?: (data: {
context: RequestContext
currentDepth?: number
depth: number
draft: boolean
field: RichTextField<Value, AdapterProps, ExtraFieldProperties>
fieldPromises: Promise<void>[]
findMany: boolean
flattenLocales: boolean
overrideAccess?: boolean
populationPromises: Promise<void>[]
req: PayloadRequestWithData
showHiddenFields: boolean
siblingDoc: Record<string, unknown>
}) => void
hooks?: RichTextHooks
hooks?: FieldBase['hooks']
i18n?: Partial<GenericLanguages>
outputSchema?: ({
collectionIDFieldTypes,
@@ -240,6 +50,27 @@ type RichTextAdapterBase<
interfaceNameDefinitions: Map<string, JSONSchema4>
isRequired: boolean
}) => JSONSchema4
/**
* Like an afterRead hook, but runs for both afterRead AND in the GraphQL resolver. For populating data, this should be used.
*
* To populate stuff / resolve field hooks, mutate the incoming populationPromises or fieldPromises array. They will then be awaited in the correct order within payload itself.
* @param data
*/
populationPromises?: (data: {
context: RequestContext
currentDepth?: number
depth: number
draft: boolean
field: RichTextField<Value, AdapterProps, ExtraFieldProperties>
fieldPromises: Promise<void>[]
findMany: boolean
flattenLocales: boolean
overrideAccess?: boolean
populationPromises: Promise<void>[]
req: PayloadRequestWithData
showHiddenFields: boolean
siblingDoc: Record<string, unknown>
}) => void
validate: Validate<
Value,
Value,

View File

@@ -42,7 +42,7 @@ export type InitPageResult = {
docID?: string
globalConfig?: SanitizedGlobalConfig
languageOptions: LanguageOptions
locale?: Locale
locale: Locale
permissions: Permissions
req: PayloadRequestWithData
translations: ClientTranslationsObject

View File

@@ -129,7 +129,8 @@ export const forgotPasswordOperation = async (incomingArgs: Arguments): Promise<
})
}
await email.sendEmail({
// eslint-disable-next-line @typescript-eslint/no-floating-promises
email.sendEmail({
from: `"${email.defaultFromName}" <${email.defaultFromAddress}>`,
html,
subject,

View File

@@ -1,4 +1,5 @@
import type { GeneratedTypes, Payload , RequestContext } from '../../../index.js'
import type { Payload, RequestContext } from '../../../index.js'
import type { GeneratedTypes } from '../../../index.js'
import type { PayloadRequestWithData } from '../../../types/index.js'
import type { Result } from '../login.js'

View File

@@ -1,4 +1,5 @@
import type { GeneratedTypes, Payload , RequestContext } from '../../../index.js'
import type { Payload, RequestContext } from '../../../index.js'
import type { GeneratedTypes } from '../../../index.js'
import type { PayloadRequestWithData } from '../../../types/index.js'
import type { Result } from '../resetPassword.js'

View File

@@ -1,4 +1,5 @@
import type { GeneratedTypes, Payload , RequestContext } from '../../../index.js'
import type { Payload, RequestContext } from '../../../index.js'
import type { GeneratedTypes } from '../../../index.js'
import type { PayloadRequestWithData } from '../../../types/index.js'
import { APIError } from '../../../errors/index.js'

View File

@@ -1,4 +1,5 @@
import type { GeneratedTypes, Payload , RequestContext } from '../../../index.js'
import type { Payload, RequestContext } from '../../../index.js'
import type { GeneratedTypes } from '../../../index.js'
import type { PayloadRequestWithData } from '../../../types/index.js'
import { APIError } from '../../../errors/index.js'

View File

@@ -2,7 +2,8 @@ import jwt from 'jsonwebtoken'
import url from 'url'
import type { BeforeOperationHook, Collection } from '../../collections/config/types.js'
import type { Document , PayloadRequestWithData } from '../../types/index.js'
import type { PayloadRequestWithData } from '../../types/index.js'
import type { Document } from '../../types/index.js'
import { buildAfterOperation } from '../../collections/operations/utils.js'
import { Forbidden } from '../../errors/index.js'

View File

@@ -64,7 +64,8 @@ export async function sendVerificationEmail(args: Args): Promise<void> {
})
}
await email.sendEmail({
// eslint-disable-next-line @typescript-eslint/no-floating-promises
email.sendEmail({
from: `"${email.defaultFromName}" <${email.defaultFromAddress}>`,
html,
subject,

View File

@@ -6,16 +6,11 @@ import type { SanitizedConfig } from '../config/types.js'
import { configToJSONSchema } from '../utilities/configToJSONSchema.js'
import Logger from '../utilities/logger.js'
export async function generateTypes(
config: SanitizedConfig,
options?: { log: boolean },
): Promise<void> {
export async function generateTypes(config: SanitizedConfig): Promise<void> {
const logger = Logger()
const outputFile = process.env.PAYLOAD_TS_OUTPUT_PATH || config.typescript.outputFile
const shouldLog = options?.log ?? true
if (shouldLog) logger.info('Compiling TS types for Collections and Globals...')
logger.info('Compiling TS types for Collections and Globals...')
const jsonSchema = configToJSONSchema(config, config.db.defaultIDType)
@@ -41,18 +36,6 @@ export async function generateTypes(
compiled += `\n\n${declare}`
}
}
// Diff the compiled types against the existing types file
try {
const existingTypes = fs.readFileSync(outputFile, 'utf-8')
if (compiled === existingTypes) {
return
}
} catch (_) {
// swallow err
}
fs.writeFileSync(outputFile, compiled)
if (shouldLog) logger.info(`Types written to ${outputFile}`)
logger.info(`Types written to ${outputFile}`)
}

View File

@@ -15,7 +15,6 @@ import { getBaseUploadFields } from '../../uploads/getBaseFields.js'
import { formatLabels } from '../../utilities/formatLabels.js'
import { isPlainObject } from '../../utilities/isPlainObject.js'
import baseVersionFields from '../../versions/baseFields.js'
import { versionDefaults } from '../../versions/defaults.js'
import { authDefaults, defaults } from './defaults.js'
export const sanitizeCollection = async (
@@ -85,20 +84,15 @@ export const sanitizeCollection = async (
if (sanitized.versions.drafts === true) {
sanitized.versions.drafts = {
autosave: false,
validate: false,
}
}
if (sanitized.versions.drafts.autosave === true) {
sanitized.versions.drafts.autosave = {
interval: versionDefaults.autosaveInterval,
interval: 2000,
}
}
if (sanitized.versions.drafts.validate === undefined) {
sanitized.versions.drafts.validate = false
}
sanitized.fields = mergeBaseFields(sanitized.fields, baseVersionFields)
}
}

View File

@@ -221,7 +221,6 @@ const collectionSchema = joi.object().keys({
interval: joi.number(),
}),
),
validate: joi.boolean(),
}),
joi.boolean(),
),

View File

@@ -165,6 +165,14 @@ export const createOperation = async <TSlug extends keyof GeneratedTypes['collec
Promise.resolve(),
)
// /////////////////////////////////////
// Write files to local storage
// /////////////////////////////////////
// if (!collectionConfig.upload.disableLocalStorage) {
// await uploadFiles(payload, filesToUpload, req.t)
// }
// /////////////////////////////////////
// beforeChange - Collection
// /////////////////////////////////////
@@ -195,10 +203,7 @@ export const createOperation = async <TSlug extends keyof GeneratedTypes['collec
global: null,
operation: 'create',
req,
skipValidation:
shouldSaveDraft &&
collectionConfig.versions.drafts &&
!collectionConfig.versions.drafts.validate,
skipValidation: shouldSaveDraft,
})
// /////////////////////////////////////
@@ -263,7 +268,8 @@ export const createOperation = async <TSlug extends keyof GeneratedTypes['collec
// /////////////////////////////////////
if (collectionConfig.auth && collectionConfig.auth.verify) {
await sendVerificationEmail({
// eslint-disable-next-line @typescript-eslint/no-floating-promises
sendVerificationEmail({
collection: { config: collectionConfig },
config: payload.config,
disableEmail: disableVerificationEmail,

View File

@@ -205,10 +205,7 @@ export const duplicateOperation = async <TSlug extends keyof GeneratedTypes['col
global: null,
operation,
req,
skipValidation:
shouldSaveDraft &&
collectionConfig.versions.drafts &&
!collectionConfig.versions.drafts.validate,
skipValidation: shouldSaveDraft,
})
// set req.locale back to the original locale

View File

@@ -1,6 +1,7 @@
import type { MarkOptional } from 'ts-essentials'
import type { GeneratedTypes , Payload } from '../../../index.js'
import type { GeneratedTypes } from '../../../index.js'
import type { Payload } from '../../../index.js'
import type { Document, PayloadRequestWithData, RequestContext } from '../../../types/index.js'
import type { File } from '../../../uploads/types.js'

View File

@@ -1,5 +1,7 @@
import type { GeneratedTypes , Payload } from '../../../index.js'
import type { Document, PayloadRequestWithData , RequestContext, Where } from '../../../types/index.js'
import type { Payload } from '../../../index.js'
import type { GeneratedTypes } from '../../../index.js'
import type { PayloadRequestWithData, RequestContext } from '../../../types/index.js'
import type { Document, Where } from '../../../types/index.js'
import type { BulkOperationResult } from '../../config/types.js'
import { APIError } from '../../../errors/index.js'

View File

@@ -270,10 +270,7 @@ export const updateOperation = async <TSlug extends keyof GeneratedTypes['collec
operation: 'update',
req,
skipValidation:
shouldSaveDraft &&
collectionConfig.versions.drafts &&
!collectionConfig.versions.drafts.validate &&
data._status !== 'published',
Boolean(collectionConfig.versions?.drafts) && data._status !== 'published',
})
// /////////////////////////////////////

View File

@@ -242,11 +242,7 @@ export const updateByIDOperation = async <TSlug extends keyof GeneratedTypes['co
global: null,
operation: 'update',
req,
skipValidation:
shouldSaveDraft &&
collectionConfig.versions.drafts &&
!collectionConfig.versions.drafts.validate &&
data._status !== 'published',
skipValidation: Boolean(collectionConfig.versions?.drafts) && data._status !== 'published',
})
// /////////////////////////////////////

View File

@@ -2,7 +2,7 @@ import type { Config } from './types.js'
export const defaults: Omit<Config, 'db' | 'editor' | 'secret'> = {
admin: {
avatar: 'gravatar',
avatar: 'default',
components: {},
custom: {},
dateFormat: 'MMMM do yyyy, h:mm a',
@@ -49,7 +49,6 @@ export const defaults: Omit<Config, 'db' | 'editor' | 'secret'> = {
serverURL: '',
telemetry: true,
typescript: {
autoGenerate: true,
outputFile: `${typeof process?.cwd === 'function' ? process.cwd() : ''}/payload-types.ts`,
},
upload: {},

View File

@@ -1,5 +1,5 @@
import { findUpSync, pathExistsSync } from 'find-up'
import { getTsconfig } from 'get-tsconfig'
import fs from 'fs'
import path from 'path'
/**
@@ -12,30 +12,37 @@ const getTSConfigPaths = (): {
outPath?: string
rootPath?: string
srcPath?: string
tsConfigPath?: string
} => {
const tsConfigResult = getTsconfig()
const tsConfig = tsConfigResult.config
const tsConfigDir = path.dirname(tsConfigResult.path)
const tsConfigPath = findUpSync('tsconfig.json')
if (!tsConfigPath) {
return {
rootPath: process.cwd(),
}
}
try {
const rootConfigDir = path.resolve(tsConfigDir, tsConfig.compilerOptions.baseUrl || '')
// Read the file as a string and remove trailing commas
const rawTsConfig = fs
.readFileSync(tsConfigPath, 'utf-8')
.replace(/,\s*\]/g, ']')
.replace(/,\s*\}/g, '}')
const tsConfig = JSON.parse(rawTsConfig)
const rootPath = process.cwd()
const srcPath = tsConfig.compilerOptions?.rootDir || path.resolve(process.cwd(), 'src')
const outPath = tsConfig.compilerOptions?.outDir || path.resolve(process.cwd(), 'dist')
let configPath = path.resolve(
rootConfigDir,
tsConfig.compilerOptions?.paths?.['@payload-config']?.[0],
)
const tsConfigDir = path.dirname(tsConfigPath)
let configPath = tsConfig.compilerOptions?.paths?.['@payload-config']?.[0]
if (configPath) {
configPath = path.resolve(rootConfigDir, configPath)
configPath = path.resolve(tsConfigDir, configPath)
}
return {
configPath,
outPath,
rootPath: rootConfigDir,
rootPath,
srcPath,
tsConfigPath: tsConfigResult.path,
}
} catch (error) {
console.error(`Error parsing tsconfig.json: ${error}`) // Do not throw the error, as we can still continue with the other config path finding methods
@@ -63,11 +70,6 @@ export const findConfig = (): string => {
const { configPath, outPath, rootPath, srcPath } = getTSConfigPaths()
// if configPath is absolute file, not folder, return it
if (path.extname(configPath) === '.js' || path.extname(configPath) === '.ts') {
return configPath
}
const searchPaths =
process.env.NODE_ENV === 'production'
? [configPath, outPath, srcPath, rootPath]

View File

@@ -69,17 +69,7 @@ export default joi.object({
meta: joi.object().keys({
defaultOGImageType: joi.string().valid('off', 'dynamic', 'static'),
description: joi.string(),
icons: joi.array().items(
joi.object().keys({
type: joi.string(),
color: joi.string(),
fetchPriority: joi.string().valid('auto', 'high', 'low'),
media: joi.string(),
rel: joi.string(),
sizes: joi.string(),
url: joi.string(),
}),
),
icons: joi.array().items(joi.object()),
openGraph: openGraphSchema,
titleSuffix: joi.string(),
}),
@@ -111,7 +101,7 @@ export default joi.object({
defaultMaxTextLength: joi.number(),
editor: joi
.object()
.optional()
.required()
.keys({
CellComponent: componentSchema.optional(),
FieldComponent: componentSchema.optional(),
@@ -199,7 +189,6 @@ export default joi.object({
sharp: joi.any(),
telemetry: joi.boolean(),
typescript: joi.object({
autoGenerate: joi.boolean(),
declare: joi.alternatives().try(joi.boolean(), joi.object({ ignoreTSError: joi.boolean() })),
outputFile: joi.string(),
}),

View File

@@ -10,7 +10,7 @@ const ogImageObj = joi.object({
export const openGraphSchema = joi.object({
description: joi.string(),
images: joi.alternatives().try(ogImageObj, joi.array().items(ogImageObj)),
images: joi.alternatives().try(joi.array().items(joi.string()), joi.array().items(ogImageObj)),
title: joi.string(),
siteName: joi.string(),
url: joi.string(),
})

View File

@@ -120,7 +120,7 @@ export type MetaConfig = {
*
* For example browser tabs, phone home screens, and search engine results.
*/
icons?: IconConfig[]
icons?: IconConfig
/**
* Overrides the auto-generated <meta name="keywords"> of admin pages
* @example `"CMS, Payload, Custom"`
@@ -615,7 +615,7 @@ export type Config = {
*/
defaultMaxTextLength?: number
/** Default richtext editor to use for richText fields */
editor?: RichTextAdapterProvider<any, any, any>
editor: RichTextAdapterProvider<any, any, any>
/**
* Email Adapter
*
@@ -719,12 +719,6 @@ export type Config = {
telemetry?: boolean
/** Control how typescript interfaces are generated from your collections. */
typescript?: {
/**
* Automatically generate types during development
* @default true
*/
autoGenerate?: boolean
/** Disable declare block in generated types file */
declare?:
| {
@@ -738,7 +732,6 @@ export type Config = {
ignoreTSError?: boolean
}
| false
/** Filename to write the generated types to */
outputFile?: string
}
@@ -754,7 +747,7 @@ export type SanitizedConfig = Omit<
> & {
collections: SanitizedCollectionConfig[]
/** Default richtext editor to use for richText fields */
editor?: RichTextAdapter<any, any, any>
editor: RichTextAdapter<any, any, any>
endpoints: Endpoint[]
globals: SanitizedGlobalConfig[]
i18n: Required<I18nOptions>

View File

@@ -12,7 +12,6 @@ export { InvalidFieldName } from './InvalidFieldName.js'
export { InvalidFieldRelationship } from './InvalidFieldRelationship.js'
export { LockedAuth } from './LockedAuth.js'
export { MissingCollectionLabel } from './MissingCollectionLabel.js'
export { MissingEditorProp } from './MissingEditorProp.js'
export { MissingFieldInputOptions } from './MissingFieldInputOptions.js'
export { MissingFieldType } from './MissingFieldType.js'
export { MissingFile } from './MissingFile.js'

View File

@@ -2,10 +2,8 @@ export {
APIError,
AuthenticationError,
DuplicateCollection,
DuplicateFieldName,
DuplicateGlobal,
ErrorDeletingFile,
FileRetrievalError,
FileUploadError,
Forbidden,
InvalidConfiguration,
@@ -13,7 +11,6 @@ export {
InvalidFieldRelationship,
LockedAuth,
MissingCollectionLabel,
MissingEditorProp,
MissingFieldInputOptions,
MissingFieldType,
MissingFile,

Some files were not shown because too many files have changed in this diff Show More