Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: validate headless config with Yup config schema #832

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 7 additions & 6 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,25 +65,26 @@
"@testing-library/react": "^16.0.0",
"@types/jest": "^29.0.3",
"@types/node-fetch": "^2.5.3",
"@types/react": "^18",
"@types/react-dom": "^18",
"expect-type": "^0.15.0",
"isomorphic-fetch": "^3.0.0",
"jest": "^29.3.1",
"msw": "^0.35.0",
"ts-jest": "^29.0.3",
"typescript": "^5.5.3",
"isomorphic-fetch": "^3.0.0",
"tsc-esm-fix": "^2.20.27",
"@types/react": "^18",
"@types/react-dom": "^18"
"typescript": "^5.5.3"
},
"dependencies": {
"@justinribeiro/lite-youtube": "^1.3.1",
"deepmerge": "^4.3.1",
"html-react-parser": "^3.0.4",
"path-to-regexp": "^6.2.0",
"react-inspector": "^6.0.1",
"schema-dts": "^1.1.2",
"swr": "^2.2.5",
"xss": "^1.0.15",
"deepmerge": "^4.3.1",
"schema-dts": "^1.1.2"
"yup": "^1.4.0"
},
"peerDependencies": {
"react": ">= 17.0.2"
Expand Down
157 changes: 157 additions & 0 deletions packages/core/src/utils/headlessConfigSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import { object, string, mixed, array, boolean, lazy } from 'yup';
import { CustomPostTypes, CustomTaxonomies } from '../types';

// Define the schema for CustomPostType
const customPostTypeSchema = object({
slug: string().required(),
endpoint: string().required(),
single: string(),
archive: string(),
matchSinglePath: boolean(),
}).noUnknown();

// Define the schema for CustomPostTypes (array of CustomPostType)
const customPostTypesSchema = array().of(customPostTypeSchema);

// Define the schema for CustomTaxonomy
const customTaxonomySchema = object({
slug: string().required(),
endpoint: string().required(),
rewrite: string(),
restParam: string(),
matchArchivePath: boolean(),
}).noUnknown();

// Define the schema for CustomTaxonomies (array of CustomTaxonomy)
const customTaxonomiesSchema = array().of(customTaxonomySchema);

export const headlessConfigSchema = object({
host: string(),
locale: string(),
sourceUrl: string(),
hostUrl: string(),

customPostTypes: mixed<
CustomPostTypes | ((defaultPostTypes: CustomPostTypes) => CustomPostTypes)
>().test(
'is-custom-post-types',
'customPostTypes must be an array or a function that returns an array',
(value) => {
if (typeof value === 'function') {
// Test the function by calling it with a dummy array
const result = value([]);
return customPostTypesSchema.isValidSync(result, {
strict: true,
abortEarly: false,
stripUnknown: false,
});
}

return customPostTypesSchema.isValidSync(value) || value === undefined;
},
),

customTaxonomies: mixed<
CustomTaxonomies | ((defaultPostTypes: CustomTaxonomies) => CustomTaxonomies)
>().test(
'is-custom-taxonomies',
'customTaxonomies must be an array or a function that returns an array',
(value) => {
if (typeof value === 'function') {
// Test the function by calling it with a dummy array
const result = value([]);

return customTaxonomiesSchema.isValidSync(result, {
strict: true,
abortEarly: false,
stripUnknown: false,
});
}

return customTaxonomiesSchema.isValidSync(value) || value === undefined;
},
),

redirectStrategy: string().oneOf(['404', 'none', 'always']),

useWordPressPlugin: boolean(),

integrations: object({
yoastSEO: object({
enabled: boolean(),
}),
polylang: object({
enabled: boolean(),
}),
}),

i18n: object({
locales: array(string()).required(),
defaultLocale: string().required(),
localeDetection: boolean(),
}).default(undefined),

preview: object({
alternativeAuthorizationHeader: boolean(),
usePostLinkForRedirect: boolean(),
}),

debug: object({
requests: boolean(),
redirects: boolean(),
devMode: boolean(),
}),

cache: object({
ttl: mixed().test(
'is-valid-ttl',
'cache.ttl must be a number or a function that returns a number',
(value) => {
if (typeof value === 'function') {
return typeof value() === 'number';
}

return typeof value === 'number' || value === undefined;
},
),
enabled: mixed().test(
'is-valid-cache-enabled',
'cache.enabled must be a boolean or a function that returns a boolean',
(value) => {
if (typeof value === 'function') {
return typeof value() === 'boolean';
}

return typeof value === 'boolean' || value === undefined;
},
),
beforeSet: mixed<Function>()
.test(
'is-function',
'cache.beforeSet must be a function',
(value) => typeof value === 'function' || value === undefined,
)
.optional(),
afterGet: mixed<Function>()
.test(
'is-function',
'cache.afterGet must be a function',
(value) => typeof value === 'function' || value === undefined,
)
.optional(),
cacheHandler: object({
set: mixed<Function>().test(
'is-function',
'cacheHandler.set must be a function',
(value) => typeof value === 'function',
),
get: mixed<Function>().test(
'is-function',
'cacheHandler.get must be a function',
(value) => typeof value === 'function',
),
}),
}),

sites: array(lazy(() => headlessConfigSchema.default(undefined))),
}).noUnknown();
1 change: 1 addition & 0 deletions packages/core/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export * from './url';
export * from './log';
export * from './decodeHtmlSpeciaChars';
export * from './getObjectProperty';
export * from './headlessConfigSchema';
18 changes: 9 additions & 9 deletions packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,30 +54,30 @@
"lint": "eslint src"
},
"dependencies": {
"negotiator": "^0.6.3",
"@formatjs/intl-localematcher": "^0.5.4",
"deepmerge": "^4.3.1",
"@headstartwp/core": "^1.4.4",
"@isaacs/ttlcache": "^1.4.1",
"deepmerge": "^4.3.1",
"loader-utils": "^3.2.0",
"schema-utils": "^4.0.0",
"@isaacs/ttlcache": "^1.4.1"
"negotiator": "^0.6.3",
"schema-utils": "^4.0.0"
},
"devDependencies": {
"@testing-library/dom": "^10.3.1",
"@testing-library/react": "^16.0.0",
"@types/jest": "^29.0.3",
"@types/react": "^18",
"@types/react-dom": "^18",
"copy-webpack-plugin": "^10.2.4",
"expect-type": "^0.15.0",
"isomorphic-fetch": "^3.0.0",
"jest": "^29.0.3",
"jest-fetch-mock": "^3.0.3",
"next-router-mock": "^0.9.13",
"node-mocks-http": "^1.14.1",
"ts-jest": "^29.0.1",
"typescript": "^5.5.3",
"isomorphic-fetch": "^3.0.0",
"jest-fetch-mock": "^3.0.3",
"tsc-esm-fix": "^2.20.27",
"@types/react": "^18",
"@types/react-dom": "^18"
"typescript": "^5.5.3"
},
"peerDependencies": {
"next": ">= 12.0.0",
Expand Down
20 changes: 19 additions & 1 deletion packages/next/src/config/withHeadstartWPConfig.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ConfigError, HeadlessConfig } from '@headstartwp/core';
import { ConfigError, HeadlessConfig, headlessConfigSchema } from '@headstartwp/core';
import { NextConfig } from 'next';
import fs from 'fs';
import { ValidationError } from 'yup';
import { ModifySourcePlugin, ConcatOperation } from './plugins/ModifySourcePlugin';

const LINARIA_EXTENSION = '.linaria.module.css';
Expand Down Expand Up @@ -106,6 +107,23 @@ export function withHeadstartWPConfig(
);
}

// Validate the config file, and log an error if it is invalid
try {
headlessConfigSchema.validateSync(headlessConfig, {
strict: true,
abortEarly: false,
stripUnknown: false,
});
} catch (error) {
if (error instanceof ValidationError) {
// eslint-disable-next-line no-console
console.error(`Error in the configuration file: ${error.errors.join(', ')}`);
} else {
// eslint-disable-next-line no-console
console.error('Unexpected error in the configuration file:', error);
}
}

const imageDomains: string[] = nextConfig.images?.domains ?? [];

const sites = headlessConfig.sites || [headlessConfig];
Expand Down