chore: run lint and prettier on entire codebase

This commit is contained in:
Alessio Gravili
2024-07-11 15:27:01 -04:00
parent f8ab5a9f1e
commit 83fd4c6622
364 changed files with 2578 additions and 2658 deletions

View File

@@ -1,18 +1,20 @@
import { jest } from '@jest/globals'
import fs from 'fs'
import fse from 'fs-extra' import fse from 'fs-extra'
import globby from 'globby'
import * as os from 'node:os'
import path from 'path' import path from 'path'
import type { CliArgs, DbType, ProjectTemplate } from '../types.js' import type { CliArgs, DbType, ProjectTemplate } from '../types.js'
import { createProject } from './create-project.js' import { createProject } from './create-project.js'
import { dbReplacements } from './replacements.js' import { dbReplacements } from './replacements.js'
import { getValidTemplates } from './templates.js' import { getValidTemplates } from './templates.js'
import globby from 'globby'
import { jest } from '@jest/globals'
import fs from 'fs'
import * as os from 'node:os'
describe('createProject', () => { describe('createProject', () => {
let projectDir: string let projectDir: string
beforeAll(() => { beforeAll(() => {
console.log = jest.fn() jest.spyOn(console, 'log').mockImplementation()
}) })
beforeEach(() => { beforeEach(() => {
@@ -27,7 +29,6 @@ describe('createProject', () => {
}) })
describe('#createProject', () => { describe('#createProject', () => {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
const args = { const args = {
_: ['project-name'], _: ['project-name'],
'--db': 'mongodb', '--db': 'mongodb',
@@ -41,15 +42,15 @@ describe('createProject', () => {
const template: ProjectTemplate = { const template: ProjectTemplate = {
name: 'plugin', name: 'plugin',
type: 'plugin', type: 'plugin',
url: 'https://github.com/payloadcms/payload-plugin-template',
description: 'Template for creating a Payload plugin', description: 'Template for creating a Payload plugin',
url: 'https://github.com/payloadcms/payload-plugin-template',
} }
await createProject({ await createProject({
cliArgs: args, cliArgs: args,
projectName,
projectDir,
template,
packageManager, packageManager,
projectDir,
projectName,
template,
}) })
const packageJsonPath = path.resolve(projectDir, 'package.json') const packageJsonPath = path.resolve(projectDir, 'package.json')
@@ -84,14 +85,14 @@ describe('createProject', () => {
await createProject({ await createProject({
cliArgs, cliArgs,
projectName,
projectDir,
template: template as ProjectTemplate,
packageManager,
dbDetails: { dbDetails: {
dbUri: `${db}://localhost:27017/create-project-test`,
type: db as DbType, type: db as DbType,
dbUri: `${db}://localhost:27017/create-project-test`,
}, },
packageManager,
projectDir,
projectName,
template: template as ProjectTemplate,
}) })
const dbReplacement = dbReplacements[db as DbType] const dbReplacement = dbReplacements[db as DbType]

View File

@@ -24,13 +24,13 @@ const writeFile = promisify(fs.writeFile)
const filename = fileURLToPath(import.meta.url) const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename) const dirname = path.dirname(filename)
type InitNextArgs = Pick<CliArgs, '--debug'> & { type InitNextArgs = {
dbType: DbType dbType: DbType
nextAppDetails?: NextAppDetails nextAppDetails?: NextAppDetails
packageManager: PackageManager packageManager: PackageManager
projectDir: string projectDir: string
useDistFiles?: boolean useDistFiles?: boolean
} } & Pick<CliArgs, '--debug'>
type InitNextResult = type InitNextResult =
| { | {
@@ -144,11 +144,11 @@ async function addPayloadConfigToTsConfig(projectDir: string, isSrcDir: boolean)
} }
function installAndConfigurePayload( function installAndConfigurePayload(
args: InitNextArgs & { args: {
nextAppDetails: NextAppDetails nextAppDetails: NextAppDetails
nextConfigType: NextConfigType nextConfigType: NextConfigType
useDistFiles?: boolean useDistFiles?: boolean
}, } & InitNextArgs,
): ):
| { payloadConfigPath: string; success: true } | { payloadConfigPath: string; success: true }
| { payloadConfigPath?: string; reason: string; success: false } { | { payloadConfigPath?: string; reason: string; success: false } {

View File

@@ -1,11 +1,16 @@
import { parseAndModifyConfigContent, withPayloadStatement } from './wrap-next-config.js'
import * as p from '@clack/prompts' import * as p from '@clack/prompts'
import { jest } from '@jest/globals' import { jest } from '@jest/globals'
import { parseAndModifyConfigContent, withPayloadStatement } from './wrap-next-config.js'
const esmConfigs = { const esmConfigs = {
defaultNextConfig: `/** @type {import('next').NextConfig} */ defaultNextConfig: `/** @type {import('next').NextConfig} */
const nextConfig = {}; const nextConfig = {};
export default nextConfig; export default nextConfig;
`,
nextConfigExportNamedDefault: `const nextConfig = {};
const wrapped = someFunc(asdf);
export { wrapped as default };
`, `,
nextConfigWithFunc: `const nextConfig = {}; nextConfigWithFunc: `const nextConfig = {};
export default someFunc(nextConfig); export default someFunc(nextConfig);
@@ -14,10 +19,6 @@ export default someFunc(nextConfig);
export default someFunc( export default someFunc(
nextConfig nextConfig
); );
`,
nextConfigExportNamedDefault: `const nextConfig = {};
const wrapped = someFunc(asdf);
export { wrapped as default };
`, `,
nextConfigWithSpread: `const nextConfig = { nextConfigWithSpread: `const nextConfig = {
...someConfig, ...someConfig,
@@ -27,12 +28,16 @@ export default nextConfig;
} }
const cjsConfigs = { const cjsConfigs = {
anonConfig: `module.exports = {};`,
defaultNextConfig: ` defaultNextConfig: `
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = {}; const nextConfig = {};
module.exports = nextConfig; module.exports = nextConfig;
`, `,
anonConfig: `module.exports = {};`, nextConfigExportNamedDefault: `const nextConfig = {};
const wrapped = someFunc(asdf);
module.exports = wrapped;
`,
nextConfigWithFunc: `const nextConfig = {}; nextConfigWithFunc: `const nextConfig = {};
module.exports = someFunc(nextConfig); module.exports = someFunc(nextConfig);
`, `,
@@ -40,10 +45,6 @@ module.exports = someFunc(nextConfig);
module.exports = someFunc( module.exports = someFunc(
nextConfig nextConfig
); );
`,
nextConfigExportNamedDefault: `const nextConfig = {};
const wrapped = someFunc(asdf);
module.exports = wrapped;
`, `,
nextConfigWithSpread: `const nextConfig = { ...someConfig }; nextConfigWithSpread: `const nextConfig = { ...someConfig };
module.exports = nextConfig; module.exports = nextConfig;
@@ -76,7 +77,7 @@ describe('parseAndInsertWithPayload', () => {
configType, configType,
) )
expect(modifiedConfigContent).toContain(importStatement) expect(modifiedConfigContent).toContain(importStatement)
expect(modifiedConfigContent).toMatch(/withPayload\(someFunc\(\n nextConfig\n\)\)/) expect(modifiedConfigContent).toMatch(/withPayload\(someFunc\(\n {2}nextConfig\n\)\)/)
}) })
it('should parse the config with a spread', () => { it('should parse the config with a spread', () => {
@@ -137,7 +138,7 @@ describe('parseAndInsertWithPayload', () => {
configType, configType,
) )
expect(modifiedConfigContent).toContain(requireStatement) expect(modifiedConfigContent).toContain(requireStatement)
expect(modifiedConfigContent).toMatch(/withPayload\(someFunc\(\n nextConfig\n\)\)/) expect(modifiedConfigContent).toMatch(/withPayload\(someFunc\(\n {2}nextConfig\n\)\)/)
}) })
it('should parse the config with a named export as default', () => { it('should parse the config with a named export as default', () => {
const { modifiedConfigContent } = parseAndModifyConfigContent( const { modifiedConfigContent } = parseAndModifyConfigContent(

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-console */
import * as p from '@clack/prompts' import * as p from '@clack/prompts'
import chalk from 'chalk' import chalk from 'chalk'

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import type { ConnectOptions } from 'mongoose' import type { ConnectOptions } from 'mongoose'
import type { Connect } from 'payload' import type { Connect } from 'payload'
@@ -24,7 +23,7 @@ export const connect: Connect = async function connect(
const urlToConnect = this.url const urlToConnect = this.url
const connectionOptions: ConnectOptions & { useFacet: undefined } = { const connectionOptions: { useFacet: undefined } & ConnectOptions = {
autoIndex: true, autoIndex: true,
...this.connectOptions, ...this.connectOptions,
useFacet: undefined, useFacet: undefined,

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-restricted-syntax, no-await-in-loop */
import type { CreateMigration, MigrationTemplateArgs } from 'payload' import type { CreateMigration, MigrationTemplateArgs } from 'payload'
import fs from 'fs' import fs from 'fs'

View File

@@ -86,7 +86,6 @@ export const find: Find = async function find(
return { return {
...result, ...result,
docs: docs.map((doc) => { docs: docs.map((doc) => {
// eslint-disable-next-line no-param-reassign
doc.id = doc._id doc.id = doc._id
return sanitizeInternalFields(doc) return sanitizeInternalFields(doc)
}), }),

View File

@@ -104,7 +104,6 @@ export const findGlobalVersions: FindGlobalVersions = async function findGlobalV
return { return {
...result, ...result,
docs: docs.map((doc) => { docs: docs.map((doc) => {
// eslint-disable-next-line no-param-reassign
doc.id = doc._id doc.id = doc._id
return sanitizeInternalFields(doc) return sanitizeInternalFields(doc)
}), }),

View File

@@ -101,7 +101,6 @@ export const findVersions: FindVersions = async function findVersions(
return { return {
...result, ...result,
docs: docs.map((doc) => { docs: docs.map((doc) => {
// eslint-disable-next-line no-param-reassign
doc.id = doc._id doc.id = doc._id
return sanitizeInternalFields(doc) return sanitizeInternalFields(doc)
}), }),

View File

@@ -43,10 +43,10 @@ export interface Args {
/** Set to false to disable auto-pluralization of collection names, Defaults to true */ /** Set to false to disable auto-pluralization of collection names, Defaults to true */
autoPluralization?: boolean autoPluralization?: boolean
/** Extra configuration options */ /** Extra configuration options */
connectOptions?: ConnectOptions & { connectOptions?: {
/** Set false to disable $facet aggregation in non-supporting databases, Defaults to true */ /** Set false to disable $facet aggregation in non-supporting databases, Defaults to true */
useFacet?: boolean useFacet?: boolean
} } & ConnectOptions
/** Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false */ /** Set to true to disable hinting to MongoDB to use 'id' as index. This is currently done when counting documents for pagination. Disabling this optimization might fix some problems with AWS DocumentDB. Defaults to false */
disableIndexHints?: boolean disableIndexHints?: boolean
migrationDir?: string migrationDir?: string
@@ -59,19 +59,19 @@ export interface Args {
url: false | string url: false | string
} }
export type MongooseAdapter = BaseDatabaseAdapter & export type MongooseAdapter = {
Args & { collections: {
collections: { [slug: string]: CollectionModel
[slug: string]: CollectionModel
}
connection: Connection
globals: GlobalModel
mongoMemoryServer: MongoMemoryReplSet
sessions: Record<number | string, ClientSession>
versions: {
[slug: string]: CollectionModel
}
} }
connection: Connection
globals: GlobalModel
mongoMemoryServer: MongoMemoryReplSet
sessions: Record<number | string, ClientSession>
versions: {
[slug: string]: CollectionModel
}
} & Args &
BaseDatabaseAdapter
declare module 'payload' { declare module 'payload' {
export interface DatabaseAdapter export interface DatabaseAdapter

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-param-reassign */
import type { PaginateOptions } from 'mongoose' import type { PaginateOptions } from 'mongoose'
import type { Init, SanitizedCollectionConfig } from 'payload' import type { Init, SanitizedCollectionConfig } from 'payload'

View File

@@ -1,6 +1,3 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable class-methods-use-this */
/* eslint-disable @typescript-eslint/no-use-before-define */
import type { IndexOptions, Schema, SchemaOptions, SchemaTypeOptions } from 'mongoose' import type { IndexOptions, Schema, SchemaOptions, SchemaTypeOptions } from 'mongoose'
import type { import type {
ArrayField, ArrayField,
@@ -196,12 +193,10 @@ const fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {
if (field.localized && config.localization) { if (field.localized && config.localization) {
config.localization.localeCodes.forEach((localeCode) => { config.localization.localeCodes.forEach((localeCode) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error Possible incorrect typing in mongoose types, this works // @ts-expect-error Possible incorrect typing in mongoose types, this works
schema.path(`${field.name}.${localeCode}`).discriminator(blockItem.slug, blockSchema) schema.path(`${field.name}.${localeCode}`).discriminator(blockItem.slug, blockSchema)
}) })
} else { } else {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error Possible incorrect typing in mongoose types, this works // @ts-expect-error Possible incorrect typing in mongoose types, this works
schema.path(field.name).discriminator(blockItem.slug, blockSchema) schema.path(field.name).discriminator(blockItem.slug, blockSchema)
} }

View File

@@ -20,11 +20,10 @@ export async function buildAndOrConditions({
const completedConditions = [] const completedConditions = []
// Loop over all AND / OR operations and add them to the AND / OR query param // Loop over all AND / OR operations and add them to the AND / OR query param
// Operations should come through as an array // Operations should come through as an array
// eslint-disable-next-line no-restricted-syntax
for (const condition of where) { for (const condition of where) {
// If the operation is properly formatted as an object // If the operation is properly formatted as an object
if (typeof condition === 'object') { if (typeof condition === 'object') {
// eslint-disable-next-line no-await-in-loop
const result = await parseParams({ const result = await parseParams({
collectionSlug, collectionSlug,
fields, fields,

View File

@@ -1,22 +1,23 @@
import { SanitizedConfig, sanitizeConfig } from 'payload' import type { Config, SanitizedConfig } from 'payload'
import { Config } from 'payload'
import { sanitizeConfig } from 'payload'
import { getLocalizedSortProperty } from './getLocalizedSortProperty.js' import { getLocalizedSortProperty } from './getLocalizedSortProperty.js'
let config: SanitizedConfig let config: SanitizedConfig
describe('get localized sort property', () => { describe('get localized sort property', () => {
beforeAll(async () => { beforeAll(async () => {
config = (await sanitizeConfig({ config = await sanitizeConfig({
localization: { localization: {
locales: ['en', 'es'],
defaultLocale: 'en', defaultLocale: 'en',
fallback: true, fallback: true,
locales: ['en', 'es'],
}, },
} as Config)) as SanitizedConfig } as Config)
}) })
it('passes through a non-localized sort property', async () => { it('passes through a non-localized sort property', async () => {
const result = getLocalizedSortProperty({ const result = getLocalizedSortProperty({
segments: ['title'],
config, config,
fields: [ fields: [
{ {
@@ -25,6 +26,7 @@ describe('get localized sort property', () => {
}, },
], ],
locale: 'en', locale: 'en',
segments: ['title'],
}) })
expect(result).toStrictEqual('title') expect(result).toStrictEqual('title')
@@ -32,7 +34,6 @@ describe('get localized sort property', () => {
it('properly localizes an un-localized sort property', () => { it('properly localizes an un-localized sort property', () => {
const result = getLocalizedSortProperty({ const result = getLocalizedSortProperty({
segments: ['title'],
config, config,
fields: [ fields: [
{ {
@@ -42,6 +43,7 @@ describe('get localized sort property', () => {
}, },
], ],
locale: 'en', locale: 'en',
segments: ['title'],
}) })
expect(result).toStrictEqual('title.en') expect(result).toStrictEqual('title.en')
@@ -49,7 +51,6 @@ describe('get localized sort property', () => {
it('keeps specifically asked-for localized sort properties', () => { it('keeps specifically asked-for localized sort properties', () => {
const result = getLocalizedSortProperty({ const result = getLocalizedSortProperty({
segments: ['title', 'es'],
config, config,
fields: [ fields: [
{ {
@@ -59,6 +60,7 @@ describe('get localized sort property', () => {
}, },
], ],
locale: 'en', locale: 'en',
segments: ['title', 'es'],
}) })
expect(result).toStrictEqual('title.es') expect(result).toStrictEqual('title.es')
@@ -66,7 +68,6 @@ describe('get localized sort property', () => {
it('properly localizes nested sort properties', () => { it('properly localizes nested sort properties', () => {
const result = getLocalizedSortProperty({ const result = getLocalizedSortProperty({
segments: ['group', 'title'],
config, config,
fields: [ fields: [
{ {
@@ -82,6 +83,7 @@ describe('get localized sort property', () => {
}, },
], ],
locale: 'en', locale: 'en',
segments: ['group', 'title'],
}) })
expect(result).toStrictEqual('group.title.en') expect(result).toStrictEqual('group.title.en')
@@ -89,7 +91,6 @@ describe('get localized sort property', () => {
it('keeps requested locale with nested sort properties', () => { it('keeps requested locale with nested sort properties', () => {
const result = getLocalizedSortProperty({ const result = getLocalizedSortProperty({
segments: ['group', 'title', 'es'],
config, config,
fields: [ fields: [
{ {
@@ -105,6 +106,7 @@ describe('get localized sort property', () => {
}, },
], ],
locale: 'en', locale: 'en',
segments: ['group', 'title', 'es'],
}) })
expect(result).toStrictEqual('group.title.es') expect(result).toStrictEqual('group.title.es')
@@ -112,7 +114,6 @@ describe('get localized sort property', () => {
it('properly localizes field within row', () => { it('properly localizes field within row', () => {
const result = getLocalizedSortProperty({ const result = getLocalizedSortProperty({
segments: ['title'],
config, config,
fields: [ fields: [
{ {
@@ -127,6 +128,7 @@ describe('get localized sort property', () => {
}, },
], ],
locale: 'en', locale: 'en',
segments: ['title'],
}) })
expect(result).toStrictEqual('title.en') expect(result).toStrictEqual('title.en')
@@ -134,7 +136,6 @@ describe('get localized sort property', () => {
it('properly localizes field within named tab', () => { it('properly localizes field within named tab', () => {
const result = getLocalizedSortProperty({ const result = getLocalizedSortProperty({
segments: ['tab', 'title'],
config, config,
fields: [ fields: [
{ {
@@ -154,6 +155,7 @@ describe('get localized sort property', () => {
}, },
], ],
locale: 'en', locale: 'en',
segments: ['tab', 'title'],
}) })
expect(result).toStrictEqual('tab.title.en') expect(result).toStrictEqual('tab.title.en')
@@ -161,14 +163,12 @@ describe('get localized sort property', () => {
it('properly localizes field within unnamed tab', () => { it('properly localizes field within unnamed tab', () => {
const result = getLocalizedSortProperty({ const result = getLocalizedSortProperty({
segments: ['title'],
config, config,
fields: [ fields: [
{ {
type: 'tabs', type: 'tabs',
tabs: [ tabs: [
{ {
label: 'Tab',
fields: [ fields: [
{ {
name: 'title', name: 'title',
@@ -176,11 +176,13 @@ describe('get localized sort property', () => {
localized: true, localized: true,
}, },
], ],
label: 'Tab',
}, },
], ],
}, },
], ],
locale: 'en', locale: 'en',
segments: ['title'],
}) })
expect(result).toStrictEqual('title.en') expect(result).toStrictEqual('title.en')

View File

@@ -1,5 +1,3 @@
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-await-in-loop */
import type { FilterQuery } from 'mongoose' import type { FilterQuery } from 'mongoose'
import type { Field, Operator, Payload, Where } from 'payload' import type { Field, Operator, Payload, Where } from 'payload'

View File

@@ -87,7 +87,6 @@ export const queryDrafts: QueryDrafts = async function queryDrafts(
return { return {
...result, ...result,
docs: docs.map((doc) => { docs: docs.map((doc) => {
// eslint-disable-next-line no-param-reassign
doc = { doc = {
_id: doc.parent, _id: doc.parent,
id: doc.parent, id: doc.parent,

View File

@@ -1,7 +1,9 @@
import { resendAdapter } from './index.js' import type { Payload } from 'payload'
import { Payload } from 'payload'
import { jest } from '@jest/globals' import { jest } from '@jest/globals'
import { resendAdapter } from './index.js'
describe('email-resend', () => { describe('email-resend', () => {
const defaultFromAddress = 'dev@payloadcms.com' const defaultFromAddress = 'dev@payloadcms.com'
const defaultFromName = 'Payload CMS' const defaultFromName = 'Payload CMS'
@@ -29,16 +31,16 @@ describe('email-resend', () => {
) as jest.Mock ) as jest.Mock
const adapter = resendAdapter({ const adapter = resendAdapter({
apiKey,
defaultFromAddress, defaultFromAddress,
defaultFromName, defaultFromName,
apiKey,
}) })
await adapter({ payload: mockPayload }).sendEmail({ await adapter({ payload: mockPayload }).sendEmail({
from, from,
to,
subject, subject,
text, text,
to,
}) })
// @ts-expect-error // @ts-expect-error
@@ -48,16 +50,16 @@ describe('email-resend', () => {
expect(request.headers.Authorization).toStrictEqual(`Bearer ${apiKey}`) expect(request.headers.Authorization).toStrictEqual(`Bearer ${apiKey}`)
expect(JSON.parse(request.body)).toMatchObject({ expect(JSON.parse(request.body)).toMatchObject({
from, from,
to,
subject, subject,
text, text,
to,
}) })
}) })
it('should throw an error if the email fails to send', async () => { it('should throw an error if the email fails to send', async () => {
const errorResponse = { const errorResponse = {
message: 'error information',
name: 'validation_error', name: 'validation_error',
message: 'error information',
statusCode: 403, statusCode: 403,
} }
global.fetch = jest.spyOn(global, 'fetch').mockImplementation( global.fetch = jest.spyOn(global, 'fetch').mockImplementation(
@@ -69,17 +71,17 @@ describe('email-resend', () => {
) as jest.Mock ) as jest.Mock
const adapter = resendAdapter({ const adapter = resendAdapter({
apiKey,
defaultFromAddress, defaultFromAddress,
defaultFromName, defaultFromName,
apiKey,
}) })
await expect(() => await expect(() =>
adapter({ payload: mockPayload }).sendEmail({ adapter({ payload: mockPayload }).sendEmail({
from, from,
to,
subject, subject,
text, text,
to,
}), }),
).rejects.toThrow( ).rejects.toThrow(
`Error sending email: ${errorResponse.statusCode} ${errorResponse.name} - ${errorResponse.message}`, `Error sending email: ${errorResponse.statusCode} ${errorResponse.name} - ${errorResponse.message}`,

View File

@@ -4,21 +4,20 @@ import jestDom from 'eslint-plugin-jest-dom'
import jest from 'eslint-plugin-jest' import jest from 'eslint-plugin-jest'
import { deepMerge } from '../../deepMerge.js' import { deepMerge } from '../../deepMerge.js'
/** @type {import('eslint').Linter.FlatConfig} */ /** @type {import('eslint').Linter.FlatConfig} */
export const index = deepMerge( export const index = deepMerge(
{ {
rules: jestRules rules: jestRules,
}, },
{ {
rules: jestDomRules rules: jestDomRules,
}, },
{ {
plugins: { plugins: {
jest, jest,
'jest-dom': jestDom, 'jest-dom': jestDom,
}, },
} },
) )
export default index export default index

View File

@@ -1,19 +1,19 @@
import reactRules from './rules/react.mjs' import reactRules from './rules/react.mjs'
import reactA11yRules from './rules/react-a11y.mjs' import reactA11yRules from './rules/react-a11y.mjs'
import jsxA11y from 'eslint-plugin-jsx-a11y' import jsxA11y from 'eslint-plugin-jsx-a11y'
import react from "@eslint-react/eslint-plugin"; import react from '@eslint-react/eslint-plugin'
import reactHooks from 'eslint-plugin-react-hooks' import reactHooks from 'eslint-plugin-react-hooks'
import globals from 'globals'; import globals from 'globals'
import { deepMerge } from '../../deepMerge.js' import { deepMerge } from '../../deepMerge.js'
/** @type {import('eslint').Linter.FlatConfig} */ /** @type {import('eslint').Linter.FlatConfig} */
export const index = deepMerge( export const index = deepMerge(
react.configs["recommended-type-checked"], react.configs['recommended-type-checked'],
{ {
rules: reactRules rules: reactRules,
}, },
{ {
rules: reactA11yRules rules: reactA11yRules,
}, },
{ {
languageOptions: { languageOptions: {
@@ -23,8 +23,8 @@ export const index = deepMerge(
parserOptions: { parserOptions: {
ecmaFeatures: { ecmaFeatures: {
jsx: true, jsx: true,
} },
} },
}, },
plugins: { plugins: {
'jsx-a11y': jsxA11y, 'jsx-a11y': jsxA11y,
@@ -35,6 +35,6 @@ export const index = deepMerge(
version: 'detect', version: 'detect',
}, },
}, },
} },
) )
export default index export default index

View File

@@ -1,4 +1,3 @@
// Sourced from https://github.com/airbnb/javascript/blob/master/packages/eslint-config-airbnb/rules/react-a11y.js // Sourced from https://github.com/airbnb/javascript/blob/master/packages/eslint-config-airbnb/rules/react-a11y.js
/** @type {import('eslint').Linter.FlatConfig} */ /** @type {import('eslint').Linter.FlatConfig} */

View File

@@ -2,11 +2,11 @@ import js from '@eslint/js'
import tseslint from 'typescript-eslint' import tseslint from 'typescript-eslint'
import perfectionistNatural from 'eslint-plugin-perfectionist/configs/recommended-natural' import perfectionistNatural from 'eslint-plugin-perfectionist/configs/recommended-natural'
import { configs as regexpPluginConfigs } from 'eslint-plugin-regexp' import { configs as regexpPluginConfigs } from 'eslint-plugin-regexp'
import eslintConfigPrettier from 'eslint-config-prettier'; import eslintConfigPrettier from 'eslint-config-prettier'
import payloadPlugin from '@payloadcms/eslint-plugin' import payloadPlugin from '@payloadcms/eslint-plugin'
import reactExtends from './configs/react/index.mjs' import reactExtends from './configs/react/index.mjs'
import jestExtends from './configs/jest/index.mjs' import jestExtends from './configs/jest/index.mjs'
import globals from 'globals'; import globals from 'globals'
import importX from 'eslint-plugin-import-x' import importX from 'eslint-plugin-import-x'
import typescriptParser from '@typescript-eslint/parser' import typescriptParser from '@typescript-eslint/parser'
import { deepMerge } from './deepMerge.js' import { deepMerge } from './deepMerge.js'
@@ -102,9 +102,11 @@ const typescriptRules = {
let FlatConfig let FlatConfig
/** @type {FlatConfig} */ /** @type {FlatConfig} */
const baseExtends = deepMerge(js.configs.recommended, perfectionistNatural , regexpPluginConfigs['flat/recommended']) const baseExtends = deepMerge(
js.configs.recommended,
perfectionistNatural,
regexpPluginConfigs['flat/recommended'],
)
/** @type {FlatConfig[]} */ /** @type {FlatConfig[]} */
export const rootEslintConfig = [ export const rootEslintConfig = [
@@ -144,7 +146,7 @@ export const rootEslintConfig = [
...baseRules, ...baseRules,
...typescriptRules, ...typescriptRules,
}, },
} },
), ),
files: ['**/*.ts'], files: ['**/*.ts'],
}, },
@@ -166,31 +168,28 @@ export const rootEslintConfig = [
...typescriptRules, ...typescriptRules,
...reactA11yRules, ...reactA11yRules,
}, },
} },
), ),
files: ['**/*.tsx'], files: ['**/*.tsx'],
}, },
{ {
name: 'Unit Tests', name: 'Unit Tests',
...deepMerge( ...deepMerge(jestExtends, {
jestExtends, plugins: {
{ payload: payloadPlugin,
plugins: { },
payload: payloadPlugin rules: {
}, ...baseRules,
rules: { ...typescriptRules,
...baseRules, '@typescript-eslint/unbound-method': 'off',
...typescriptRules, },
'@typescript-eslint/unbound-method': 'off', }),
},
}
),
files: ['**/*.spec.ts'], files: ['**/*.spec.ts'],
}, },
{ {
name: 'Payload Config', name: 'Payload Config',
plugins: { plugins: {
payload: payloadPlugin payload: payloadPlugin,
}, },
rules: { rules: {
...baseRules, ...baseRules,

View File

@@ -4,7 +4,6 @@ import noRelativeMonorepoImports from './customRules/no-relative-monorepo-import
import noImportsFromExportsDir from './customRules/no-imports-from-exports-dir.js' import noImportsFromExportsDir from './customRules/no-imports-from-exports-dir.js'
import noFlakyAssertions from './customRules/no-flaky-assertions.js' import noFlakyAssertions from './customRules/no-flaky-assertions.js'
/** /**
* @type {import('eslint').ESLint.Plugin} * @type {import('eslint').ESLint.Plugin}
*/ */

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-floating-promises */
import type { SanitizedConfig } from 'payload' import type { SanitizedConfig } from 'payload'
import fs from 'fs' import fs from 'fs'

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-param-reassign */
import type { OperationArgs } from 'graphql-http' import type { OperationArgs } from 'graphql-http'
import type { GraphQLInfo, SanitizedConfig } from 'payload' import type { GraphQLInfo, SanitizedConfig } from 'payload'

View File

@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */ /* eslint-disable @typescript-eslint/no-unsafe-enum-comparison */
/** /**
* Created by Ivo Meißner on 28.07.17. * Created by Ivo Meißner on 28.07.17.

View File

@@ -16,7 +16,6 @@ function ensureObject(value) {
function parseObject(typeName, ast, variables) { function parseObject(typeName, ast, variables) {
const value = Object.create(null) const value = Object.create(null)
ast.fields.forEach((field) => { ast.fields.forEach((field) => {
// eslint-disable-next-line no-use-before-define
value[field.name.value] = parseLiteral(typeName, field.value, variables) value[field.name.value] = parseLiteral(typeName, field.value, variables)
}) })

View File

@@ -14,7 +14,6 @@ export type Resolver = (
context: { context: {
req: PayloadRequest req: PayloadRequest
}, },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
) => Promise<{ totalDocs: number }> ) => Promise<{ totalDocs: number }>
export function countResolver(collection: Collection): Resolver { export function countResolver(collection: Collection): Resolver {

View File

@@ -1,6 +1,3 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable no-await-in-loop */
/* eslint-disable no-restricted-syntax */
import type { GraphQLFieldConfig, GraphQLType } from 'graphql' import type { GraphQLFieldConfig, GraphQLType } from 'graphql'
import type { import type {
ArrayField, ArrayField,

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
import type { Field, FieldAffectingData } from 'payload' import type { Field, FieldAffectingData } from 'payload'
import { GraphQLInputObjectType, GraphQLList } from 'graphql' import { GraphQLInputObjectType, GraphQLList } from 'graphql'

View File

@@ -1,6 +1,10 @@
/* eslint-disable no-param-reassign */ import type {
import type { GraphQLInfo } from 'payload' Collection,
import type { Collection, Field, SanitizedCollectionConfig, SanitizedConfig } from 'payload' Field,
GraphQLInfo,
SanitizedCollectionConfig,
SanitizedConfig,
} from 'payload'
import { import {
GraphQLBoolean, GraphQLBoolean,

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-param-reassign */
import { GraphQLBoolean, GraphQLInt, GraphQLNonNull, GraphQLString } from 'graphql' import { GraphQLBoolean, GraphQLInt, GraphQLNonNull, GraphQLString } from 'graphql'
import pluralize from 'pluralize' import pluralize from 'pluralize'
const { singular } = pluralize const { singular } = pluralize

View File

@@ -45,19 +45,19 @@ const GeoJSONObject = new GraphQLInputObjectType({
}) })
type DefaultsType = { type DefaultsType = {
[key in staticTypes]: {
operators: {
name: string
type: ((field: FieldAffectingData, parentName: string) => GraphQLType) | GraphQLType
}[]
}
} & {
[key in dynamicTypes]: { [key in dynamicTypes]: {
operators: { operators: {
name: string name: string
type: (field: FieldAffectingData, parentName: string) => GraphQLType type: (field: FieldAffectingData, parentName: string) => GraphQLType
}[] }[]
} }
} & {
[key in staticTypes]: {
operators: {
name: string
type: ((field: FieldAffectingData, parentName: string) => GraphQLType) | GraphQLType
}[]
}
} }
const defaults: DefaultsType = { const defaults: DefaultsType = {

View File

@@ -1,4 +1,3 @@
/* eslint-disable indent */
/* eslint-disable jest/prefer-strict-equal */ /* eslint-disable jest/prefer-strict-equal */
import formatName from './formatName' import formatName from './formatName'

View File

@@ -34,9 +34,9 @@ export const mergeData = async <T>(args: {
returnNumberOfRequests?: boolean returnNumberOfRequests?: boolean
serverURL: string serverURL: string
}): Promise< }): Promise<
T & { {
_numberOfRequests?: number _numberOfRequests?: number
} } & T
> => { > => {
const { const {
apiRoute, apiRoute,

View File

@@ -7,7 +7,7 @@ import './index.scss'
export const baseClass = 'doc-tab' export const baseClass = 'doc-tab'
export const DocumentTab: React.FC<DocumentTabProps & DocumentTabConfig> = (props) => { export const DocumentTab: React.FC<DocumentTabConfig & DocumentTabProps> = (props) => {
const { const {
Pill, Pill,
apiURL, apiURL,

View File

@@ -16,9 +16,9 @@ export type DocumentViewKey = (typeof documentViewKeys)[number]
export const tabs: Record< export const tabs: Record<
DocumentViewKey, DocumentViewKey,
DocumentTabConfig & { {
order?: number // TODO: expose this to the globalConfig config order?: number // TODO: expose this to the globalConfig config
} } & DocumentTabConfig
> = { > = {
API: { API: {
condition: ({ collectionConfig, globalConfig }) => condition: ({ collectionConfig, globalConfig }) =>

View File

@@ -109,7 +109,6 @@ export const RootLayout = async ({
fallbackLang={clientConfig.i18n.fallbackLanguage} fallbackLang={clientConfig.i18n.fallbackLanguage}
languageCode={languageCode} languageCode={languageCode}
languageOptions={languageOptions} languageOptions={languageOptions}
// eslint-disable-next-line react/jsx-no-bind
switchLanguageServerAction={switchLanguageServerAction} switchLanguageServerAction={switchLanguageServerAction}
theme={theme} theme={theme}
translations={i18n.translations} translations={i18n.translations}

View File

@@ -50,7 +50,6 @@ const handleError = async (
let cached = global._payload_graphql let cached = global._payload_graphql
if (!cached) { if (!cached) {
// eslint-disable-next-line no-multi-assign
cached = global._payload_graphql = { graphql: null, promise: null } cached = global._payload_graphql = { graphql: null, promise: null }
} }

View File

@@ -11,11 +11,11 @@ import './index.scss'
const baseClass = 'template-default' const baseClass = 'template-default'
export type DefaultTemplateProps = ServerProps & { export type DefaultTemplateProps = {
children?: React.ReactNode children?: React.ReactNode
className?: string className?: string
visibleEntities: VisibleEntities visibleEntities: VisibleEntities
} } & ServerProps
export const DefaultTemplate: React.FC<DefaultTemplateProps> = ({ export const DefaultTemplate: React.FC<DefaultTemplateProps> = ({
children, children,

View File

@@ -10,7 +10,6 @@ let cached: {
} = global._payload } = global._payload
if (!cached) { if (!cached) {
// eslint-disable-next-line no-multi-assign
cached = global._payload = { payload: null, promise: null, reload: false } cached = global._payload = { payload: null, promise: null, reload: false }
} }

View File

@@ -12,7 +12,7 @@ const defaultOpenGraph = {
title: 'Payload App', title: 'Payload App',
} }
export const meta = async (args: MetaConfig & { serverURL: string }): Promise<any> => { export const meta = async (args: { serverURL: string } & MetaConfig): Promise<any> => {
const { const {
defaultOGImageType, defaultOGImageType,
description, description,

View File

@@ -10,12 +10,12 @@ import './index.scss'
const baseClass = 'dashboard' const baseClass = 'dashboard'
export type DashboardProps = ServerProps & { export type DashboardProps = {
Link: React.ComponentType<any> Link: React.ComponentType<any>
navGroups?: ReturnType<typeof groupNavItems> navGroups?: ReturnType<typeof groupNavItems>
permissions: Permissions permissions: Permissions
visibleEntities: VisibleEntities visibleEntities: VisibleEntities
} } & ServerProps
export const DefaultDashboard: React.FC<DashboardProps> = (props) => { export const DefaultDashboard: React.FC<DashboardProps> = (props) => {
const { const {

View File

@@ -12,10 +12,10 @@ import { generateMetadata as versionMeta } from '../Version/meta.js'
import { generateMetadata as versionsMeta } from '../Versions/meta.js' import { generateMetadata as versionsMeta } from '../Versions/meta.js'
export type GenerateEditViewMetadata = ( export type GenerateEditViewMetadata = (
args: Parameters<GenerateViewMetadata>[0] & { args: {
collectionConfig?: SanitizedCollectionConfig | null collectionConfig?: SanitizedCollectionConfig | null
globalConfig?: SanitizedGlobalConfig | null globalConfig?: SanitizedGlobalConfig | null
}, } & Parameters<GenerateViewMetadata>[0],
) => Promise<Metadata> ) => Promise<Metadata>
export const getMetaBySegment: GenerateEditViewMetadata = async ({ export const getMetaBySegment: GenerateEditViewMetadata = async ({

View File

@@ -28,7 +28,7 @@ export const getViewsFromConfig = ({
}: { }: {
collectionConfig?: SanitizedCollectionConfig collectionConfig?: SanitizedCollectionConfig
config: SanitizedConfig config: SanitizedConfig
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
docPermissions: CollectionPermission | GlobalPermission docPermissions: CollectionPermission | GlobalPermission
globalConfig?: SanitizedGlobalConfig globalConfig?: SanitizedGlobalConfig
routeSegments: string[] routeSegments: string[]

View File

@@ -8,9 +8,9 @@ import type { GenerateViewMetadata } from '../Root/index.js'
import { meta } from '../../utilities/meta.js' import { meta } from '../../utilities/meta.js'
export const generateListMetadata = async ( export const generateListMetadata = async (
args: Parameters<GenerateViewMetadata>[0] & { args: {
collectionConfig: SanitizedCollectionConfig collectionConfig: SanitizedCollectionConfig
}, } & Parameters<GenerateViewMetadata>[0],
): Promise<Metadata> => { ): Promise<Metadata> => {
const { collectionConfig, config, i18n } = args const { collectionConfig, config, i18n } = args

View File

@@ -56,9 +56,9 @@ const StaticToolbar: React.FC<EditViewProps> = (props) => {
} }
export const LivePreviewToolbar: React.FC< export const LivePreviewToolbar: React.FC<
EditViewProps & { {
draggable?: boolean draggable?: boolean
} } & EditViewProps
> = (props) => { > = (props) => {
const { draggable } = props const { draggable } = props

View File

@@ -14,7 +14,7 @@ export interface PopupMessage {
export const usePopupWindow = (props: { export const usePopupWindow = (props: {
eventType?: string eventType?: string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onMessage?: (searchParams: PopupMessage['searchParams']) => Promise<void> onMessage?: (searchParams: PopupMessage['searchParams']) => Promise<void>
url: string url: string
}): { }): {

View File

@@ -10,9 +10,9 @@ const baseClass = 'logout'
export { generateLogoutMetadata } from './meta.js' export { generateLogoutMetadata } from './meta.js'
export const LogoutView: React.FC< export const LogoutView: React.FC<
AdminViewProps & { {
inactivity?: boolean inactivity?: boolean
} } & AdminViewProps
> = ({ inactivity, initPageResult, searchParams }) => { > = ({ inactivity, initPageResult, searchParams }) => {
const { const {
req: { req: {

View File

@@ -15,7 +15,6 @@ export const generatePageMetadata = async ({
}: { }: {
config: Promise<SanitizedConfig> | SanitizedConfig config: Promise<SanitizedConfig> | SanitizedConfig
params?: { [key: string]: string | string[] } params?: { [key: string]: string | string[] }
//eslint-disable-next-line @typescript-eslint/require-await
}): Promise<Metadata> => { }): Promise<Metadata> => {
const config = await configPromise const config = await configPromise

View File

@@ -47,9 +47,9 @@ const getTranslatedOptions = (
} }
const Select: React.FC< const Select: React.FC<
Omit<Props, 'field'> & { {
field: MappedField & SelectFieldProps field: MappedField & SelectFieldProps
} } & Omit<Props, 'field'>
> = ({ comparison, diffMethod, field, i18n, locale, version }) => { > = ({ comparison, diffMethod, field, i18n, locale, version }) => {
let placeholder = '' let placeholder = ''

View File

@@ -10,9 +10,9 @@ import Nested from '../Nested/index.js'
const baseClass = 'tabs-diff' const baseClass = 'tabs-diff'
const Tabs: React.FC< const Tabs: React.FC<
Omit<Props, 'field'> & { {
field: MappedField & TabsFieldProps field: MappedField & TabsFieldProps
} } & Omit<Props, 'field'>
> = ({ comparison, diffComponents, field, i18n, locale, locales, permissions, version }) => { > = ({ comparison, diffComponents, field, i18n, locale, locales, permissions, version }) => {
return ( return (
<div className={baseClass}> <div className={baseClass}>

View File

@@ -15,8 +15,8 @@ export type Props = {
version: Record<string, any> version: Record<string, any>
} }
export type FieldDiffProps = Props & { export type FieldDiffProps = {
diffMethod: DiffMethod diffMethod: DiffMethod
field: MappedField field: MappedField
isRichText: boolean isRichText: boolean
} } & Props

View File

@@ -9,13 +9,9 @@ import type { SanitizedGlobalConfig } from '../globals/config/types.js'
import type { PayloadRequest, RequestContext } from '../types/index.js' import type { PayloadRequest, RequestContext } from '../types/index.js'
import type { WithServerSidePropsComponentProps } from './elements/WithServerSideProps.js' import type { WithServerSidePropsComponentProps } from './elements/WithServerSideProps.js'
export type RichTextFieldProps< export type RichTextFieldProps<Value extends object, AdapterProps, ExtraFieldProperties = {}> = {
Value extends object,
AdapterProps,
ExtraFieldProperties = {},
> = Omit<RichTextField<Value, AdapterProps, ExtraFieldProperties>, 'type'> & {
path?: string path?: string
} } & Omit<RichTextField<Value, AdapterProps, ExtraFieldProperties>, 'type'>
export type AfterReadRichTextHookArgs< export type AfterReadRichTextHookArgs<
TData extends TypeWithID = any, TData extends TypeWithID = any,
@@ -146,8 +142,8 @@ export type AfterReadRichTextHook<
TValue = any, TValue = any,
TSiblingData = any, TSiblingData = any,
> = ( > = (
args: BaseRichTextHookArgs<TData, TValue, TSiblingData> & args: AfterReadRichTextHookArgs<TData, TValue, TSiblingData> &
AfterReadRichTextHookArgs<TData, TValue, TSiblingData>, BaseRichTextHookArgs<TData, TValue, TSiblingData>,
) => Promise<TValue> | TValue ) => Promise<TValue> | TValue
export type AfterChangeRichTextHook< export type AfterChangeRichTextHook<
@@ -155,8 +151,8 @@ export type AfterChangeRichTextHook<
TValue = any, TValue = any,
TSiblingData = any, TSiblingData = any,
> = ( > = (
args: BaseRichTextHookArgs<TData, TValue, TSiblingData> & args: AfterChangeRichTextHookArgs<TData, TValue, TSiblingData> &
AfterChangeRichTextHookArgs<TData, TValue, TSiblingData>, BaseRichTextHookArgs<TData, TValue, TSiblingData>,
) => Promise<TValue> | TValue ) => Promise<TValue> | TValue
export type BeforeChangeRichTextHook< export type BeforeChangeRichTextHook<
@@ -252,10 +248,10 @@ export type RichTextAdapter<
Value extends object = object, Value extends object = object,
AdapterProps = any, AdapterProps = any,
ExtraFieldProperties = {}, ExtraFieldProperties = {},
> = RichTextAdapterBase<Value, AdapterProps, ExtraFieldProperties> & { > = {
CellComponent: React.FC<any> CellComponent: React.FC<any>
FieldComponent: React.FC<RichTextFieldProps<Value, AdapterProps, ExtraFieldProperties>> FieldComponent: React.FC<RichTextFieldProps<Value, AdapterProps, ExtraFieldProperties>>
} } & RichTextAdapterBase<Value, AdapterProps, ExtraFieldProperties>
export type RichTextAdapterProvider< export type RichTextAdapterProvider<
Value extends object = object, Value extends object = object,

View File

@@ -35,11 +35,11 @@ export type CellComponentProps = {
schemaPath: string schemaPath: string
} }
export type DefaultCellComponentProps<T = any> = CellComponentProps & { export type DefaultCellComponentProps<T = any> = {
cellData: T cellData: T
customCellContext?: { customCellContext?: {
collectionSlug?: SanitizedCollectionConfig['slug'] collectionSlug?: SanitizedCollectionConfig['slug']
uploadConfig?: SanitizedCollectionConfig['upload'] uploadConfig?: SanitizedCollectionConfig['upload']
} }
rowData: RowData rowData: RowData
} } & CellComponentProps

View File

@@ -25,23 +25,23 @@ export type MonthPickerProps = {
} }
export type ConditionalDateProps = export type ConditionalDateProps =
| (SharedProps & | ({
DayPickerProps & pickerAppearance: 'dayOnly'
TimePickerProps & { } & DayPickerProps &
pickerAppearance?: 'dayAndTime' SharedProps)
}) | ({
| (SharedProps & pickerAppearance: 'monthOnly'
DayPickerProps & { } & MonthPickerProps &
pickerAppearance: 'dayOnly' SharedProps)
}) | ({
| (SharedProps & pickerAppearance: 'timeOnly'
MonthPickerProps & { } & SharedProps &
pickerAppearance: 'monthOnly' TimePickerProps)
}) | ({
| (SharedProps & pickerAppearance?: 'dayAndTime'
TimePickerProps & { } & DayPickerProps &
pickerAppearance: 'timeOnly' SharedProps &
}) TimePickerProps)
| (SharedProps & { | ({
pickerAppearance?: 'default' pickerAppearance?: 'default'
}) } & SharedProps)

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-param-reassign */
import type { CollectionConfig } from '../collections/config/types.js' import type { CollectionConfig } from '../collections/config/types.js'
import type { Field, TabAsField } from '../fields/config/types.js' import type { Field, TabAsField } from '../fields/config/types.js'
import type { PayloadRequest } from '../types/index.js' import type { PayloadRequest } from '../types/index.js'

View File

@@ -1,4 +1,4 @@
export * from './types.js' export * from './cookies.js'
export { extractJWT } from './extractJWT.js' export { extractJWT } from './extractJWT.js'
export * from './cookies.js' export * from './types.js'

View File

@@ -27,7 +27,7 @@ export type Options<TSlug extends CollectionSlug> = {
async function localLogin<TSlug extends CollectionSlug>( async function localLogin<TSlug extends CollectionSlug>(
payload: Payload, payload: Payload,
options: Options<TSlug>, options: Options<TSlug>,
): Promise<Result & { user: DataFromCollectionSlug<TSlug> }> { ): Promise<{ user: DataFromCollectionSlug<TSlug> } & Result> {
const { const {
collection: collectionSlug, collection: collectionSlug,
data, data,

View File

@@ -39,7 +39,7 @@ export type Arguments<TSlug extends CollectionSlug> = {
export const loginOperation = async <TSlug extends CollectionSlug>( export const loginOperation = async <TSlug extends CollectionSlug>(
incomingArgs: Arguments<TSlug>, incomingArgs: Arguments<TSlug>,
): Promise<Result & { user: DataFromCollectionSlug<TSlug> }> => { ): Promise<{ user: DataFromCollectionSlug<TSlug> } & Result> => {
let args = incomingArgs let args = incomingArgs
try { try {
@@ -253,7 +253,7 @@ export const loginOperation = async <TSlug extends CollectionSlug>(
})) || user })) || user
}, Promise.resolve()) }, Promise.resolve())
let result: Result & { user: DataFromCollectionSlug<TSlug> } = { let result: { user: DataFromCollectionSlug<TSlug> } & Result = {
exp: (jwt.decode(token) as jwt.JwtPayload).exp, exp: (jwt.decode(token) as jwt.JwtPayload).exp,
token, token,
user, user,

View File

@@ -14,8 +14,8 @@ import { killTransaction } from '../../utilities/killTransaction.js'
export type Arguments<TSlug extends CollectionSlug> = { export type Arguments<TSlug extends CollectionSlug> = {
collection: Collection collection: Collection
data: RequiredDataFromCollectionSlug<TSlug> & data: AuthOperationsFromCollectionSlug<TSlug>['registerFirstUser'] &
AuthOperationsFromCollectionSlug<TSlug>['registerFirstUser'] RequiredDataFromCollectionSlug<TSlug>
req: PayloadRequest req: PayloadRequest
} }

View File

@@ -16,7 +16,7 @@ export const JWTAuthentication: AuthStrategyFunction = async ({
}) => { }) => {
try { try {
const token = extractJWT({ headers, payload }) const token = extractJWT({ headers, payload })
const decodedPayload = jwt.verify(token, payload.secret) as jwt.JwtPayload & JWTToken const decodedPayload = jwt.verify(token, payload.secret) as JWTToken & jwt.JwtPayload
const collection = payload.collections[decodedPayload.collection] const collection = payload.collections[decodedPayload.collection]

View File

@@ -3,7 +3,7 @@ import scmp from 'scmp'
import type { TypeWithID } from '../../../collections/config/types.js' import type { TypeWithID } from '../../../collections/config/types.js'
type Doc = TypeWithID & Record<string, unknown> type Doc = Record<string, unknown> & TypeWithID
type Args = { type Args = {
doc: Doc doc: Doc

View File

@@ -4,7 +4,7 @@ import type { PayloadRequest } from '../../../types/index.js'
type Args = { type Args = {
collection: SanitizedCollectionConfig collection: SanitizedCollectionConfig
doc: TypeWithID & Record<string, unknown> doc: Record<string, unknown> & TypeWithID
payload: Payload payload: Payload
req: PayloadRequest req: PayloadRequest
} }

View File

@@ -4,7 +4,7 @@ import type { PayloadRequest } from '../../../types/index.js'
type Args = { type Args = {
collection: SanitizedCollectionConfig collection: SanitizedCollectionConfig
doc: TypeWithID & Record<string, unknown> doc: Record<string, unknown> & TypeWithID
payload: Payload payload: Payload
req: PayloadRequest req: PayloadRequest
} }

View File

@@ -26,7 +26,7 @@ const injectInlineSourceMap = ({
export async function compile( export async function compile(
sourcecode: string, sourcecode: string,
filename: string, filename: string,
options: ts.CompilerOptions & { fallbackToTs?: (filename: string) => boolean }, options: { fallbackToTs?: (filename: string) => boolean } & ts.CompilerOptions,
): Promise<string> { ): Promise<string> {
if (filename.endsWith('.d.ts')) { if (filename.endsWith('.d.ts')) {
return '' return ''

View File

@@ -10,18 +10,15 @@ export type ServerOnlyCollectionAdminProperties = keyof Pick<
'components' | 'hidden' | 'preview' 'components' | 'hidden' | 'preview'
> >
export type ClientCollectionConfig = Omit< export type ClientCollectionConfig = {
SanitizedCollectionConfig, admin: {
'admin' | 'fields' | ServerOnlyCollectionProperties livePreview?: Omit<LivePreviewConfig, ServerOnlyLivePreviewProperties>
> & { } & Omit<
admin: Omit<
SanitizedCollectionConfig['admin'], SanitizedCollectionConfig['admin'],
'fields' | 'livePreview' | ServerOnlyCollectionAdminProperties 'fields' | 'livePreview' | ServerOnlyCollectionAdminProperties
> & { >
livePreview?: Omit<LivePreviewConfig, ServerOnlyLivePreviewProperties>
}
fields: ClientFieldConfig[] fields: ClientFieldConfig[]
} } & Omit<SanitizedCollectionConfig, 'admin' | 'fields' | ServerOnlyCollectionProperties>
import type { TFunction } from '@payloadcms/translations' import type { TFunction } from '@payloadcms/translations'

View File

@@ -111,7 +111,6 @@ export const deleteOperation = async <TSlug extends CollectionSlug>(
const errors = [] const errors = []
/* eslint-disable no-param-reassign */
const promises = docs.map(async (doc) => { const promises = docs.map(async (doc) => {
let result let result

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-underscore-dangle */
import type { FindOneArgs } from '../../database/types.js' import type { FindOneArgs } from '../../database/types.js'
import type { CollectionSlug } from '../../index.js' import type { CollectionSlug } from '../../index.js'
import type { PayloadRequest } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-underscore-dangle */
import httpStatus from 'http-status' import httpStatus from 'http-status'
import type { PayloadRequest } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'

View File

@@ -22,15 +22,15 @@ export type BaseOptions<TSlug extends CollectionSlug> = {
user?: Document user?: Document
} }
export type ByIDOptions<TSlug extends CollectionSlug> = BaseOptions<TSlug> & { export type ByIDOptions<TSlug extends CollectionSlug> = {
id: number | string id: number | string
where?: never where?: never
} } & BaseOptions<TSlug>
export type ManyOptions<TSlug extends CollectionSlug> = BaseOptions<TSlug> & { export type ManyOptions<TSlug extends CollectionSlug> = {
id?: never id?: never
where: Where where: Where
} } & BaseOptions<TSlug>
export type Options<TSlug extends CollectionSlug> = ByIDOptions<TSlug> | ManyOptions<TSlug> export type Options<TSlug extends CollectionSlug> = ByIDOptions<TSlug> | ManyOptions<TSlug>

View File

@@ -36,15 +36,15 @@ export type BaseOptions<TSlug extends CollectionSlug> = {
user?: Document user?: Document
} }
export type ByIDOptions<TSlug extends CollectionSlug> = BaseOptions<TSlug> & { export type ByIDOptions<TSlug extends CollectionSlug> = {
id: number | string id: number | string
where?: never where?: never
} } & BaseOptions<TSlug>
export type ManyOptions<TSlug extends CollectionSlug> = BaseOptions<TSlug> & { export type ManyOptions<TSlug extends CollectionSlug> = {
id?: never id?: never
where: Where where: Where
} } & BaseOptions<TSlug>
export type Options<TSlug extends CollectionSlug> = ByIDOptions<TSlug> | ManyOptions<TSlug> export type Options<TSlug extends CollectionSlug> = ByIDOptions<TSlug> | ManyOptions<TSlug>

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-underscore-dangle */
import httpStatus from 'http-status' import httpStatus from 'http-status'
import type { FindOneArgs } from '../../database/types.js' import type { FindOneArgs } from '../../database/types.js'

View File

@@ -98,7 +98,7 @@ export const buildAfterOperation = async <
TOperationGeneric extends CollectionSlug, TOperationGeneric extends CollectionSlug,
O extends keyof AfterOperationMap<TOperationGeneric> = keyof AfterOperationMap<TOperationGeneric>, O extends keyof AfterOperationMap<TOperationGeneric> = keyof AfterOperationMap<TOperationGeneric>,
>( >(
operationArgs: Omit<AfterOperationArg<TOperationGeneric>, 'req'> & { operation: O }, operationArgs: { operation: O } & Omit<AfterOperationArg<TOperationGeneric>, 'req'>,
): Promise<OperationResult<TOperationGeneric, O> | any> => { ): Promise<OperationResult<TOperationGeneric, O> | any> => {
const { args, collection, operation, result } = operationArgs const { args, collection, operation, result } = operationArgs

View File

@@ -34,17 +34,14 @@ export type ServerOnlyRootProperties = keyof Pick<
export type ServerOnlyRootAdminProperties = keyof Pick<SanitizedConfig['admin'], 'components'> export type ServerOnlyRootAdminProperties = keyof Pick<SanitizedConfig['admin'], 'components'>
export type ClientConfig = Omit< export type ClientConfig = {
SanitizedConfig, admin: {
'admin' | 'collections' | 'globals' | ServerOnlyRootProperties
> & {
admin: Omit<SanitizedConfig['admin'], ServerOnlyRootAdminProperties & 'livePreview'> & {
livePreview?: Omit<LivePreviewConfig, ServerOnlyLivePreviewProperties> livePreview?: Omit<LivePreviewConfig, ServerOnlyLivePreviewProperties>
} } & Omit<SanitizedConfig['admin'], 'livePreview' & ServerOnlyRootAdminProperties>
collections: ClientCollectionConfig[] collections: ClientCollectionConfig[]
custom?: Record<string, any> custom?: Record<string, any>
globals: ClientGlobalConfig[] globals: ClientGlobalConfig[]
} } & Omit<SanitizedConfig, 'admin' | 'collections' | 'globals' | ServerOnlyRootProperties>
export const createClientConfig = async ({ export const createClientConfig = async ({
config, config,

View File

@@ -73,7 +73,6 @@ export const findConfig = (): string => {
? [configPath, outPath, srcPath, rootPath] ? [configPath, outPath, srcPath, rootPath]
: [configPath, srcPath, rootPath] : [configPath, srcPath, rootPath]
// eslint-disable-next-line no-restricted-syntax
for (const searchPath of searchPaths) { for (const searchPath of searchPaths) {
if (!searchPath) continue if (!searchPath) continue

View File

@@ -41,7 +41,6 @@ type Prettify<T> = {
[K in keyof T]: T[K] [K in keyof T]: T[K]
} & NonNullable<unknown> } & NonNullable<unknown>
// eslint-disable-next-line no-use-before-define
export type Plugin = (config: Config) => Config | Promise<Config> export type Plugin = (config: Config) => Config | Promise<Config>
export type LivePreviewConfig = { export type LivePreviewConfig = {
@@ -347,7 +346,7 @@ export const serverProps: (keyof ServerProps)[] = [
] ]
export type CustomComponent<TAdditionalProps extends any = any> = React.ComponentType< export type CustomComponent<TAdditionalProps extends any = any> = React.ComponentType<
TAdditionalProps & Partial<ServerProps> Partial<ServerProps> & TAdditionalProps
> >
export type Locale = { export type Locale = {
@@ -382,17 +381,17 @@ export type BaseLocalizationConfig = {
} }
export type LocalizationConfigWithNoLabels = Prettify< export type LocalizationConfigWithNoLabels = Prettify<
BaseLocalizationConfig & { {
/** /**
* List of supported locales * List of supported locales
* @example `["en", "es", "fr", "nl", "de", "jp"]` * @example `["en", "es", "fr", "nl", "de", "jp"]`
*/ */
locales: string[] locales: string[]
} } & BaseLocalizationConfig
> >
export type LocalizationConfigWithLabels = Prettify< export type LocalizationConfigWithLabels = Prettify<
BaseLocalizationConfig & { {
/** /**
* List of supported locales with labels * List of supported locales with labels
* @example { * @example {
@@ -402,17 +401,17 @@ export type LocalizationConfigWithLabels = Prettify<
* } * }
*/ */
locales: Locale[] locales: Locale[]
} } & BaseLocalizationConfig
> >
export type SanitizedLocalizationConfig = Prettify< export type SanitizedLocalizationConfig = Prettify<
LocalizationConfigWithLabels & { {
/** /**
* List of supported locales * List of supported locales
* @example `["en", "es", "fr", "nl", "de", "jp"]` * @example `["en", "es", "fr", "nl", "de", "jp"]`
*/ */
localeCodes: string[] localeCodes: string[]
} } & LocalizationConfigWithLabels
> >
/** /**
@@ -547,10 +546,10 @@ export type Config = {
dateFormat?: string dateFormat?: string
/** If set to true, the entire Admin panel will be disabled. */ /** If set to true, the entire Admin panel will be disabled. */
disable?: boolean disable?: boolean
livePreview?: LivePreviewConfig & { livePreview?: {
collections?: string[] collections?: string[]
globals?: string[] globals?: string[]
} } & LivePreviewConfig
/** Base meta data to use for the Admin Panel. Included properties are titleSuffix, ogImage, and favicon. */ /** Base meta data to use for the Admin Panel. Included properties are titleSuffix, ogImage, and favicon. */
meta?: MetaConfig meta?: MetaConfig
routes?: { routes?: {
@@ -758,10 +757,7 @@ export type Config = {
upload?: ExpressFileUploadOptions upload?: ExpressFileUploadOptions
} }
export type SanitizedConfig = Omit< export type SanitizedConfig = {
DeepRequired<Config>,
'collections' | 'editor' | 'endpoint' | 'globals' | 'i18n' | 'localization' | 'upload'
> & {
collections: SanitizedCollectionConfig[] collections: SanitizedCollectionConfig[]
/** Default richtext editor to use for richText fields */ /** Default richtext editor to use for richText fields */
editor?: RichTextAdapter<any, any, any> editor?: RichTextAdapter<any, any, any>
@@ -774,13 +770,16 @@ export type SanitizedConfig = Omit<
configDir: string configDir: string
rawConfig: string rawConfig: string
} }
upload: ExpressFileUploadOptions & { upload: {
/** /**
* Deduped list of adapters used in the project * Deduped list of adapters used in the project
*/ */
adapters: string[] adapters: string[]
} } & ExpressFileUploadOptions
} } & Omit<
DeepRequired<Config>,
'collections' | 'editor' | 'endpoint' | 'globals' | 'i18n' | 'localization' | 'upload'
>
export type EditConfig = export type EditConfig =
| ( | (

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-param-reassign */
import type { MarkOptional } from 'ts-essentials' import type { MarkOptional } from 'ts-essentials'
import type { import type {

View File

@@ -129,7 +129,6 @@ export async function getLocalizedPaths({
if (nestedPathToQuery) { if (nestedPathToQuery) {
const relatedCollection = payload.collections[matchedField.relationTo].config const relatedCollection = payload.collections[matchedField.relationTo].config
// eslint-disable-next-line no-await-in-loop
const remainingPaths = await getLocalizedPaths({ const remainingPaths = await getLocalizedPaths({
collectionSlug: relatedCollection.slug, collectionSlug: relatedCollection.slug,
fields: relatedCollection.fields, fields: relatedCollection.fields,

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-restricted-syntax, no-await-in-loop */
import fs from 'fs' import fs from 'fs'
import type { CreateMigration } from '../types.js' import type { CreateMigration } from '../types.js'

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-restricted-syntax, no-await-in-loop */
import type { PayloadRequest } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import type { BaseDatabaseAdapter } from '../types.js' import type { BaseDatabaseAdapter } from '../types.js'
@@ -23,7 +22,7 @@ export async function migrate(this: BaseDatabaseAdapter): Promise<void> {
// Run migration if not found in database // Run migration if not found in database
if (existingMigration) { if (existingMigration) {
continue // eslint-disable-line no-continue continue
} }
const start = Date.now() const start = Date.now()

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-restricted-syntax, no-await-in-loop */
import type { PayloadRequest } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import type { BaseDatabaseAdapter } from '../types.js' import type { BaseDatabaseAdapter } from '../types.js'

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-restricted-syntax, no-await-in-loop */
import type { PayloadRequest } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import type { BaseDatabaseAdapter } from '../types.js' import type { BaseDatabaseAdapter } from '../types.js'

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-restricted-syntax, no-await-in-loop */
import type { PayloadRequest } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import type { BaseDatabaseAdapter } from '../types.js' import type { BaseDatabaseAdapter } from '../types.js'

View File

@@ -25,7 +25,7 @@ export async function migrateStatus(this: BaseDatabaseAdapter): Promise<void> {
const existingMigration = existingMigrations.find((m) => m.name === migration.name) const existingMigration = existingMigrations.find((m) => m.name === migration.name)
return { return {
Name: migration.name, Name: migration.name,
// eslint-disable-next-line perfectionist/sort-objects
Batch: existingMigration?.batch, Batch: existingMigration?.batch,
Ran: existingMigration ? 'Yes' : 'No', Ran: existingMigration ? 'Yes' : 'No',
} }

View File

@@ -1,8 +1,6 @@
/* eslint-disable no-restricted-syntax */
import type { SanitizedCollectionConfig } from '../../collections/config/types.js' import type { SanitizedCollectionConfig } from '../../collections/config/types.js'
import type { Field, FieldAffectingData } from '../../fields/config/types.js' import type { Field, FieldAffectingData } from '../../fields/config/types.js'
import type { SanitizedGlobalConfig } from '../../globals/config/types.js' import type { SanitizedGlobalConfig } from '../../globals/config/types.js'
/* eslint-disable no-await-in-loop */
import type { Operator, PayloadRequest, Where, WhereField } from '../../types/index.js' import type { Operator, PayloadRequest, Where, WhereField } from '../../types/index.js'
import type { EntityPolicies } from './types.js' import type { EntityPolicies } from './types.js'

View File

@@ -51,10 +51,8 @@ export async function validateSearchParam({
const { slug } = collectionConfig || globalConfig const { slug } = collectionConfig || globalConfig
if (globalConfig && !policies.globals[slug]) { if (globalConfig && !policies.globals[slug]) {
// eslint-disable-next-line no-param-reassign
globalConfig.fields = fields globalConfig.fields = fields
// eslint-disable-next-line no-param-reassign
policies.globals[slug] = await getEntityPolicies({ policies.globals[slug] = await getEntityPolicies({
type: 'global', type: 'global',
entity: globalConfig, entity: globalConfig,
@@ -85,7 +83,6 @@ export async function validateSearchParam({
if (!overrideAccess && fieldAffectsData(field)) { if (!overrideAccess && fieldAffectsData(field)) {
if (collectionSlug) { if (collectionSlug) {
if (!policies.collections[collectionSlug]) { if (!policies.collections[collectionSlug]) {
// eslint-disable-next-line no-param-reassign
policies.collections[collectionSlug] = await getEntityPolicies({ policies.collections[collectionSlug] = await getEntityPolicies({
type: 'collection', type: 'collection',
entity: req.payload.collections[collectionSlug].config, entity: req.payload.collections[collectionSlug].config,

View File

@@ -222,17 +222,17 @@ type BaseVersionArgs = {
where?: Where where?: Where
} }
export type FindVersionsArgs = BaseVersionArgs & { export type FindVersionsArgs = {
collection: string collection: string
} } & BaseVersionArgs
export type FindVersions = <T = TypeWithID>( export type FindVersions = <T = TypeWithID>(
args: FindVersionsArgs, args: FindVersionsArgs,
) => Promise<PaginatedDocs<TypeWithVersion<T>>> ) => Promise<PaginatedDocs<TypeWithVersion<T>>>
export type FindGlobalVersionsArgs = BaseVersionArgs & { export type FindGlobalVersionsArgs = {
global: string global: string
} } & BaseVersionArgs
export type FindGlobalArgs = { export type FindGlobalArgs = {
locale?: string locale?: string
@@ -395,10 +395,10 @@ export type DeleteManyArgs = {
export type DeleteMany = (args: DeleteManyArgs) => Promise<void> export type DeleteMany = (args: DeleteManyArgs) => Promise<void>
export type Migration = MigrationData & { export type Migration = {
down: ({ payload, req }: { payload: Payload; req: PayloadRequest }) => Promise<boolean> down: ({ payload, req }: { payload: Payload; req: PayloadRequest }) => Promise<boolean>
up: ({ payload, req }: { payload: Payload; req: PayloadRequest }) => Promise<boolean> up: ({ payload, req }: { payload: Payload; req: PayloadRequest }) => Promise<boolean>
} } & MigrationData
export type MigrationData = { export type MigrationData = {
batch?: number batch?: number

View File

@@ -1,4 +1,3 @@
/* eslint-disable max-classes-per-file */
import httpStatus from 'http-status' import httpStatus from 'http-status'
class ExtendableError<TData extends object = { [key: string]: unknown }> extends Error { class ExtendableError<TData extends object = { [key: string]: unknown }> extends Error {

View File

@@ -1,7 +1,5 @@
export * from '../fields/validations.js'
export { defaults as collectionDefaults } from '../collections/config/defaults.js' export { defaults as collectionDefaults } from '../collections/config/defaults.js'
export { serverProps } from '../config/types.js' export { serverProps } from '../config/types.js'
export { export {
fieldAffectsData, fieldAffectsData,
fieldHasMaxDepth, fieldHasMaxDepth,
@@ -19,6 +17,8 @@ export {
valueIsValueWithRelation, valueIsValueWithRelation,
} from '../fields/config/types.js' } from '../fields/config/types.js'
export * from '../fields/validations.js'
export { validOperators } from '../types/constants.js' export { validOperators } from '../types/constants.js'
export { formatFilesize } from '../uploads/formatFilesize.js' export { formatFilesize } from '../uploads/formatFilesize.js'

View File

@@ -1,6 +1,4 @@
import { Config } from '../../config/types.js' import type { Config } from '../../config/types.js'
import { InvalidFieldName, InvalidFieldRelationship, MissingFieldType } from '../../errors/index.js'
import { sanitizeFields } from './sanitize.js'
import type { import type {
ArrayField, ArrayField,
Block, Block,
@@ -11,14 +9,17 @@ import type {
TextField, TextField,
} from './types.js' } from './types.js'
import { InvalidFieldName, InvalidFieldRelationship, MissingFieldType } from '../../errors/index.js'
import { sanitizeFields } from './sanitize.js'
describe('sanitizeFields', () => { describe('sanitizeFields', () => {
const config = {} as Config const config = {} as Config
it('should throw on missing type field', async () => { it('should throw on missing type field', async () => {
const fields: Field[] = [ const fields: Field[] = [
// @ts-expect-error // @ts-expect-error
{ {
label: 'some-collection',
name: 'Some Collection', name: 'Some Collection',
label: 'some-collection',
}, },
] ]
await expect(async () => { await expect(async () => {
@@ -32,9 +33,9 @@ describe('sanitizeFields', () => {
it('should throw on invalid field name', async () => { it('should throw on invalid field name', async () => {
const fields: Field[] = [ const fields: Field[] = [
{ {
label: 'some.collection',
name: 'some.collection', name: 'some.collection',
type: 'text', type: 'text',
label: 'some.collection',
}, },
] ]
await expect(async () => { await expect(async () => {
@@ -68,9 +69,9 @@ describe('sanitizeFields', () => {
it('should allow auto-label override', async () => { it('should allow auto-label override', async () => {
const fields: Field[] = [ const fields: Field[] = [
{ {
label: 'Do not label',
name: 'someField', name: 'someField',
type: 'text', type: 'text',
label: 'Do not label',
}, },
] ]
const sanitizedField = ( const sanitizedField = (
@@ -89,9 +90,9 @@ describe('sanitizeFields', () => {
it('should allow label opt-out', async () => { it('should allow label opt-out', async () => {
const fields: Field[] = [ const fields: Field[] = [
{ {
label: false,
name: 'someField', name: 'someField',
type: 'text', type: 'text',
label: false,
}, },
] ]
const sanitizedField = ( const sanitizedField = (
@@ -108,6 +109,8 @@ describe('sanitizeFields', () => {
it('should allow label opt-out for arrays', async () => { it('should allow label opt-out for arrays', async () => {
const arrayField: ArrayField = { const arrayField: ArrayField = {
name: 'items',
type: 'array',
fields: [ fields: [
{ {
name: 'itemName', name: 'itemName',
@@ -115,8 +118,6 @@ describe('sanitizeFields', () => {
}, },
], ],
label: false, label: false,
name: 'items',
type: 'array',
} }
const sanitizedField = ( const sanitizedField = (
await sanitizeFields({ await sanitizeFields({
@@ -133,20 +134,20 @@ describe('sanitizeFields', () => {
it('should allow label opt-out for blocks', async () => { it('should allow label opt-out for blocks', async () => {
const fields: Field[] = [ const fields: Field[] = [
{ {
name: 'noLabelBlock',
type: 'blocks',
blocks: [ blocks: [
{ {
slug: 'number',
fields: [ fields: [
{ {
name: 'testNumber', name: 'testNumber',
type: 'number', type: 'number',
}, },
], ],
slug: 'number',
}, },
], ],
label: false, label: false,
name: 'noLabelBlock',
type: 'blocks',
}, },
] ]
const sanitizedField = ( const sanitizedField = (
@@ -166,14 +167,14 @@ describe('sanitizeFields', () => {
it('should label arrays with plural and singular', async () => { it('should label arrays with plural and singular', async () => {
const fields: Field[] = [ const fields: Field[] = [
{ {
name: 'items',
type: 'array',
fields: [ fields: [
{ {
name: 'itemName', name: 'itemName',
type: 'text', type: 'text',
}, },
], ],
name: 'items',
type: 'array',
}, },
] ]
const sanitizedField = ( const sanitizedField = (
@@ -192,14 +193,14 @@ describe('sanitizeFields', () => {
it('should label blocks with plural and singular', async () => { it('should label blocks with plural and singular', async () => {
const fields: Field[] = [ const fields: Field[] = [
{ {
blocks: [
{
fields: [{ name: 'testNumber', type: 'number' }],
slug: 'number',
},
],
name: 'specialBlock', name: 'specialBlock',
type: 'blocks', type: 'blocks',
blocks: [
{
slug: 'number',
fields: [{ name: 'testNumber', type: 'number' }],
},
],
}, },
] ]
const sanitizedField = ( const sanitizedField = (
@@ -225,10 +226,10 @@ describe('sanitizeFields', () => {
const validRelationships = ['some-collection'] const validRelationships = ['some-collection']
const fields: Field[] = [ const fields: Field[] = [
{ {
label: 'my-relationship',
name: 'My Relationship', name: 'My Relationship',
relationTo: 'some-collection',
type: 'relationship', type: 'relationship',
label: 'my-relationship',
relationTo: 'some-collection',
}, },
] ]
await expect(async () => { await expect(async () => {
@@ -240,10 +241,10 @@ describe('sanitizeFields', () => {
const validRelationships = ['some-collection', 'another-collection'] const validRelationships = ['some-collection', 'another-collection']
const fields: Field[] = [ const fields: Field[] = [
{ {
label: 'my-relationship',
name: 'My Relationship', name: 'My Relationship',
relationTo: ['some-collection', 'another-collection'],
type: 'relationship', type: 'relationship',
label: 'my-relationship',
relationTo: ['some-collection', 'another-collection'],
}, },
] ]
await expect(async () => { await expect(async () => {
@@ -254,22 +255,22 @@ describe('sanitizeFields', () => {
it('should not throw on valid relationship inside blocks', async () => { it('should not throw on valid relationship inside blocks', async () => {
const validRelationships = ['some-collection'] const validRelationships = ['some-collection']
const relationshipBlock: Block = { const relationshipBlock: Block = {
slug: 'relationshipBlock',
fields: [ fields: [
{ {
label: 'my-relationship',
name: 'My Relationship', name: 'My Relationship',
relationTo: 'some-collection',
type: 'relationship', type: 'relationship',
label: 'my-relationship',
relationTo: 'some-collection',
}, },
], ],
slug: 'relationshipBlock',
} }
const fields: Field[] = [ const fields: Field[] = [
{ {
blocks: [relationshipBlock],
label: 'Layout Blocks',
name: 'layout', name: 'layout',
type: 'blocks', type: 'blocks',
blocks: [relationshipBlock],
label: 'Layout Blocks',
}, },
] ]
await expect(async () => { await expect(async () => {
@@ -281,10 +282,10 @@ describe('sanitizeFields', () => {
const validRelationships = ['some-collection'] const validRelationships = ['some-collection']
const fields: Field[] = [ const fields: Field[] = [
{ {
label: 'my-relationship',
name: 'My Relationship', name: 'My Relationship',
relationTo: 'not-valid',
type: 'relationship', type: 'relationship',
label: 'my-relationship',
relationTo: 'not-valid',
}, },
] ]
await expect(async () => { await expect(async () => {
@@ -296,10 +297,10 @@ describe('sanitizeFields', () => {
const validRelationships = ['some-collection', 'another-collection'] const validRelationships = ['some-collection', 'another-collection']
const fields: Field[] = [ const fields: Field[] = [
{ {
label: 'my-relationship',
name: 'My Relationship', name: 'My Relationship',
relationTo: ['some-collection', 'not-valid'],
type: 'relationship', type: 'relationship',
label: 'my-relationship',
relationTo: ['some-collection', 'not-valid'],
}, },
] ]
await expect(async () => { await expect(async () => {
@@ -310,22 +311,22 @@ describe('sanitizeFields', () => {
it('should throw on invalid relationship inside blocks', async () => { it('should throw on invalid relationship inside blocks', async () => {
const validRelationships = ['some-collection'] const validRelationships = ['some-collection']
const relationshipBlock: Block = { const relationshipBlock: Block = {
slug: 'relationshipBlock',
fields: [ fields: [
{ {
label: 'my-relationship',
name: 'My Relationship', name: 'My Relationship',
relationTo: 'not-valid',
type: 'relationship', type: 'relationship',
label: 'my-relationship',
relationTo: 'not-valid',
}, },
], ],
slug: 'relationshipBlock',
} }
const fields: Field[] = [ const fields: Field[] = [
{ {
blocks: [relationshipBlock],
label: 'Layout Blocks',
name: 'layout', name: 'layout',
type: 'blocks', type: 'blocks',
blocks: [relationshipBlock],
label: 'Layout Blocks',
}, },
] ]
await expect(async () => { await expect(async () => {
@@ -337,8 +338,8 @@ describe('sanitizeFields', () => {
const fields: Field[] = [ const fields: Field[] = [
{ {
name: 'My Checkbox', name: 'My Checkbox',
required: true,
type: 'checkbox', type: 'checkbox',
required: true,
}, },
] ]

View File

@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable no-use-before-define */
import type { EditorProps } from '@monaco-editor/react' import type { EditorProps } from '@monaco-editor/react'
import type { CSSProperties } from 'react' import type { CSSProperties } from 'react'
@@ -241,8 +241,8 @@ export interface FieldBase {
validate?: Validate validate?: Validate
} }
export type NumberField = FieldBase & { export type NumberField = {
admin?: Admin & { admin?: {
/** Set this property to a string that will be used for browser autocomplete. */ /** Set this property to a string that will be used for browser autocomplete. */
autoComplete?: string autoComplete?: string
components?: { components?: {
@@ -255,33 +255,34 @@ export type NumberField = FieldBase & {
placeholder?: Record<string, string> | string placeholder?: Record<string, string> | string
/** Set a value for the number field to increment / decrement using browser controls. */ /** Set a value for the number field to increment / decrement using browser controls. */
step?: number step?: number
} } & Admin
/** Maximum value accepted. Used in the default `validation` function. */ /** Maximum value accepted. Used in the default `validation` function. */
max?: number max?: number
/** Minimum value accepted. Used in the default `validation` function. */ /** Minimum value accepted. Used in the default `validation` function. */
min?: number min?: number
type: 'number' type: 'number'
} & ( } & (
| { | {
/** Makes this field an ordered array of numbers instead of just a single number. */ /** Makes this field an ordered array of numbers instead of just a single number. */
hasMany: true hasMany: true
/** Maximum number of numbers in the numbers array, if `hasMany` is set to true. */ /** Maximum number of numbers in the numbers array, if `hasMany` is set to true. */
maxRows?: number maxRows?: number
/** Minimum number of numbers in the numbers array, if `hasMany` is set to true. */ /** Minimum number of numbers in the numbers array, if `hasMany` is set to true. */
minRows?: number minRows?: number
} }
| { | {
/** Makes this field an ordered array of numbers instead of just a single number. */ /** Makes this field an ordered array of numbers instead of just a single number. */
hasMany?: false | undefined hasMany?: false | undefined
/** Maximum number of numbers in the numbers array, if `hasMany` is set to true. */ /** Maximum number of numbers in the numbers array, if `hasMany` is set to true. */
maxRows?: undefined maxRows?: undefined
/** Minimum number of numbers in the numbers array, if `hasMany` is set to true. */ /** Minimum number of numbers in the numbers array, if `hasMany` is set to true. */
minRows?: undefined minRows?: undefined
} }
) ) &
FieldBase
export type TextField = FieldBase & { export type TextField = {
admin?: Admin & { admin?: {
autoComplete?: string autoComplete?: string
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
@@ -291,31 +292,32 @@ export type TextField = FieldBase & {
} }
placeholder?: Record<string, string> | string placeholder?: Record<string, string> | string
rtl?: boolean rtl?: boolean
} } & Admin
maxLength?: number maxLength?: number
minLength?: number minLength?: number
type: 'text' type: 'text'
} & ( } & (
| { | {
/** Makes this field an ordered array of strings instead of just a single string. */ /** Makes this field an ordered array of strings instead of just a single string. */
hasMany: true hasMany: true
/** Maximum number of strings in the strings array, if `hasMany` is set to true. */ /** Maximum number of strings in the strings array, if `hasMany` is set to true. */
maxRows?: number maxRows?: number
/** Minimum number of strings in the strings array, if `hasMany` is set to true. */ /** Minimum number of strings in the strings array, if `hasMany` is set to true. */
minRows?: number minRows?: number
} }
| { | {
/** Makes this field an ordered array of strings instead of just a single string. */ /** Makes this field an ordered array of strings instead of just a single string. */
hasMany?: false | undefined hasMany?: false | undefined
/** Maximum number of strings in the strings array, if `hasMany` is set to true. */ /** Maximum number of strings in the strings array, if `hasMany` is set to true. */
maxRows?: undefined maxRows?: undefined
/** Minimum number of strings in the strings array, if `hasMany` is set to true. */ /** Minimum number of strings in the strings array, if `hasMany` is set to true. */
minRows?: undefined minRows?: undefined
} }
) ) &
FieldBase
export type EmailField = FieldBase & { export type EmailField = {
admin?: Admin & { admin?: {
autoComplete?: string autoComplete?: string
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
@@ -324,12 +326,12 @@ export type EmailField = FieldBase & {
beforeInput?: CustomComponent[] beforeInput?: CustomComponent[]
} }
placeholder?: Record<string, string> | string placeholder?: Record<string, string> | string
} } & Admin
type: 'email' type: 'email'
} } & FieldBase
export type TextareaField = FieldBase & { export type TextareaField = {
admin?: Admin & { admin?: {
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
Label?: CustomComponent<LabelProps> Label?: CustomComponent<LabelProps>
@@ -339,26 +341,26 @@ export type TextareaField = FieldBase & {
placeholder?: Record<string, string> | string placeholder?: Record<string, string> | string
rows?: number rows?: number
rtl?: boolean rtl?: boolean
} } & Admin
maxLength?: number maxLength?: number
minLength?: number minLength?: number
type: 'textarea' type: 'textarea'
} } & FieldBase
export type CheckboxField = FieldBase & { export type CheckboxField = {
admin?: Admin & { admin?: {
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
Label?: CustomComponent<LabelProps> Label?: CustomComponent<LabelProps>
afterInput?: CustomComponent[] afterInput?: CustomComponent[]
beforeInput?: CustomComponent[] beforeInput?: CustomComponent[]
} }
} } & Admin
type: 'checkbox' type: 'checkbox'
} } & FieldBase
export type DateField = FieldBase & { export type DateField = {
admin?: Admin & { admin?: {
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
Label?: CustomComponent<LabelProps> Label?: CustomComponent<LabelProps>
@@ -367,14 +369,14 @@ export type DateField = FieldBase & {
} }
date?: ConditionalDateProps date?: ConditionalDateProps
placeholder?: Record<string, string> | string placeholder?: Record<string, string> | string
} } & Admin
type: 'date' type: 'date'
} } & FieldBase
export type GroupField = Omit<FieldBase, 'required' | 'validation'> & { export type GroupField = {
admin?: Admin & { admin?: {
hideGutter?: boolean hideGutter?: boolean
} } & Admin
fields: Field[] fields: Field[]
/** Customize generated GraphQL and Typescript schema names. /** Customize generated GraphQL and Typescript schema names.
* By default, it is bound to the collection. * By default, it is bound to the collection.
@@ -384,47 +386,48 @@ export type GroupField = Omit<FieldBase, 'required' | 'validation'> & {
*/ */
interfaceName?: string interfaceName?: string
type: 'group' type: 'group'
} } & Omit<FieldBase, 'required' | 'validation'>
export type RowAdmin = Omit<Admin, 'description'> export type RowAdmin = Omit<Admin, 'description'>
export type RowField = Omit<FieldBase, 'admin' | 'label' | 'name'> & { export type RowField = {
admin?: RowAdmin admin?: RowAdmin
fields: Field[] fields: Field[]
type: 'row' type: 'row'
} } & Omit<FieldBase, 'admin' | 'label' | 'name'>
export type CollapsibleField = Omit<FieldBase, 'label' | 'name'> & { export type CollapsibleField = {
fields: Field[] fields: Field[]
type: 'collapsible' type: 'collapsible'
} & ( } & (
| { | {
admin: Admin & { admin: {
components: { components: {
RowLabel: RowLabelComponent RowLabel: RowLabelComponent
} & Admin['components'] } & Admin['components']
initCollapsed?: boolean initCollapsed?: boolean
} } & Admin
label?: Required<FieldBase['label']> label?: Required<FieldBase['label']>
} }
| { | {
admin?: Admin & { admin?: {
initCollapsed?: boolean initCollapsed?: boolean
} } & Admin
label: Required<FieldBase['label']> label: Required<FieldBase['label']>
} }
) ) &
Omit<FieldBase, 'label' | 'name'>
export type TabsAdmin = Omit<Admin, 'description'> export type TabsAdmin = Omit<Admin, 'description'>
type TabBase = Omit<FieldBase, 'required' | 'validation'> & { type TabBase = {
description?: Description description?: Description
fields: Field[] fields: Field[]
interfaceName?: string interfaceName?: string
saveToJWT?: boolean | string saveToJWT?: boolean | string
} } & Omit<FieldBase, 'required' | 'validation'>
export type NamedTab = TabBase & { export type NamedTab = {
/** Customize generated GraphQL and Typescript schema names. /** Customize generated GraphQL and Typescript schema names.
* The slug is used by default. * The slug is used by default.
* *
@@ -432,9 +435,9 @@ export type NamedTab = TabBase & {
* **Note**: Top level types can collide, ensure they are unique amongst collections, arrays, groups, blocks, tabs. * **Note**: Top level types can collide, ensure they are unique amongst collections, arrays, groups, blocks, tabs.
*/ */
interfaceName?: string interfaceName?: string
} } & TabBase
export type UnnamedTab = Omit<TabBase, 'name'> & { export type UnnamedTab = {
interfaceName?: never interfaceName?: never
/** /**
* Can be either: * Can be either:
@@ -448,20 +451,20 @@ export type UnnamedTab = Omit<TabBase, 'name'> & {
| LabelFunction | LabelFunction
| string | string
localized?: never localized?: never
} } & Omit<TabBase, 'name'>
export type Tab = NamedTab | UnnamedTab export type Tab = NamedTab | UnnamedTab
export type TabsField = Omit<FieldBase, 'admin' | 'localized' | 'name' | 'saveToJWT'> & { export type TabsField = {
admin?: TabsAdmin admin?: TabsAdmin
tabs: Tab[] tabs: Tab[]
type: 'tabs' type: 'tabs'
} } & Omit<FieldBase, 'admin' | 'localized' | 'name' | 'saveToJWT'>
export type TabAsField = Tab & { export type TabAsField = {
name?: string name?: string
type: 'tab' type: 'tab'
} } & Tab
export type UIField = { export type UIField = {
admin: { admin: {
@@ -492,7 +495,7 @@ export type UIField = {
type: 'ui' type: 'ui'
} }
export type UploadField = FieldBase & { export type UploadField = {
admin?: { admin?: {
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
@@ -508,33 +511,33 @@ export type UploadField = FieldBase & {
maxDepth?: number maxDepth?: number
relationTo: CollectionSlug relationTo: CollectionSlug
type: 'upload' type: 'upload'
} } & FieldBase
type CodeAdmin = Admin & { type CodeAdmin = {
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
Label?: CustomComponent<LabelProps> Label?: CustomComponent<LabelProps>
} }
editorOptions?: EditorProps['options'] editorOptions?: EditorProps['options']
language?: string language?: string
} } & Admin
export type CodeField = Omit<FieldBase, 'admin'> & { export type CodeField = {
admin?: CodeAdmin admin?: CodeAdmin
maxLength?: number maxLength?: number
minLength?: number minLength?: number
type: 'code' type: 'code'
} } & Omit<FieldBase, 'admin'>
type JSONAdmin = Admin & { type JSONAdmin = {
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
Label?: CustomComponent<LabelProps> Label?: CustomComponent<LabelProps>
} }
editorOptions?: EditorProps['options'] editorOptions?: EditorProps['options']
} } & Admin
export type JSONField = Omit<FieldBase, 'admin'> & { export type JSONField = {
admin?: JSONAdmin admin?: JSONAdmin
jsonSchema?: { jsonSchema?: {
fileMatch: string[] fileMatch: string[]
@@ -542,17 +545,17 @@ export type JSONField = Omit<FieldBase, 'admin'> & {
uri: string uri: string
} }
type: 'json' type: 'json'
} } & Omit<FieldBase, 'admin'>
export type SelectField = FieldBase & { export type SelectField = {
admin?: Admin & { admin?: {
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
Label?: CustomComponent<LabelProps> Label?: CustomComponent<LabelProps>
} }
isClearable?: boolean isClearable?: boolean
isSortable?: boolean isSortable?: boolean
} } & Admin
/** /**
* Customize the SQL table name * Customize the SQL table name
*/ */
@@ -564,9 +567,9 @@ export type SelectField = FieldBase & {
hasMany?: boolean hasMany?: boolean
options: Option[] options: Option[]
type: 'select' type: 'select'
} } & FieldBase
type SharedRelationshipProperties = FieldBase & { type SharedRelationshipProperties = {
filterOptions?: FilterOptions filterOptions?: FilterOptions
hasMany?: boolean hasMany?: boolean
/** /**
@@ -577,54 +580,55 @@ type SharedRelationshipProperties = FieldBase & {
maxDepth?: number maxDepth?: number
type: 'relationship' type: 'relationship'
} & ( } & (
| { | {
hasMany: true hasMany: true
/** /**
* @deprecated Use 'maxRows' instead * @deprecated Use 'maxRows' instead
*/ */
max?: number max?: number
maxRows?: number maxRows?: number
/** /**
* @deprecated Use 'minRows' instead * @deprecated Use 'minRows' instead
*/ */
min?: number min?: number
minRows?: number minRows?: number
} }
| { | {
hasMany?: false | undefined hasMany?: false | undefined
/** /**
* @deprecated Use 'maxRows' instead * @deprecated Use 'maxRows' instead
*/ */
max?: undefined max?: undefined
maxRows?: undefined maxRows?: undefined
/** /**
* @deprecated Use 'minRows' instead * @deprecated Use 'minRows' instead
*/ */
min?: undefined min?: undefined
minRows?: undefined minRows?: undefined
} }
) ) &
FieldBase
type RelationshipAdmin = Admin & { type RelationshipAdmin = {
allowCreate?: boolean allowCreate?: boolean
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
Label?: CustomComponent<LabelProps> Label?: CustomComponent<LabelProps>
} }
isSortable?: boolean isSortable?: boolean
} } & Admin
export type PolymorphicRelationshipField = SharedRelationshipProperties & { export type PolymorphicRelationshipField = {
admin?: RelationshipAdmin & { admin?: {
sortOptions?: { [collectionSlug: CollectionSlug]: string } sortOptions?: { [collectionSlug: CollectionSlug]: string }
} } & RelationshipAdmin
relationTo: CollectionSlug[] relationTo: CollectionSlug[]
} } & SharedRelationshipProperties
export type SingleRelationshipField = SharedRelationshipProperties & { export type SingleRelationshipField = {
admin?: RelationshipAdmin & { admin?: {
sortOptions?: string sortOptions?: string
} } & RelationshipAdmin
relationTo: CollectionSlug relationTo: CollectionSlug
} } & SharedRelationshipProperties
export type RelationshipField = PolymorphicRelationshipField | SingleRelationshipField export type RelationshipField = PolymorphicRelationshipField | SingleRelationshipField
export type ValueWithRelation = { export type ValueWithRelation = {
@@ -646,13 +650,13 @@ export type RichTextField<
Value extends object = any, Value extends object = any,
AdapterProps = any, AdapterProps = any,
ExtraProperties = object, ExtraProperties = object,
> = FieldBase & { > = {
admin?: Admin & { admin?: {
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
Label?: CustomComponent<LabelProps> Label?: CustomComponent<LabelProps>
} }
} } & Admin
editor?: editor?:
| RichTextAdapter<Value, AdapterProps, AdapterProps> | RichTextAdapter<Value, AdapterProps, AdapterProps>
| RichTextAdapterProvider<Value, AdapterProps, AdapterProps> | RichTextAdapterProvider<Value, AdapterProps, AdapterProps>
@@ -663,10 +667,11 @@ export type RichTextField<
*/ */
maxDepth?: number maxDepth?: number
type: 'richText' type: 'richText'
} & ExtraProperties } & ExtraProperties &
FieldBase
export type ArrayField = FieldBase & { export type ArrayField = {
admin?: Admin & { admin?: {
components?: { components?: {
RowLabel?: RowLabelComponent RowLabel?: RowLabelComponent
} & Admin['components'] } & Admin['components']
@@ -675,7 +680,7 @@ export type ArrayField = FieldBase & {
* Disable drag and drop sorting * Disable drag and drop sorting
*/ */
isSortable?: boolean isSortable?: boolean
} } & Admin
/** /**
* Customize the SQL table name * Customize the SQL table name
*/ */
@@ -692,16 +697,16 @@ export type ArrayField = FieldBase & {
maxRows?: number maxRows?: number
minRows?: number minRows?: number
type: 'array' type: 'array'
} } & FieldBase
export type RadioField = FieldBase & { export type RadioField = {
admin?: Admin & { admin?: {
components?: { components?: {
Error?: CustomComponent<ErrorProps> Error?: CustomComponent<ErrorProps>
Label?: CustomComponent<LabelProps> Label?: CustomComponent<LabelProps>
} }
layout?: 'horizontal' | 'vertical' layout?: 'horizontal' | 'vertical'
} } & Admin
/** /**
* Customize the SQL table name * Customize the SQL table name
*/ */
@@ -712,7 +717,7 @@ export type RadioField = FieldBase & {
enumName?: DBIdentifierName enumName?: DBIdentifierName
options: Option[] options: Option[]
type: 'radio' type: 'radio'
} } & FieldBase
export type Block = { export type Block = {
admin?: { admin?: {
@@ -743,25 +748,25 @@ export type Block = {
slug: string slug: string
} }
export type BlockField = FieldBase & { export type BlockField = {
admin?: Admin & { admin?: {
initCollapsed?: boolean initCollapsed?: boolean
/** /**
* Disable drag and drop sorting * Disable drag and drop sorting
*/ */
isSortable?: boolean isSortable?: boolean
} } & Admin
blocks: Block[] blocks: Block[]
defaultValue?: unknown defaultValue?: unknown
labels?: Labels labels?: Labels
maxRows?: number maxRows?: number
minRows?: number minRows?: number
type: 'blocks' type: 'blocks'
} } & FieldBase
export type PointField = FieldBase & { export type PointField = {
type: 'point' type: 'point'
} } & FieldBase
export type Field = export type Field =
| ArrayField | ArrayField
@@ -828,9 +833,9 @@ export type NonPresentationalField =
| TextareaField | TextareaField
| UploadField | UploadField
export type FieldWithPath = Field & { export type FieldWithPath = {
path?: string path?: string
} } & Field
export type FieldWithSubFields = ArrayField | CollapsibleField | GroupField | RowField export type FieldWithSubFields = ArrayField | CollapsibleField | GroupField | RowField

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-param-reassign */
import type { RichTextAdapter } from '../../../admin/RichText.js' import type { RichTextAdapter } from '../../../admin/RichText.js'
import type { SanitizedCollectionConfig } from '../../../collections/config/types.js' import type { SanitizedCollectionConfig } from '../../../collections/config/types.js'
import type { SanitizedGlobalConfig } from '../../../globals/config/types.js' import type { SanitizedGlobalConfig } from '../../../globals/config/types.js'

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-param-reassign */
import type { RichTextAdapter } from '../../../admin/RichText.js' import type { RichTextAdapter } from '../../../admin/RichText.js'
import type { SanitizedCollectionConfig } from '../../../collections/config/types.js' import type { SanitizedCollectionConfig } from '../../../collections/config/types.js'
import type { SanitizedGlobalConfig } from '../../../globals/config/types.js' import type { SanitizedGlobalConfig } from '../../../globals/config/types.js'

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-param-reassign */
import type { RichTextAdapter } from '../../../admin/RichText.js' import type { RichTextAdapter } from '../../../admin/RichText.js'
import type { SanitizedCollectionConfig } from '../../../collections/config/types.js' import type { SanitizedCollectionConfig } from '../../../collections/config/types.js'
import type { SanitizedGlobalConfig } from '../../../globals/config/types.js' import type { SanitizedGlobalConfig } from '../../../globals/config/types.js'

View File

@@ -1,6 +1,7 @@
import type { ValidateOptions } from './config/types.js'
import { jest } from '@jest/globals' import { jest } from '@jest/globals'
import type { ValidateOptions } from './config/types.js'
import { number, password, point, relationship, select, text, textarea } from './validations.js' import { number, password, point, relationship, select, text, textarea } from './validations.js'
const t = jest.fn((string) => string) const t = jest.fn((string) => string)
@@ -8,9 +9,7 @@ const t = jest.fn((string) => string)
let options: ValidateOptions<any, any, any> = { let options: ValidateOptions<any, any, any> = {
data: undefined, data: undefined,
operation: 'create', operation: 'create',
siblingData: undefined,
req: { req: {
t,
context: {}, context: {},
payload: { payload: {
config: { config: {
@@ -20,7 +19,9 @@ let options: ValidateOptions<any, any, any> = {
}, },
}, },
}, },
t,
}, },
siblingData: undefined,
} }
describe('Field Validations', () => { describe('Field Validations', () => {
@@ -216,32 +217,32 @@ describe('Field Validations', () => {
describe('relationship', () => { describe('relationship', () => {
const relationCollection = { const relationCollection = {
slug: 'relation',
fields: [ fields: [
{ {
name: 'id', name: 'id',
type: 'text', type: 'text',
}, },
], ],
slug: 'relation',
} }
const relationshipOptions = { const relationshipOptions = {
...options, ...options,
relationTo: 'relation',
req: { req: {
...options.req, ...options.req,
payload: { payload: {
...options.req.payload, ...options.req.payload,
config: {
collections: [relationCollection],
},
collections: { collections: {
relation: { relation: {
config: relationCollection, config: relationCollection,
}, },
}, },
config: {
collections: [relationCollection],
},
}, },
}, },
relationTo: 'relation',
} }
it('should handle required', async () => { it('should handle required', async () => {
const val = undefined const val = undefined
@@ -292,8 +293,8 @@ describe('Field Validations', () => {
describe('select', () => { describe('select', () => {
const selectOptions = { const selectOptions = {
...options, ...options,
options: ['one', 'two', 'three'],
type: 'select', type: 'select',
options: ['one', 'two', 'three'],
} }
const optionsRequired = { const optionsRequired = {
...selectOptions, ...selectOptions,

View File

@@ -168,7 +168,7 @@ export const code: Validate<string, unknown, unknown, CodeField> = (
return true return true
} }
export const json: Validate<string, unknown, unknown, JSONField & { jsonError?: string }> = async ( export const json: Validate<string, unknown, unknown, { jsonError?: string } & JSONField> = async (
value, value,
{ jsonError, jsonSchema, req: { t }, required }, { jsonError, jsonSchema, req: { t }, required },
) => { ) => {
@@ -250,7 +250,6 @@ export const date: Validate<Date, unknown, unknown, DateField> = (
{ req: { t }, required }, { req: { t }, required },
) => { ) => {
if (value && !isNaN(Date.parse(value.toString()))) { if (value && !isNaN(Date.parse(value.toString()))) {
/* eslint-disable-line */
return true return true
} }

View File

@@ -19,18 +19,15 @@ export type ServerOnlyGlobalAdminProperties = keyof Pick<
'components' | 'hidden' | 'preview' 'components' | 'hidden' | 'preview'
> >
export type ClientGlobalConfig = Omit< export type ClientGlobalConfig = {
SanitizedGlobalConfig, admin: {
'admin' | 'fields' | ServerOnlyGlobalProperties
> & {
admin: Omit<
SanitizedGlobalConfig['admin'],
ServerOnlyGlobalAdminProperties & 'fields' & 'livePreview'
> & {
livePreview?: Omit<LivePreviewConfig, ServerOnlyLivePreviewProperties> livePreview?: Omit<LivePreviewConfig, ServerOnlyLivePreviewProperties>
} } & Omit<
SanitizedGlobalConfig['admin'],
'fields' & 'livePreview' & ServerOnlyGlobalAdminProperties
>
fields: ClientFieldConfig[] fields: ClientFieldConfig[]
} } & Omit<SanitizedGlobalConfig, 'admin' | 'fields' | ServerOnlyGlobalProperties>
export const createClientGlobalConfig = ({ export const createClientGlobalConfig = ({
global, global,

View File

@@ -1,4 +1,3 @@
/* eslint-disable no-underscore-dangle */
import type { FindGlobalVersionsArgs } from '../../database/types.js' import type { FindGlobalVersionsArgs } from '../../database/types.js'
import type { PayloadRequest } from '../../types/index.js' import type { PayloadRequest } from '../../types/index.js'
import type { TypeWithVersion } from '../../versions/types.js' import type { TypeWithVersion } from '../../versions/types.js'

View File

@@ -83,7 +83,7 @@ export interface GeneratedTypes {
} }
} }
collectionsUntyped: { collectionsUntyped: {
[slug: string]: TypeWithID & Record<string, unknown> [slug: string]: Record<string, unknown> & TypeWithID
} }
globalsUntyped: { globalsUntyped: {
[slug: string]: Record<string, unknown> [slug: string]: Record<string, unknown>
@@ -293,7 +293,7 @@ export class BasePayload {
login = async <TSlug extends CollectionSlug>( login = async <TSlug extends CollectionSlug>(
options: LoginOptions<TSlug>, options: LoginOptions<TSlug>,
): Promise<LoginResult & { user: DataFromCollectionSlug<TSlug> }> => { ): Promise<{ user: DataFromCollectionSlug<TSlug> } & LoginResult> => {
const { login } = localOperations.auth const { login } = localOperations.auth
return login<TSlug>(this, options) return login<TSlug>(this, options)
} }
@@ -632,7 +632,6 @@ export default initialized
let cached = global._payload let cached = global._payload
if (!cached) { if (!cached) {
// eslint-disable-next-line no-multi-assign
cached = global._payload = { payload: null, promise: null } cached = global._payload = { payload: null, promise: null }
} }
@@ -669,14 +668,52 @@ export interface DatabaseAdapter extends BaseDatabaseAdapter {}
export type { Payload, RequestContext } export type { Payload, RequestContext }
export * from './types/index.js' export type { FieldTypes } from './admin/forms/FieldTypes.js'
export type * from './admin/types.js' export type * from './admin/types.js'
export type * from './uploads/types.js' export { default as executeAccess } from './auth/executeAccess.js'
export { executeAuthStrategies } from './auth/executeAuthStrategies.js'
export { getAccessResults } from './auth/getAccessResults.js'
export { getFieldsToSign } from './auth/getFieldsToSign.js'
export * from './auth/index.js'
export { accessOperation } from './auth/operations/access.js'
export { forgotPasswordOperation } from './auth/operations/forgotPassword.js'
export { initOperation } from './auth/operations/init.js'
export { loginOperation } from './auth/operations/login.js'
export { logoutOperation } from './auth/operations/logout.js'
export type { MeOperationResult } from './auth/operations/me.js' export type { MeOperationResult } from './auth/operations/me.js'
export { meOperation } from './auth/operations/me.js'
export { refreshOperation } from './auth/operations/refresh.js'
export { registerFirstUserOperation } from './auth/operations/registerFirstUser.js'
export { resetPasswordOperation } from './auth/operations/resetPassword.js'
export { unlockOperation } from './auth/operations/unlock.js'
export { verifyEmailOperation } from './auth/operations/verifyEmail.js'
export type {
AuthStrategyFunction,
AuthStrategyFunctionArgs,
CollectionPermission,
DocumentPermissions,
FieldPermissions,
GlobalPermission,
IncomingAuthType,
Permission,
Permissions,
User,
VerifyConfig,
} from './auth/types.js'
export type { ClientCollectionConfig } from './collections/config/client.js' export type { ClientCollectionConfig } from './collections/config/client.js'
export { createClientCollectionConfig } from './collections/config/client.js'
export type { export type {
AfterChangeHook as CollectionAfterChangeHook, AfterChangeHook as CollectionAfterChangeHook,
AfterDeleteHook as CollectionAfterDeleteHook, AfterDeleteHook as CollectionAfterDeleteHook,
@@ -712,9 +749,30 @@ export type {
} from './collections/config/types.js' } from './collections/config/types.js'
export { createDataloaderCacheKey, getDataLoader } from './collections/dataloader.js' export { createDataloaderCacheKey, getDataLoader } from './collections/dataloader.js'
export { countOperation } from './collections/operations/count.js'
export { createOperation } from './collections/operations/create.js'
export { deleteOperation } from './collections/operations/delete.js'
export { deleteByIDOperation } from './collections/operations/deleteByID.js'
export { docAccessOperation } from './collections/operations/docAccess.js'
export { duplicateOperation } from './collections/operations/duplicate.js'
export { findOperation } from './collections/operations/find.js'
export { findByIDOperation } from './collections/operations/findByID.js'
export { findVersionByIDOperation } from './collections/operations/findVersionByID.js'
export { findVersionsOperation } from './collections/operations/findVersions.js'
export { restoreVersionOperation } from './collections/operations/restoreVersion.js'
export { updateOperation } from './collections/operations/update.js'
export { updateByIDOperation } from './collections/operations/updateByID.js'
export { buildConfig } from './config/build.js' export { buildConfig } from './config/build.js'
export type { ClientConfig } from './config/client.js' export type { ClientConfig } from './config/client.js'
export { createClientConfig } from './config/client.js'
export { defaults } from './config/defaults.js'
export { sanitizeConfig } from './config/sanitize.js'
export type { export type {
Access, Access,
AccessArgs, AccessArgs,
@@ -724,7 +782,85 @@ export type {
EntityDescriptionFunction, EntityDescriptionFunction,
SanitizedConfig, SanitizedConfig,
} from './config/types.js' } from './config/types.js'
export * from './config/types.js'
export { combineQueries } from './database/combineQueries.js'
export { createDatabaseAdapter } from './database/createDatabaseAdapter.js'
export { default as flattenWhereToOperators } from './database/flattenWhereToOperators.js'
export { getLocalizedPaths } from './database/getLocalizedPaths.js'
export { createMigration } from './database/migrations/createMigration.js'
export { getMigrations } from './database/migrations/getMigrations.js'
export { getPredefinedMigration } from './database/migrations/getPredefinedMigration.js'
export { migrate } from './database/migrations/migrate.js'
export { migrateDown } from './database/migrations/migrateDown.js'
export { migrateRefresh } from './database/migrations/migrateRefresh.js'
export { migrateReset } from './database/migrations/migrateReset.js'
export { migrateStatus } from './database/migrations/migrateStatus.js'
export { migrationTemplate } from './database/migrations/migrationTemplate.js'
export { migrationsCollection } from './database/migrations/migrationsCollection.js'
export { readMigrationFiles } from './database/migrations/readMigrationFiles.js'
export type * from './database/queryValidation/types.js'
export type { EntityPolicies, PathToQuery } from './database/queryValidation/types.js'
export { validateQueryPaths } from './database/queryValidation/validateQueryPaths.js'
export { validateSearchParam } from './database/queryValidation/validateSearchParams.js'
export type {
BaseDatabaseAdapter,
BeginTransaction,
CommitTransaction,
Connect,
Count,
CountArgs,
Create,
CreateArgs,
CreateGlobal,
CreateGlobalArgs,
CreateGlobalVersion,
CreateGlobalVersionArgs,
CreateMigration,
CreateVersion,
CreateVersionArgs,
DBIdentifierName,
DatabaseAdapterResult as DatabaseAdapterObj,
DeleteMany,
DeleteManyArgs,
DeleteOne,
DeleteOneArgs,
DeleteVersions,
DeleteVersionsArgs,
Destroy,
Find,
FindArgs,
FindGlobal,
FindGlobalArgs,
FindGlobalVersions,
FindGlobalVersionsArgs,
FindOne,
FindOneArgs,
FindVersions,
FindVersionsArgs,
Init,
Migration,
MigrationData,
MigrationTemplateArgs,
PaginatedDocs,
QueryDrafts,
QueryDraftsArgs,
RollbackTransaction,
Transaction,
UpdateGlobal,
UpdateGlobalArgs,
UpdateGlobalVersion,
UpdateGlobalVersionArgs,
UpdateOne,
UpdateOneArgs,
UpdateVersion,
UpdateVersionArgs,
} from './database/types.js'
export type { EmailAdapter as PayloadEmailAdapter, SendEmailOptions } from './email/types.js' export type { EmailAdapter as PayloadEmailAdapter, SendEmailOptions } from './email/types.js'
export { export {
@@ -750,9 +886,11 @@ export {
QueryError, QueryError,
ValidationError, ValidationError,
} from './errors/index.js' } from './errors/index.js'
export { baseBlockFields } from './fields/baseFields/baseBlockFields.js'
export { baseIDField } from './fields/baseFields/baseIDField.js'
export type { ClientFieldConfig } from './fields/config/client.js' export type { ClientFieldConfig } from './fields/config/client.js'
export { createClientFieldConfig } from './fields/config/client.js'
export { sanitizeFields } from './fields/config/sanitize.js'
export type { export type {
ArrayField, ArrayField,
Block, Block,
@@ -809,14 +947,16 @@ export type {
ValidateOptions, ValidateOptions,
ValueWithRelation, ValueWithRelation,
} from './fields/config/types.js' } from './fields/config/types.js'
export { default as getDefaultValue } from './fields/getDefaultValue.js'
export { traverseFields as afterChangeTraverseFields } from './fields/hooks/afterChange/traverseFields.js' export { traverseFields as afterChangeTraverseFields } from './fields/hooks/afterChange/traverseFields.js'
export { promise as afterReadPromise } from './fields/hooks/afterRead/promise.js' export { promise as afterReadPromise } from './fields/hooks/afterRead/promise.js'
export { traverseFields as afterReadTraverseFields } from './fields/hooks/afterRead/traverseFields.js' export { traverseFields as afterReadTraverseFields } from './fields/hooks/afterRead/traverseFields.js'
export { traverseFields as beforeChangeTraverseFields } from './fields/hooks/beforeChange/traverseFields.js' export { traverseFields as beforeChangeTraverseFields } from './fields/hooks/beforeChange/traverseFields.js'
export { traverseFields as beforeValidateTraverseFields } from './fields/hooks/beforeValidate/traverseFields.js'
export { traverseFields as beforeValidateTraverseFields } from './fields/hooks/beforeValidate/traverseFields.js'
export { default as sortableFieldTypes } from './fields/sortableFieldTypes.js'
export type { ClientGlobalConfig } from './globals/config/client.js' export type { ClientGlobalConfig } from './globals/config/client.js'
export { createClientGlobalConfig } from './globals/config/client.js'
export type { export type {
AfterChangeHook as GlobalAfterChangeHook, AfterChangeHook as GlobalAfterChangeHook,
AfterReadHook as GlobalAfterReadHook, AfterReadHook as GlobalAfterReadHook,
@@ -828,7 +968,12 @@ export type {
GlobalConfig, GlobalConfig,
SanitizedGlobalConfig, SanitizedGlobalConfig,
} from './globals/config/types.js' } from './globals/config/types.js'
export { docAccessOperation as docAccessOperationGlobal } from './globals/operations/docAccess.js'
export { findOneOperation } from './globals/operations/findOne.js'
export { findVersionByIDOperation as findVersionByIDOperationGlobal } from './globals/operations/findVersionByID.js'
export { findVersionsOperation as findVersionsOperationGlobal } from './globals/operations/findVersions.js'
export { restoreVersionOperation as restoreVersionOperationGlobal } from './globals/operations/restoreVersion.js'
export { updateOperation as updateOperationGlobal } from './globals/operations/update.js'
export type { export type {
CollapsedPreferences, CollapsedPreferences,
DocumentPreferences, DocumentPreferences,
@@ -838,210 +983,64 @@ export type {
PreferenceUpdateRequest, PreferenceUpdateRequest,
TabsPreferences, TabsPreferences,
} from './preferences/types.js' } from './preferences/types.js'
export { getLocalI18n } from './translations/getLocalI18n.js'
export { getLocalI18n } from './translations/getLocalI18n.js'
export * from './types/index.js'
export { getFileByPath } from './uploads/getFileByPath.js'
export type * from './uploads/types.js'
export { combineMerge } from './utilities/combineMerge.js' export { combineMerge } from './utilities/combineMerge.js'
export { commitTransaction } from './utilities/commitTransaction.js'
export { export {
configToJSONSchema, configToJSONSchema,
entityToJSONSchema, entityToJSONSchema,
fieldsToJSONSchema, fieldsToJSONSchema,
withNullableJSONSchemaType, withNullableJSONSchemaType,
} from './utilities/configToJSONSchema.js' } from './utilities/configToJSONSchema.js'
export { createArrayFromCommaDelineated } from './utilities/createArrayFromCommaDelineated.js' export { createArrayFromCommaDelineated } from './utilities/createArrayFromCommaDelineated.js'
export { createLocalReq } from './utilities/createLocalReq.js' export { createLocalReq } from './utilities/createLocalReq.js'
export { deepCopyObject } from './utilities/deepCopyObject.js' export { deepCopyObject } from './utilities/deepCopyObject.js'
export { deepMerge } from './utilities/deepMerge.js' export { deepMerge } from './utilities/deepMerge.js'
export { default as flattenTopLevelFields } from './utilities/flattenTopLevelFields.js' export { default as flattenTopLevelFields } from './utilities/flattenTopLevelFields.js'
export { formatLabels, formatNames, toWords } from './utilities/formatLabels.js' export { formatLabels, formatNames, toWords } from './utilities/formatLabels.js'
export { getCollectionIDFieldTypes } from './utilities/getCollectionIDFieldTypes.js' export { getCollectionIDFieldTypes } from './utilities/getCollectionIDFieldTypes.js'
export { getObjectDotNotation } from './utilities/getObjectDotNotation.js' export { getObjectDotNotation } from './utilities/getObjectDotNotation.js'
export { isEntityHidden } from './utilities/isEntityHidden.js'
export { isPlainObject } from './utilities/isPlainObject.js'
export { isValidID } from './utilities/isValidID.js'
export { default as isolateObjectProperty } from './utilities/isolateObjectProperty.js'
export { mapAsync } from './utilities/mapAsync.js'
export { mergeListSearchAndWhere } from './utilities/mergeListSearchAndWhere.js'
export { buildVersionCollectionFields } from './versions/buildCollectionFields.js'
export { buildVersionGlobalFields } from './versions/buildGlobalFields.js'
export { versionDefaults } from './versions/defaults.js'
export { deleteCollectionVersions } from './versions/deleteCollectionVersions.js'
export { enforceMaxVersions } from './versions/enforceMaxVersions.js'
export { getLatestCollectionVersion } from './versions/getLatestCollectionVersion.js'
export { getLatestGlobalVersion } from './versions/getLatestGlobalVersion.js'
export { saveVersion } from './versions/saveVersion.js'
export type { TypeWithVersion } from './versions/types.js'
export * from './config/types.js'
export type { FieldTypes } from './admin/forms/FieldTypes.js'
export type {
AuthStrategyFunction,
AuthStrategyFunctionArgs,
CollectionPermission,
DocumentPermissions,
FieldPermissions,
GlobalPermission,
IncomingAuthType,
Permission,
Permissions,
User,
VerifyConfig,
} from './auth/types.js'
export { createClientCollectionConfig } from './collections/config/client.js'
export { createClientConfig } from './config/client.js'
export { defaults } from './config/defaults.js'
export type {
BaseDatabaseAdapter,
BeginTransaction,
CommitTransaction,
Connect,
Count,
CountArgs,
Create,
CreateArgs,
CreateGlobal,
CreateGlobalArgs,
CreateGlobalVersion,
CreateGlobalVersionArgs,
CreateMigration,
CreateVersion,
CreateVersionArgs,
DBIdentifierName,
DatabaseAdapterResult as DatabaseAdapterObj,
DeleteMany,
DeleteManyArgs,
DeleteOne,
DeleteOneArgs,
DeleteVersions,
DeleteVersionsArgs,
Destroy,
Find,
FindArgs,
FindGlobal,
FindGlobalArgs,
FindGlobalVersions,
FindGlobalVersionsArgs,
FindOne,
FindOneArgs,
FindVersions,
FindVersionsArgs,
Init,
Migration,
MigrationData,
MigrationTemplateArgs,
PaginatedDocs,
QueryDrafts,
QueryDraftsArgs,
RollbackTransaction,
Transaction,
UpdateGlobal,
UpdateGlobalArgs,
UpdateGlobalVersion,
UpdateGlobalVersionArgs,
UpdateOne,
UpdateOneArgs,
UpdateVersion,
UpdateVersionArgs,
} from './database/types.js'
export { baseBlockFields } from './fields/baseFields/baseBlockFields.js'
export { baseIDField } from './fields/baseFields/baseIDField.js'
export { createClientFieldConfig } from './fields/config/client.js'
export { sanitizeFields } from './fields/config/sanitize.js'
export { createClientGlobalConfig } from './globals/config/client.js'
export type * from './database/queryValidation/types.js'
export { accessOperation } from './auth/operations/access.js'
export { forgotPasswordOperation } from './auth/operations/forgotPassword.js'
export { initOperation } from './auth/operations/init.js'
export { loginOperation } from './auth/operations/login.js'
export { logoutOperation } from './auth/operations/logout.js'
export { meOperation } from './auth/operations/me.js'
export { refreshOperation } from './auth/operations/refresh.js'
export { registerFirstUserOperation } from './auth/operations/registerFirstUser.js'
export { resetPasswordOperation } from './auth/operations/resetPassword.js'
export { unlockOperation } from './auth/operations/unlock.js'
export { verifyEmailOperation } from './auth/operations/verifyEmail.js'
export { countOperation } from './collections/operations/count.js'
export { createOperation } from './collections/operations/create.js'
export { deleteOperation } from './collections/operations/delete.js'
export { deleteByIDOperation } from './collections/operations/deleteByID.js'
export { docAccessOperation } from './collections/operations/docAccess.js'
export { duplicateOperation } from './collections/operations/duplicate.js'
export { findOperation } from './collections/operations/find.js'
export { findByIDOperation } from './collections/operations/findByID.js'
export { findVersionByIDOperation } from './collections/operations/findVersionByID.js'
export { findVersionsOperation } from './collections/operations/findVersions.js'
export { restoreVersionOperation } from './collections/operations/restoreVersion.js'
export { updateOperation } from './collections/operations/update.js'
export { updateByIDOperation } from './collections/operations/updateByID.js'
export { sanitizeConfig } from './config/sanitize.js'
export type { EntityPolicies, PathToQuery } from './database/queryValidation/types.js'
export { default as getDefaultValue } from './fields/getDefaultValue.js'
export { default as sortableFieldTypes } from './fields/sortableFieldTypes.js'
export { docAccessOperation as docAccessOperationGlobal } from './globals/operations/docAccess.js'
export { findOneOperation } from './globals/operations/findOne.js'
export { findVersionByIDOperation as findVersionByIDOperationGlobal } from './globals/operations/findVersionByID.js'
export { findVersionsOperation as findVersionsOperationGlobal } from './globals/operations/findVersions.js'
export { restoreVersionOperation as restoreVersionOperationGlobal } from './globals/operations/restoreVersion.js'
export { updateOperation as updateOperationGlobal } from './globals/operations/update.js'
export * from './auth/index.js'
export { default as executeAccess } from './auth/executeAccess.js'
export { executeAuthStrategies } from './auth/executeAuthStrategies.js'
export { getAccessResults } from './auth/getAccessResults.js'
export { getFieldsToSign } from './auth/getFieldsToSign.js'
export { combineQueries } from './database/combineQueries.js'
export { createDatabaseAdapter } from './database/createDatabaseAdapter.js'
export { default as flattenWhereToOperators } from './database/flattenWhereToOperators.js'
export { getLocalizedPaths } from './database/getLocalizedPaths.js'
export { createMigration } from './database/migrations/createMigration.js'
export { getMigrations } from './database/migrations/getMigrations.js'
export { getPredefinedMigration } from './database/migrations/getPredefinedMigration.js'
export { migrate } from './database/migrations/migrate.js'
export { migrateDown } from './database/migrations/migrateDown.js'
export { migrateRefresh } from './database/migrations/migrateRefresh.js'
export { migrateReset } from './database/migrations/migrateReset.js'
export { migrateStatus } from './database/migrations/migrateStatus.js'
export { migrationTemplate } from './database/migrations/migrationTemplate.js'
export { migrationsCollection } from './database/migrations/migrationsCollection.js'
export { readMigrationFiles } from './database/migrations/readMigrationFiles.js'
export { validateQueryPaths } from './database/queryValidation/validateQueryPaths.js'
export { validateSearchParam } from './database/queryValidation/validateSearchParams.js'
export { getFileByPath } from './uploads/getFileByPath.js'
export { commitTransaction } from './utilities/commitTransaction.js'
export { getDependencies }
export { initTransaction } from './utilities/initTransaction.js' export { initTransaction } from './utilities/initTransaction.js'
export { isEntityHidden } from './utilities/isEntityHidden.js'
export { isPlainObject } from './utilities/isPlainObject.js'
export { isValidID } from './utilities/isValidID.js'
export { default as isolateObjectProperty } from './utilities/isolateObjectProperty.js'
export { killTransaction } from './utilities/killTransaction.js' export { killTransaction } from './utilities/killTransaction.js'
export { mapAsync } from './utilities/mapAsync.js'
export { mergeListSearchAndWhere } from './utilities/mergeListSearchAndWhere.js'
export { buildVersionCollectionFields } from './versions/buildCollectionFields.js'
export { buildVersionGlobalFields } from './versions/buildGlobalFields.js'
export { versionDefaults } from './versions/defaults.js'
export { deleteCollectionVersions } from './versions/deleteCollectionVersions.js'
export { enforceMaxVersions } from './versions/enforceMaxVersions.js'
export { getLatestCollectionVersion } from './versions/getLatestCollectionVersion.js'
export { getLatestGlobalVersion } from './versions/getLatestGlobalVersion.js'
export { getDependencies }
export { saveVersion } from './versions/saveVersion.js'
export type { TypeWithVersion } from './versions/types.js'

View File

@@ -8,7 +8,7 @@ export type PreferenceRequest = {
user: PayloadRequest['user'] user: PayloadRequest['user']
} }
export type PreferenceUpdateRequest = PreferenceRequest & { value: unknown } export type PreferenceUpdateRequest = { value: unknown } & PreferenceRequest
export type CollapsedPreferences = string[] export type CollapsedPreferences = string[]

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