import { CREATED_BY_FIELD } from './builtins.js' import { conditionIssues } from './conditions.js' import { ADMIN_ICONS, type CollectionConfig, type Config, type GlobalConfig, type NavGroup, } from './config.js' import { checkConfigKeys } from './config-keys.js' import { ADAPTER_API_VERSION } from './database.js' import { warnDeprecated } from './deprecation.js' import { hasEmail } from './email-providers.js' import type { ConfigIssue } from './errors.js' import { FIELD_TYPES, type Field, type RichTextBlock, type SelectOption } from './fields.js' import { NAV_ID, navGroups, navIds } from './nav.js' import { fieldAt, SEARCHABLE_TYPES } from './search.js' import { turnstileKeyProblem } from './spam.js' import { isTimeZone } from './time-of-day.js' import { SYSTEM_EVENTS, WEBHOOK_EVENTS } from './webhooks.js' export const MIN_SECRET_LENGTH = 32 /** Collections that Easy CMS provides. They can be relationship targets. */ export const BUILTIN_COLLECTIONS = ['users', 'media'] as const /** Slugs that would clash with Easy CMS's own tables or routes. */ const RESERVED_SLUGS = new Set([ 'admin', 'globals', 'sessions', 'login-attempts', 'document-versions', 'scheduled-jobs', 'webhook-deliveries', 'email-deliveries', 'database-backups', 'user-roles', 'user-identities', 'audit-logs', 'api-keys', 'jobs', 'outbox', 'realtime-events', 'auth', 'migrations', 'access', 'healthz', 'readyz', ]) const SYSTEM_FIELD_NAMES = new Set(['id', 'createdAt', 'updatedAt']) /** Fields `index: 'trigram'` is for: plain text the `like` operator searches. */ const TRIGRAM_TYPES: ReadonlySet = new Set(['text', 'textarea', 'email']) const SLUG_PATTERN = /^[a-z][a-z0-9_-]*$/ const FIELD_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/ /** Checks a config and returns every problem found. An empty array means it is valid. */ export function validateConfig(config: Config): ConfigIssue[] { const issues: ConfigIssue[] = [] const add = (path: string, message: string, hint?: string) => issues.push(hint ? { path, message, hint } : { path, message }) if (typeof config !== 'object' || config === null) { add('config', 'must be an object', 'export default defineConfig({ ... })') return issues } validateSecret(config.secret, add) validatePreviousSecrets(config.previousSecrets, config.secret, add) validateCronSecret(config.cronSecret, (issue) => issues.push(issue)) checkConfigKeys(config, (issue) => issues.push(issue)) validateAdapterVersions(config, add) if (!config.db || typeof config.db.name !== 'string' || typeof config.db.init !== 'function') { add('db', 'is required', "pass a database adapter, e.g. db: sqlite({ url: 'file:./cms.db' })") } validateAdmin(config, add) validateAdminViews(config, add) validateUpload(config, add) validateBackups(config, add, (issue) => issues.push(issue)) validateAudit(config, add) validateLogs(config, add) validateCountCache(config, add) validateOutbox(config, add) validateRealtime(config, add) validateEmailLog(config, add) validateSearch(config, add) validateTelemetry(config, add) validateMaxPage(config, add) validateHttpCache(config, add) validateAuth(config, add) validateCors(config.cors, add) validateLocalization(config, add) validateWebhooks(config, add) warnNestedUnique(config, (issue) => issues.push(issue)) warnAdminOffPages(config, (issue) => issues.push(issue)) const collections = asArray(config.collections, 'collections', add) const globals = asArray(config.globals, 'globals', add) const collectionSlugs = new Set([...BUILTIN_COLLECTIONS]) const seenCollections = new Set() collections.forEach((collection, i) => { const slug = checkSlug(collection, `collections[${i}]`, seenCollections, add) if (slug) collectionSlugs.add(slug) }) const seenGlobals = new Set() globals.forEach((global, i) => { checkSlug(global, `globals[${i}]`, seenGlobals, add) }) validateEndpoints(config, collectionSlugs, add) validateCommands(config, add) validateJobs(config, add) validateIntegrations(config, add) validateListeners(config, add) validateAi(config, add) validateTimeZone(config, add) validateEvents(config, add) const apiKeys: unknown = config.apiKeys if (apiKeys !== undefined && typeof apiKeys !== 'boolean') add('apiKeys', 'must be true or false') const nav = validateNav(config, add) collections.forEach((collection, i) => { const path = `collections.${collection.slug ?? `[${i}]`}` validateContainer(collection, path, collectionSlugs, add, { collection: true, rbac: config.auth?.rbac === true, nav, }) validateUseAsTitle(collection, path, add) validateMenuItem(collection.admin, `${path}.admin`, add) const editIn: unknown = collection.admin?.editIn if (editIn !== undefined && editIn !== 'page' && editIn !== 'drawer') add(`${path}.admin.editIn`, `must be "page" or "drawer" (got ${JSON.stringify(editIn)})`) const permissions: unknown = collection.admin?.permissions if ( permissions !== undefined && !(Array.isArray(permissions) && permissions.every((p) => p === 'publish')) ) add(`${path}.admin.permissions`, "must be a list of operations: 'publish'") validateActions(collection.actions, `${path}.actions`, collectionSlugs, add) }) globals.forEach((global, i) => { const path = `globals.${global.slug ?? `[${i}]`}` validateContainer(global, path, collectionSlugs, add, { collection: false, rbac: config.auth?.rbac === true, nav, }) validateMenuItem(global.admin, `${path}.admin`, add) }) const plugins: unknown = config.plugins if ( plugins !== undefined && (!Array.isArray(plugins) || plugins.some((p) => typeof p !== 'function')) ) { add('plugins', 'must be an array of functions', 'a plugin is (config) => config') } return issues } type Add = (path: string, message: string, hint?: string) => void function validateSecret(secret: unknown, add: Add) { const hint = `set EASY_CMS_SECRET to a random string of at least ${MIN_SECRET_LENGTH} characters, e.g. \`openssl rand -hex 32\`` if (typeof secret !== 'string' || secret.length === 0) { // Usually the variable is in .env but the production server does not read that file. add( 'secret', 'is required', `${hint}. In production, set it in the server's environment: not every server reads .env (Nuxt's does not)`, ) } else if (secret.length < MIN_SECRET_LENGTH) { add('secret', `must be at least ${MIN_SECRET_LENGTH} characters (got ${secret.length})`, hint) } else if (process.env.NODE_ENV === 'production' && guessable(secret)) { add('secret', 'looks like an example or a repeated pattern, not a random string', hint) } } /** `previousSecrets`: as long as `secret`, and not `secret` itself. */ function validatePreviousSecrets(value: unknown, secret: unknown, add: Add) { if (value === undefined) return if (!Array.isArray(value)) { add('previousSecrets', 'must be an array of strings', 'e.g. previousSecrets: [oldSecret]') return } for (const [i, previous] of value.entries()) { if (typeof previous !== 'string' || previous.length < MIN_SECRET_LENGTH) add( `previousSecrets[${i}]`, `must be a string of at least ${MIN_SECRET_LENGTH} characters, like secret`, ) else if (previous === secret) add(`previousSecrets[${i}]`, 'is the same as secret', 'list only secrets used before it') } } /** * `cronSecret` (or `CRON_SECRET`) lets a request run jobs: as long as `secret`. Set in the config * it must be; from the environment (set by a host, maybe) a short one is a warning. */ function validateCronSecret(value: unknown, push: (issue: ConfigIssue) => void) { const hint = `use a random string of at least ${MIN_SECRET_LENGTH} characters, e.g. \`openssl rand -hex 32\`` if (value !== undefined) { if (typeof value !== 'string') push({ path: 'cronSecret', message: 'must be a string' }) else if (value.length < MIN_SECRET_LENGTH) push({ path: 'cronSecret', message: `must be at least ${MIN_SECRET_LENGTH} characters (got ${value.length})`, hint, }) return } const env = process.env.CRON_SECRET if (env && env.length < MIN_SECRET_LENGTH) push({ path: 'cronSecret', message: `CRON_SECRET is ${env.length} characters; anyone who guesses it can run jobs`, hint, severity: 'warning', }) } /** * Without the admin UI, password and verification emails link to `auth.members.pages`: without * them the links would open admin pages that aren't there. */ function warnAdminOffPages(config: Config, push: (issue: ConfigIssue) => void) { if (config.admin?.enabled !== false || !hasEmail(config)) return const pages = config.auth?.members?.pages const missing = (['resetPassword', 'verifyEmail'] as const).filter((p) => !pages?.[p]) if (missing.length === 0) return push({ path: 'auth.members.pages', message: `without the admin UI, emails link to your site's pages: set ${missing.join(' and ')}`, hint: "e.g. pages: { resetPassword: '/reset-password', verifyEmail: '/verify-email' }", severity: 'warning', }) } /** * `unique` holds for top-level fields only: in a group, array or block it would be ignored, and * with `uniqueWithin` (e.g. per tenant) there would be nothing to scope it by. A warning, since * configs written before this check still work as they did. */ function warnNestedUnique(config: Config, push: (issue: ConfigIssue) => void) { const walk = (fields: readonly Field[] | undefined, path: string, nested: boolean) => { for (const field of Array.isArray(fields) ? fields : []) { if (typeof field !== 'object' || field === null) continue const at = `${path}.${String(field.name)}` if (nested && field.unique === true) push({ path: `${at}.unique`, message: 'only works on top-level fields; inside a group, array or block it is ignored', hint: 'move the field to the top level, or check uniqueness in a beforeValidate hook', severity: 'warning', }) if (field.type === 'group' || field.type === 'array') walk(field.fields, `${at}.fields`, true) if (field.type === 'blocks' || field.type === 'richText') for (const block of Array.isArray(field.blocks) ? field.blocks : []) walk(block?.fields, `${at}.blocks.${String(block?.slug)}`, true) } } for (const [kind, list] of [ ['collections', config.collections], ['globals', config.globals], ] as const) for (const container of Array.isArray(list) ? list : []) walk(container?.fields, `${kind}.${String(container?.slug)}.fields`, false) } /** A storage adapter that hands out public URLs (S3 with `publicURL`, a public Blob store). */ function publicURLs(storage: unknown): boolean { const url = (storage as { url?: (key: string) => string | undefined }).url try { return typeof url === 'function' && url.call(storage, 'backup.db.gz') !== undefined } catch { return false } } /** A placeholder (`change-me`), or so few different characters it can't be random. */ function guessable(secret: string): boolean { return /change[-_ ]?me|example|placeholder|secret-?key/i.test(secret) || new Set(secret).size < 8 } function validateAdmin(config: Config, add: Add) { const admin = config.admin if (admin === undefined) return if ((admin as unknown) === false || typeof admin !== 'object' || admin === null) { add('admin', 'must be an object', 'to turn the admin UI off: admin: { enabled: false }') return } const enabled: unknown = admin.enabled if (enabled !== undefined && typeof enabled !== 'boolean') add('admin.enabled', 'must be true or false') if (admin.path !== undefined && (typeof admin.path !== 'string' || !admin.path.startsWith('/'))) { add('admin.path', 'must start with "/"', "e.g. path: '/admin'") } if (admin.locale !== undefined && admin.locale !== 'en' && admin.locale !== 'th') { add('admin.locale', `must be "en" or "th" (got ${JSON.stringify(admin.locale)})`) } const siteURL: unknown = admin.siteURL if ( siteURL !== undefined && (typeof siteURL !== 'string' || !/^(\/|https?:\/\/)/.test(siteURL)) ) { add( 'admin.siteURL', 'must be a path starting with "/" or an http(s) URL', "e.g. siteURL: 'https://example.com'", ) } const switcher: unknown = admin.switcher if (switcher !== undefined && switcher !== null) { const { cookie, options } = switcher as { cookie?: unknown; options?: unknown } if (typeof cookie !== 'string' || !/^[A-Za-z0-9_-]+$/.test(cookie)) add('admin.switcher.cookie', 'must be a cookie name (letters, digits, - and _)') if (typeof options !== 'string' || !options.startsWith('/')) add('admin.switcher.options', 'must be a path under the API starting with "/"') } const modules: unknown = admin.modules if (modules !== undefined) { if (!Array.isArray(modules)) { add('admin.modules', 'must be an array', "e.g. modules: ['@easy-cms/plugin-seo/admin']") } else { for (const [i, module] of modules.entries()) { if (typeof module !== 'string' || module.trim() === '') { add(`admin.modules[${i}]`, 'must be a package export or a file path') } else if (/^[a-z][a-z0-9+.-]*:/i.test(module) || module.startsWith('//')) { add( `admin.modules[${i}]`, 'must be a package export or a file path, not a URL', "admin modules are served from your server, e.g. '@easy-cms/plugin-seo/admin'", ) } } } } const brand: unknown = admin.brand if (brand === undefined) return if (typeof brand !== 'object' || brand === null) { add('admin.brand', 'must be an object', "e.g. brand: { name: 'Acme', color: '#0f766e' }") return } const { name, logo, color } = brand as Record if (name !== undefined && (typeof name !== 'string' || name.trim() === '')) { add('admin.brand.name', 'must be a non-empty string') } if ( logo !== undefined && (typeof logo !== 'string' || !/^(\/|https?:\/\/|data:image\/)/.test(logo)) ) { add( 'admin.brand.logo', 'must be a path starting with "/" or an http(s) URL', "e.g. logo: '/logo.svg'", ) } if (color !== undefined && (typeof color !== 'string' || !/^#[0-9a-f]{6}$/i.test(color))) { add('admin.brand.color', `must be a hex color like "#0f766e" (got ${JSON.stringify(color)})`) } } const PAGE_PATH = /^[a-z0-9]+(-[a-z0-9]+)*$/ /** Pages (`admin.pages`) and dashboard widgets (`admin.dashboard`), e.g. from plugins. */ function validateAdminViews(config: Config, add: Add) { const access = (value: unknown, path: string) => { if (value !== undefined && typeof value !== 'function') add( `${path}.access`, 'must be a function', 'e.g. access: ({ user }) => user.role === "admin"', ) } const pages: unknown = config.admin?.pages if (pages !== undefined) { if (!Array.isArray(pages)) { add( 'admin.pages', 'must be an array', "e.g. pages: [{ path: 'stats', label: 'Stats', component: 'ecms-stats' }]", ) } else { const seen = new Set() pages.forEach((page: unknown, i) => { const path = `admin.pages[${i}]` if (typeof page !== 'object' || page === null) { add(path, 'must be an object') return } const p = page as Record if (typeof p.path !== 'string' || !PAGE_PATH.test(p.path)) { add( `${path}.path`, `must be lowercase letters, digits and "-" (got ${JSON.stringify(p.path)})`, "e.g. path: 'forms-overview'", ) } else if (seen.has(p.path)) { add(`${path}.path`, `"${p.path}" is used by another page`) } else { seen.add(p.path) } validateComponent(p.component, `${path}.component`, add) const label = p.label if ( !(typeof label === 'string' && label.trim() !== '') && !(typeof label === 'object' && label !== null && !Array.isArray(label)) ) add( `${path}.label`, 'must be a string or { en, th }', "e.g. label: { en: 'Stats', th: 'สถิติ' }", ) validateMenuItem(p as { icon?: unknown; order?: unknown }, path, add) if (p.group !== 'content' && p.group !== false) validateGroup(p.group, navIds(navGroups(config.admin?.nav ?? [])), `${path}.group`, add) access(p.access, path) }) } } const widgets: unknown = config.admin?.dashboard if (widgets !== undefined) { if (!Array.isArray(widgets)) { add( 'admin.dashboard', 'must be an array', "e.g. dashboard: [{ component: 'ecms-stats-widget' }]", ) } else { const tags = new Set() widgets.forEach((widget: unknown, i) => { const path = `admin.dashboard[${i}]` if (typeof widget !== 'object' || widget === null) { add(path, 'must be an object') return } const w = widget as Record validateComponent(w.component, `${path}.component`, add) if (w.width !== undefined && w.width !== 'half' && w.width !== 'full') add(`${path}.width`, 'must be "half" or "full"') if ( w.label !== undefined && !(typeof w.label === 'string' && w.label.trim() !== '') && !(typeof w.label === 'object' && w.label !== null && !Array.isArray(w.label)) ) add(`${path}.label`, 'must be a string or { en, th }') // Settings → Roles gives panels to roles by their tag. const component = w.component as { tag?: unknown } | string | undefined const tag = typeof component === 'string' ? component : component?.tag if (config.auth?.rbac === true && typeof tag === 'string') { if (tags.has(tag)) add( `${path}.component`, `another panel uses "${tag}"`, 'with auth.rbac, roles are given panels by their tag: use one tag per panel', ) tags.add(tag) } access(w.access, path) }) } } } /** A menu item's `admin.icon` and `admin.order`. */ function validateMenuItem( admin: { icon?: unknown; order?: unknown } | undefined, path: string, add: Add, ) { const icon = admin?.icon if (icon !== undefined && !(ADMIN_ICONS as readonly unknown[]).includes(icon)) add(`${path}.icon`, `unknown icon ${JSON.stringify(icon)}`, `one of: ${ADMIN_ICONS.join(', ')}`) const order = admin?.order if (order !== undefined && (typeof order !== 'number' || !Number.isFinite(order))) add(`${path}.order`, 'must be a number') } function validateAuth(config: Config, add: Add) { const auth = config.auth if (auth === undefined) return if (auth.rbac !== undefined && typeof auth.rbac !== 'boolean') add('auth.rbac', 'must be true or false') if (typeof auth.password === 'object' && auth.password !== null) { const { breakGlass } = auth.password as { breakGlass?: unknown } if ( !Array.isArray(breakGlass) || breakGlass.length === 0 || breakGlass.some((email) => typeof email !== 'string' || !email.includes('@')) ) add( 'auth.password.breakGlass', 'must list the emails of the accounts that may still use a password', "e.g. { breakGlass: ['emergency@example.com'] }", ) } else if (auth.password !== undefined && typeof auth.password !== 'boolean') add('auth.password', 'must be true, false or { breakGlass: [emails] }') if (auth.setupCode !== undefined && typeof auth.setupCode !== 'string') add('auth.setupCode', 'must be a string') const providers: unknown = auth.providers // Providers in the code, or sign-in integrations to turn on in the admin. const signsIn = (Array.isArray(providers) && providers.length > 0) || (config.integrations ?? []).some((i) => (i as { signIn?: unknown }).signIn) if (auth.locked !== undefined && typeof auth.locked !== 'boolean') add('auth.locked', 'must be true or false') if (providers !== undefined) { if (!Array.isArray(providers)) { add( 'auth.providers', 'must be an array', 'e.g. providers: [google({ clientId, clientSecret })]', ) } else { const ids = new Set() providers.forEach((provider: unknown, i) => { const p = provider as Record | null const path = `auth.providers[${i}]` if ( typeof p !== 'object' || p === null || typeof p.authorizationURL !== 'function' || typeof p.callback !== 'function' ) { add( path, 'must be a provider', 'e.g. google({ clientId, clientSecret }) from @easy-cms/auth-oauth', ) return } if (typeof p.id !== 'string' || !PAGE_PATH.test(p.id)) add(`${path}.id`, 'must be lowercase letters, digits and "-"') else if (RESERVED_PROVIDER_IDS.has(p.id)) add(`${path}.id`, `"${p.id}" is a route of /auth`, 'give the provider another id') else if (ids.has(p.id)) add(`${path}.id`, `"${p.id}" is used by another provider`, 'give one of them its own id') else ids.add(p.id) if (typeof p.name !== 'string' || p.name.trim() === '') add(`${path}.name`, 'must be a name') }) } } const signUp = auth.providerSignUp as { domains?: unknown; role?: unknown } | undefined if (signUp !== undefined) { if ( typeof signUp !== 'object' || signUp === null || !Array.isArray(signUp.domains) || signUp.domains.some((d) => typeof d !== 'string' || !/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(d)) ) add('auth.providerSignUp.domains', 'must be email domains', "e.g. domains: ['example.com']") if (signUp?.role === 'admin') add( 'auth.providerSignUp.role', 'can\'t be "admin"', 'make admins by hand, in Settings → Users', ) else if ( signUp?.role !== undefined && (typeof signUp.role !== 'string' || (!auth.rbac && !(auth.roles ?? ['admin', 'editor']).includes(signUp.role))) ) add('auth.providerSignUp.role', 'must be one of auth.roles') if (!signsIn) add('auth.providerSignUp', 'needs auth.providers or a sign-in plugin') } if (auth.password !== undefined && auth.password !== true && !signsIn) add( 'auth.password', 'turning passwords off needs auth.providers or a sign-in plugin', 'otherwise nobody else could sign in', ) if (auth.roles !== undefined) { const roles: unknown = auth.roles if (!Array.isArray(roles) || roles.some((r) => typeof r !== 'string' || r === '')) { add('auth.roles', 'must be an array of non-empty strings') } else if (!roles.includes('admin')) { add('auth.roles', 'must include "admin"', "e.g. roles: ['admin', 'editor']") } } validateMembers(auth.members, (auth.roles ?? ['admin', 'editor']) as readonly string[], add) for (const key of [ 'tokenExpiration', 'maxLoginAttempts', 'lockWindow', 'resetPasswordExpiration', 'inviteExpiration', ] as const) { const value = auth[key] if (value !== undefined && !(Number.isInteger(value) && value > 0)) { add(`auth.${key}`, 'must be a positive integer') } } if (auth.emails !== undefined) { const emails: unknown = auth.emails if (typeof emails !== 'object' || emails === null) add('auth.emails', 'must be an object') else for (const [name, fn] of Object.entries(emails)) { if (!['resetPassword', 'invite', 'passwordChanged'].includes(name)) add( `auth.emails.${name}`, 'unknown email', 'use resetPassword, invite or passwordChanged', ) else if (typeof fn !== 'function') add( `auth.emails.${name}`, 'must be a function ({ user, url, locale }) => { subject, text }', ) } } if (auth.trustedOrigins !== undefined) { for (const [i, origin] of auth.trustedOrigins.entries()) { if (typeof origin !== 'string' || !/^https?:\/\/[^/]+$/.test(origin)) { add( `auth.trustedOrigins[${i}]`, `must be an origin like "https://example.com" (got ${JSON.stringify(origin)})`, ) } } } } const LOCALE_PATTERN = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/ const LOCALIZABLE = new Set([ 'text', 'textarea', 'email', 'slug', 'richText', 'number', 'boolean', 'date', 'json', 'select', 'upload', 'relationship', 'blocks', 'array', ]) function validateMembers(members: unknown, roles: readonly string[], add: Add) { if (members === undefined) return const { roles: memberRoles, signUp: signup, pages } = (members ?? {}) as Record if (!Array.isArray(memberRoles) || memberRoles.some((r) => typeof r !== 'string')) { add('auth.members.roles', 'must be an array of roles', "e.g. roles: ['customer']") return } for (const role of memberRoles as string[]) { if (role === 'admin') add('auth.members.roles', 'can\'t include "admin"') else if (!roles.includes(role)) add('auth.members.roles', `"${role}" must be one of auth.roles too`) } if (signup !== undefined) { const { role, verifyEmail, turnstile } = (signup ?? {}) as Record if (typeof role !== 'string' || !(memberRoles as string[]).includes(role)) add('auth.members.signUp.role', 'must be one of auth.members.roles') if (verifyEmail !== undefined && typeof verifyEmail !== 'boolean') add('auth.members.signUp.verifyEmail', 'must be true or false') if ( turnstile !== undefined && (typeof (turnstile as Record)?.siteKey !== 'string' || typeof (turnstile as Record)?.secretKey !== 'string') ) add('auth.members.signUp.turnstile', 'needs siteKey and secretKey') else if (turnstile !== undefined) { const problem = turnstileKeyProblem(turnstile as { siteKey: string; secretKey: string }) if (problem) add('auth.members.signUp.turnstile', problem) } } for (const [key, value] of Object.entries((pages ?? {}) as Record)) if (value !== undefined && typeof value !== 'string') add(`auth.members.pages.${key}`, 'must be a path or URL', "e.g. '/account/verify'") } function validateLocalization(config: Config, add: Add) { const localization = config.localization if (localization !== undefined && localization !== false) { const locales = localization?.locales if (!Array.isArray(locales) || locales.length === 0) { add('localization.locales', 'must be a non-empty list of locales', "locales: ['th', 'en']") } else { const seen = new Set() for (const [i, locale] of locales.entries()) { if (typeof locale !== 'string' || !LOCALE_PATTERN.test(locale)) { add( `localization.locales[${i}]`, `must be a locale code like "th" or "en-US" (got ${JSON.stringify(locale)})`, ) } else if (seen.has(locale)) { add(`localization.locales[${i}]`, `duplicate locale "${locale}"`) } seen.add(locale) } const fallbackDefault = localization.defaultLocale if (fallbackDefault !== undefined && !locales.includes(fallbackDefault)) { add('localization.defaultLocale', `must be one of the locales (got "${fallbackDefault}")`) } } } const walk = (fields: readonly Field[] | undefined, path: string, insideLocalized = false) => { if (!Array.isArray(fields)) return for (const field of fields) { if (typeof field?.name !== 'string') continue const fieldPath = `${path}.${field.name}` if (field.localized) { if (!localization) { add( `${fieldPath}.localized`, 'needs `localization` in the config', "localization: { locales: ['th', 'en'] }", ) } else if (!LOCALIZABLE.has(field.type)) { add( `${fieldPath}.localized`, `${field.type} fields cannot be localized`, 'localize the fields inside it instead', ) } else if (insideLocalized) { add( `${fieldPath}.localized`, 'is inside a localized field, which already holds one value per locale', ) } } const inside = insideLocalized || field.localized === true if (field.type === 'group' || field.type === 'array') walk(field.fields, `${fieldPath}.fields`, inside) if (field.type === 'blocks') for (const block of field.blocks ?? []) walk(block?.fields, `${fieldPath}.blocks.${block?.slug}`, inside) } } for (const [i, c] of (config.collections ?? []).entries()) walk(c?.fields, `collections[${i}].fields`) for (const [i, g] of (config.globals ?? []).entries()) walk(g?.fields, `globals[${i}].fields`) } function validateWebhooks(config: Config, add: Add) { const email: unknown = config.email if ( email !== undefined && (typeof email !== 'object' || email === null || typeof (email as { send?: unknown }).send !== 'function') ) add( 'email', 'must be an email adapter with a send() function', 'e.g. email: consoleEmail() or smtp({ … }) from @easy-cms/email-smtp', ) const hooks = config.webhooks if (hooks === undefined) return if (!Array.isArray(hooks)) { add('webhooks', 'must be a list', "webhooks: [{ url: 'https://example.com/hook' }]") return } const collections = new Set([ ...BUILTIN_COLLECTIONS, ...(config.collections ?? []).map((c) => c?.slug), ]) const globals = new Set((config.globals ?? []).map((g) => g?.slug)) const custom = new Set([...(config.events ?? []), ...SYSTEM_EVENTS]) for (const [i, hook] of hooks.entries()) { const path = `webhooks[${i}]` if (typeof hook?.url !== 'string' || !/^https?:\/\/\S+$/.test(hook.url)) { add(`${path}.url`, 'must be an http(s) URL') } for (const event of hook?.events ?? []) { if (!(WEBHOOK_EVENTS as readonly string[]).includes(event) && !custom.has(event)) add( `${path}.events`, `unknown event "${event}"`, `use: ${[...WEBHOOK_EVENTS, ...custom].join(', ')}`, ) } for (const slug of hook?.collections ?? []) if (!collections.has(slug)) add(`${path}.collections`, `unknown collection "${slug}"`) for (const slug of hook?.globals ?? []) if (!globals.has(slug)) add(`${path}.globals`, `unknown global "${slug}"`) } } function validateCors(cors: unknown, add: Add) { if (cors === undefined || cors === '*') return if (!Array.isArray(cors)) { add('cors', 'must be a list of origins or "*"', 'cors: ["https://my-site.com"]') return } for (const [i, origin] of cors.entries()) { if (typeof origin !== 'string' || !/^https?:\/\/[^/]+$/.test(origin)) { add( `cors[${i}]`, `must be an origin like "https://example.com" (got ${JSON.stringify(origin)})`, ) } } } function validateUpload(config: Config, add: Add) { const upload = config.upload // Upload fields put in a folder need folders. if (upload?.folders !== true) { const walk = (fields: readonly Field[], path: string) => { for (const [i, field] of fields.entries()) { const at = `${path}.fields[${i}]` if (field.type === 'upload' && field.folder !== undefined) add(`${at}.folder`, 'needs upload.folders: true', 'upload: { folders: true }') if ((field.type === 'group' || field.type === 'array') && Array.isArray(field.fields)) walk(field.fields, at) if ((field.type === 'blocks' || field.type === 'richText') && Array.isArray(field.blocks)) for (const [b, block] of field.blocks.entries()) if (Array.isArray(block?.fields)) walk(block.fields, `${at}.blocks[${b}]`) } } for (const [i, c] of (config.collections ?? []).entries()) if (Array.isArray(c?.fields)) walk(c.fields, `collections[${i}]`) for (const [i, g] of (config.globals ?? []).entries()) if (Array.isArray(g?.fields)) walk(g.fields, `globals[${i}]`) } if (upload === undefined) return if ( upload.maxFileSize !== undefined && !(Number.isInteger(upload.maxFileSize) && upload.maxFileSize > 0) ) { add('upload.maxFileSize', 'must be a positive integer (bytes)') } if (upload.dir !== undefined && (typeof upload.dir !== 'string' || upload.dir.length === 0)) { add('upload.dir', 'must be a non-empty string') } const mimeTypes: unknown = upload.mimeTypes if ( mimeTypes !== undefined && (!Array.isArray(mimeTypes) || mimeTypes.length === 0 || !mimeTypes.every((t) => typeof t === 'string' && MIME_PATTERN.test(t))) ) add( 'upload.mimeTypes', 'must be a list of MIME types or groups (documents, office, archives)', "e.g. mimeTypes: ['image/*', 'documents']", ) if (upload.folders !== undefined && typeof upload.folders !== 'boolean') add('upload.folders', 'must be true or false') const privateStorage: unknown = upload.privateStorage if ( privateStorage !== undefined && (typeof privateStorage !== 'object' || privateStorage === null || typeof (privateStorage as { get?: unknown }).get !== 'function') ) add('upload.privateStorage', 'must be a storage adapter', 'e.g. s3Storage({ … })') const fromURL: unknown = upload.fromURL if (fromURL === undefined) return if (typeof fromURL !== 'object' || fromURL === null) { add('upload.fromURL', 'must be an object', "e.g. fromURL: { allowedHosts: ['*'] }") return } const { allowedHosts, allowPrivate } = fromURL as Record if (!Array.isArray(allowedHosts) || allowedHosts.length === 0) { add( 'upload.fromURL.allowedHosts', 'must be a non-empty array of host names', "e.g. allowedHosts: ['images.example.com', '*.cdn.example.com'] or ['*'] for any public host", ) } else { allowedHosts.forEach((host: unknown, i) => { if (typeof host !== 'string' || !HOST_PATTERN.test(host)) add( `upload.fromURL.allowedHosts[${i}]`, `must be a host name like "images.example.com", "*.example.com" or "*" (got ${JSON.stringify(host)})`, ) }) } if (allowPrivate !== undefined && typeof allowPrivate !== 'boolean') add('upload.fromURL.allowPrivate', 'must be true or false') } /** `*`, `host.name` or `*.host.name`: no scheme, port or path. */ /** A media folder's key (`upload` fields' `folder`). */ const FOLDER_KEY = /^[a-z0-9][a-z0-9_-]{0,59}$/ /** A MIME type, `type/*`, or a group of types (`documents`, `office`, `archives`). */ const MIME_PATTERN = /^([\w.+-]+\/(\*|[\w.+-]+)|documents|office|archives)$/i const HOST_PATTERN = /^(\*|(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*)$/i /** `audit`: true, or its settings. */ function validateHttpCache(config: Config, add: Add) { const times = (value: unknown, path: string, purge: boolean) => { if (value === undefined) return if (value === false && !purge) return if (typeof value !== 'object' || value === null) { add(path, purge ? 'must be an object' : 'must be false or an object') return } const v = value as Record for (const key of ['sMaxAge', 'staleWhileRevalidate']) if (v[key] !== undefined && !(Number.isInteger(v[key]) && (v[key] as number) >= 0)) add(`${path}.${key}`, 'must be a whole number of seconds, 0 or more') if (purge && v.purge !== undefined && typeof v.purge !== 'function') add(`${path}.purge`, 'must be a function') } times(config.httpCache, 'httpCache', true) for (const c of config.collections ?? []) times(c?.httpCache, `collections.${c?.slug}.httpCache`, false) for (const g of config.globals ?? []) times(g?.httpCache, `globals.${g?.slug}.httpCache`, false) } function validateMaxPage(config: Config, add: Add) { const max: unknown = config.maxPage if (max !== undefined && !(Number.isInteger(max) && (max as number) >= 1)) add('maxPage', 'must be a whole number, 1 or more') } function validateEmailLog(config: Config, add: Add) { const value: unknown = config.emailLog if (value === undefined || value === false) return const keepDays = (value as { keepDays?: unknown } | null)?.keepDays if (typeof value !== 'object' || value === null) add('emailLog', 'must be false or { keepDays }') else if (keepDays !== undefined && !(Number.isInteger(keepDays) && (keepDays as number) >= 1)) add('emailLog.keepDays', 'must be a whole number of days, 1 or more') } function validateOutbox(config: Config, add: Add) { if (config.outbox !== undefined && typeof config.outbox !== 'boolean') add('outbox', 'must be true or false') } function validateRealtime(config: Config, add: Add) { const collections = Array.isArray(config.collections) ? config.collections : [] collections.forEach((c, i) => { const value: unknown = (c as { realtime?: unknown } | null)?.realtime if (value !== undefined && typeof value !== 'boolean') add(`collections[${i}].realtime`, 'must be true or false') }) const enabled = collections.some((c) => c?.realtime === true) // `/realtime` is the stream; the collection's own list would be unreachable. if (enabled && collections.some((c) => c?.slug === 'realtime')) add( 'collections', 'a collection named "realtime" clashes with `GET /realtime`', 'rename it', ) const value: unknown = config.realtime if (value === undefined) return if (typeof value !== 'object' || value === null || Array.isArray(value)) { add( 'realtime', 'must be an object', '{ retentionHours, pollMs, heartbeatMs, maxPerUser, maxConnections }', ) return } const options = value as Record const positive = (key: string, min: number, what: string) => { const n = options[key] if (n !== undefined && !(typeof n === 'number' && Number.isInteger(n) && n >= min)) add(`realtime.${key}`, `must be a whole number of ${what}, ${min} or more`) } positive('retentionHours', 1, 'hours') positive('pollMs', 10, 'milliseconds') positive('heartbeatMs', 100, 'milliseconds') positive('maxPerUser', 1, 'connections') positive('maxConnections', 1, 'connections') } function validateTelemetry(config: Config, add: Add) { const value: unknown = config.telemetry if (value === undefined || typeof value === 'boolean') return if (typeof value !== 'object' || value === null) { add('telemetry', 'must be true, false or { traces, metrics }') return } for (const [key, v] of Object.entries(value)) if (key !== 'traces' && key !== 'metrics') add(`telemetry.${key}`, 'is not an option', 'traces or metrics') else if (typeof v !== 'boolean') add(`telemetry.${key}`, 'must be true or false') } /** `search` and the collections' `search.fields`. */ function validateSearch(config: Config, add: Add) { const adapter: unknown = config.search if (adapter !== undefined) { const a = adapter as Record | null if ( typeof a !== 'object' || a === null || !['index', 'remove', 'clear', 'search'].every((m) => typeof a[m] === 'function') ) add('search', 'must be a search adapter', 'e.g. search: memorySearch()') // `GET /search` would hide the collection's own route. for (const c of config.collections ?? []) if (c?.slug === 'search') add( 'collections.search.slug', '"search" is the search route when `search` is set', 'choose another slug', ) } for (const c of config.collections ?? []) { const search: unknown = c?.search if (search === undefined) continue const path = `collections.${c.slug}.search` if (adapter === undefined) { add(path, 'needs a search adapter in the config', 'e.g. search: memorySearch()') continue } const fields = (search as { fields?: unknown } | null)?.fields if (!Array.isArray(fields) || fields.length === 0) { add( `${path}.fields`, 'must list the fields to index', "e.g. search: { fields: ['title', 'body'] }", ) continue } for (const name of fields) { const field = typeof name === 'string' ? fieldAt(c.fields ?? [], name) : undefined if (!field) add(`${path}.fields`, `has no field "${String(name)}"`) else if (!SEARCHABLE_TYPES.has(field.type) || field.hidden) add( `${path}.fields`, `can't index "${name}" (${field.hidden ? 'hidden' : field.type})`, 'text, textarea, email, slug, select, rich text, array, group and blocks fields hold text', ) } } } function validateCountCache(config: Config, add: Add) { const seconds: unknown = config.countCacheSeconds if ( seconds !== undefined && !(typeof seconds === 'number' && Number.isFinite(seconds) && seconds >= 0) ) add('countCacheSeconds', 'must be a number of seconds, 0 or more') } function validateLogs(config: Config, add: Add) { const logs: unknown = config.logs if (logs === undefined) return if (typeof logs !== 'object' || logs === null) { add('logs', 'must be an object', "e.g. logs: { format: 'json' }") return } const { format, requests } = logs as Record if (format !== undefined && format !== 'pretty' && format !== 'json') add('logs.format', "must be 'pretty' or 'json'") if (requests !== undefined && typeof requests !== 'boolean') add('logs.requests', 'must be true or false') } function validateAudit(config: Config, add: Add) { const audit: unknown = config.audit if (audit !== undefined && typeof audit !== 'boolean') { const a = audit as Record | null if (typeof a !== 'object' || a === null) add('audit', 'must be true or { keepDays, values, failedLogins }') else { if ( a.keepDays !== undefined && !(Number.isInteger(a.keepDays) && (a.keepDays as number) >= 0) ) add('audit.keepDays', 'must be a number of days (0: keep all)') if (a.values !== undefined && typeof a.values !== 'boolean') add('audit.values', 'must be true or false') if ( a.failedLogins !== undefined && !(Number.isInteger(a.failedLogins) && (a.failedLogins as number) > 0) ) add('audit.failedLogins', 'must be a positive number') } } } function validateBackups(config: Config, add: Add, push: (issue: ConfigIssue) => void) { const pushWarning = (path: string, message: string, hint: string) => push({ path, message, hint, severity: 'warning' }) const backups: unknown = config.backups if (backups === undefined) return if (typeof backups !== 'object' || backups === null) { add('backups', 'must be an object', "e.g. backups: { frequency: 'daily', keep: 7 }") return } const { frequency, at, keep, dir, storage, sqlite, encryptionKey, locked } = backups as Record< string, unknown > if ( encryptionKey !== undefined && (typeof encryptionKey !== 'string' || encryptionKey.length < MIN_SECRET_LENGTH) ) add( 'backups.encryptionKey', `must be at least ${MIN_SECRET_LENGTH} characters`, 'e.g. `openssl rand -hex 32`, kept somewhere other than the backups', ) if (frequency !== undefined && frequency !== 'daily' && frequency !== 'weekly') add('backups.frequency', 'must be "daily" or "weekly"') if (at !== undefined && (typeof at !== 'string' || !TIME_OF_DAY.test(at))) add('backups.at', 'must be a time like "03:00"') if (keep !== undefined && !(Number.isInteger(keep) && (keep as number) >= 1)) add('backups.keep', 'must be a whole number, 1 or more') if (locked !== undefined && typeof locked !== 'boolean') add('backups.locked', 'must be true or false') if (dir !== undefined && (typeof dir !== 'string' || dir.trim() === '')) add('backups.dir', 'must be a folder name') if ( typeof dir === 'string' && dir.replace(/^\.\//, '').replace(/\/+$/, '') === (config.upload?.dir ?? 'uploads').replace(/^\.\//, '').replace(/\/+$/, '') ) add('backups.dir', 'must not be the uploads folder: uploads are served publicly') if ( storage !== undefined && (typeof storage !== 'object' || storage === null || typeof (storage as { put?: unknown }).put !== 'function') ) add('backups.storage', 'must be a storage adapter, e.g. s3Storage()') else if (storage !== undefined && publicURLs(storage)) { // A backup holds the whole database, password hashes included. const message = encryptionKey ? 'gives files public URLs; the backups are encrypted, but keep them in a private bucket' : 'gives files public URLs: anyone with the address of a backup could download the whole database' pushWarning( 'backups.storage', message, 'use a private bucket (no publicURL), or set backups.encryptionKey', ) } if (sqlite !== undefined && typeof sqlite !== 'function') add( 'backups.sqlite', "must be the sqlite adapter, e.g. import { sqlite } from '@easy-cms/db-sqlite'", ) } function asArray(value: readonly T[] | undefined, path: string, add: Add): readonly T[] { if (value === undefined) return [] if (!Array.isArray(value)) { add(path, 'must be an array') return [] } return value } function checkSlug( container: CollectionConfig | GlobalConfig, path: string, seen: Set, add: Add, ): string | undefined { const slug: unknown = container.slug if (typeof slug !== 'string' || !SLUG_PATTERN.test(slug)) { add( `${path}.slug`, `must be lowercase letters, digits, "-" or "_", starting with a letter (got ${JSON.stringify(slug)})`, ) return undefined } if (RESERVED_SLUGS.has(slug)) { add(`${path}.slug`, `"${slug}" is reserved by Easy CMS`, 'choose another slug') return undefined } if (seen.has(slug)) { add(`${path}.slug`, `duplicate slug "${slug}"`) return undefined } seen.add(slug) return slug } const isLabel = (value: unknown) => (typeof value === 'string' && value.trim() !== '') || (typeof value === 'object' && value !== null && !Array.isArray(value) && Object.values(value).length > 0 && Object.values(value).every((v) => typeof v === 'string')) /** `admin.nav` and `admin.commands`; returns every group id. */ function validateNav(config: Config, add: Add): ReadonlySet { const nav: unknown = config.admin?.nav if (nav !== undefined) { if (!Array.isArray(nav)) add('admin.nav', 'must be a list of groups', "e.g. nav: [{ id: 'shop', label: 'Shop' }]") else nav.forEach((group: unknown, i) => { const check = (g: unknown, path: string, child: boolean) => { const { id, label, children, order } = (g ?? {}) as Record if (typeof id !== 'string' || !NAV_ID.test(id)) add(`${path}.id`, 'must be lowercase letters, digits and -', "e.g. 'shop'") if (!isLabel(label)) add(`${path}.label`, 'must be a string or { en, th }') if (order !== undefined && typeof order !== 'number') add(`${path}.order`, 'must be a number') validateMenuItem(g as { icon?: unknown }, path, add) if (children !== undefined) { if (child) add(`${path}.children`, 'groups go one level deep') else if (!Array.isArray(children)) add(`${path}.children`, 'must be a list of groups') else children.forEach((c: unknown, j) => { check(c, `${path}.children[${j}]`, true) }) } } check(group, `admin.nav[${i}]`, false) }) } const commands: unknown = config.admin?.commands if (commands !== undefined) { if (!Array.isArray(commands)) add('admin.commands', 'must be a list') else commands.forEach((c: unknown, i) => { const { label, href } = (c ?? {}) as Record if (!isLabel(label)) add(`admin.commands[${i}].label`, 'must be a string or { en, th }') if (typeof href !== 'string' || !href.startsWith('/') || href.startsWith('//')) add( `admin.commands[${i}].href`, 'must be a path in the admin', "e.g. '/collections/orders'", ) }) } return navIds(navGroups(Array.isArray(nav) ? (nav as NavGroup[]) : [])) } /** A menu group: `settings`, a group's id, or a label; a path with `.` must be a group's. */ function validateGroup(group: unknown, ids: ReadonlySet, path: string, add: Add) { if (group === undefined || group === 'settings') return if (typeof group === 'string' && group.includes('.') && !ids.has(group)) { add( path, `no menu group "${group}" in admin.nav`, "declare it: nav: [{ id: 'shop', label: 'Shop', children: [{ id: 'catalog', label: 'Catalog' }] }]", ) return } if (!isLabel(group)) add( path, `must be a group's id, 'settings' or a label (got ${JSON.stringify(group)})`, "e.g. group: 'shop' or { en: 'Shop', th: 'ร้านค้า' }", ) } /** `admin.layout`: tabs, collapsible sections and rows naming top-level fields once each. */ function validateLayout( layout: unknown, container: CollectionConfig | GlobalConfig, path: string, add: Add, ) { if (!Array.isArray(layout)) { add(path, 'must be a list', "e.g. layout: [{ tab: 'Content', fields: ['title'] }]") return } const fields = new Map((container.fields ?? []).map((f) => [f.name, f])) const seen = new Set() const name = (value: unknown, at: string) => { if (typeof value !== 'string' || !fields.has(value)) { add(at, `no top-level field ${JSON.stringify(value)}`) return } if (fields.get(value)?.admin?.position === 'sidebar') add(at, `"${value}" is in the sidebar (admin.position: 'sidebar')`) if (seen.has(value)) add(at, `"${value}" is placed twice`) seen.add(value) } const nodes = (list: unknown, at: string, top: boolean) => { if (!Array.isArray(list)) { add(at, 'must be a list') return } const tabs = list.filter((n) => typeof n === 'object' && n !== null && 'tab' in n).length if (top && tabs > 0 && tabs !== list.length) add(at, 'with tabs, every entry at the top is a tab') list.forEach((node: unknown, i) => { const p = `${at}[${i}]` if (typeof node === 'string') { name(node, p) return } const n = (node ?? {}) as Record if ('tab' in n) { if (!top) add(p, 'tabs go at the top of the layout only') if (!isLabel(n.tab)) add(`${p}.tab`, 'must be a string or { en, th }') nodes(n.fields, `${p}.fields`, false) } else if ('collapsible' in n) { if (!isLabel(n.collapsible)) add(`${p}.collapsible`, 'must be a string or { en, th }') nodes(n.fields, `${p}.fields`, false) } else if ('row' in n) { if (!Array.isArray(n.row) || n.row.length === 0) add(`${p}.row`, 'must be a list of field names') else n.row.forEach((f: unknown, j) => { name(f, `${p}.row[${j}]`) }) } else add(p, 'must be a field name, { tab }, { collapsible } or { row }') }) } nodes(layout, path, true) } function validateCollectionAdmin(admin: Record, path: string, add: Add) { const { badge, count, empty, views } = admin if (views !== undefined) { if (!Array.isArray(views)) add(`${path}.views`, 'must be an array') const ids = new Set() for (const [i, raw] of (Array.isArray(views) ? views : []).entries()) { const view = (raw ?? {}) as Record const at = `${path}.views[${i}]` if (typeof view.id !== 'string' || !/^[a-z0-9][a-z0-9_-]*$/.test(view.id)) add(`${at}.id`, 'must be lowercase letters, digits, "-" or "_"', "e.g. id: 'to-review'") else if (ids.has(view.id)) add(`${at}.id`, `duplicate view "${view.id}"`) else ids.add(view.id) if (!isLabel(view.label)) add(`${at}.label`, 'must be a string or { en, th }') if ( view.where !== undefined && (typeof view.where !== 'object' || view.where === null || Array.isArray(view.where)) ) add(`${at}.where`, 'must be a where query', "e.g. { status: { equals: 'draft' } }") if (view.pageSize !== undefined && ![10, 25, 50, 100].includes(view.pageSize as number)) add(`${at}.pageSize`, 'must be 10, 25, 50 or 100') if ( view.density !== undefined && !['comfortable', 'compact'].includes(view.density as string) ) add(`${at}.density`, "must be 'comfortable' or 'compact'") } } if (badge !== undefined) { const b = (badge ?? {}) as Record if (typeof b.where !== 'object' || b.where === null || Array.isArray(b.where)) add(`${path}.badge.where`, 'must be a where query', "e.g. { status: { equals: 'paid' } }") if (b.tone !== undefined && !['accent', 'warning', 'danger'].includes(b.tone as string)) add(`${path}.badge.tone`, "must be 'accent', 'warning' or 'danger'") } if (count !== undefined && typeof count !== 'boolean') add(`${path}.count`, 'must be true or false') if (admin.export !== undefined && typeof admin.export !== 'boolean') add(`${path}.export`, 'must be true or false') if (empty !== undefined) { const e = (empty ?? {}) as Record if (e.description !== undefined && !isLabel(e.description)) add(`${path}.empty.description`, 'must be a string or { en, th }') if (e.link !== undefined) { const l = (e.link ?? {}) as Record if (!isLabel(l.label) || typeof l.href !== 'string') add(`${path}.empty.link`, 'needs label and href') } } } function validateContainer( container: CollectionConfig | GlobalConfig, path: string, collectionSlugs: ReadonlySet, add: Add, { collection, rbac, nav }: { collection: boolean; rbac: boolean; nav: ReadonlySet }, ) { if (!Array.isArray(container.fields)) { add(`${path}.fields`, 'must be an array') return } const versions = container.versions if (versions !== undefined && typeof versions !== 'boolean') { const keep = typeof versions === 'object' && versions !== null ? versions.keep : undefined if (typeof versions !== 'object' || versions === null) { add(`${path}.versions`, 'must be true, false or { keep }') } else if (keep !== undefined && (!Number.isInteger(keep) || keep < 1)) { add(`${path}.versions.keep`, 'must be a positive integer') } } if (container.schedule && !container.drafts) { add(`${path}.schedule`, 'needs `drafts: true`', 'scheduling publishes and unpublishes drafts') } if (container.preview !== undefined && typeof container.preview !== 'function') { add( `${path}.preview`, 'must be a function ({ doc }) => url', // biome-ignore lint/suspicious/noTemplateCurlyInString: an example shown to the user 'preview: ({ doc }) => `/posts/${doc.slug}`', ) } const admin: unknown = container.admin if (admin !== undefined) { if (typeof admin !== 'object' || admin === null) { add(`${path}.admin`, 'must be an object', "e.g. admin: { sidebar: ['ecms-my-panel'] }") } else { const sidebar: unknown = (admin as { sidebar?: unknown }).sidebar if (sidebar !== undefined) validateComponents(sidebar, `${path}.admin.sidebar`, add) validateGroup((admin as { group?: unknown }).group, nav, `${path}.admin.group`, add) const layout: unknown = (admin as { layout?: unknown }).layout if (layout !== undefined) validateLayout(layout, container, `${path}.admin.layout`, add) if (collection) validateCollectionAdmin(admin as Record, `${path}.admin`, add) const list: unknown = (admin as { list?: unknown }).list if (list !== undefined) validateList(list, container, `${path}.admin.list`, add) const calendar: unknown = (admin as { calendar?: unknown }).calendar if (collection && calendar !== undefined) validateCalendar(calendar, container, `${path}.admin.calendar`, add) const owner: unknown = (admin as { ownerField?: unknown }).ownerField if (owner !== undefined) { const field = container.fields.find((f) => f.name === owner) if ( !collection || container.slug === 'users' || field?.type !== 'relationship' || field.to !== 'users' || field.hasMany ) add( `${path}.admin.ownerField`, 'must name a relationship field to "users" (not hasMany) of a collection', "e.g. { name: 'author', type: 'relationship', to: 'users' }", ) } } } // With roles from the admin, `createdBy` is Easy CMS's. const createdBy = container.fields.find((f) => f.name === CREATED_BY_FIELD.name) if (rbac && createdBy && createdBy !== CREATED_BY_FIELD) add( `${path}.fields.createdBy`, '"createdBy" is added by Easy CMS with auth.rbac', 'rename the field; to use it as the owner, set admin.ownerField', ) const reserved = new Set(SYSTEM_FIELD_NAMES) if (container.drafts) reserved.add('status') validateFields(container.fields, `${path}.fields`, reserved, collectionSlugs, add) } function validateFields( fields: readonly Field[], path: string, reserved: ReadonlySet, collectionSlugs: ReadonlySet, add: Add, ) { const names = new Set() const byName = new Map() fields.forEach((field, i) => { const name: unknown = field?.name if (typeof name !== 'string' || !FIELD_NAME_PATTERN.test(name)) { add(`${path}[${i}].name`, `must be a valid identifier (got ${JSON.stringify(name)})`) return } if (name === '__proto__') { add(`${path}[${i}].name`, '"__proto__" is reserved by JavaScript') return } if (name === 'constructor' || name === 'prototype') warnDeprecated( 'EASY_CMS_DEP006', `A field named "${name}" (${path}.${name}) works through 1.x; rename it before 2.0.`, ) if (reserved.has(name)) { add(`${path}.${name}`, `"${name}" is reserved`, 'Easy CMS adds this field automatically') } if (names.has(name)) add(`${path}.${name}`, `duplicate field name "${name}"`) names.add(name) const index: unknown = (field as { index?: unknown }).index if (index !== undefined && typeof index !== 'boolean' && index !== 'trigram') add(`${path}.${name}.index`, "must be true, false or 'trigram'") else if (index === 'trigram' && !TRIGRAM_TYPES.has(field.type)) add( `${path}.${name}.index`, `'trigram' is for text, textarea and email fields, not ${field.type}`, 'use index: true', ) byName.set(name, field) }) for (const field of fields) { if (typeof field?.name !== 'string') continue const fieldPath = `${path}.${field.name}` const type: unknown = field.type if (!(FIELD_TYPES as readonly unknown[]).includes(type)) { add( `${fieldPath}.type`, `unknown field type ${JSON.stringify(type)}`, `use one of: ${FIELD_TYPES.join(', ')}`, ) continue } validateField(field, fieldPath, byName, collectionSlugs, add) } } function validateCalendar( calendar: unknown, container: CollectionConfig | GlobalConfig, path: string, add: Add, ) { if (typeof calendar !== 'object' || calendar === null) { add(path, 'must be an object', "e.g. calendar: { start: 'startsAt', end: 'endsAt' }") return } const { start, end, color } = calendar as { start?: unknown; end?: unknown; color?: unknown } const fieldNamed = (name: unknown) => typeof name === 'string' ? container.fields.find((f) => f.name === name) : undefined for (const [key, value, required] of [ ['start', start, true], ['end', end, false], ] as const) { if (value === undefined && !required) continue if (fieldNamed(value)?.type !== 'date') add( `${path}.${key}`, 'must name a top-level date field', `e.g. { name: '${key}sAt', type: 'date' }`, ) } if (start !== undefined && start === end) add(`${path}.end`, 'must differ from start') if (color === undefined) return const field = fieldNamed(color) if ( (field?.type !== 'select' && field?.type !== 'relationship') || ('hasMany' in field && field.hasMany) ) add( `${path}.color`, 'must name a top-level select or relationship field (not hasMany)', "e.g. color: 'category'", ) } function validateList( list: unknown, container: CollectionConfig | GlobalConfig, path: string, add: Add, ) { if (typeof list !== 'object' || list === null) { add(path, 'must be an object', "e.g. list: { tree: 'parent' }") return } const { tree, sort } = list as { tree?: unknown; sort?: unknown } if (sort !== undefined && (typeof sort !== 'string' || !sort.replace(/^-/, ''))) add(`${path}.sort`, 'must be a field name, with - for descending', "e.g. sort: 'title'") if (tree === undefined) return const field = container.fields.find((f) => f.name === tree) if ( field?.type !== 'relationship' || field.to !== container.slug || field.hasMany || field.localized ) { add( `${path}.tree`, `must name a relationship field to "${container.slug}" (not hasMany or localized)`, `e.g. { name: 'parent', type: 'relationship', to: '${container.slug}' }`, ) } } /** `minRows` / `maxRows` of a relationship or upload: only with `hasMany`. */ function validateManyRange( field: { hasMany?: boolean; minRows?: number; maxRows?: number }, path: string, add: Add, ) { if ((field.minRows !== undefined || field.maxRows !== undefined) && !field.hasMany) { add(path, 'minRows and maxRows need hasMany: true') return } checkRange(field.minRows, field.maxRows, 'minRows', 'maxRows', path, add) } function validateField( field: Field, path: string, siblings: ReadonlyMap, collectionSlugs: ReadonlySet, add: Add, ) { const position: unknown = field.admin?.position if (position !== undefined && position !== 'sidebar') { add(`${path}.admin.position`, `must be "sidebar" (got ${JSON.stringify(position)})`) } const admin: unknown = field.admin if (admin !== undefined) { if (typeof admin !== 'object' || admin === null) { add(`${path}.admin`, 'must be an object', "e.g. admin: { component: 'ecms-color-picker' }") } else { const { component, after, cell, width, condition, description } = admin as { component?: unknown after?: unknown cell?: unknown width?: unknown condition?: unknown description?: unknown } if ( width !== undefined && !['1/4', '1/3', '1/2', '2/3', '3/4', 'full'].includes(width as string) ) add(`${path}.admin.width`, "must be '1/4', '1/3', '1/2', '2/3', '3/4' or 'full'") if (description !== undefined && !isLabel(description)) add(`${path}.admin.description`, 'must be a string or { en, th }') if (condition !== undefined) for (const issue of conditionIssues(condition, [...siblings.keys()])) add(`${path}.admin.condition`, issue) if (component !== undefined) validateComponent(component, `${path}.admin.component`, add) if (after !== undefined) validateComponents(after, `${path}.admin.after`, add) if (cell !== undefined) validateComponent(cell, `${path}.admin.cell`, add) } } if (field.uniqueWithin !== undefined) { if (!field.unique && field.type !== 'slug') add(`${path}.uniqueWithin`, 'needs `unique: true` (or a slug field)') else for (const name of [field.uniqueWithin].flat()) { const scope = siblings.get(name) if (!scope || scope === field) { add(`${path}.uniqueWithin`, `no sibling field named "${name}"`) } else if ( !['relationship', 'select', 'text', 'number'].includes(scope.type) || ('hasMany' in scope && scope.hasMany) || scope.localized ) { add( `${path}.uniqueWithin`, `"${name}" must be a single, unlocalized relationship, select, text or number field`, ) } } } switch (field.type) { case 'text': case 'textarea': checkRange(field.minLength, field.maxLength, 'minLength', 'maxLength', path, add) break case 'number': checkRange(field.min, field.max, 'min', 'max', path, add) break case 'select': validateSelect(field.options, field.defaultValue, field.hasMany, path, add) break case 'slug': if (field.from !== undefined) { const source = siblings.get(field.from) if (!source) { add(`${path}.from`, `no sibling field named "${field.from}"`) } else if (source.type !== 'text') { add(`${path}.from`, `"${field.from}" must be a text field (got ${source.type})`) } } break case 'relationship': { const to: unknown = field.to // A list (#327): values are `{ relationTo, value }`, even with one collection in it. if (Array.isArray(to)) { if (to.length === 0) add(`${path}.to`, 'needs at least one collection') if (new Set(to).size !== to.length) add(`${path}.to`, 'names a collection twice') } for (const target of Array.isArray(to) ? to : [to]) { if (typeof target !== 'string' || !collectionSlugs.has(target)) { add( `${path}.to`, `unknown collection ${JSON.stringify(target)}`, `use one of: ${[...collectionSlugs].join(', ')}`, ) } } validateManyRange(field, path, add) break } case 'upload': validateManyRange(field, path, add) if (field.folder !== undefined && !FOLDER_KEY.test(String(field.folder))) add( `${path}.folder`, 'must be a folder key: lowercase letters, digits, "-" or "_"', "e.g. folder: 'banners'", ) if (field.folderOnly !== undefined && field.folder === undefined) add(`${path}.folderOnly`, 'needs folder') if (field.mimeTypes !== undefined) { const types: unknown = field.mimeTypes if ( !Array.isArray(types) || types.length === 0 || !types.every((t) => typeof t === 'string' && MIME_PATTERN.test(t)) ) { add( `${path}.mimeTypes`, 'must be a list of MIME types or groups (documents, office, archives)', "e.g. mimeTypes: ['image/*', 'documents']", ) } } break case 'ui': { // A component in the form, storing nothing: no value options. if (!field.admin?.component) add( `${path}.admin.component`, 'is required on a ui field', "e.g. { name: 'estimate', type: 'ui', admin: { component: 'acme-estimate' } }", ) const stored = [ 'required', 'unique', 'uniqueWithin', 'index', 'defaultValue', 'validate', 'access', 'hidden', 'localized', ] as const for (const option of stored) if ((field as unknown as Record)[option] !== undefined) add(`${path}.${option}`, 'has no effect on a ui field, which stores nothing') break } case 'array': case 'group': if (!Array.isArray(field.fields) || field.fields.length === 0) { add(`${path}.fields`, 'must contain at least one field') break } if (field.fields.every((f) => f?.type === 'ui')) add(`${path}.fields`, 'must contain a field that stores a value, not only ui fields') if (field.type === 'array') checkRange(field.minRows, field.maxRows, 'minRows', 'maxRows', path, add) validateFields(field.fields, `${path}.fields`, new Set(['id']), collectionSlugs, add) break case 'blocks': { if (!Array.isArray(field.blocks) || field.blocks.length === 0) { add( `${path}.blocks`, 'must contain at least one block', "blocks: [{ slug: 'hero', fields: [...] }]", ) break } checkRange(field.minRows, field.maxRows, 'minRows', 'maxRows', path, add) const seen = new Set() for (const [i, block] of field.blocks.entries()) { const blockPath = `${path}.blocks[${i}]` if (typeof block?.slug !== 'string' || !SLUG_PATTERN.test(block.slug)) { add( `${blockPath}.slug`, 'must be lowercase letters, digits, "-" or "_", starting with a letter', ) } else if (seen.has(block.slug)) { add(`${blockPath}.slug`, `duplicate block "${block.slug}"`) } else { seen.add(block.slug) } if (!Array.isArray(block?.fields)) { add(`${blockPath}.fields`, 'must be an array') continue } validateFields( block.fields, `${blockPath}.fields`, new Set(['id', 'blockType']), collectionSlugs, add, ) } break } case 'richText': { // Blocks between paragraphs (#328). const blocks: unknown = field.blocks if (blocks === undefined) break if (!Array.isArray(blocks) || blocks.length === 0) { add( `${path}.blocks`, 'must be a list of at least one block', "blocks: [{ slug: 'callout', fields: [...] }]", ) break } const seen = new Set() for (const [i, block] of (blocks as RichTextBlock[]).entries()) { const blockPath = `${path}.blocks[${i}]` if (typeof block?.slug !== 'string' || !SLUG_PATTERN.test(block.slug)) { add( `${blockPath}.slug`, 'must be lowercase letters, digits, "-" or "_", starting with a letter', ) } else if (seen.has(block.slug)) { add(`${blockPath}.slug`, `duplicate block "${block.slug}"`) } else { seen.add(block.slug) } const summary: unknown = block?.admin?.summary if (summary !== undefined && typeof summary !== 'string' && typeof summary !== 'function') add(`${blockPath}.admin.summary`, 'must be a function or the tag of a custom element') if (!Array.isArray(block?.fields)) { add(`${blockPath}.fields`, 'must be an array') continue } // No rich text or blocks inside, and nothing localized: the whole document is. const walk = (fields: readonly Field[], at: string) => { for (const inner of fields) { const here = `${at}.${inner.name}` if (inner.type === 'richText' || inner.type === 'blocks') add(here, `a ${inner.type} field can't be inside a rich text block`) if (inner.localized) add( `${here}.localized`, "fields in rich text blocks can't be localized", 'set localized on the rich text field: its blocks follow its locale', ) if ((inner.type === 'group' || inner.type === 'array') && Array.isArray(inner.fields)) walk(inner.fields, `${here}.fields`) } } walk(block.fields, `${blockPath}.fields`) validateFields(block.fields, `${blockPath}.fields`, new Set(), collectionSlugs, add) } break } } } /** * Custom element names from admin modules: lowercase letters, digits and `-`, with at least one * `-` (the official plugins use `ecms--…`; pick a prefix of your own). */ export const ADMIN_COMPONENT_TAG = /^[a-z][a-z0-9]*(-[a-z0-9]+)+$/ function validateComponent(component: unknown, path: string, add: Add) { const tag = typeof component === 'object' && component !== null ? (component as { tag?: unknown }).tag : component if (typeof tag !== 'string' || !ADMIN_COMPONENT_TAG.test(tag)) { add( path, `must be a custom element name: lowercase, with a "-" (got ${JSON.stringify(tag)})`, "e.g. 'ecms-color-picker' or { tag: 'ecms-color-picker', props: { palette: 'brand' } }", ) return } if (typeof component === 'object' && component !== null) { const props: unknown = (component as { props?: unknown }).props if ( props !== undefined && (typeof props !== 'object' || props === null || Array.isArray(props)) ) add(`${path}.props`, 'must be an object of plain JSON values') } } function validateComponents(components: unknown, path: string, add: Add) { if (!Array.isArray(components)) { add(path, 'must be an array of components', "e.g. ['ecms-seo-preview']") return } for (const [i, component] of components.entries()) { validateComponent(component, `${path}[${i}]`, add) } } const ENDPOINT_METHODS = ['get', 'post', 'put', 'patch', 'delete'] const ENDPOINT_SEGMENT = /^(:[A-Za-z_][A-Za-z0-9_]*|[A-Za-z0-9._~-]+)$/ /** First path segments the built-in REST API uses besides collection slugs. */ const RESERVED_ENDPOINT_ROOTS = new Set([ 'users', 'globals', 'admin', 'jobs', 'media', 'api-keys', 'auth', 'healthz', 'readyz', // Kept free for later versions. 'system', 'health', 'internal', ]) /** `/auth//…` of providers can't be `/auth/`. */ export const RESERVED_PROVIDER_IDS: ReadonlySet = new Set([ 'login', 'logout', 'me', 'init', 'signup', 'verify-email', 'forgot-password', 'reset-password', 'first-register', 'identities', 'test', ]) function validateCommands(config: Config, add: Add) { const commands: unknown = config.cliCommands if (commands === undefined) return if (!Array.isArray(commands)) { add( 'cliCommands', 'must be an array', "e.g. cliCommands: [{ name: 'my:task', description, run }]", ) return } const seen = new Set() commands.forEach((command: unknown, i) => { const path = `commands[${i}]` const { name, description, run } = (command ?? {}) as Record if (typeof name !== 'string' || !/^[a-z][a-z0-9-]*(:[a-z0-9-]+)*$/.test(name)) add(`${path}.name`, 'must be lowercase letters, digits, - and :', "e.g. 'nested:rebuild'") else if (seen.has(name)) add(`${path}.name`, `"${name}" is already used by another command`) else seen.add(name) if (typeof description !== 'string') add(`${path}.description`, 'must be a string') if (typeof run !== 'function') add(`${path}.run`, 'must be a function') }) } /** `HH:MM`, 24-hour. */ const TIME_OF_DAY = /^([01]\d|2[0-3]):[0-5]\d$/ function validateTimeZone(config: Config, add: Add) { const zone: unknown = config.timeZone if (zone === undefined) return if (typeof zone !== 'string' || !isTimeZone(zone)) add('timeZone', 'must be an IANA time zone', "e.g. 'Asia/Bangkok' or 'UTC'") } function validateJobs(config: Config, add: Add) { const jobs: unknown = config.jobs if (jobs === undefined) return if (!Array.isArray(jobs)) { add('jobs', 'must be an array', "e.g. jobs: [{ name: 'shop:clean-up', every: 3600, run }]") return } const seen = new Set() jobs.forEach((job: unknown, i) => { const path = `jobs[${i}]` const { name, every, at, adminSchedule, run } = (job ?? {}) as Record if (typeof name !== 'string' || !/^[a-z][a-z0-9-]*(:[a-z0-9-]+)*$/.test(name)) add(`${path}.name`, 'must be lowercase letters, digits, - and :', "e.g. 'shop:clean-up'") else if (seen.has(name)) add(`${path}.name`, `"${name}" is already used by another job`) else seen.add(name) if (every !== undefined && (typeof every !== 'number' || !(every > 0))) add(`${path}.every`, 'must be a number of seconds above 0') if (at !== undefined) { if (typeof at !== 'string' || !TIME_OF_DAY.test(at)) add(`${path}.at`, 'must be a time like "02:00"') else if (typeof every === 'number' && (every <= 0 || every % 86_400 !== 0)) add( `${path}.every`, 'must be a number of whole days with `at`', 'e.g. 86400 (daily) or 604800 (weekly)', ) } if (adminSchedule !== undefined && typeof adminSchedule !== 'boolean') add(`${path}.adminSchedule`, 'must be true or false') if (typeof run !== 'function') add(`${path}.run`, 'must be a function') }) } function validateEvents(config: Config, add: Add) { const events: unknown = config.events if (events === undefined) return if (!Array.isArray(events)) { add('events', 'must be an array', "e.g. events: ['order.paid']") return } events.forEach((event: unknown, i) => { if (typeof event !== 'string' || !/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/.test(event)) add(`events[${i}]`, 'must be named . in lowercase', "e.g. 'order.paid'") }) } function validateEndpoints(config: Config, collectionSlugs: ReadonlySet, add: Add) { const endpoints: unknown = config.endpoints if (endpoints === undefined) return if (!Array.isArray(endpoints)) { add( 'endpoints', 'must be an array', "e.g. endpoints: [{ path: '/hello', method: 'get', handler }]", ) return } const seen = new Set() endpoints.forEach((endpoint: unknown, i) => { const path = `endpoints[${i}]` if (typeof endpoint !== 'object' || endpoint === null) { add(path, 'must be an object { path, method, handler }') return } const { path: route, method, handler, root, access } = endpoint as Record if (root !== undefined && typeof root !== 'boolean') add(`${path}.root`, 'must be true or false') const segments = typeof route === 'string' ? route.split('/').slice(1) : [] if ( typeof route !== 'string' || !route.startsWith('/') || segments.length === 0 || !segments.every((s) => ENDPOINT_SEGMENT.test(s)) ) { add(`${path}.path`, `must be a path like "/seo/generate" (got ${JSON.stringify(route)})`) } else { const first = segments[0] as string if (first.startsWith(':')) { add(`${path}.path`, 'must start with a fixed segment, not a parameter') } else if (root === true) { const taken = [ config.routes?.api ?? '/api/cms', `/${(config.admin?.path ?? '/admin').replace(/^\/+|\/+$/g, '')}`, '/healthz', '/readyz', ] .map((p) => p.replace(/\/+$/, '')) .find((p) => route === p || route.startsWith(`${p}/`) || p.startsWith(`${route}/`)) if (taken) add( `${path}.path`, `"${route}" is served by ${taken === '/healthz' || taken === '/readyz' ? 'the standalone server' : `"${taken}"`}`, ) } else if (RESERVED_ENDPOINT_ROOTS.has(first) || collectionSlugs.has(first)) { add( `${path}.path`, `"/${first}" is used by the built-in API`, 'start the path with your plugin or feature name, e.g. "/seo/generate"', ) } } const verb = typeof method === 'string' ? method.toLowerCase() : method if (typeof verb !== 'string' || !ENDPOINT_METHODS.includes(verb)) { add( `${path}.method`, `must be one of ${ENDPOINT_METHODS.join(', ')} (got ${JSON.stringify(method)})`, ) } if (typeof handler !== 'function') add(`${path}.handler`, 'must be a function') if (access !== undefined && typeof access !== 'function') add(`${path}.access`, 'must be a function ({ user }) => boolean') if (typeof route === 'string' && typeof verb === 'string') { // Parameters match anything, so "/a/:x" and "/a/:y" are the same route. const key = `${root === true ? 'root ' : ''}${verb} ${route.replace(/:[A-Za-z_][A-Za-z0-9_]*/g, ':')}` if (seen.has(key)) add(`${path}.path`, `duplicate endpoint ${verb.toUpperCase()} ${route}`) seen.add(key) } }) } function checkRange( min: number | undefined, max: number | undefined, minName: string, maxName: string, path: string, add: Add, ) { if (min !== undefined && max !== undefined && min > max) { add(path, `${minName} (${min}) is greater than ${maxName} (${max})`) } } function validateSelect( options: readonly SelectOption[] | undefined, defaultValue: string | readonly string[] | undefined, hasMany: boolean | undefined, path: string, add: Add, ) { if (!Array.isArray(options) || options.length === 0) { add(`${path}.options`, 'must contain at least one option') return } const values = options.map((o) => (typeof o === 'string' ? o : o.value)) const duplicates = values.filter((v, i) => values.indexOf(v) !== i) if (duplicates.length > 0) { add(`${path}.options`, `duplicate option values: ${[...new Set(duplicates)].join(', ')}`) } if (defaultValue === undefined) return const defaults = typeof defaultValue === 'string' ? [defaultValue] : defaultValue if (typeof defaultValue !== 'string' && !hasMany) { add(`${path}.defaultValue`, 'must be a single value unless hasMany is true') } for (const value of defaults) { if (!values.includes(value)) { add(`${path}.defaultValue`, `"${value}" is not one of the options`) } } } function validateUseAsTitle(collection: CollectionConfig, path: string, add: Add) { if (collection.useAsTitle === undefined || !Array.isArray(collection.fields)) return const field = collection.fields.find((f) => f.name === collection.useAsTitle) if (!field) { add(`${path}.useAsTitle`, `no top-level field named "${collection.useAsTitle}"`) } else if (!['text', 'textarea', 'email', 'slug', 'number', 'date'].includes(field.type)) { add( `${path}.useAsTitle`, `"${field.name}" is a ${field.type} field and cannot be shown as a title`, ) } } /** Adapters written for another adapter interface than this Easy CMS's. */ function validateAdapterVersions(config: Config, add: Add) { const adapters: [string, unknown][] = [ ['db', config.db], ['upload.storage', config.upload?.storage], ['upload.privateStorage', config.upload?.privateStorage], ['backups.storage', config.backups?.storage], ['email', config.email], ['search', config.search], ...(config.auth?.providers ?? []).map( (p, i) => [`auth.providers[${i}]`, p] as [string, unknown], ), ] for (const [path, adapter] of adapters) { const version = (adapter as { apiVersion?: unknown } | undefined)?.apiVersion if (version !== undefined && version !== ADAPTER_API_VERSION) add( path, `is written for adapter API ${String(version)}; this Easy CMS has ${ADAPTER_API_VERSION}`, Number(version) > ADAPTER_API_VERSION ? 'upgrade Easy CMS (every @easy-cms/* package)' : 'upgrade the adapter to a version for this Easy CMS', ) } } /** Plugins' integrations (#311): ids, categories, and what connecting needs. */ function validateIntegrations(config: Config, add: Add) { const list: unknown = config.integrations if (list === undefined) return if (!Array.isArray(list)) { add('integrations', 'must be an array') return } const ids = new Set() for (const [i, raw] of list.entries()) { const at = `integrations[${i}]` const item = (raw ?? {}) as Record if (typeof item.id !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(item.id)) add(`${at}.id`, 'must be lowercase letters, digits and "-"', "e.g. id: 'telegram'") else if (ids.has(item.id)) add(`${at}.id`, `two integrations are named "${item.id}"`) else ids.add(item.id) if (!isLabel(item.label)) add(`${at}.label`, 'must be a string or { en, th }') if ( ![ 'social', 'ai', 'notifications', 'automation', 'backups', 'email', 'analytics', 'sign-in', ].includes(item.category as string) ) add( `${at}.category`, "must be 'social', 'ai', 'notifications', 'automation', 'backups', 'email', 'analytics' or 'sign-in'", ) if (item.category === 'sign-in') { const signIn = (item.signIn ?? {}) as Record if (typeof signIn.create !== 'function') add(`${at}.signIn`, 'needs signIn.create(values, { app }) returning an auth provider') } if (item.category === 'email') { const email = (item.email ?? {}) as Record if (typeof email.create !== 'function') add(`${at}.email`, 'needs email.create(values): use defineEmailProvider()') } if (item.kind === 'fields') { if (!Array.isArray(item.fields) || item.fields.length === 0) add(`${at}.fields`, 'needs at least one field to fill') } else if (item.kind === 'oauth') { const oauth = (item.oauth ?? {}) as Record if (typeof oauth.authorizeUrl !== 'function' || typeof oauth.exchange !== 'function') add(`${at}.oauth`, 'needs authorizeUrl and exchange functions') } else add(`${at}.kind`, "must be 'fields' or 'oauth'") if (item.test !== undefined && typeof item.test !== 'function') add(`${at}.test`, 'must be a function') if (item.icon !== undefined && typeof item.icon !== 'string') { // Paths only: the admin draws them, so nothing else may ride along. const logo = (item.icon ?? {}) as { paths?: unknown; color?: unknown; viewBox?: unknown } const hex = (v: unknown) => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v) const paths = Array.isArray(logo.paths) ? logo.paths : [] if ( paths.length === 0 || paths.some((p) => { const path = (p ?? {}) as { d?: unknown; fill?: unknown } return ( typeof path.d !== 'string' || !/^[MmLlHhVvCcSsQqTtAaZzEe0-9.,\s+-]+$/.test(path.d) || (path.fill !== undefined && !hex(path.fill)) ) }) ) add( `${at}.icon`, 'must be an admin icon name, or { paths: [{ d, fill? }], color? } with SVG path data', ) if (logo.color !== undefined && !hex(logo.color)) add(`${at}.icon.color`, 'must be #rrggbb') if ( logo.viewBox !== undefined && !(typeof logo.viewBox === 'string' && /^-?[\d.]+( -?[\d.]+){3}$/.test(logo.viewBox)) ) add(`${at}.icon.viewBox`, "must be four numbers, e.g. '0 0 24 24'") } for (const [f, field] of (Array.isArray(item.fields) ? item.fields : []).entries()) { const fieldItem = (field ?? {}) as Record if (fieldItem.lookup !== undefined && typeof fieldItem.lookup !== 'function') add(`${at}.fields[${f}].lookup`, 'must be a function') } } } /** Plugins' event listeners (#356): event names, or `'*'`, and a handler. */ function validateListeners(config: Config, add: Add) { const list: unknown = config.listeners if (list === undefined) return if (!Array.isArray(list)) { add('listeners', 'must be an array') return } for (const [i, raw] of list.entries()) { const item = (raw ?? {}) as Record const events = item.events if ( events !== '*' && !(Array.isArray(events) && events.every((e) => typeof e === 'string' && e.length > 0)) ) add(`listeners[${i}].events`, "must be event names or '*'", "e.g. events: ['order.created']") if (typeof item.handler !== 'function') add(`listeners[${i}].handler`, 'must be a function') } } /** AI providers (#357) answer with an integration's connections; features have unique ids. */ function validateAi(config: Config, add: Add) { const ai: unknown = config.ai if (ai !== undefined) { const providers = (ai as { providers?: unknown })?.providers if (!Array.isArray(providers)) add('ai.providers', 'must be an array') else { const ids = new Set((config.integrations ?? []).map((i) => i?.id)) for (const [i, raw] of providers.entries()) { const provider = (raw ?? {}) as Record if (typeof provider.integration !== 'string' || !ids.has(provider.integration)) add(`ai.providers[${i}].integration`, 'must be the id of an integration') if (typeof provider.generate !== 'function') add(`ai.providers[${i}].generate`, 'must be a function') } } const limits = (ai as { limits?: Record })?.limits const whole = (v: unknown) => Number.isInteger(v) && (v as number) >= 0 if (limits?.perUserPerDay !== undefined && !whole(limits.perUserPerDay)) add('ai.limits.perUserPerDay', 'must be a whole number, 0 or more') for (const [role, value] of Object.entries((limits?.roles ?? {}) as Record)) if (!whole(value)) add(`ai.limits.roles.${role}`, 'must be a whole number, 0 or more') } const features: unknown = config.aiFeatures if (features === undefined) return if (!Array.isArray(features)) { add('aiFeatures', 'must be an array') return } const seen = new Set() for (const [i, raw] of features.entries()) { const feature = (raw ?? {}) as Record if (typeof feature.id !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(feature.id)) add(`aiFeatures[${i}].id`, 'must be lowercase letters, digits and "-"', "e.g. id: 'alt-text'") else if (seen.has(feature.id) || ['test', 'alt-text', 'translate'].includes(feature.id)) add(`aiFeatures[${i}].id`, `"${feature.id}" is taken`) else seen.add(feature.id) if (!isLabel(feature.label)) add(`aiFeatures[${i}].label`, 'must be a string or { en, th }') } } const ACTION_NAME = /^[a-z][a-z0-9-]{0,47}$/ const ACTION_PLACES = new Set(['document', 'row', 'bulk']) const ACTION_FIELD_TYPES = new Set([ 'text', 'textarea', 'number', 'select', 'boolean', 'date', 'email', 'relationship', ]) /** A collection's actions (#386): names, places, the form's field types and `run`. */ function validateActions( value: unknown, path: string, collectionSlugs: Set, add: (path: string, message: string, hint?: string) => void, ) { if (value === undefined) return if (!Array.isArray(value)) { add(path, 'must be a list of actions') return } const seen = new Set() value.forEach((action: Record, i) => { const name = typeof action?.name === 'string' ? action.name : undefined const at = `${path}.${name ?? `[${i}]`}` if (!name || !ACTION_NAME.test(name)) add(`${at}.name`, 'must be lowercase letters, digits and "-", starting with a letter') else if (seen.has(name)) add(`${at}.name`, `"${name}" is used by another action`) else seen.add(name) if (action?.label === undefined) add(`${at}.label`, 'is required') if (typeof action?.run !== 'function') add(`${at}.run`, 'must be a function') for (const key of ['when', 'access'] as const) if (action?.[key] !== undefined && typeof action[key] !== 'function') add(`${at}.${key}`, 'must be a function') const on = action?.on if ( on !== undefined && !( Array.isArray(on) && on.length > 0 && on.every((p) => typeof p === 'string' && ACTION_PLACES.has(p)) ) ) add(`${at}.on`, "must list 'document', 'row' or 'bulk'") const byDefault = action?.default if (byDefault !== undefined && byDefault !== 'admins' && byDefault !== 'editors') add(`${at}.default`, "must be 'admins' or 'editors'") const fields = action?.fields if (fields === undefined) return if (!Array.isArray(fields)) { add(`${at}.fields`, 'must be a list of fields') return } fields.forEach((field: Record, j) => { const fieldAt = `${at}.fields.${typeof field?.name === 'string' ? field.name : `[${j}]`}` if (typeof field?.name !== 'string' || !field.name) add(`${fieldAt}.name`, 'is required') if (typeof field?.type !== 'string' || !ACTION_FIELD_TYPES.has(field.type)) add( `${fieldAt}.type`, `must be one of ${[...ACTION_FIELD_TYPES].join(', ')}`, 'an action’s form takes simple fields', ) if (field?.type === 'relationship') { const targets = Array.isArray(field.to) ? field.to : [field.to] for (const target of targets) if (typeof target !== 'string' || !collectionSlugs.has(target)) add(`${fieldAt}.to`, `"${String(target)}" is not a collection`) } }) }) }