@astro-paper/cli
Version:
A comprehensive CLI tool for AstroPaper blog theme management
84 lines (83 loc) • 3.17 kB
JavaScript
import { z } from 'zod';
const siteConfigSchema = z.object({
website: z.string().url(),
author: z.string(),
profile: z.string().url(),
desc: z.string(),
title: z.string(),
ogImage: z.string(),
lightAndDarkMode: z.boolean(),
postPerIndex: z.number(),
postPerPage: z.number(),
scheduledPostMargin: z.number(),
showArchives: z.boolean(),
showBackButton: z.boolean(),
editPost: z.object({
enabled: z.boolean(),
text: z.string(),
url: z.string(),
}),
dynamicOgImage: z.boolean(),
dir: z.enum(['ltr', 'rtl', 'auto']),
lang: z.string(),
timezone: z.string(),
});
/**
* Extracts and parses the SITE configuration object from the config file content
* @param configContent Raw content of the config file
* @returns Parsed and validated SITE configuration object
*/
export function getSiteObj(configContent) {
// Step 1: Extract the SITE object (remove everything before '{' and after '}')
const extractObject = (str) => {
return str
.replace(/^[^{]*(?={)/, '') // Remove everything before '{' (excluding it)
.replace(/(?<=})[^}]*$/, ''); // Remove everything after '}' (excluding it)
};
// Step 2: Remove JavaScript comments (both single-line and multi-line)
const removeComments = (str) => {
return str
.replace(/\/\*[\s\S]*?\*\//g, '') // Remove multi-line comments
.replace(/\/\/[^\n]*$/gm, '') // Remove single-line comments
.trim();
};
// Step 3: Convert to valid JSON
const convertToValidJson = (str) => {
return (str
// Add quotes to property names only
.replace(/(\b\w+)(?=\s*:)/g, '"$1"')
// Convert the multiplication expression to number
.replace(/15 \* 60 \* 1000/g, '900000')
// Handle nested object properties (for editPost object)
.replace(/"editPost":\s*{\s*([^}]+)}/g, (match, inner) => {
return `"editPost": {${inner
.split(',')
.map((prop) => {
const [key] = prop.split(':');
return `"${key.trim()}":${prop.split(':').slice(1).join(':')}`;
})
.join(',')}}`;
})
// Remove extra whitespace
.replace(/\s+/g, ' ')
.trim());
};
try {
// Apply all transformations in sequence
const objectStr = extractObject(configContent);
const withoutComments = removeComments(objectStr);
const validJson = convertToValidJson(withoutComments);
console.log(validJson);
// Parse JSON and validate against schema
const parsedConfig = JSON.parse(validJson);
return siteConfigSchema.parse(parsedConfig);
}
catch (error) {
if (error instanceof z.ZodError) {
throw new Error(`Invalid SITE configuration: ${error.errors
.map(e => `${e.path.join('.')}: ${e.message}`)
.join(', ')}`);
}
throw new Error(`Failed to parse SITE configuration: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}