#!/usr/bin/env node /* eslint-disable no-console */ import 'dotenv/config'; import { exec } from 'child_process'; import fs from 'fs/promises'; import path from 'path'; import boxen from 'boxen'; import enquirer from 'enquirer'; import kleur from 'kleur'; import ora from 'ora'; import yargs from 'yargs'; import { hideBin } from 'yargs/helpers'; import { provisionThemeMetafields, type ProvisionResult } from '../../lib/metafield/provision.js'; import { pool } from '../../lib/postgres/connection.js'; import { dryRunDiff, installOrUpgrade } from '../../lib/theme/install.js'; import { readManifest, validateManifest, warnUnknownTypes, type Manifest, type ValidationError } from '../../lib/theme/manifest.js'; import { assertValidThemeId } from '../../lib/theme/themeId.js'; import { uploadFile } from '../../modules/cms/services/uploadFile.js'; import { ensureRoutesLoaded } from '../lib/ensureRoutesLoaded.js'; const { prompt } = enquirer; const argv = yargs(hideBin(process.argv)) .option('dry-run', { type: 'boolean', default: false }) .option('content-only', { type: 'boolean', default: false, description: 'Install the theme content but do not change the active theme' }) .option('yes', { alias: 'y', type: 'boolean', default: false, description: 'Skip the post-activation build prompt' }) .help() .parseSync(); function themeDir(id: string): string { return path.join(process.cwd(), 'themes', id); } async function selectTheme(): Promise { const themesDir = path.join(process.cwd(), 'themes'); let themeNames: string[] = []; try { const files = await fs.readdir(themesDir, { withFileTypes: true }); themeNames = files .filter((dirent) => dirent.isDirectory()) .map((dirent) => dirent.name); if (themeNames.length === 0) { console.error(kleur.red('No themes found in themes directory.')); process.exit(1); } } catch (err) { console.error(kleur.red('Error reading themes directory:'), err); process.exit(1); } const response: any = await prompt({ type: 'select', name: 'theme', message: 'Select a theme to activate:', choices: themeNames }); return response.theme; } async function updateConfig(theme: string) { const configDir = path.join(process.cwd(), 'config'); const configPath = path.join(configDir, 'default.json'); try { try { await fs.access(configDir); } catch { await fs.mkdir(configDir, { recursive: true }); } let config: any = {}; try { const configData = await fs.readFile(configPath, 'utf8'); config = JSON.parse(configData); } catch (err: any) { if (err.code !== 'ENOENT') { throw err; } } config.system = config.system || {}; config.system.theme = theme; await fs.writeFile(configPath, JSON.stringify(config, null, 2), 'utf8'); console.log( boxen(kleur.green(`Theme updated to "${theme}" in config/default.json`), { padding: 1, borderColor: 'green' }) ); } catch (err) { console.error(kleur.red('Error updating config:'), err); process.exit(1); } } async function runBuild() { const spinner = ora('Running build...').start(); return new Promise((resolve, reject) => { exec('npm run build', (error, stdout, stderr) => { if (error) { spinner.fail('Build failed'); console.error(stderr); return reject(error); } spinner.succeed('Build completed successfully'); console.log(stdout); return resolve(); }); }); } async function confirmBuild() { // Non-interactive (CI / piped) or `--yes`: never block on a prompt. if (argv.yes || !process.stdin.isTTY) return false; const response: any = await prompt({ type: 'confirm', name: 'runBuild', initial: true, message: 'Would you like to run "npm run build" now?' }); return response.runBuild; } function describe(e: ValidationError): string { const where = e.index !== undefined ? `${e.scope}[${e.index}]` : e.scope; return ` - ${where}: ${e.message}`; } function printValidationErrors(errors: ValidationError[]): void { console.error(kleur.red(`theme.json failed validation (${errors.length}):`)); for (const e of errors) console.error(kleur.red(describe(e))); } function printValidationWarnings(warnings: ValidationError[]): void { for (const w of warnings) console.warn(kleur.yellow(describe(w))); } function printCounts(counts: { widgets_added: number; widgets_updated: number; widgets_removed: number; placements_added: number; placements_updated: number; placements_removed: number; landing_pages_added?: number; landing_pages_updated?: number; }): void { const pagesAdded = counts.landing_pages_added ?? 0; const pagesUpdated = counts.landing_pages_updated ?? 0; console.log( ` Added: ${counts.widgets_added} widgets, ${counts.placements_added} placements` + (pagesAdded > 0 ? `, ${pagesAdded} landing pages` : '') ); console.log( ` Updated: ${counts.widgets_updated} widgets, ${counts.placements_updated} placements` + (pagesUpdated > 0 ? `, ${pagesUpdated} landing pages` : '') ); console.log( ` Removed: ${counts.widgets_removed} widgets, ${counts.placements_removed} placements` ); } function printProvisionResult(result: ProvisionResult): void { if ( result.seeded.length + result.adopted.length + result.retired.length > 0 ) { console.log( ` Metafields: ${result.seeded.length} seeded, ` + `${result.adopted.length} adopted, ${result.retired.length} retired` ); for (const ref of result.retired) { console.log( kleur.dim( ` retired '${ref}' — no longer declared by the manifest ` + `(definition left in place; still visible in entity forms)` ) ); } } if (result.conflicts.length > 0) { console.log( kleur.yellow(` Metafield conflicts: ${result.conflicts.length} (declaration skipped, existing definition kept):`) ); for (const c of result.conflicts) { for (const d of c.details) { console.log( kleur.yellow( ` ${c.ref}: ${d.field} declared=${JSON.stringify(d.declared)} ` + `existing=${JSON.stringify(d.incumbent)} — immutable; use a new key` ) ); } } } for (const w of result.warnings) { console.warn(kleur.yellow(` metafield: ${w.message}`)); } for (const e of result.errors) { console.error(kleur.red(` metafield: ${e.message}`)); } } /** * Run the manifest install pipeline (validate → soft-warn → dry-run|apply). * Returns false to abort activation (validation failure), true to proceed. */ async function runInstallPipeline( themeId: string, manifest: Manifest ): Promise { const found = await validateManifest(manifest, { themeId, pool }); const errors = found.filter((e) => e.severity !== 'warning'); printValidationWarnings(found.filter((e) => e.severity === 'warning')); if (errors.length > 0) { printValidationErrors(errors); return false; } // Soft warning for never-before-seen widget types (non-blocking). const known = new Set( (await pool.query<{ type: string }>(`SELECT DISTINCT type FROM widget_instance`)).rows.map( (r) => r.type ) ); warnUnknownTypes(manifest, known, (m) => console.warn(kleur.yellow(m))); if (argv['dry-run']) { const diff = await dryRunDiff(themeId, manifest, pool); if (!diff) { console.log( kleur.bold( `Dry run — '${themeId}' is not yet installed; activation would do a ` + `fresh install of ${manifest.widgets.length} widgets, ` + `${manifest.placements.length} placements` + (manifest.landingPages?.length ? `, ${manifest.landingPages.length} landing pages` : '') + `.` ) ); } else { console.log(kleur.bold(`Dry run — pending changes for '${themeId}':`)); printCounts(diff.counts); console.log(` Conflicts: ${diff.conflicts.length}`); for (const p of diff.releasedLandingPages ?? []) { console.log( kleur.dim( ` landing page '${p.name}' would be released (row kept, theme widgets removed)` ) ); } } const declared = manifest.metafieldDefinitions?.length ?? 0; if (declared > 0) { console.log( ` Metafield definitions declared: ${declared} (ensured on ` + `activation and at every server boot — not part of the content diff)` ); } return false; // dry run never proceeds to config write } // Uploading a theme's assets goes through the store's storage provider, and // the LOCAL provider builds its public URL from the `staticAsset` route // (`/assets/*`). A CLI has no app, so the route registry is empty and // `buildUrl` throws. Load the routes the same way `evershop build` does — // module metadata only, no database, no bootstrap. ensureRoutesLoaded(); const result = await installOrUpgrade({ themeId, manifest, pool, themeDir: themeDir(themeId), // The store's configured provider, not the local disk: `uploadFile` reads // the `fileStorage` setting (config fallback), so a theme's images land in // the same bucket as everything the merchant uploads. uploadAsset: (files, destination) => uploadFile(files as unknown as Express.Multer.File[], destination) }); if (result.storeRefs) { const rows = result.storeRefs.resolved; const exact = rows.filter((r) => r.match === 'exact').length; const byName = rows.filter((r) => r.match === 'name'); const unresolved = rows.filter((r) => r.match === 'unresolved'); console.log( ` Store references: ${rows.length} (${exact} matched exactly` + `${byName.length > 0 ? `, ${byName.length} by name` : ''}` + `${unresolved.length > 0 ? `, ${unresolved.length} unmatched` : ''})` ); for (const r of byName) { console.log( kleur.yellow( ` matched by name: ${r.entity} '${r.key}' → ${r.value}` ) ); } if (unresolved.length > 0) { console.warn( kleur.yellow( ` These widgets have nothing to show until the data exists — ` + `activation never creates it. Pick a replacement in the page builder, ` + `or add the ${unresolved.length === 1 ? 'record' : 'records'} and re-activate:` ) ); for (const r of unresolved) { console.warn(kleur.yellow(` ${r.entity} ${r.by}='${r.key}' not found`)); } } } if (result.assets) { const { uploaded, missing } = result.assets; if (uploaded.length > 0) { console.log( kleur.green( ` Uploaded ${uploaded.length} theme asset${uploaded.length === 1 ? '' : 's'} to file storage.` ) ); } if (missing.length > 0) { console.warn( kleur.yellow( ` ${missing.length} declared asset${missing.length === 1 ? ' is' : 's are'} missing from ` + `themes/${themeId}/public/ and ${missing.length === 1 ? 'was' : 'were'} not uploaded:` ) ); for (const m of missing) console.warn(kleur.yellow(` ${m}`)); } } if (result.command === 'rejected') { console.error( kleur.red(`Refusing to activate '${themeId}': ${result.rejectedReason}`) ); return false; } if (result.command === 'no-op') { console.log(kleur.green(`'${themeId}' content already up to date.`)); if (result.contentDriftAtSameVersion) { console.warn( kleur.yellow( ` Note: theme.json content differs from what's installed, but ` + `version ${manifest.version} is unchanged — bump the version to ` + `apply the changes.` ) ); } } else { console.log( kleur.green( `${result.command === 'install' ? 'Installed' : 'Upgraded'} ` + `'${themeId}' (version ${manifest.version}).` ) ); printCounts(result.counts); if ( result.adopted && (result.adopted.widgets > 0 || result.adopted.placements > 0 || result.adopted.landingPages > 0) ) { console.log( kleur.dim( ` Adopted: ${result.adopted.widgets} widgets, ${result.adopted.placements} placements` + (result.adopted.landingPages > 0 ? `, ${result.adopted.landingPages} landing pages` : '') + ` already in the DB (left unchanged — recorded as the install baseline).` ) ); } if (result.releasedLandingPages?.length) { console.log( kleur.yellow( ` Landing pages no longer shipped by this theme (${result.releasedLandingPages.length}) — ` + `their rows were LEFT IN PLACE and are now empty:` ) ); for (const p of result.releasedLandingPages) { console.log(kleur.yellow(` '${p.name}' (${p.uuid})`)); } } if (result.conflicts.length > 0) { console.log( kleur.yellow( ` Conflicts: ${result.conflicts.length} (your customizations preserved):` ) ); for (const c of result.conflicts) { console.log( kleur.yellow( ` widget ${c.widget_uuid} field ${c.field_path}: ` + `manifest=${JSON.stringify(c.manifest_value)} kept=${JSON.stringify( c.user_value )}` ) ); } } } // Metafield definitions ensure — its own step and transaction, AFTER the // installer: three installer branches commit-and-return early (fresh // install, rejected, no-op) and the ensure must run on every outcome // except a rejected downgrade. Idempotent; also re-runs at server boot. const provision = await provisionThemeMetafields( themeId, manifest.metafieldDefinitions ?? [], pool ); printProvisionResult(provision); return true; } async function activateTheme() { const themeId = assertValidThemeId( argv._[1] != null ? String(argv._[1]) : await selectTheme() ); // The theme directory must exist before we touch anything. A non-existent // id (a typo, or a flag like `--content-only` mis-parsed as the id when args // aren't passed after `--`) must NEVER reach `updateConfig` — writing a // bogus `config.system.theme` breaks the server on its next start. try { await fs.access(themeDir(themeId)); } catch { console.error( kleur.red( `Theme '${themeId}' not found — there is no directory at ${themeDir( themeId )}. Check the name (and, with npm, pass args after \`--\`: ` + `\`npm run theme:active -- ${themeId} --content-only\`).` ) ); process.exit(1); } const manifest = await readManifest(themeDir(themeId)); if (manifest === null) { console.log( kleur.dim( `No theme.json for '${themeId}' — presentation-only theme, no content to install.` ) ); } else { const proceed = await runInstallPipeline(themeId, manifest); if (!proceed) { // Validation failure or dry run — don't change the active theme. process.exit(argv['dry-run'] ? 0 : 1); } } // `--content-only`: install the content but leave the active theme alone // (CI provisioning + e2e). Skips the config write + build. if (argv['content-only']) { console.log( kleur.dim(`Content installed for '${themeId}' (active theme unchanged).`) ); return; } await updateConfig(themeId); const shouldBuild = await confirmBuild(); if (shouldBuild) { await runBuild(); } else { console.log( kleur.yellow('Remember to run "npm run build" later to apply changes.') ); } } activateTheme() .then(() => process.exit(0)) .catch((err) => { console.error(kleur.red('An error occurred:'), err); process.exit(1); });