#!/usr/bin/env node /* eslint-disable no-console, jsdoc/require-param-type */ /** * generate-plugin.js * * Multi-block plugin generator from scaffold with mustache template processing. * Supports both JSON config file and interactive wizard. * * Usage: * Generator mode: node scripts/generate-plugin.js --config my-plugin-config.json * Template mode: node scripts/generate-plugin.js --config my-plugin-config.json --in-place * Validate: node scripts/generate-plugin.js --validate my-plugin-config.json * Help: node scripts/generate-plugin.js --help */ const { execFileSync } = require('child_process'); const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const readline = require('readline'); const Ajv2020 = require('ajv/dist/2020'); const Mustache = require('mustache'); // Paths const scaffoldDir = path.resolve(__dirname, '..'); const schemaPath = path.join( scaffoldDir, '.github/schemas/plugin-config.schema.json' ); // Output base: --output-dir , or generated-plugins/ in the current folder. const outputDirArgIndex = process.argv.indexOf('--output-dir'); const outputBaseDir = path.resolve( process.cwd(), outputDirArgIndex !== -1 && process.argv[outputDirArgIndex + 1] ? process.argv[outputDirArgIndex + 1] : 'generated-plugins' ); // License URIs for the schema's supported license identifiers. const LICENSE_URIS = { 'GPL-2.0-or-later': 'https://www.gnu.org/licenses/gpl-2.0.html', 'GPL-3.0-or-later': 'https://www.gnu.org/licenses/gpl-3.0.html', MIT: 'https://opensource.org/licenses/MIT', 'Apache-2.0': 'https://www.apache.org/licenses/LICENSE-2.0', }; // Every file a generated plugin is rendered from. The rest of the scaffold is // the generator's own tooling and is never copied. const PLUGIN_TEMPLATE_DIR = path.join(scaffoldDir, 'plugin-template'); // Standard toolchain proven in a generated plugin (spec 003). const STANDARD_TOOLCHAIN = require('./toolchain/standard-toolchain.json'); // Lockfiles for the standard toolchain, proven in lightspeedwp/ls-test. Every // generated plugin has the same dependencies, so one pair serves them all; // `npm run toolchain:lockfiles` refreshes them (see generateLockfiles). const TOOLCHAIN_LOCKFILES = { npm: path.join(__dirname, 'toolchain', 'standard-toolchain.package-lock.json'), composer: path.join(__dirname, 'toolchain', 'standard-toolchain.composer.lock'), }; // Block template rendered once per post type (see generatePerCPTBlocks). const COLLECTION_BLOCK_TEMPLATE = 'src/blocks/collection'; // Template mode flag const isTemplateMode = process.argv.includes('--in-place') || process.argv.includes('--template'); // Create logs directory const logsDir = path.join(scaffoldDir, 'logs'); if (!fs.existsSync(logsDir)) { fs.mkdirSync(logsDir, { recursive: true }); } // Global log state let logStream = null; let logFile = null; let logEntries = []; /** * Initialize logging for a specific plugin slug * @param {string} slug - Plugin slug for log file name */ function initializeLogging(slug) { if (logStream) { return; // Already initialized } logFile = path.join(logsDir, `generate-plugin-${slug}.log`); // Load existing log entries if file exists if (fs.existsSync(logFile)) { try { const existingContent = fs.readFileSync(logFile, 'utf8'); if (existingContent.trim()) { logEntries = JSON.parse(existingContent); } } catch (error) { // If file exists but is not valid JSON, start fresh logEntries = []; } } // Stream not needed - we'll write synchronously on close logStream = true; // Flag to indicate logging is initialized } /** * Log function - stores entries in JSON format * @param {string} level - Log level (INFO, WARN, ERROR, DEBUG) * @param {string} message - Log message * @param {Object} data - Optional additional data */ function log(level, message, data = null) { const entry = { timestamp: new Date().toISOString(), level, message, ...(data && { data }), }; logEntries.push(entry); // Console output for immediate feedback const consoleMessage = `[${entry.timestamp}] [${level}] ${message}`; if (level === 'ERROR') { console.error(consoleMessage); } else if (level === 'WARN') { console.warn(consoleMessage); } else { console.log(consoleMessage); } } /** * Close log stream and finalize log file */ function closeLogging() { if (logFile && logEntries.length > 0) { try { // Write synchronously to ensure log persists fs.writeFileSync( logFile, JSON.stringify(logEntries, null, 2), 'utf8' ); } catch (error) { console.error('Failed to write log file:', error.message); } } logStream = null; } // Cleanup on exit process.on('exit', () => { closeLogging(); }); process.on('SIGINT', () => { log('WARN', 'Generator interrupted by user'); closeLogging(); process.exit(1); }); /** * Sanitize user input to prevent security vulnerabilities * @param input * @param type */ function sanitizeInput(input, type = 'text') { if (!input || typeof input !== 'string') { return input; } // Remove null bytes and control characters let sanitized = input.replace(/[\x00-\x1F\x7F]/g, ''); switch (type) { case 'slug': // Convert to lowercase, replace spaces and underscores with hyphens sanitized = sanitized.toLowerCase().replace(/[\s_]+/g, '-'); // Only lowercase letters, numbers, and hyphens sanitized = sanitized.replace(/[^a-z0-9-]/g, ''); // Remove consecutive hyphens sanitized = sanitized.replace(/-+/g, '-'); // Trim hyphens from ends sanitized = sanitized.replace(/^-+|-+$/g, ''); // Truncate to 50 characters if (sanitized.length > 50) { sanitized = sanitized.substring(0, 50).replace(/-+$/, ''); } break; case 'namespace': // Convert to lowercase, replace spaces and hyphens with underscores sanitized = sanitized.toLowerCase().replace(/[\s-]+/g, '_'); // Only lowercase letters, numbers, and underscores sanitized = sanitized.replace(/[^a-z0-9_]/g, ''); // Remove consecutive underscores sanitized = sanitized.replace(/_+/g, '_'); // Trim underscores from ends sanitized = sanitized.replace(/^_+|_+$/g, ''); break; case 'name': // Trim whitespace sanitized = sanitized.trim(); // Collapse multiple spaces sanitized = sanitized.replace(/\s+/g, ' '); // Title case each word sanitized = sanitized.replace(/\b\w/g, (char) => char.toUpperCase() ); // Remove potentially dangerous characters but allow spaces sanitized = sanitized.replace(/[<>{}[\]\\\/]/g, ''); break; case 'url': // Trim whitespace sanitized = sanitized.trim(); // Add https:// if no protocol if (!/^https?:\/\//i.test(sanitized)) { sanitized = 'https://' + sanitized; } // Basic URL sanitization try { const url = new URL(sanitized); if (!['http:', 'https:'].includes(url.protocol)) { return ''; } // Remove trailing slash sanitized = url.href.replace(/\/$/, ''); } catch { return ''; } break; case 'version': // Handle two-digit versions (1.2 -> 1.2.0) if (/^\d+\.\d+$/.test(sanitized)) { sanitized = sanitized + '.0'; } // Semantic version only if (!/^\d+\.\d+\.\d+(-[a-zA-Z0-9.-]+)?$/.test(sanitized)) { sanitized = '1.0.0'; } break; default: // Trim whitespace sanitized = sanitized.trim(); // Collapse multiple spaces sanitized = sanitized.replace(/\s+/g, ' '); // Remove potentially dangerous characters sanitized = sanitized.replace(/[<>{}[\]\\]/g, ''); } return sanitized; } /** * Load and validate JSON schema */ function loadSchema() { try { const schemaContent = fs.readFileSync(schemaPath, 'utf8'); return JSON.parse(schemaContent); } catch (error) { log('ERROR', `Failed to load schema: ${error.message}`); throw new Error(`Schema load error: ${error.message}`); } } /** * Validate configuration against schema * @param config */ function validateConfig(config) { // Explicit, human-readable check for the functional-only/content-model // conflict (FR-009): content_model: "none" combined with a non-empty // post_types or taxonomies array is contradictory configuration, not a // valid combination. Checked ahead of the generic schema validation // below so the reported error names the fields directly rather than // surfacing a raw Ajv "must NOT be valid" message. if ( config.content_model === 'none' && ((config.post_types && config.post_types.length > 0) || (config.taxonomies && config.taxonomies.length > 0)) ) { const conflictMessage = 'Configuration error: "content_model" is set to "none" (functional-only) but ' + `"post_types" contains ${config.post_types?.length || 0} entr${ config.post_types?.length === 1 ? 'y' : 'ies' } and "taxonomies" contains ${ config.taxonomies?.length || 0 } entr${config.taxonomies?.length === 1 ? 'y' : 'ies'}. ` + 'Remove the post_types/taxonomies entries, or set "content_model" to "custom" (or omit it) to keep them.'; if (process.env.NODE_ENV !== 'test') { log('ERROR', conflictMessage); } return { valid: false, errors: [{ message: conflictMessage }], }; } const schema = loadSchema(); // Suppress Ajv warnings about unknown formats in test mode const originalWarn = console.warn; if (process.env.NODE_ENV === 'test') { console.warn = () => {}; } const ajv = new Ajv2020({ allErrors: true, strict: false }); const validate = ajv.compile(schema); const valid = validate(config); // Restore console.warn if (process.env.NODE_ENV === 'test') { console.warn = originalWarn; } if (!valid) { const errors = validate.errors .map((err) => { return ` - ${err.instancePath || 'root'}: ${err.message}`; }) .join('\n'); // Only log if not in test mode if (process.env.NODE_ENV !== 'test') { log('ERROR', `Validation errors:\n${errors}`); } return { valid: false, errors: validate.errors }; } // Only log if not in test mode if (process.env.NODE_ENV !== 'test') { log('INFO', 'Configuration validated successfully'); } return { valid: true, errors: null }; } /** * Apply defaults and derive computed values * @param config */ function applyDefaults(config) { const result = { ...config }; // Derive functional-only mode from the content_model flag. When true, // downstream generation steps skip all post-type/taxonomy scaffolding // regardless of legacy cpt_slug/post_types normalization below. result.isFunctionalOnly = result.content_model === 'none'; // Auto-derive namespace and textdomain from slug if (result.slug) { // Templates use the plugin_slug and slug placeholders interchangeably. result.plugin_slug = result.slug; result.textdomain = result.textdomain || result.slug; result.namespace = result.namespace || result.slug.replace(/-/g, '_'); } // Set defaults result.version = result.version || '1.0.0'; result.requires_wp = result.requires_wp || '6.5'; result.requires_php = result.requires_php || '8.0'; result.license = result.license || 'GPL-2.0-or-later'; // readme.txt and plugin header values. Undefined placeholders render as // empty strings, so these must always resolve to something valid. result.license_uri = result.license_uri || LICENSE_URIS[result.license] || ''; result.tested_up_to = result.tested_up_to || result.requires_wp; // Repository for package.json homepage, repository and bugs, which the // WordPress package lint requires. result.repository_url = ( result.repository_url || `https://github.com/lightspeedwp/${result.slug}` ).replace(/\/+$/, ''); result.contributors = result.contributors || String(result.author || '') .toLowerCase() .replace(/[^a-z0-9]/g, ''); result.description = result.description || 'A WordPress multi-block plugin.'; // Default blocks - no default blocks as templates are removed result.blocks = result.blocks || []; // Initialize arrays result.post_types = result.post_types || []; result.taxonomies = result.taxonomies || []; result.fields = result.fields || []; // If using legacy single post type format, convert to array if (result.cpt_slug || result.name_singular) { const legacyPostType = { slug: result.cpt_slug || result.slug?.split('-')[0]?.substring(0, 20), singular: result.name_singular || result.name?.replace(/s$/, ''), plural: result.name_plural || (result.name_singular ? result.name_singular + 's' : result.name), supports: result.cpt_supports || [ 'title', 'editor', 'thumbnail', 'excerpt', 'revisions', ], has_archive: result.cpt_has_archive !== false, public: result.cpt_public !== false, menu_icon: result.cpt_menu_icon || 'dashicons-admin-post', taxonomies: result.taxonomies || [], fields: result.fields || [], }; result.post_types = [legacyPostType]; // Clean up legacy fields (but don't delete taxonomies and fields yet - need to process them) delete result.cpt_slug; delete result.name_singular; delete result.name_plural; delete result.cpt_supports; delete result.cpt_has_archive; delete result.cpt_public; delete result.cpt_menu_icon; } // Convert legacy embedded taxonomies/fields to top-level arrays const taxonomyMap = new Map(); // Dedupe taxonomies across post types const postTypeFieldMap = new Map(); // Track fields by post type result.post_types = result.post_types.map((postType) => { const pt = { ...postType }; // Auto-derive plural from singular if not set if (pt.singular && !pt.plural) { pt.plural = pt.singular + 's'; } // Default supports pt.supports = pt.supports || [ 'title', 'editor', 'thumbnail', 'excerpt', 'revisions', ]; // Default settings pt.has_archive = pt.has_archive !== false; pt.public = pt.public !== false; pt.menu_icon = pt.menu_icon || 'dashicons-admin-post'; // Handle taxonomies - convert to array of slugs if needed if (pt.taxonomies && pt.taxonomies.length > 0) { const taxonomySlugs = []; pt.taxonomies.forEach(tax => { if (typeof tax === 'string') { // Already a slug, keep it taxonomySlugs.push(tax); } else if (tax && typeof tax === 'object' && tax.slug) { // Legacy object format - extract to top-level taxonomies taxonomySlugs.push(tax.slug); if (!taxonomyMap.has(tax.slug)) { taxonomyMap.set(tax.slug, { slug: tax.slug, singular: tax.singular || tax.slug, plural: tax.plural || tax.singular + 's', hierarchical: tax.hierarchical !== false, post_types: [pt.slug] }); } else { // Add this post type to existing taxonomy const existing = taxonomyMap.get(tax.slug); if (!existing.post_types.includes(pt.slug)) { existing.post_types.push(pt.slug); } } } }); pt.taxonomies = taxonomySlugs; } else { pt.taxonomies = []; } // Handle fields - move to top-level fields array if (pt.fields && pt.fields.length > 0) { postTypeFieldMap.set(pt.slug, pt.fields); delete pt.fields; } return pt; }); // Merge extracted taxonomies into top-level array taxonomyMap.forEach(tax => { // Check if already exists in result.taxonomies const existing = result.taxonomies.find(t => t.slug === tax.slug); if (!existing) { result.taxonomies.push(tax); } else { // Merge post_types tax.post_types.forEach(pt => { if (!existing.post_types.includes(pt)) { existing.post_types.push(pt); } }); } }); // Merge extracted fields into top-level array postTypeFieldMap.forEach((fields, postTypeSlug) => { const existing = result.fields.find(f => f.post_type === postTypeSlug); if (!existing) { result.fields.push({ post_type: postTypeSlug, field_group: fields }); } }); // For backward compatibility, set first post type properties as top-level if (result.post_types.length > 0) { const firstPostType = result.post_types[0]; result.cpt_slug = firstPostType.slug; result.cpt_name = firstPostType.singular; // Display name for the post type result.cpt_singular = firstPostType.singular; result.cpt_plural = firstPostType.plural; result.cpt_icon = firstPostType.menu_icon; result.name_singular = firstPostType.singular; result.name_plural = firstPostType.plural; result.cpt_supports = firstPostType.supports; result.cpt_has_archive = firstPostType.has_archive; result.cpt_public = firstPostType.public; result.cpt_menu_icon = firstPostType.menu_icon; // Legacy format expects embedded arrays result.taxonomies_legacy = firstPostType.taxonomies || []; result.fields_legacy = result.fields.find(f => f.post_type === firstPostType.slug)?.field_group || []; } // Defaults for the collection components (PostSelector, TaxonomyFilter, // QueryControls): the first post type and taxonomy, or the core ones. result.post_type_slug = result.post_types[0]?.slug || 'post'; result.taxonomy_slug = result.taxonomies[0]?.slug || 'category'; // Without a post type, the content-model files (patterns, field groups) // fall back to core posts, and a functional-only plugin's example field // groups in inc/class-repeater-fields.php attach to none. if (result.cpt_slug === undefined) { result.cpt_slug = result.isFunctionalOnly ? '' : result.post_type_slug; } // gettext date format, e.g. 2026-10-28 12:00+0000. result.pot_date = new Date() .toISOString() .replace('T', ' ') .replace(/:\d{2}\.\d{3}Z$/, '+0000'); return result; } /** * Apply mustache filters (transformations) * @param value * @param filter */ function applyFilter(value, filter) { switch (filter) { case 'upper': return value.toUpperCase(); case 'lower': return value.toLowerCase(); case 'pascalCase': return value .split(/[-_\s]+/) .filter((part) => part.length > 0) .map( (part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase() ) .join(''); case 'camelCase': const parts = value .split(/[-_\s]+/) .filter((part) => part.length > 0); if (parts.length === 0) { return value; } return ( parts[0].toLowerCase() + parts .slice(1) .map( (part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase() ) .join('') ); case 'kebabCase': // Handle camelCase value = value.replace(/([a-z])([A-Z])/g, '$1-$2'); // Convert spaces and underscores to hyphens return value.toLowerCase().replace(/[_\s]+/g, '-'); case 'snakeCase': // Handle camelCase value = value.replace(/([a-z])([A-Z])/g, '$1_$2'); // Convert spaces and hyphens to underscores return value.toLowerCase().replace(/[-\s]+/g, '_'); case 'title': return value.replace(/\b\w/g, (letter) => letter.toUpperCase()); default: return value; } } // Filters, as mustache.js dotted names: {{upper.namespace}} renders the // namespace in upper case. mustache.js has no filter syntax, so each filter // is an object holding every config value with the filter applied. const FILTERS = [ 'upper', 'lower', 'pascalCase', 'camelCase', 'kebabCase', 'snakeCase', 'title', ]; // Optional values, which render empty when the config leaves them out. Any // other tag with no value fails generation (see findUnsetTags()). const OPTIONAL_TAGS = { author_uri: '' }; // Copied as they are: mustache.js would read GitHub Actions `${{ ... }}` // expressions, and Spec Kit's `{{args}}` and `{{ inputs.* }}` placeholders, // as tags. Paths are relative to plugin-template/. // The WordPress skills vendored by scripts/sync-agent-skills.ts are unmodified // upstream copies, so they are never rendered either. const UNRENDERED_PATHS = [ '.github/workflows', '.gemini/commands', '.specify/workflows', ...require('./agent-skills.json').skills.map( (skill) => `.agents/skills/${skill}` ), ]; /** * Whether a plugin-template/ path is copied without rendering. * * @param {string} relativePath Path relative to plugin-template/. * @return {boolean} True when the file is not rendered. */ function isUnrendered(relativePath) { return UNRENDERED_PATHS.some( (unrendered) => relativePath === unrendered || relativePath.startsWith(`${unrendered}/`) ); } /** * Build the mustache.js view: the config, plus one object per filter. * * @param {Object} config Configuration object. * @return {Object} View for Mustache.render(). */ function buildView(config) { const values = { ...OPTIONAL_TAGS, ...config }; const scalars = Object.entries(values).filter(([, value]) => ['string', 'number'].includes(typeof value) ); const view = { ...values }; for (const filter of FILTERS) { view[filter] = Object.fromEntries( scalars.map(([key, value]) => [key, applyFilter(String(value), filter)]) ); } return view; } /** * Render template tags with mustache.js. * * Values are not HTML-escaped: templates are PHP, JavaScript, JSON and * Markdown, not HTML. Unset tags render as empty strings, as in mustache.js; * findUnsetTags() reports them. * * @param {string} content Template content. * @param {Object} config Configuration object. * @return {string} Rendered content. */ function replaceMustacheVars(content, config) { return Mustache.render(content, buildView(config), {}, { escape: (value) => String(value), }); } /** * List the tags in a template that have no value in the config. * * @param {string} content Template content. * @param {Object} config Configuration object. * @return {string[]} Unset tag names, such as `taxonomy_slug` or `upper.foo`. */ function findUnsetTags(content, config) { const context = new Mustache.Context(buildView(config)); const names = new Set(); const collect = (tokens) => tokens.forEach(([type, name, , , children]) => { if (['name', '&', '#', '^'].includes(type)) { names.add(name); } if (children) { collect(children); } }); collect(Mustache.parse(content)); return [...names].filter((name) => context.lookup(name) === undefined); } // Unset tags found while rendering, as `file: tag` lines. generatePlugin() // fails when any are left, rather than writing empty values into the plugin. let unsetTags = []; /** * Render a template file's content or name, recording unset tags. * * @param {string} content Template content or file name. * @param {Object} config Configuration object. * @param {string} file Template path, for the error message. * @return {string} Rendered content. */ function renderTemplate(content, config, file) { findUnsetTags(content, config).forEach((tag) => unsetTags.push(`${file}: {{${tag}}}`) ); return replaceMustacheVars(content, config); } /** * Copy file with mustache replacement * @param srcPath * @param destPath * @param config */ function copyFileWithReplacement(srcPath, destPath, config) { try { const content = fs.readFileSync(srcPath, 'utf8'); const file = path.relative(PLUGIN_TEMPLATE_DIR, srcPath); const replaced = isUnrendered(file) ? content : renderTemplate(content, config, file); // Ensure destination directory exists const destDir = path.dirname(destPath); if (!fs.existsSync(destDir)) { fs.mkdirSync(destDir, { recursive: true }); } fs.writeFileSync(destPath, replaced, 'utf8'); // Keep the executable bit of scripts such as .specify/scripts/bash/*.sh. fs.chmodSync(destPath, fs.statSync(srcPath).mode); log( 'DEBUG', `Copied and processed: ${path.relative(scaffoldDir, srcPath)} -> ${path.relative(outputBaseDir, destPath)}` ); } catch (error) { log('ERROR', `Failed to copy ${srcPath}: ${error.message}`); throw error; } } /** * Copy directory recursively with mustache replacement * @param srcDir * @param destDir * @param config * @param excludePaths */ function copyDirWithReplacement(srcDir, destDir, config, excludePaths = []) { const entries = fs.readdirSync(srcDir, { withFileTypes: true }); for (const entry of entries) { const srcPath = path.join(srcDir, entry.name); const relativePath = path.relative(PLUGIN_TEMPLATE_DIR, srcPath); // Skip excluded paths, and OS junk files in any folder. if ( entry.name === '.DS_Store' || excludePaths.some( (exclude) => relativePath === exclude || relativePath.startsWith(`${exclude}/`) ) ) { log('DEBUG', `Skipping excluded path: ${relativePath}`); continue; } // Replace mustache in file/dir names const destName = renderTemplate(entry.name, config, relativePath); const destPath = path.join(destDir, destName); // Links such as .claude/skills/test -> ../../.agents/skills/test stay // links, with the same relative target. if (entry.isSymbolicLink()) { fs.rmSync(destPath, { force: true }); fs.symlinkSync(fs.readlinkSync(srcPath), destPath); continue; } if (entry.isDirectory()) { if (!fs.existsSync(destPath)) { fs.mkdirSync(destPath, { recursive: true }); } copyDirWithReplacement(srcPath, destPath, config, excludePaths); } else { copyFileWithReplacement(srcPath, destPath, config); } } } /** * Remove barrel-file export lines for content-model hooks/components that * were excluded from the copy in functional-only mode. * * Excluding usePostType.js/useTaxonomies.js/useCollection.js and the * PostSelector/TaxonomyFilter components (see the functional-only * excludePaths block above) leaves src/hooks/index.js and * src/components/index.js still re-exporting them, which would break the * generated plugin's build. This strips just those export lines. * * @param {string} outputDir - Output directory path * @param {boolean} isFunctionalOnly - Whether functional-only mode is active */ function stripExcludedModuleExports(outputDir, isFunctionalOnly) { if (!isFunctionalOnly) { return; } const barrelFiles = [ { file: path.join(outputDir, 'src', 'hooks', 'index.js'), excludedNames: ['usePostType', 'useTaxonomies', 'useCollection'], }, { file: path.join(outputDir, 'src', 'components', 'index.js'), excludedNames: ['PostSelector', 'TaxonomyFilter', 'QueryControls'], }, ]; for (const { file, excludedNames } of barrelFiles) { if (!fs.existsSync(file)) { continue; } const lines = fs.readFileSync(file, 'utf8').split('\n'); const filtered = lines.filter((line) => { return !excludedNames.some((name) => line.includes(`as ${name} }`) ); }); fs.writeFileSync(file, filtered.join('\n'), 'utf8'); log( 'INFO', `Stripped functional-only exports from ${path.relative( outputDir, file )}`, { excludedNames } ); } } /** * Process files in place (template mode) * Renders the template tags in plugin-template/, which hoistPluginTemplate() * then moves to the repository root. The scaffold's own files are not rendered. * @param {string} targetDir - plugin-template/ in the repository being converted * @param {Object} config - Configuration object */ function processFilesInPlace(targetDir, config) { // Left behind by installing or building inside plugin-template/. const excludePaths = ['node_modules', 'vendor', 'build']; // Process directory recursively function processDirectory(dir) { const entries = fs.readdirSync(dir, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dir, entry.name); const relativePath = path.relative(targetDir, fullPath); // Skip excluded paths, and links: their targets are rendered // where they live. if ( entry.isSymbolicLink() || excludePaths.some( (exclude) => relativePath === exclude || relativePath.startsWith(`${exclude}/`) ) ) { log('DEBUG', `Skipping excluded path: ${relativePath}`); continue; } if (entry.isDirectory()) { // Recursively process subdirectory processDirectory(fullPath); // Rename directory if it contains mustache variables if (entry.name.includes('{{')) { const newName = renderTemplate(entry.name, config, relativePath); const newPath = path.join(dir, newName); if (fullPath !== newPath) { log( 'INFO', `Renaming directory: ${relativePath} -> ${newName}` ); fs.renameSync(fullPath, newPath); } } } else { // Process file content const fileContent = fs.readFileSync(fullPath, 'utf8'); const newContent = isUnrendered(relativePath) ? fileContent : renderTemplate(fileContent, config, relativePath); if (fileContent !== newContent) { log( 'INFO', `Replacing mustache variables in: ${relativePath}` ); fs.writeFileSync(fullPath, newContent, 'utf8'); } // Rename file if it contains mustache variables if (entry.name.includes('{{')) { const newName = renderTemplate(entry.name, config, relativePath); const newPath = path.join(dir, newName); if (fullPath !== newPath) { log( 'INFO', `Renaming file: ${relativePath} -> ${newName}` ); fs.renameSync(fullPath, newPath); } } } } } processDirectory(targetDir); } /** * Move the rendered plugin-template/ files up to the repository root * (template mode), replacing the scaffold's own copies of shared files such as * eslint.config.mjs and .gitignore. * * @param {string} targetDir - Repository root being turned into the plugin */ function hoistPluginTemplate(targetDir) { const templateDir = path.join(targetDir, 'plugin-template'); if (!fs.existsSync(templateDir)) { log('WARN', 'plugin-template/ not found, nothing to move to the root'); return; } function moveEntries(srcDir, destDir) { for (const entry of fs.readdirSync(srcDir, { withFileTypes: true })) { const srcPath = path.join(srcDir, entry.name); const destPath = path.join(destDir, entry.name); if (entry.isDirectory() && fs.existsSync(destPath)) { moveEntries(srcPath, destPath); continue; } fs.rmSync(destPath, { recursive: true, force: true }); fs.renameSync(srcPath, destPath); } } // The template ships these configs under their Gutenberg names. Remove the // scaffold's own copies, which would otherwise win (phpcs.xml over // phpcs.xml.dist). for (const file of ['eslint.config.cjs', '.prettierrc.js', '.stylelintrc.json', 'phpcs.xml']) { fs.rmSync(path.join(targetDir, file), { force: true }); } // The plugin's Spec Kit replaces the scaffold's own, rather than merging // with it. fs.rmSync(path.join(targetDir, '.specify'), { recursive: true, force: true }); moveEntries(templateDir, targetDir); fs.rmSync(templateDir, { recursive: true, force: true }); log('INFO', 'Moved plugin-template/ files to the repository root'); } /** * Prompt user for confirmation (template mode) * @param {string} message - Confirmation message * @return {Promise} - True if confirmed, false otherwise */ function promptConfirmation(message) { return new Promise((resolve) => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question(`${message} (y/N): `, (answer) => { rl.close(); resolve( answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes' ); }); }); } /** * Generate plugin from configuration * @param config * @param {boolean} inPlace - If true, generates in current directory (template mode) */ function generatePlugin(config, inPlace = false) { // Initialize logging with plugin slug initializeLogging(config.slug || 'unknown'); log('INFO', 'Plugin generator starting', { nodeVersion: process.version, workingDirectory: process.cwd(), mode: inPlace ? 'template' : 'generator', }); log('INFO', `Starting plugin generation: ${config.name} (${config.slug})`); // Apply defaults and validation const fullConfig = applyDefaults(config); log('INFO', 'Validating configuration', { slug: fullConfig.slug }); const validation = validateConfig(fullConfig); if (!validation.valid) { log('ERROR', 'Configuration validation failed', { errors: validation.errors, }); throw new Error('Configuration validation failed'); } log('INFO', 'Configuration validated successfully', { slug: fullConfig.slug, name: fullConfig.name, version: fullConfig.version, }); // Functional-only mode relies on the exclusion-aware copy path and export // stripping, which only run in generator mode. processFilesInPlace() would // leave every content-model file in place, so reject the combination before // any files are touched. if (inPlace && fullConfig.isFunctionalOnly) { const inPlaceMessage = 'Configuration error: "content_model" is set to "none" (functional-only), ' + 'which is not supported in in-place (--in-place/--template) mode. ' + 'Run the generator without --in-place to create a functional-only plugin.'; if (process.env.NODE_ENV !== 'test') { log('ERROR', inPlaceMessage); } throw new Error(inPlaceMessage); } // Determine output directory based on mode let outputDir; if (inPlace) { // Template mode: use current directory outputDir = process.cwd(); log('INFO', `Template mode: Generating in-place at ${outputDir}`); } else { // Generator mode: create output folder outputDir = path.join(outputBaseDir, fullConfig.slug); log('INFO', `Generator mode: Creating output at ${outputDir}`); } if (!inPlace) { // Generator mode: check if output directory exists if (fs.existsSync(outputDir)) { log('WARN', `Output directory exists: ${outputDir}`); if (!process.argv.includes('--force')) { throw new Error( 'Output directory already exists. Use --force to overwrite.' ); } log('INFO', 'Removing existing output directory'); fs.rmSync(outputDir, { recursive: true, force: true }); } fs.mkdirSync(outputDir, { recursive: true }); log('INFO', `Created output directory: ${outputDir}`); } else { // Template mode: ensure we're in a valid directory log('INFO', 'Template mode: Validating current directory'); } // Paths in plugin-template/ to exclude from copying const excludePaths = [ // Left behind by installing or building inside plugin-template/. 'node_modules', 'vendor', 'build', // Per-post-type template: never copied as-is. generatePerCPTBlocks() // renders one {post-type}-collection block from it per post type, and // is skipped entirely in functional-only mode. COLLECTION_BLOCK_TEMPLATE, 'logs', 'tmp', 'reports', 'generated-plugins', 'output-plugin', 'output', '.git', '.github/reports', '.github/agents', '.github/prompts', // tests/, docs/ and bin/ in plugin-template/ belong to the plugin. 'scripts', '.dry-run-backup', 'plugin-config.json', // Scaffold lockfiles describe the scaffold's own dependency graph. // generateLockfiles() writes the plugin's own lockfiles below. 'package-lock.json', 'composer.lock', ]; // Functional-only mode: exclude the static content-model files that // copyDirWithReplacement() would otherwise always copy, regardless of // whether any post_types/taxonomies are configured (FR-005). if (fullConfig.isFunctionalOnly) { excludePaths.push( 'patterns/{{slug}}-grid.php', 'patterns/{{slug}}-archive.php', 'patterns/{{slug}}-card.php', 'patterns/{{slug}}-featured.php', 'patterns/{{slug}}-meta.php', 'patterns/{{slug}}-single.php', 'patterns/{{slug}}-slider.php', 'scf-json/group_{{slug}}_example.json', 'src/hooks/usePostType.js', 'src/hooks/useTaxonomies.js', 'src/hooks/useCollection.js', 'src/components/TaxonomyFilter', 'src/components/PostSelector', // Imports TaxonomyFilter, so it cannot be built without it. 'src/components/QueryControls' ); } // Render the plugin files with mustache replacement unsetTags = []; if (inPlace) { log('INFO', 'Replacing mustache variables in current directory...'); // In template mode, process files in place processFilesInPlace(path.join(outputDir, 'plugin-template'), fullConfig); hoistPluginTemplate(outputDir); } else { log('INFO', 'Copying plugin-template files to output directory...'); // In generator mode, render plugin-template/ into the output copyDirWithReplacement( PLUGIN_TEMPLATE_DIR, outputDir, fullConfig, excludePaths ); stripExcludedModuleExports(outputDir, fullConfig.isFunctionalOnly); // Generate per-CPT blocks after copying if ( !fullConfig.isFunctionalOnly && fullConfig.post_types && fullConfig.post_types.length > 0 ) { log('INFO', 'Generating per-CPT blocks'); generatePerCPTBlocks(outputDir, fullConfig); log('INFO', 'Per-CPT block generation completed'); } // Generate src/index.js with dynamic block imports log('INFO', 'Generating src/index.js with block imports'); generateSrcIndexFile(outputDir, fullConfig); } if (unsetTags.length) { throw new Error( `Template tags with no value in the configuration:\n ${[ ...new Set(unsetTags), ].join('\n ')}` ); } // Generate package.json log('INFO', 'Generating package.json'); const packageJson = generatePackageJson(outputDir, fullConfig); // Generate composer.json log('INFO', 'Generating composer.json'); const composerJson = generateComposerJson(outputDir, fullConfig); // Generate package-lock.json and composer.lock generateLockfiles(outputDir, packageJson, composerJson); // Generate README.md log('INFO', 'Generating README.md'); generateReadme(outputDir, fullConfig); // Generate CHANGELOG.md generateChangelog(outputDir, fullConfig); // Generate post-type JSON files if ( !fullConfig.isFunctionalOnly && fullConfig.post_types && fullConfig.post_types.length > 0 ) { log('INFO', 'Generating post-type JSON files'); generatePostTypeJSONFiles(outputDir, fullConfig); // Generate taxonomy SCF field groups log('INFO', 'Generating taxonomy field groups'); generateTaxonomySCFGroups(outputDir, fullConfig); } // Generate SCF JSON field group. Skipped in functional-only mode: field // groups belong to a content model, so top-level fields must not produce // field-group JSON (FR-004). if ( !fullConfig.isFunctionalOnly && fullConfig.fields && fullConfig.fields.length > 0 ) { log('INFO', 'Generating SCF field group JSON'); generateSCFFieldGroup(outputDir, fullConfig); } // Format the rendered JavaScript, so a plugin passes its own lint:js // whatever the length of its slug (spec 003, FR-007). if (!inPlace) { formatGeneratedOutput(outputDir); } log('INFO', 'Plugin generated successfully', { outputDirectory: outputDir, mode: inPlace ? 'template' : 'generator', slug: fullConfig.slug, name: fullConfig.name, version: fullConfig.version, }); // Output next steps console.log('\nāœ… Plugin generated successfully!\n'); console.log('šŸ“¦ Next steps:\n'); if (!inPlace) { console.log(` cd ${outputDir}`); } console.log(' composer install'); console.log(' npm install'); console.log(' npm run build\n'); console.log(`šŸ“ Log file: ${logFile}\n`); return outputDir; } /** * Generate one collection block per post type from the collection template. * * The template in COLLECTION_BLOCK_TEMPLATE is excluded from the main copy and * rendered here once per post type, with that post type's variables, into * src/blocks/{post-type}-collection. Generic blocks (slider, field-display) * are not post-type specific and are copied once by the main copy step. * * @param {string} outputDir - Output directory path * @param {Object} config - Plugin configuration */ function generatePerCPTBlocks(outputDir, config) { if (!config.post_types || config.post_types.length === 0) { log('INFO', 'No post types defined, skipping per-CPT block generation'); return; } const templateDir = path.join(PLUGIN_TEMPLATE_DIR, COLLECTION_BLOCK_TEMPLATE); if (!fs.existsSync(templateDir)) { log('WARN', `Collection block template not found: ${COLLECTION_BLOCK_TEMPLATE}`); return; } const blocksDir = path.join(outputDir, 'src', 'blocks'); config.post_types.forEach((postType) => { const blockConfig = { ...config, cpt_slug: postType.slug, cpt_name: postType.singular, // Display name for the post type cpt_singular: postType.singular, cpt_plural: postType.plural, cpt_icon: postType.menu_icon, cpt_menu_icon: postType.menu_icon, cpt_supports: postType.supports, }; const blockDirName = `${applyFilter(postType.slug, 'kebabCase')}-collection`; const blockPath = path.join(blocksDir, blockDirName); fs.mkdirSync(blockPath, { recursive: true }); copyDirWithReplacement(templateDir, blockPath, blockConfig, []); log('INFO', `Generated block: ${blockDirName}`, { postType: postType.slug, }); }); log('INFO', 'Per-CPT block generation completed', { blocksGenerated: config.post_types.length, postTypes: config.post_types.map((pt) => pt.slug), }); } /** * Generate src/index.js with dynamic block imports * Creates the main entry point file with imports for all generated blocks * @param {string} outputDir - Output directory path * @param {Object} config - Plugin configuration */ function generateSrcIndexFile(outputDir, config) { const blocksDir = path.join(outputDir, 'src', 'blocks'); const indexPath = path.join(outputDir, 'src', 'index.js'); if (!fs.existsSync(blocksDir)) { log('WARN', 'Blocks directory not found, skipping src/index.js generation'); return; } // Get all block directories with an entry point (skips asset folders such as icons/) const blockDirs = fs.readdirSync(blocksDir, { withFileTypes: true }) .filter(entry => entry.isDirectory()) .filter(entry => fs.existsSync(path.join(blocksDir, entry.name, 'index.js'))) .map(entry => entry.name) .sort(); if (blockDirs.length === 0) { log('WARN', 'No blocks found, skipping src/index.js generation'); return; } // Generate block imports const blockImports = blockDirs .map(blockDir => `import './blocks/${blockDir}';`) .join('\n'); // Generate the file content const content = `/** * ${config.name} Plugin - Main Entry Point * * Registers all blocks from the blocks directory. * * @package */ // Import blocks. ${blockImports} // Import global styles. import './scss/style.scss'; import './scss/editor.scss'; `; fs.writeFileSync(indexPath, content, 'utf8'); log('INFO', `Generated src/index.js with ${blockDirs.length} block imports`, { blocks: blockDirs }); } /** * Generate individual post-type JSON files from config * @param {string} outputDir - Output directory path * @param {Object} config - Plugin configuration */ function generatePostTypeJSONFiles(outputDir, config) { if (!config.post_types || config.post_types.length === 0) { log('INFO', 'No post types defined, skipping post-type JSON generation'); return; } log('INFO', 'Generating post-type JSON files in scf-json/', { postTypeCount: config.post_types.length }); const scfJsonDir = path.join(outputDir, 'scf-json'); if (!fs.existsSync(scfJsonDir)) { fs.mkdirSync(scfJsonDir, { recursive: true }); log('INFO', 'Created scf-json directory'); } // Generate SCF-formatted JSON file for each post type config.post_types.forEach((postType) => { // Create SCF post type format const scfPostType = { key: `post_type_${postType.slug}`, title: postType.singular, post_type: postType.slug, menu_order: 0, active: true, public: postType.public !== false, hierarchical: postType.hierarchical || false, exclude_from_search: false, publicly_queryable: true, show_ui: true, show_in_menu: true, show_in_nav_menus: true, show_in_rest: true, rest_base: postType.slug + 's', rest_controller_class: '', menu_position: 20, menu_icon: postType.menu_icon || 'dashicons-admin-post', capability_type: 'post', supports: postType.supports || ['title', 'editor', 'thumbnail'], taxonomies: postType.taxonomies || [], has_archive: postType.has_archive !== false, rewrite: { slug: postType.slug, with_front: true }, can_export: true, delete_with_user: false, labels: { name: postType.plural, singular_name: postType.singular, menu_name: postType.plural, all_items: `All ${postType.plural}`, add_new: 'Add New', add_new_item: `Add New ${postType.singular}`, edit_item: `Edit ${postType.singular}`, new_item: `New ${postType.singular}`, view_item: `View ${postType.singular}`, view_items: `View ${postType.plural}`, search_items: `Search ${postType.plural}`, not_found: `No ${postType.plural.toLowerCase()} found`, not_found_in_trash: `No ${postType.plural.toLowerCase()} found in Trash`, archives: `${postType.singular} Archives`, attributes: `${postType.singular} Attributes`, insert_into_item: `Insert into ${postType.singular.toLowerCase()}`, uploaded_to_this_item: `Uploaded to this ${postType.singular.toLowerCase()}`, filter_items_list: `Filter ${postType.plural.toLowerCase()} list`, items_list_navigation: `${postType.plural} list navigation`, items_list: `${postType.plural} list` } }; // Write SCF-formatted JSON file const filePath = path.join(scfJsonDir, `post-type-${postType.slug}.json`); fs.writeFileSync( filePath, JSON.stringify(scfPostType, null, '\t'), 'utf8' ); log('INFO', `Generated post-type JSON: ${filePath}`, { slug: postType.slug }); }); log('INFO', 'Post-type JSON files generated successfully in scf-json/', { filesGenerated: config.post_types.length }); } /** * Generate SCF field groups for taxonomies * Creates SCF-formatted taxonomy JSON files that SCF will use to register taxonomies * Uses top-level taxonomies array * @param {string} outputDir - Output directory path * @param {Object} config - Plugin configuration */ function generateTaxonomySCFGroups(outputDir, config) { // Use top-level taxonomies array if available if (!config.taxonomies || config.taxonomies.length === 0) { log('INFO', 'No taxonomies defined, skipping taxonomy JSON generation'); return; } const scfJsonDir = path.join(outputDir, 'scf-json'); if (!fs.existsSync(scfJsonDir)) { fs.mkdirSync(scfJsonDir, { recursive: true }); log('INFO', 'Created scf-json directory'); } // Generate SCF-formatted JSON file for each taxonomy config.taxonomies.forEach((taxonomy) => { // Create SCF taxonomy format const scfTaxonomy = { key: `taxonomy_${taxonomy.slug}`, title: taxonomy.singular, taxonomy: taxonomy.slug, menu_order: 0, active: true, object_type: taxonomy.post_types || [], public: true, publicly_queryable: true, hierarchical: taxonomy.hierarchical !== false, show_ui: true, show_in_menu: true, show_in_nav_menus: true, show_in_rest: true, rest_base: taxonomy.slug + 's', rest_controller_class: '', show_tagcloud: true, show_in_quick_edit: true, show_admin_column: true, labels: { name: taxonomy.plural, singular_name: taxonomy.singular, menu_name: taxonomy.plural, search_items: `Search ${taxonomy.plural}`, all_items: `All ${taxonomy.plural}`, edit_item: `Edit ${taxonomy.singular}`, update_item: `Update ${taxonomy.singular}`, add_new_item: `Add New ${taxonomy.singular}`, new_item_name: `New ${taxonomy.singular} Name` }, rewrite: { slug: taxonomy.slug, with_front: true, hierarchical: taxonomy.hierarchical !== false } }; // Add hierarchical-specific labels if (taxonomy.hierarchical) { scfTaxonomy.labels.parent_item = `Parent ${taxonomy.singular}`; scfTaxonomy.labels.parent_item_colon = `Parent ${taxonomy.singular}:`; } else { // Add non-hierarchical specific labels scfTaxonomy.labels.popular_items = `Popular ${taxonomy.plural}`; scfTaxonomy.labels.separate_items_with_commas = `Separate ${taxonomy.plural.toLowerCase()} with commas`; scfTaxonomy.labels.add_or_remove_items = `Add or remove ${taxonomy.plural.toLowerCase()}`; scfTaxonomy.labels.choose_from_most_used = `Choose from the most used ${taxonomy.plural.toLowerCase()}`; } // Write SCF-formatted JSON file const filePath = path.join(scfJsonDir, `taxonomy-${taxonomy.slug}.json`); fs.writeFileSync( filePath, JSON.stringify(scfTaxonomy, null, '\t'), 'utf8' ); log('INFO', `Generated taxonomy JSON: ${filePath}`, { slug: taxonomy.slug, postTypes: scfTaxonomy.object_type }); }); log('INFO', 'Taxonomy JSON files generated successfully in scf-json/', { filesGenerated: config.taxonomies.length }); } /** * Generate SCF JSON field group file from config * Supports both old format (config.fields as array) and new format (config.fields with post_type/field_group) * @param {string} outputDir - Output directory path * @param {Object} config - Plugin configuration */ function generateSCFFieldGroup(outputDir, config) { if (!config.fields || config.fields.length === 0) { log('INFO', 'No custom fields defined, skipping SCF JSON generation'); return; } const scfJsonDir = path.join(outputDir, 'scf-json'); if (!fs.existsSync(scfJsonDir)) { fs.mkdirSync(scfJsonDir, { recursive: true }); log('INFO', 'Created scf-json directory'); } // Check if using new structure (array of {post_type, field_group}) const hasNewStructure = config.fields.some(f => f.post_type && f.field_group); if (hasNewStructure) { // New structure: Generate a field group for each post type config.fields.forEach(fieldGroupDef => { if (!fieldGroupDef.post_type || !fieldGroupDef.field_group || fieldGroupDef.field_group.length === 0) { return; } const postType = fieldGroupDef.post_type; const fields = fieldGroupDef.field_group; log('INFO', `Generating SCF field group for post type: ${postType}`, { fieldCount: fields.length }); // Map config fields to SCF field format const scfFields = fields.map((field, index) => { const fieldKey = `field_${postType}_${field.name}`; const scfField = { key: fieldKey, label: field.label, name: field.name, type: field.type, instructions: field.instructions || '', required: field.required ? 1 : 0, }; // Add optional properties if (field.default_value !== undefined) { scfField.default_value = field.default_value; } if (field.placeholder) { scfField.placeholder = field.placeholder; } if (field.choices) { scfField.choices = field.choices; } if (field.return_format) { scfField.return_format = field.return_format; } if (field.multiple !== undefined) { scfField.multiple = field.multiple ? 1 : 0; } if (field.allow_null !== undefined) { scfField.allow_null = field.allow_null ? 1 : 0; } // Add type-specific properties if (field.type === 'number') { if (field.min !== undefined) scfField.min = field.min; if (field.max !== undefined) scfField.max = field.max; if (field.step !== undefined) scfField.step = field.step; } return scfField; }); // Get post type label const postTypeDef = config.post_types?.find(pt => pt.slug === postType); const postTypeLabel = postTypeDef?.singular || postType.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()); // Create the field group const fieldGroup = { key: `group_${postType}_fields`, title: `${postTypeLabel} Fields`, fields: scfFields, location: [ [ { param: 'post_type', operator: '==', value: postType, }, ], ], menu_order: 0, position: 'normal', style: 'default', label_placement: 'top', instruction_placement: 'label', hide_on_screen: [], active: true, }; // Write the JSON file const outputPath = path.join(scfJsonDir, `group_${postType}_fields.json`); fs.writeFileSync(outputPath, JSON.stringify(fieldGroup, null, 4), 'utf8'); log('INFO', `Generated SCF field group: ${outputPath}`, { postType, fieldCount: scfFields.length }); }); log('INFO', 'All SCF field groups generated successfully', { groupsGenerated: config.fields.length }); } else { // Old structure: Single field group for main post type (backward compatibility) log('INFO', 'Generating SCF JSON field group (legacy format)'); // Map config fields to SCF field format const scfFields = config.fields.map((field, index) => { const fieldKey = `field_${config.slug}_${field.name}`; const scfField = { key: fieldKey, label: field.label, name: field.name, type: field.type, instructions: field.instructions || '', required: field.required ? 1 : 0, }; // Add optional properties if (field.default_value !== undefined) { scfField.default_value = field.default_value; } if (field.placeholder) { scfField.placeholder = field.placeholder; } if (field.choices) { scfField.choices = field.choices; } if (field.return_format) { scfField.return_format = field.return_format; } if (field.multiple !== undefined) { scfField.multiple = field.multiple ? 1 : 0; } if (field.allow_null !== undefined) { scfField.allow_null = field.allow_null ? 1 : 0; } // Add type-specific properties if (field.type === 'number') { if (field.min !== undefined) scfField.min = field.min; if (field.max !== undefined) scfField.max = field.max; if (field.step !== undefined) scfField.step = field.step; } return scfField; }); // Create the field group const fieldGroup = { key: `group_${config.slug}_fields`, title: `${config.name} Fields`, fields: scfFields, location: [ [ { param: 'post_type', operator: '==', value: config.cpt_slug || config.slug, }, ], ], menu_order: 0, position: 'normal', style: 'default', label_placement: 'top', instruction_placement: 'label', hide_on_screen: [], active: true, }; // Write the JSON file const outputPath = path.join(scfJsonDir, `group_${config.slug}_fields.json`); fs.writeFileSync(outputPath, JSON.stringify(fieldGroup, null, 4), 'utf8'); log('INFO', `Generated SCF field group: ${outputPath}`, { fieldCount: scfFields.length }); } } /** * Format a generated plugin's JavaScript with the WordPress Prettier config. * * Templates hold {{tags}}, which render to values of any length, so line * wrapping can only be settled after rendering. Uses the scaffold's own * Prettier, as the plugin has no node_modules yet. * * @param {string} outputDir Generated plugin directory. */ function formatGeneratedOutput(outputDir) { log('INFO', 'Formatting generated source with the WordPress Prettier config'); execFileSync( process.execPath, [ require.resolve('prettier/bin/prettier.cjs'), '--config', require.resolve('@wordpress/prettier-config'), '--no-editorconfig', '--log-level', 'warn', '--write', 'src/**/*.{js,jsx}', 'test/**/*.js', '*.{js,cjs,mjs}', ], { cwd: outputDir, stdio: 'pipe' } ); } /** * Generate package.json * @param outputDir * @param config */ function generatePackageJson(outputDir, config) { // Field order follows @wordpress/npm-package-json-lint-config, so the // generated plugin passes its own lint:pkg. const packageJson = { name: config.slug, version: config.version, description: config.description, author: config.author, license: config.license, keywords: ['wordpress', 'block-plugin', 'gutenberg'], homepage: config.repository_url, repository: { type: 'git', url: `${config.repository_url}.git` }, bugs: { url: `${config.repository_url}/issues` }, engines: STANDARD_TOOLCHAIN.engines, main: 'build/index.js', dependencies: STANDARD_TOOLCHAIN.dependencies, devDependencies: STANDARD_TOOLCHAIN.devDependencies, scripts: STANDARD_TOOLCHAIN.scripts.all, 'lint-staged': STANDARD_TOOLCHAIN.lintStaged, }; const packagePath = path.join(outputDir, 'package.json'); fs.writeFileSync(packagePath, `${JSON.stringify(packageJson, null, '\t')}\n`, 'utf8'); log('INFO', 'Generated package.json'); return packageJson; } /** * Generate composer.json * @param outputDir * @param config */ function generateComposerJson(outputDir, config) { const composerJson = { name: `${config.namespace}/${config.slug}`, description: config.description, version: config.version, type: 'wordpress-plugin', license: config.license, authors: [ { name: config.author, homepage: config.author_uri || '', }, ], require: { php: `>=${config.requires_php}`, }, 'require-dev': STANDARD_TOOLCHAIN.composer['require-dev'], scripts: STANDARD_TOOLCHAIN.composer.scripts, config: { 'allow-plugins': { 'dealerdirect/phpcodesniffer-composer-installer': true, }, }, }; const composerPath = path.join(outputDir, 'composer.json'); fs.writeFileSync( composerPath, `${JSON.stringify(composerJson, null, '\t')}\n`, 'utf8' ); log('INFO', 'Generated composer.json'); return composerJson; } /** * Composer's content-hash for a composer.json, as Locker::getContentHash() * computes it: the MD5 of the relevant keys, sorted, encoded as PHP's * json_encode() does by default (escaped slashes and non-ASCII characters). * * @param {Object} composerJson Parsed composer.json. * @return {string} The hash. */ function composerContentHash(composerJson) { const relevant = {}; for (const key of [ 'name', 'version', 'require', 'require-dev', 'conflict', 'replace', 'provide', 'minimum-stability', 'prefer-stable', 'repositories', 'extra', ]) { if (key in composerJson) { relevant[key] = composerJson[key]; } } if (composerJson.config?.platform) { relevant.config = { platform: composerJson.config.platform }; } const sorted = Object.fromEntries( Object.keys(relevant) .sort() .map((key) => [key, relevant[key]]) ); const encoded = JSON.stringify(sorted) .replace(/\//g, '\\/') .replace( /[\u007f-\uffff]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}` ); return crypto.createHash('md5').update(encoded).digest('hex'); } /** * Write package-lock.json and composer.lock from the standard toolchain's * lockfiles, with this plugin's name, version and content-hash, so `npm ci` * and `composer install` install the versions proven in ls-test. * * @param {string} outputDir Plugin directory. * @param {Object} packageJson The generated package.json. * @param {Object} composerJson The generated composer.json. */ function generateLockfiles(outputDir, packageJson, composerJson) { const npmLock = JSON.parse(fs.readFileSync(TOOLCHAIN_LOCKFILES.npm, 'utf8')); npmLock.name = packageJson.name; npmLock.version = packageJson.version; Object.assign(npmLock.packages[''], { name: packageJson.name, version: packageJson.version, license: packageJson.license, }); fs.writeFileSync( path.join(outputDir, 'package-lock.json'), // npm keeps package.json's tab indentation in its lockfile. `${JSON.stringify(npmLock, null, '\t')}\n`, 'utf8' ); const composerLock = JSON.parse( fs.readFileSync(TOOLCHAIN_LOCKFILES.composer, 'utf8') ); composerLock['content-hash'] = composerContentHash(composerJson); composerLock.platform = Object.fromEntries( Object.entries(composerJson.require).filter(([name]) => /^(php|ext-|lib-)/.test(name) ) ); fs.writeFileSync( path.join(outputDir, 'composer.lock'), `${JSON.stringify(composerLock, null, 4)}\n`, 'utf8' ); log('INFO', 'Generated package-lock.json and composer.lock'); } /** * Generate README.md * @param outputDir * @param config */ function generateReadme(outputDir, config) { const readme = `# ${config.name} ${config.description} ## Installation 1. Install dependencies: \`\`\`bash composer install npm install \`\`\` 2. Build assets: \`\`\`bash npm run build \`\`\` 3. Activate the plugin in WordPress ## Development Start development mode with file watching: \`\`\`bash npm run start \`\`\` ## Checks \`\`\`bash npm run lint # JavaScript, CSS, package.json, block.json and Markdown npm run test:unit # Vitest composer run lint # PHPCS composer run phpstan # PHPStan \`\`\` ## End-to-end tests Start WordPress (add \`-- --runtime=playground\` if Docker is not available), then run Playwright: \`\`\`bash npm run env:start npm run test:e2e \`\`\` The site runs at . See DEVELOPMENT.md for every command. ## Requirements - WordPress ${config.requires_wp}+ - PHP ${config.requires_php}+ - Node.js 24.18+ (for development) - Secure Custom Fields plugin ## License ${config.license} `; const readmePath = path.join(outputDir, 'README.md'); fs.writeFileSync(readmePath, readme, 'utf8'); log('INFO', 'Generated README.md'); } /** * Generate a fresh CHANGELOG.md for the new plugin. * * The scaffold's own CHANGELOG.md records the scaffold's history, so it is * excluded from the copy and replaced with an initial Keep a Changelog file. * * @param {string} outputDir Output directory path. * @param {Object} config Plugin configuration. */ function generateChangelog(outputDir, config) { const changelog = `# Changelog All notable changes to ${config.name} will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ## [${config.version}] ### Added - Initial release of ${config.name}. `; fs.writeFileSync(path.join(outputDir, 'CHANGELOG.md'), changelog, 'utf8'); log('INFO', 'Generated CHANGELOG.md'); } /** * Load configuration from JSON file * @param filePath */ function loadConfigFile(filePath) { try { const content = fs.readFileSync(filePath, 'utf8'); return JSON.parse(content); } catch (error) { log('ERROR', `Failed to load config file: ${error.message}`); throw new Error(`Config file error: ${error.message}`); } } /** * Show help message */ function showHelp() { console.log(` Multi-Block Plugin Generator Usage: node scripts/generate-plugin.js [options] Options: --config Path to JSON configuration file --validate Validate configuration file without generating --in-place Generate in current directory (template mode) --template Alias for --in-place --force Overwrite existing output directory --output-dir Write to // instead of generated-plugins// --help Show this help message Modes: Generator Mode (default): - Creates plugin in generated-plugins// - Use when generating multiple plugins or experimenting - Keeps scaffold pristine Template Mode (--in-place): - Replaces mustache variables in current directory - Use when creating ONE plugin from a template repo - Modifies files in place Examples: # Generator mode (default) - creates output folder node scripts/generate-plugin.js --config my-plugin.json # Template mode - generates in current directory node scripts/generate-plugin.js --config my-plugin.json --in-place # Validate configuration node scripts/generate-plugin.js --validate my-plugin.json Configuration: See .github/schemas/plugin-config.schema.json for schema See scripts/fixtures/plugin-config.example.json for example `); } /** * Main execution */ async function main() { const args = process.argv.slice(2); // Show help if (args.includes('--help') || args.includes('-h')) { showHelp(); process.exit(0); } // Validate mode const validateIndex = args.indexOf('--validate'); if (validateIndex !== -1) { const configFile = args[validateIndex + 1]; if (!configFile) { console.error('āŒ Error: --validate requires a file path'); process.exit(1); } try { const config = loadConfigFile(configFile); const fullConfig = applyDefaults(config); const validation = validateConfig(fullConfig); if (validation.valid) { console.log('āœ… Configuration is valid'); process.exit(0); } else { console.error('āŒ Configuration validation failed'); process.exit(1); } } catch (error) { console.error(`āŒ Error: ${error.message}`); process.exit(1); } } // Config file mode const configIndex = args.indexOf('--config'); if (configIndex !== -1) { const configFile = args[configIndex + 1]; if (!configFile) { console.error('āŒ Error: --config requires a file path'); showHelp(); process.exit(1); } try { const config = loadConfigFile(configFile); const inPlace = isTemplateMode; // Prompt confirmation for template mode if (inPlace) { console.log('\nāš ļø Template Mode Enabled\n'); console.log( 'This will modify files in the current directory by replacing mustache variables.' ); console.log( 'This action CANNOT be undone without Git or a backup.\n' ); const confirmed = await promptConfirmation( 'Are you sure you want to proceed with in-place generation?' ); if (!confirmed) { console.log('\nāŒ Generation cancelled by user'); log('INFO', 'Template mode generation cancelled by user'); process.exit(0); } } generatePlugin(config, inPlace); process.exit(0); } catch (error) { console.error(`āŒ Error: ${error.message}`); log('ERROR', `Generation failed: ${error.stack}`); process.exit(1); } } // Interactive mode - delegate to agent console.log('šŸ”§ Starting interactive plugin generator...\n'); console.log('For interactive mode, use the agent:'); console.log(' node scripts/generate-plugin.agent.js\n'); console.log('Or provide a configuration file:'); console.log(' node scripts/generate-plugin.js --config my-plugin.json\n'); showHelp(); process.exit(0); } // Export functions for testing if (typeof module !== 'undefined' && module.exports) { module.exports = { sanitizeInput, loadSchema, validateConfig, applyDefaults, applyFilter, replaceMustacheVars, findUnsetTags, generatePlugin, loadConfigFile, composerContentHash, }; } // Run if executed directly if (require.main === module) { main().catch((error) => { console.error(`āŒ Fatal error: ${error.message}`); log('ERROR', `Fatal error: ${error.stack}`); process.exit(1); }); }