Commit Graph

122 Commits

Author SHA1 Message Date
Elliot DeNolf
f18ca9cc2b build: move larger scripts into tools dir in workspace (#10653)
Having the `scripts` dir re-use all packages from the top-level was
getting quite unwieldy. Created new `tools` directory that is part of
the workspace. Packages are exported with the `@tools` package
namespace.
2025-01-20 11:34:51 -05:00
Jarrod Flesch
813e70be1f feat: adds multi-tenant plugin (#10447)
### Multi Tenant Plugin
This PR adds a `@payloadcms/plugin-multi-tenant` package. The goal is to
consolidate a source of truth for multi-tenancy. Currently we are
maintaining different implementations for clients, users in discord and
our examples repo. When updates or new paradigms arise we need to
communicate this with everyone and update code examples which is hard to
maintain.

### What does it do?
- adds a tenant selector to the sidebar, above the nav links
- adds a hidden tenant field to every collection that you specify
- adds an array field to your users collection, allowing you to assign
users to tenants
- by default combines the access control (to enabled collections) that
you define, with access control based on the tenants assigned to user on
the request
- by default adds a baseListFilter that filters the documents shown in
the list view with the selected tenant in the admin panel

### What does it not do?
- it does not implement multi-tenancy for your frontend. You will need
to query data for specific tenants to build your website/application
- it does not add a tenants collection, you **NEED** to add a tenants
collection, where you can define what types of fields you would like on
it

### The plugin config

Most of the options listed below are _optional_, but it is easier to
just lay out all of the configuration options.

**TS Type**
```ts
type MultiTenantPluginConfig<ConfigTypes = unknown> = {
  /**
   * After a tenant is deleted, the plugin will attempt to clean up related documents
   * - removing documents with the tenant ID
   * - removing the tenant from users
   *
   * @default true
   */
  cleanupAfterTenantDelete?: boolean
  /**
   * Automatically
   */
  collections: {
    [key in CollectionSlug]?: {
      /**
       * Set to `true` if you want the collection to behave as a global
       *
       * @default false
       */
      isGlobal?: boolean
      /**
       * Set to `false` if you want to manually apply the baseListFilter
       *
       * @default true
       */
      useBaseListFilter?: boolean
      /**
       * Set to `false` if you want to handle collection access manually without the multi-tenant constraints applied
       *
       * @default true
       */
      useTenantAccess?: boolean
    }
  }
  /**
   * Enables debug mode
   * - Makes the tenant field visible in the admin UI within applicable collections
   *
   * @default false
   */
  debug?: boolean
  /**
   * Enables the multi-tenant plugin
   *
   * @default true
   */
  enabled?: boolean
  /**
   * Field configuration for the field added to all tenant enabled collections
   */
  tenantField?: {
    access?: RelationshipField['access']
    /**
     * The name of the field added to all tenant enabled collections
     *
     * @default 'tenant'
     */
    name?: string
  }
  /**
   * Field configuration for the field added to the users collection
   *
   * If `includeDefaultField` is `false`, you must include the field on your users collection manually
   * This is useful if you want to customize the field or place the field in a specific location
   */
  tenantsArrayField?:
    | {
        /**
         * Access configuration for the array field
         */
        arrayFieldAccess?: ArrayField['access']
        /**
         * When `includeDefaultField` is `true`, the field will be added to the users collection automatically
         */
        includeDefaultField?: true
        /**
         * Additional fields to include on the tenants array field
         */
        rowFields?: Field[]
        /**
         * Access configuration for the tenant field
         */
        tenantFieldAccess?: RelationshipField['access']
      }
    | {
        arrayFieldAccess?: never
        /**
         * When `includeDefaultField` is `false`, you must include the field on your users collection manually
         */
        includeDefaultField?: false
        rowFields?: never
        tenantFieldAccess?: never
      }
  /**
   * The slug for the tenant collection
   *
   * @default 'tenants'
   */
  tenantsSlug?: string
  /**
   * Function that determines if a user has access to _all_ tenants
   *
   * Useful for super-admin type users
   */
  userHasAccessToAllTenants?: (
    user: ConfigTypes extends { user: User } ? ConfigTypes['user'] : User,
  ) => boolean
}
```

**Example usage**
```ts
import type { Config } from './payload-types'
import { buildConfig } from 'payload'

export default buildConfig({
  plugins: [
    multiTenantPlugin<Config>({
      collections: {
        pages: {},
      },
      userHasAccessToAllTenants: (user) => isSuperAdmin(user),
    }),
  ],
})
```


### How to configure Collections as Globals for multi-tenant

When using multi-tenant, globals need to actually be configured as
collections so the content can be specific per tenant.
To do that, you can mark a collection with `isGlobal` and it will behave
like a global and users will not see the list view.

```ts
multiTenantPlugin({
  collections: {
    navigation: {
      isGlobal: true,
    },
  },
})
```
2025-01-15 14:47:46 -05:00
Elliot DeNolf
4629784c99 ci(scripts): publish-canary script always bump minor, more realistic [skip ci][skip lint] 2025-01-14 21:16:11 -05:00
Paul
7321f9f3d5 templates: add support for scheduled publish to the website template [no lint] (#10455)
Adds configuration for vercel cron jobs and scheduled publish/unpublish
in website templates
2025-01-08 13:43:47 -06:00
Elliot DeNolf
6dcf817c22 ci(scripts): create draft release with release script, cleanup [skip ci] 2025-01-03 09:00:01 -05:00
Patrik
52b1a9a720 templates: removes DATABASE_URI env var from with-vercel-website template .env.example (#10098)
### What?

Previously, the `with-vercel-website` template included a `DATABASE_URI`
env var in the `.env.example` file - which was unneeded.

### Why?

The `with-vercel-website` template uses a `POSTGRES_URL` env var for the
db connection string env var instead.

### How?

Removes the `DATABASE_URI` env var from the .env.example file.

Also, updates the `DATABASE_URI` db string names in the following
templates from `payloadtests` to `your-database-name` for a more generic
/ clear name:
- with-postgres
- with-vercel-mongodb
- with-vercel-postgres
- with-vercel-website
2024-12-20 11:02:06 -05:00
Elliot DeNolf
4bfa329fa4 templates: document local development (#10032)
Provide docker-compose for spinning up postgres locally along w/
relevant info in README.
2024-12-17 15:17:18 -05:00
Alessio Gravili
f5c13deb24 build: fix tsconfig monorepo setup (#10028)
Should fix messed up import suggestions and simplifies all tsconfigs
through inheritance.

One main issue was that packages were inheriting `baseURL: "."` from the
root tsconfig. This caused incorrect import suggestions that start with
"packages/...".

This PR ensures that packages do not inherit this baseURL: "." property,
while ensuring the root, non-inherited tsconfig still keeps it to get
tests to work (the importMap needs it)
2024-12-17 14:49:29 -05:00
Elliot DeNolf
e04be4bf62 templates: improve gen-templates script (#10015)
- Allow gen templates script to take template dir name arg
- All `skipDockerCompose` and `skipConfig`
2024-12-17 10:00:17 -05:00
Elliot DeNolf
e236c28b9c ci: add PR co-authors to contributors section of release notes 2024-12-07 14:45:43 -05:00
Jarrod Flesch
fa7ed3f621 fix(ui): stale locale value from useLocale (#9582)
### What?
Fixes issue with stale locale from searchParams

### Why?
Bad use of useEffect/useState inside our useSearchParams provider.

### How?
Memoize the locale instead of relying on the useEffect which was causing
unnecessary renders with stale values.
2024-12-04 14:00:17 -05:00
Elliot DeNolf
f5aad49ba7 ci: template bump workflow (#9733)
This create a workflow that will trigger upon every release and do the
following:

- Re-generate all template lockfiles as needed (only blank and website
need them for payload cloud)
- Re-generate all postgres migrations for any pg-based template
- Commit changes
- Create PR
2024-12-03 23:06:32 -05:00
Paul
5b3079a88e chore(scripts): fix generate template variations script (#9671) 2024-12-02 23:30:52 +00:00
Elliot DeNolf
e4c3c5b1d2 ci: allow more commit types in release notes (#9677)
More commit types will now show in the release notes. The full list of
allowable types are the following and will show in order:

```ts
const commitTypesForChangelog = [
  'feat',
  'fix',
  'perf',
  'refactor',
  'docs',
  'style',
  'test',
  'templates',
  'examples',
  'build',
  'ci',
  'chore',
]
  ```
2024-12-02 15:59:52 -05:00
Elliot DeNolf
6af4deefc2 fix(plugin-search): missing copyfiles script, incorrect scss import (#9552)
.tsx files were introduced into the plugin-search package, but an
appropriate `copyfiles` script was not introduced to get these files
into the dist output.

This was causing a `Module not found: Can't resolve './index.scss'`
error on build.

---------

Co-authored-by: Alessio Gravili <alessio@gravili.de>
2024-11-26 20:28:07 -07:00
Elliot DeNolf
8658945d7b chore(templates): remove unneeded lock files, add hook (#9508)
- Update lock files for blank, website
- Delete unneeded lock files
- Adds git hook to ensure no new lockfiles are added for _other than_
blank and website.
2024-11-25 10:04:41 -05:00
Elliot DeNolf
4f1a4a28a3 chore: remove changelog.md from git staging 2024-11-19 14:33:10 -05:00
Elliot DeNolf
41d2e64a3a ci(scripts): remove updating changelog.md 2024-11-19 14:31:55 -05:00
Elliot DeNolf
7fe207937f ci: update release script for v3 2024-11-18 20:05:55 -05:00
Elliot DeNolf
c9040b6095 chore(templates): update templates after branch rename 2024-11-17 12:52:18 -05:00
Elliot DeNolf
55d5edda6b ci: update pr action 2024-11-16 17:05:44 -05:00
Elliot DeNolf
1393d84bca feat(templates): programmatic migration gen (#9238)
Programmatically generate lockfiles and postgres migrations
2024-11-15 21:47:05 -05:00
Elliot DeNolf
1b16730b20 chore: remove useless script, can use HUSKY=0 2024-11-12 20:50:52 -05:00
Elliot DeNolf
def595e645 feat(templates): add with-vercel-website (#9144)
Add new `with-vercel-website` that uses the website template as a base.
2024-11-12 13:12:37 -05:00
Jacob Fletcher
c96fa613bc feat!: on demand rsc (#8364)
Currently, Payload renders all custom components on initial compile of
the admin panel. This is problematic for two key reasons:
1. Custom components do not receive contextual data, i.e. fields do not
receive their field data, edit views do not receive their document data,
etc.
2. Components are unnecessarily rendered before they are used

This was initially required to support React Server Components within
the Payload Admin Panel for two key reasons:
1. Fields can be dynamically rendered within arrays, blocks, etc.
2. Documents can be recursively rendered within a "drawer" UI, i.e.
relationship fields
3. Payload supports server/client component composition 

In order to achieve this, components need to be rendered on the server
and passed as "slots" to the client. Currently, the pattern for this is
to render custom server components in the "client config". Then when a
view or field is needed to be rendered, we first check the client config
for a "pre-rendered" component, otherwise render our client-side
fallback component.

But for the reasons listed above, this pattern doesn't exactly make
custom server components very useful within the Payload Admin Panel,
which is where this PR comes in. Now, instead of pre-rendering all
components on initial compile, we're able to render custom components
_on demand_, only as they are needed.

To achieve this, we've established [this
pattern](https://github.com/payloadcms/payload/pull/8481) of React
Server Functions in the Payload Admin Panel. With Server Functions, we
can iterate the Payload Config and return JSX through React's
`text/x-component` content-type. This means we're able to pass
contextual props to custom components, such as data for fields and
views.

## Breaking Changes

1. Add the following to your root layout file, typically located at
`(app)/(payload)/layout.tsx`:

    ```diff
    /* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
    /* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
    + import type { ServerFunctionClient } from 'payload'

    import config from '@payload-config'
    import { RootLayout } from '@payloadcms/next/layouts'
    import { handleServerFunctions } from '@payloadcms/next/utilities'
    import React from 'react'

    import { importMap } from './admin/importMap.js'
    import './custom.scss'

    type Args = {
      children: React.ReactNode
    }

+ const serverFunctions: ServerFunctionClient = async function (args) {
    +  'use server'
    +  return handleServerFunctions({
    +    ...args,
    +    config,
    +    importMap,
    +  })
    + }

    const Layout = ({ children }: Args) => (
      <RootLayout
        config={config}
        importMap={importMap}
    +  serverFunctions={serverFunctions}
      >
        {children}
      </RootLayout>
    )

    export default Layout
    ```

2. If you were previously posting to the `/api/form-state` endpoint, it
no longer exists. Instead, you'll need to invoke the `form-state` Server
Function, which can be done through the _new_ `getFormState` utility:

    ```diff
    - import { getFormState } from '@payloadcms/ui'
    - const { state } = await getFormState({
    -   apiRoute: '',
    -   body: {
    -     // ...
    -   },
    -   serverURL: ''
    - })

    + const { getFormState } = useServerFunctions()
    +
    + const { state } = await getFormState({
    +   // ...
    + })
    ```

## Breaking Changes

```diff
- useFieldProps()
- useCellProps()
```

More details coming soon.

---------

Co-authored-by: Alessio Gravili <alessio@gravili.de>
Co-authored-by: Jarrod Flesch <jarrodmflesch@gmail.com>
Co-authored-by: James <james@trbl.design>
2024-11-11 13:59:05 -05:00
Elliot DeNolf
320916f542 ci: build templates with packed deps (#8970)
Build templates using packed deps from the repo.
2024-11-07 10:49:21 -05:00
Elliot DeNolf
1b1dc82cfb feat!: rename @payloadcms/plugin-cloud (#8828)
BREAKING CHANGE: Rename `@payloadcms/plugin-cloud` to
`@payloadcms/payload-cloud`. Anyone using the existing plugin will need
to switch to using the new package.

## Why?

Since v3 will be using _fixed versioning_, all versions of `^3` must be
available. Unfortunately, the `@payloadcms/plugin-cloud` version has
already breached that version number. Renaming will allow it to be on
the same version as other monorepo packages.

Additionally, the name `plugin-cloud` is quite ambiguous and sometimes
is confused with `plugin-cloud-storage`, so using `payload-cloud` feels
like a good move to make this more evident.
2024-10-24 21:19:15 -04:00
Elliot DeNolf
a15765395d chore: add plugin-sentry to publish list 2024-10-10 16:40:01 -04:00
Elliot DeNolf
d88e0617d6 chore: sort release note sections 2024-10-06 09:59:51 -07:00
Elliot DeNolf
50da2125a5 fix(templates): proper migration file import source for vercel-postgres (#8394)
- Add `ci` npm script properly for postgres templates
- Fix import source for migration files when using
`@payloadcms/db-vercel-postgres`
2024-09-24 12:24:59 -04:00
Elliot DeNolf
e72f12af97 feat: templates update (#8391)
Run generate templates script
2024-09-24 11:20:35 -04:00
Elliot DeNolf
c3bc2ba4a4 chore: bold the scope in release notes 2024-09-20 23:00:03 -04:00
Dan Ribbens
6ef2bdea15 feat!: join field (#7518)
## Description

- Adds a new "join" field type to Payload and is supported by all database adapters
- The UI uses a table view for the new field
- `db-mongodb` changes relationships to be stored as ObjectIDs instead of strings (for now querying works using both types internally to the DB so no data migration should be necessary unless you're querying directly, see breaking changes for details
- Adds a reusable traverseFields utility to Payload to make it easier to work with nested fields, used internally and for plugin maintainers

```ts
export const Categories: CollectionConfig = {
    slug: 'categories',
    fields: [
        {
            name: 'relatedPosts',
            type: 'join',
            collection: 'posts',
            on: 'category',
        }
    ]
}
```

BREAKING CHANGES:
All mongodb relationship and upload values will be stored as MongoDB ObjectIDs instead of strings going forward. If you have existing data and you are querying data directly, outside of Payload's APIs, you get different results. For example, a `contains` query will no longer works given a partial ID of a relationship since the ObjectID requires the whole identifier to work. 

---------

Co-authored-by: Jacob Fletcher <jacobsfletch@gmail.com>
Co-authored-by: James <james@trbl.design>
2024-09-20 11:10:16 -04:00
Alessio Gravili
b6a8d1c461 perf(richtext-lexical)!: greatly simplify lexical loading and improve performance (#8041)
We noticed that we can bring functions down to the client directly
without having to wrap them in a component first. This greatly
simplifies the loading of all lexical client components

**BREAKING:**
- `createClientComponent` is no longer exported as it's not needed
anymore
- The exported `ClientComponentProps` type has been renamed to
`BaseClientFeatureProps`.
- The order of arguments in `sanitizeClientEditorConfig` has changed
2024-09-03 12:48:41 -04:00
Elliot DeNolf
39cd8283c8 chore(scripts): release notes emoji 2024-09-01 19:39:52 -04:00
Elliot DeNolf
828f5d866d build(scripts): add lint scripts to all, turbo lint tasks [skip ci] 2024-08-28 21:55:51 -04:00
Elliot DeNolf
8c9ff3d54b revert(scripts): publish script progress prefix 2024-08-27 19:53:15 -04:00
Elliot DeNolf
2bbb02b9c0 chore(scripts): add package count to publish script [skip ci] 2024-08-27 14:41:47 -04:00
Elliot DeNolf
d05be016ce ci(scripts): emoji release notes 2024-08-23 16:25:50 -04:00
Elliot DeNolf
825d8b83d1 feat(templates): add vercel postgres template (#7841)
- docs: add db-vercel-postgres info
- feat: update template variations
2024-08-23 15:17:26 -04:00
Elliot DeNolf
3e5c31a024 chore(scripts): add db-vercel-postgres to publish list 2024-08-21 22:55:29 -04:00
Elliot DeNolf
631431e006 feat: @payloadcms/db-vercel-postgres adapter (#7806)
Dedicated adapter for Vercel Postgres

- Uses the `@vercel/postgres` package under the hood.
- No `pg` dependency, speeds up invocation
- Includes refactoring all base postgres functionality into a
`BasePostgresAdapter` type, which will ease implementation of [other
adapters supported by
drizzle-orm](https://orm.drizzle.team/docs/get-started-postgresql)

## Usage

```ts
import { buildConfig } from 'payload'
import { vercelPostgresAdapter } from '@payloadcms/db-vercel-postgres'

export default buildConfig({
  db: vercelPostgresAdapter({
    pool: {
      connectionString: process.env.DATABASE_URI,
    },
  }),
  // ...rest of config
})
```

### Automatic Connection String Detection

Have Vercel automatically detect from environment variable (typically
`process.env.POSTGRES_URL`)

```ts
export default buildConfig({
  db: postgresAdapter(),
  // ...rest of config
})
```
2024-08-21 22:54:47 -04:00
Alessio Gravili
ebd43c7763 feat: pre-compile ui and richtext-lexical with react compiler (#7688)
This noticeably improves performance in the admin panel, for example
when there are multiple richtext editors on one page (& likely
performance in other areas too, though I mainly tested rich text).

The babel plugin currently only optimizes files with a 'use client'
directive at the top - thus we have to make sure to add use client
wherever possible, even if it's imported by a parent client component.

There's one single component that broke when it was compiled using the
React compiler (it stopped being reactive and failed one of our admin
e2e tests):
150808f608
opting out of it completely fixed that issue

Fixes https://github.com/payloadcms/payload/issues/7366
2024-08-19 17:31:36 -04:00
Alessio Gravili
3d86bf1974 chore: update website and blank templates to incorporate import map changes (#7664) 2024-08-14 09:10:40 -04:00
Elliot DeNolf
5fc9f76406 feat: filename compound index (#7651)
Allow a compound index to be used for upload collections via a
`filenameCompoundIndex` field. Previously, `filename` was always treated
as unique.

Usage:

```ts
{
  slug: 'upload-field',
   upload: {
     // Slugs to include in compound index
     filenameCompoundIndex: ['filename', 'alt'],
  },
}
```
2024-08-13 13:55:10 -04:00
Elliot DeNolf
ba6ef6777f ci: auto release canary on success (#7444)
Automatically release canary on successful workflow.
2024-07-31 00:11:28 -04:00
Elliot DeNolf
0627272d6c chore(scripts): adjust release notes indent 2024-07-24 14:27:36 -04:00
Dan Ribbens
09ad6e4280 feat(drizzle): abstract shared sql code to new package (#7320)
- Abstract shared sql code to a new drizzle package
- Adds sqlite package, not ready to publish until drizzle patches some
issues
- Add `transactionOptions` to allow customizing or disabling db
transactions
- Adds "experimental" label to the `schemaName` property until drizzle
patches an issue
2024-07-24 12:43:29 -04:00
Jacob Fletcher
904ec0160e feat: adds @payloadcms/live-preview-vue to release pipeline (#7328) 2024-07-24 10:07:34 -04:00
Elliot DeNolf
4e6a7d489c chore(scripts): delete-recursively output spacing 2024-07-22 21:26:21 -04:00