Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

fix(power-pages): unify template preview schema (#859)

Priyanshu Agrawal198d91b94abc
diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.md
index cd2747f01..5e9bf350c 100644
--- a/plugins/power-pages/AGENTS.md
+++ b/plugins/power-pages/AGENTS.md
@@ -14,6 +14,17 @@ Add offline Vally suites under `evals/power-pages/<skill>/` as individual skills
Use synthetic fixtures and contained local artifacts; live environment access is outside these evaluations.
Production plugin installs do not include the repository's evaluation runtime.
+## Template catalog previews
+
+SPA and non-SPA catalog entries use `responsivePreviews`: page records with `id`, `displayName`, `desktop`, and `mobile`.
+Preserve page identity and device pairs through artifact caching, the template browser, and creation-status rendering.
+For older SPA manifests, use `previewImages` only when `responsivePreviews` is absent; an explicit empty array stays empty.
+A SPA variant's own preview definition overrides its family's, including a legacy variant list.
+Inherit family previews only when the variant defines neither field.
+Keep this precedence in `scripts/lib/template-catalog.js`; create-site caches the effective variant previews before rendering and reuses them on the status page.
+The read-only browser shows each framework's effective previews in a labeled group within the family tab.
+The non-SPA experience-preview disclosure in `references/non-spa-preview.md` is separate and unchanged.
+
## Non-SPA creation and shared design quality
`scripts/telemetry-config.js` delegates preference changes to the bundled shared CLI and adds the non-SPA creation disclosure.
diff --git a/plugins/power-pages/scripts/lib/template-catalog.js b/plugins/power-pages/scripts/lib/template-catalog.js
index c4c700cc8..e1a7b5d5c 100644
--- a/plugins/power-pages/scripts/lib/template-catalog.js
+++ b/plugins/power-pages/scripts/lib/template-catalog.js
@@ -236,6 +236,22 @@ function assertValidSha(sha) {
}
}
+function validateResponsivePreviews(previews, context) {
+ if (!Array.isArray(previews)) return `${context} responsivePreviews must be an array`;
+ const ids = new Set();
+ for (const preview of previews) {
+ if (!preview || typeof preview !== 'object' || Array.isArray(preview)) {
+ return `${context} responsive preview must be an object`;
+ }
+ for (const field of ['id', 'displayName', 'desktop', 'mobile']) {
+ if (!isNonEmptyString(preview[field])) return `${context} responsive preview missing string field: ${field}`;
+ }
+ if (ids.has(preview.id)) return `${context} has duplicate responsive preview id: ${preview.id}`;
+ ids.add(preview.id);
+ }
+ return null;
+}
+
function validateCatalogShape(catalog) {
// Raw `templates/manifest.json` shape:
// { "$schema": "./schemas/templates-manifest.schema.json", "templates": [
@@ -244,7 +260,9 @@ function validateCatalogShape(catalog) {
// "keywords": ["311", "citizen-services"],
// "audience": ["makers", "developers"],
// "requiredDataverseLanguages": [1033],
- // "previewImages": ["spa/311-portal/previews/home.png"],
+ // "responsivePreviews": [{ "id": "home", "displayName": "Home",
+ // "desktop": "spa/311-portal/previews/desktop-home.png",
+ // "mobile": "spa/311-portal/previews/mobile-home.png" }],
// "seedDataPath": "spa/311-portal/seed/data.json",
// "author": "Microsoft" }
// ] }
@@ -280,6 +298,10 @@ function validateCatalogShape(catalog) {
if (!Array.isArray(template.keywords)) return `template ${template.id} keywords must be an array`;
const solutionSettingsError = validateSolutionSettings(template.solutions, template.id);
if (solutionSettingsError) return solutionSettingsError;
+ if (template.responsivePreviews !== undefined) {
+ const error = validateResponsivePreviews(template.responsivePreviews, `template ${template.id}`);
+ if (error) return error;
+ }
if (isCreateWebsiteApiTemplate(template)) {
if (!isNonEmptyString(template.provisioning.templateName)) {
return `template ${template.id} provisioning.templateName must be a non-empty string`;
@@ -287,19 +309,6 @@ function validateCatalogShape(catalog) {
for (const field of ['capabilities', 'requirements', 'responsivePreviews']) {
if (!Array.isArray(template[field])) return `template ${template.id} ${field} must be an array`;
}
- const previewIds = new Set();
- for (const preview of template.responsivePreviews) {
- if (!preview || typeof preview !== 'object' || Array.isArray(preview)) {
- return `template ${template.id} responsive preview must be an object`;
- }
- for (const field of ['id', 'displayName', 'desktop', 'mobile']) {
- if (!isNonEmptyString(preview[field])) {
- return `template ${template.id} responsive preview missing string field: ${field}`;
- }
- }
- if (previewIds.has(preview.id)) return `template ${template.id} has duplicate responsive preview id: ${preview.id}`;
- previewIds.add(preview.id);
- }
for (const field of ['previewImages', 'requiredDataverseLanguages', 'seedDataPath', 'variants']) {
if (template[field] !== undefined) return `template ${template.id} create-website-api must not define ${field}`;
}
@@ -311,9 +320,12 @@ function validateCatalogShape(catalog) {
) {
return `template ${template.id} requiredDataverseLanguages must be a non-empty array of positive integers`;
}
- if (!Array.isArray(template.previewImages)) {
+ if (template.previewImages !== undefined && !Array.isArray(template.previewImages)) {
return `template ${template.id} previewImages must be an array`;
}
+ if (template.responsivePreviews === undefined && template.previewImages === undefined) {
+ return `template ${template.id} responsivePreviews or previewImages must be an array`;
+ }
}
if (isNestedFamilyTemplate(template)) {
const seenFrameworks = new Set();
@@ -334,6 +346,10 @@ function validateCatalogShape(catalog) {
if (variant.previewImages !== undefined && !Array.isArray(variant.previewImages)) {
return `template ${template.id} variant ${framework} previewImages must be an array`;
}
+ if (variant.responsivePreviews !== undefined) {
+ const error = validateResponsivePreviews(variant.responsivePreviews, `template ${template.id} variant ${framework}`);
+ if (error) return error;
+ }
if (
variant.requiredDataverseLanguages !== undefined &&
(
@@ -364,6 +380,22 @@ function resolveCatalogArtifactPath(catalogPath, artifactPath) {
return `${base}/${artifactPath.replace(/^\/+/, '')}`;
}
+function materializeResponsivePreviews(previews, catalogPath) {
+ return previews.map((preview) => ({
+ ...preview,
+ desktop: resolveCatalogArtifactPath(catalogPath, preview.desktop),
+ mobile: resolveCatalogArtifactPath(catalogPath, preview.mobile),
+ }));
+}
+
+function effectivePreviewFields(source, fallback) {
+ // A variant's legacy list still overrides family previews during migration.
+ // Explicit empty lists mean no previews, not permission to inherit another list.
+ if (source.responsivePreviews !== undefined) return { responsivePreviews: source.responsivePreviews };
+ if (source.previewImages !== undefined) return { previewImages: source.previewImages };
+ return fallback ? effectivePreviewFields(fallback) : { previewImages: [] };
+}
+
function materializeCatalogArtifactPaths(catalog, catalogPath) {
return {
...catalog,
@@ -382,11 +414,7 @@ function materializeCatalogArtifactPaths(catalog, catalogPath) {
} : {}),
};
if (Array.isArray(template.responsivePreviews)) {
- materialized.responsivePreviews = template.responsivePreviews.map((preview) => ({
- ...preview,
- desktop: resolveCatalogArtifactPath(catalogPath, preview.desktop),
- mobile: resolveCatalogArtifactPath(catalogPath, preview.mobile),
- }));
+ materialized.responsivePreviews = materializeResponsivePreviews(template.responsivePreviews, catalogPath);
}
if (template.seedDataPath) {
materialized.seedDataPath = resolveCatalogArtifactPath(catalogPath, template.seedDataPath);
@@ -397,6 +425,9 @@ function materializeCatalogArtifactPaths(catalog, catalogPath) {
if (Array.isArray(variant.previewImages)) {
materializedVariant.previewImages = variant.previewImages.map((imagePath) => resolveCatalogArtifactPath(catalogPath, imagePath));
}
+ if (Array.isArray(variant.responsivePreviews)) {
+ materializedVariant.responsivePreviews = materializeResponsivePreviews(variant.responsivePreviews, catalogPath);
+ }
if (variant.seedDataPath) {
materializedVariant.seedDataPath = resolveCatalogArtifactPath(catalogPath, variant.seedDataPath);
}
@@ -420,7 +451,7 @@ function normalizeCatalogFamilies(catalog = {}) {
keywords: template.keywords || [],
audience: template.audience || [],
requiredDataverseLanguages: template.requiredDataverseLanguages || [],
- previewImages: template.previewImages || [],
+ ...effectivePreviewFields(template),
...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),
...(template.solutions?.length ? { solutions: template.solutions } : {}),
author: template.author,
@@ -435,7 +466,7 @@ function normalizeCatalogFamilies(catalog = {}) {
keywords: template.keywords || [],
audience: template.audience || [],
requiredDataverseLanguages: template.requiredDataverseLanguages || [],
- previewImages: template.previewImages || [],
+ ...effectivePreviewFields(template),
...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),
...(template.solutions?.length ? { solutions: template.solutions } : {}),
author: template.author,
@@ -450,7 +481,7 @@ function normalizeCatalogFamilies(catalog = {}) {
keywords: template.keywords || [],
audience: template.audience || [],
requiredDataverseLanguages: template.requiredDataverseLanguages || [],
- previewImages: template.previewImages || [],
+ ...effectivePreviewFields(template),
...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),
...(template.solutions?.length ? { solutions: template.solutions } : {}),
author: template.author,
@@ -467,7 +498,7 @@ function normalizeCatalogFamilies(catalog = {}) {
keywords: template.keywords || [],
audience: template.audience || [],
requiredDataverseLanguages: variant.requiredDataverseLanguages || template.requiredDataverseLanguages || [],
- previewImages: Array.isArray(variant.previewImages) ? variant.previewImages : (template.previewImages || []),
+ ...effectivePreviewFields(variant, template),
...(variant.seedDataPath || template.seedDataPath ? { seedDataPath: variant.seedDataPath || template.seedDataPath } : {}),
...(template.solutions?.length ? { solutions: template.solutions } : {}),
author: template.author,
@@ -1254,6 +1285,8 @@ module.exports = {
validateTemplateVariantDirectory,
validateCatalogShape,
normalizeCatalogFamilies,
+ effectivePreviewFields,
+ validateResponsivePreviews,
isSpaTemplate,
isCreateWebsiteApiTemplate,
zipFileNames,
diff --git a/plugins/power-pages/scripts/render-template-browser.js b/plugins/power-pages/scripts/render-template-browser.js
index cd949f405..5f78bd88d 100644
--- a/plugins/power-pages/scripts/render-template-browser.js
+++ b/plugins/power-pages/scripts/render-template-browser.js
@@ -5,6 +5,7 @@ const fs = require('fs');
const path = require('path');
const { renderTemplate, escapeHtml, escapeHtmlAttribute } = require('./lib/render-template');
const { openInDefaultBrowser } = require('./lib/default-browser');
+const { effectivePreviewFields } = require('./lib/template-catalog');
// Accepted argv shape:
// --templatesJsonPath /tmp/templates.json --outputPath /tmp/browser.html [--open]
@@ -32,11 +33,12 @@ function renderKeywordChips(keywords) {
}
function renderPreviewImages(template) {
- const images = Array.isArray(template.previews)
- ? template.previews.flatMap((preview) => [
+ const previews = template.responsivePreviews ?? template.previews;
+ const images = Array.isArray(previews)
+ ? previews.flatMap((preview) => [
{ url: preview.desktop, label: `${preview.displayName} - desktop` },
{ url: preview.mobile, label: `${preview.displayName} - mobile` },
- ])
+ ]).filter((image) => image.url)
: (Array.isArray(template.previewImages)
? template.previewImages.map((url, index) => ({ url, label: `Preview ${index + 1}` }))
: []);
@@ -94,6 +96,22 @@ function renderFrameworkVariants(template) {
`;
}
+function renderTemplatePreviews(template) {
+ const variants = template.kind === 'non-spa' ? [] : normalizeVariants(template);
+ if (variants.length === 0) return renderPreviewImages(template);
+ return variants.map((variant) => `
+ <div class="variant-previews">
+ <div class="field-label">${escapeHtml(frameworkLabel(variant.framework))}</div>
+ <div class="preview-stack">
+ ${renderPreviewImages({
+ displayName: template.displayName,
+ ...effectivePreviewFields(variant, template),
+ })}
+ </div>
+ </div>
+ `).join('');
+}
+
function templateTabId(index) {
return `template-${index + 1}`;
}
@@ -131,7 +149,7 @@ function renderTemplateSectionsHtml(templates) {
<p class="template-desc">${escapeHtml(template.description)}</p>
<div class="field-label previews-label">Previews</div>
<div class="preview-stack">
- ${renderPreviewImages(template)}
+ ${renderTemplatePreviews(template)}
</div>
</section>
`).join('');
diff --git a/plugins/power-pages/scripts/render-template-import-status.js b/plugins/power-pages/scripts/render-template-import-status.js
index 8d0ae647f..7de7c4dc1 100644
--- a/plugins/power-pages/scripts/render-template-import-status.js
+++ b/plugins/power-pages/scripts/render-template-import-status.js
@@ -6,6 +6,7 @@ const path = require('path');
const { fileURLToPath, pathToFileURL } = require('url');
const { renderTemplate } = require('./lib/render-template');
const { openInDefaultBrowser } = require('./lib/default-browser');
+const { validateResponsivePreviews } = require('./lib/template-catalog');
const LOCAL_PREVIEW_SIGNATURES = {
'.png': Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
@@ -21,6 +22,7 @@ function parseArgs(argv) {
else if (argv[i] === '--statusPath') args.statusPath = argv[++i];
else if (argv[i] === '--outputPath') args.outputPath = argv[++i];
else if (argv[i] === '--previewImagesJson') args.previewImages = JSON.parse(argv[++i] || '[]');
+ else if (argv[i] === '--responsivePreviewsJson') args.responsivePreviews = JSON.parse(argv[++i] || '[]');
else if (argv[i] === '--solutionCount') args.solutionCount = Number(argv[++i]);
else if (argv[i] === '--open') args.open = true;
}
@@ -76,12 +78,12 @@ function toDataUrl(filePath) {
return `data:image/png;base64,${fs.readFileSync(filePath).toString('base64')}`;
}
-function buildModel({ templateName, templateDescription, statusPath, outputPath, previewImages, solutionCount }) {
+function buildModel({ templateName, templateDescription, statusPath, outputPath, previewImages = [], responsivePreviews, solutionCount }) {
const statusUrl = path.dirname(path.resolve(statusPath)) === path.dirname(path.resolve(outputPath))
? path.basename(statusPath)
: pathToFileURL(path.resolve(statusPath)).href;
const previewGroups = new Map();
- for (let index = 0; index < previewImages.length; index++) {
+ for (let index = 0; responsivePreviews === undefined && index < previewImages.length; index++) {
const image = previewImages[index];
const url = previewImageUrl(image, index, path.dirname(path.resolve(outputPath)));
if (!url) continue;
@@ -109,7 +111,18 @@ function buildModel({ templateName, templateDescription, statusPath, outputPath,
const device = deviceMatch ? deviceMatch[1].toLowerCase() : 'desktop';
preview[device] = url;
}
- const previews = [...previewGroups.values()];
+ let previews = [...previewGroups.values()];
+ if (responsivePreviews !== undefined) {
+ const error = validateResponsivePreviews(responsivePreviews, 'Import status');
+ if (error) throw new Error(error);
+ const outputDir = path.dirname(path.resolve(outputPath));
+ previews = responsivePreviews.map((preview, index) => ({
+ name: preview.id,
+ displayName: preview.displayName,
+ desktop: previewImageUrl(preview.desktop, index * 2, outputDir),
+ mobile: previewImageUrl(preview.mobile, index * 2 + 1, outputDir),
+ })).filter((preview) => preview.desktop || preview.mobile);
+ }
const pluralSolutions = solutionCount > 1;
const pluginRoot = path.resolve(__dirname, '..');
@@ -181,11 +194,12 @@ function renderTemplateImportStatus({
statusPath,
outputPath,
previewImages = [],
+ responsivePreviews,
solutionCount = 1,
open = false,
}, deps = {}) {
if (!templateName || !statusPath || !outputPath) {
- throw new Error('Usage: render-template-import-status.js --templateName <name> --statusPath <path> --outputPath <path> [--templateDescription <description>] [--previewImagesJson <json>] [--solutionCount <count>] [--open]');
+ throw new Error('Usage: render-template-import-status.js --templateName <name> --statusPath <path> --outputPath <path> [--templateDescription <description>] [--responsivePreviewsJson <json> | --previewImagesJson <json>] [--solutionCount <count>] [--open]');
}
if (!Number.isSafeInteger(solutionCount) || solutionCount < 1) {
throw new Error('solutionCount must be a positive integer');
@@ -198,7 +212,7 @@ function renderTemplateImportStatus({
'assets',
'non-spa-creation-status-template.html',
);
- const model = buildModel({ templateName, templateDescription, statusPath, outputPath, previewImages, solutionCount });
+ const model = buildModel({ templateName, templateDescription, statusPath, outputPath, previewImages, responsivePreviews, solutionCount });
// Unlike the standalone non-SPA page, SPA import is served over HTTP and polls
// a same-origin JSON feed. Allow its local images/feed plus only the explicit
// remote preview origins, while retaining default-src 'none' and nonce scripts.
diff --git a/plugins/power-pages/scripts/tests/render-template-browser.test.js b/plugins/power-pages/scripts/tests/render-template-browser.test.js
index eb18141ee..af8ab03d2 100644
--- a/plugins/power-pages/scripts/tests/render-template-browser.test.js
+++ b/plugins/power-pages/scripts/tests/render-template-browser.test.js
@@ -5,6 +5,7 @@ const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
+const { normalizeCatalogFamilies } = require('../lib/template-catalog');
const {
parseArgs,
@@ -16,6 +17,92 @@ function tempDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'template-browser-test-'));
}
+for (const emptyFamily of [true, false]) {
+ test(`nested SPA browser honors variant preview overrides with ${emptyFamily ? 'empty' : 'nonempty'} family previews`, (t) => {
+ const dir = tempDir();
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const pair = (name) => [{
+ id: name, displayName: `${name} page`,
+ desktop: `https://example.test/${name}-wide.png`,
+ mobile: `https://example.test/${name}-narrow.png`,
+ }];
+ const template = {
+ id: 'supplier-portal', displayName: 'Supplier Portal', kind: 'spa',
+ description: 'Supplier invoice portal', keywords: [],
+ responsivePreviews: emptyFamily ? [] : pair('family'),
+ previewImages: ['https://example.test/ignored-family.png'],
+ variants: {
+ react: {},
+ vue: { responsivePreviews: pair('vue'), previewImages: ['https://example.test/ignored-vue.png'] },
+ angular: { previewImages: ['https://example.test/angular-legacy.png'] },
+ astro: emptyFamily ? { responsivePreviews: [] } : { previewImages: [] },
+ },
+ };
+ for (const [shape, family] of [
+ ['raw', template],
+ ['normalized', normalizeCatalogFamilies({ templates: [template] })[0]],
+ ]) {
+ const templatesJsonPath = path.join(dir, `${shape}.json`);
+ const outputPath = path.join(dir, `${shape}.html`);
+ fs.writeFileSync(templatesJsonPath, JSON.stringify({ TEMPLATES_JSON: [family] }));
+ assert.equal(renderTemplateBrowser({ templatesJsonPath, outputPath }).status, 'ok');
+ const html = fs.readFileSync(outputPath, 'utf8');
+ assert.match(html, /vue-wide\.png/);
+ assert.match(html, /vue-narrow\.png/);
+ assert.match(html, /angular-legacy\.png/);
+ const groups = html.split('<div class="variant-previews">').slice(1);
+ assert.equal(groups.length, 4);
+ const [react, vue, angular, astro] = groups;
+ assert.match(react, /class="field-label">React</);
+ assert.match(vue, /class="field-label">Vue</);
+ assert.match(vue, /vue page - desktop/);
+ assert.match(vue, /vue-wide\.png/);
+ assert.match(vue, /vue-narrow\.png/);
+ assert.doesNotMatch(vue, /family-wide\.png|ignored-vue/);
+ assert.match(angular, /class="field-label">Angular</);
+ assert.match(angular, /angular-legacy\.png/);
+ assert.doesNotMatch(angular, /family-wide\.png/);
+ assert.match(astro, /class="field-label">Astro</);
+ assert.match(astro, /No preview image yet/);
+ assert.doesNotMatch(astro, /family-wide\.png/);
+ if (emptyFamily) assert.match(react, /No preview image yet/);
+ else {
+ assert.match(react, /family-wide\.png/);
+ assert.match(react, /family-narrow\.png/);
+ }
+ assert.doesNotMatch(html, /ignored-family|ignored-vue/);
+ assert.doesNotMatch(html, /data-tab="template-2"/);
+ }
+ });
+}
+
+test('SPA browser uses responsive page labels and pairs ahead of legacy images', (t) => {
+ const dir = tempDir();
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const dataPath = path.join(dir, 'templates.json');
+ const outputPath = path.join(dir, 'browser.html');
+ const template = {
+ displayName: '311 Portal', kind: 'spa', framework: 'react',
+ previewImages: ['https://legacy.example/ignored.png'],
+ responsivePreviews: [{
+ id: 'requests', displayName: 'Service <requests>',
+ desktop: 'https://example.com/wide.png', mobile: 'https://example.com/narrow.png',
+ }],
+ };
+ fs.writeFileSync(dataPath, JSON.stringify({ TEMPLATES_JSON: [template] }));
+ assert.equal(renderTemplateBrowser({ templatesJsonPath: dataPath, outputPath }).status, 'ok');
+ const html = fs.readFileSync(outputPath, 'utf8');
+ assert.match(html, /Service &lt;requests&gt; - desktop/);
+ assert.match(html, /Service &lt;requests&gt; - mobile/);
+ assert.match(html, /wide\.png/);
+ assert.match(html, /narrow\.png/);
+ assert.doesNotMatch(html, /legacy\.example/);
+ fs.writeFileSync(dataPath, JSON.stringify({ TEMPLATES_JSON: [{ ...template, responsivePreviews: [] }] }));
+ const emptyPath = path.join(dir, 'empty.html');
+ renderTemplateBrowser({ templatesJsonPath: dataPath, outputPath: emptyPath });
+ assert.match(fs.readFileSync(emptyPath, 'utf8'), /No preview image yet/);
+});
+
test('parseArgs accepts templates JSON, output path, and open switch', () => {
assert.deepEqual(parseArgs([
'--templatesJsonPath', '/tmp/templates.json',
diff --git a/plugins/power-pages/scripts/tests/render-template-import-status.test.js b/plugins/power-pages/scripts/tests/render-template-import-status.test.js
index 401bf64dc..5b76b1de7 100644
--- a/plugins/power-pages/scripts/tests/render-template-import-status.test.js
+++ b/plugins/power-pages/scripts/tests/render-template-import-status.test.js
@@ -18,6 +18,52 @@ function tempDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'template-import-status-test-'));
}
+test('create-site forwards the selected variant structured previews with a legacy CLI fallback', () => {
+ const skill = fs.readFileSync(path.join(__dirname, '../../skills/create-site/SKILL.md'), 'utf8');
+ assert.match(skill, /each SPA family and variant, prefer `responsivePreviews` when present/);
+ assert.match(skill, /preserving the page's `id` and `displayName`/);
+ assert.match(skill, /variant defines neither field/);
+ assert.match(skill, /--responsivePreviewsJson '<JSON array of SELECTED_TEMPLATE_VARIANT\.responsivePreviews/);
+ assert.match(skill, /replace `--responsivePreviewsJson` with `--previewImagesJson`/);
+});
+
+test('structured SPA previews keep explicit page identity and device pairing through the CLI', (t) => {
+ const dir = tempDir();
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const desktop = path.join(dir, 'wide.png');
+ const mobile = path.join(dir, 'narrow.png');
+ const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
+ fs.writeFileSync(desktop, png);
+ fs.writeFileSync(mobile, png);
+ const responsivePreviews = [{
+ id: 'service-requests', displayName: 'Service requests',
+ desktop, mobile,
+ }];
+ const outputPath = path.join(dir, 'status', 'index.html');
+ const args = parseArgs([
+ '--templateName', '311 Portal',
+ '--statusPath', path.join(dir, 'status', 'status.json'),
+ '--outputPath', outputPath,
+ '--responsivePreviewsJson', JSON.stringify(responsivePreviews),
+ '--previewImagesJson', '["https://legacy.example/ignored.png"]',
+ ]);
+ assert.deepEqual(args.responsivePreviews, responsivePreviews);
+ const model = buildModel(args);
+ assert.deepEqual(model.template.previews, [{
+ name: 'service-requests', displayName: 'Service requests',
+ desktop: 'preview-images/preview-01.png',
+ mobile: 'preview-images/preview-02.png',
+ }]);
+ assert.deepEqual(fs.readFileSync(path.join(dir, 'status', model.template.previews[0].desktop)), png);
+ assert.deepEqual(fs.readFileSync(path.join(dir, 'status', model.template.previews[0].mobile)), png);
+ assert.equal(renderTemplateImportStatus(args).status, 'ok');
+ const html = fs.readFileSync(outputPath, 'utf8');
+ assert.match(html, /"name":"service-requests","displayName":"Service requests"/);
+ assert.doesNotMatch(html, /legacy\.example/);
+ assert.deepEqual(buildModel({ ...args, responsivePreviews: [] }).template.previews, []);
+ assert.throws(() => buildModel({ ...args, responsivePreviews: [{}] }), /missing string field/);
+});
+
test('parseArgs accepts import status page inputs', () => {
assert.deepEqual(parseArgs([
'--templateName', 'Supplier Portal',
diff --git a/plugins/power-pages/scripts/tests/template-catalog.test.js b/plugins/power-pages/scripts/tests/template-catalog.test.js
index 8082e03b6..256e45a01 100644
--- a/plugins/power-pages/scripts/tests/template-catalog.test.js
+++ b/plugins/power-pages/scripts/tests/template-catalog.test.js
@@ -92,6 +92,93 @@ const VALID_TRADITIONAL_TEMPLATE_FAMILY = {
},
};
+const RESPONSIVE_PREVIEWS = [{
+ id: 'requests',
+ displayName: 'Service requests',
+ desktop: 'spa/company-portal/previews/wide.png',
+ mobile: 'spa/company-portal/previews/narrow.png',
+}];
+
+test('SPA responsive previews validate without legacy images and reject malformed pages', () => {
+ const { previewImages, ...template } = VALID_TEMPLATE;
+ const validate = (responsivePreviews) => validateCatalogShape({
+ templates: [{ ...template, responsivePreviews }],
+ });
+ assert.equal(validate(RESPONSIVE_PREVIEWS), null);
+ assert.equal(validate([]), null);
+ assert.match(validate(null), /responsivePreviews must be an array/);
+ assert.match(validate([null]), /responsive preview must be an object/);
+ for (const field of ['id', 'displayName', 'desktop', 'mobile']) {
+ assert.match(validate([{ ...RESPONSIVE_PREVIEWS[0], [field]: '' }]), new RegExp(`missing string field: ${field}`));
+ }
+ assert.match(validate([...RESPONSIVE_PREVIEWS, ...RESPONSIVE_PREVIEWS]), /duplicate responsive preview id/);
+ assert.match(validateCatalogShape({ templates: [template] }), /responsivePreviews or previewImages/);
+ assert.match(validateCatalogShape({
+ templates: [{ ...VALID_TEMPLATE_FAMILY, variants: { react: { responsivePreviews: [{}] } } }],
+ }), /variant react responsive preview missing string field/);
+});
+
+test('responsive SPA previews resolve manifest-relative paths and survive normalized selection', async (t) => {
+ const dir = tempDir();
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const { previewImages, ...template } = VALID_TEMPLATE;
+ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: SHA, cacheRoot: dir }, {
+ requestJson: async () => ({ templates: [{ ...template, responsivePreviews: RESPONSIVE_PREVIEWS }] }),
+ });
+ assert.equal(result.ok, true, result.error);
+ const expected = RESPONSIVE_PREVIEWS.map((preview) => ({
+ ...preview,
+ desktop: `templates/${preview.desktop}`,
+ mobile: `templates/${preview.mobile}`,
+ }));
+ assert.deepEqual(result.catalog.templates[0].responsivePreviews, expected);
+ assert.deepEqual(result.selectableCatalog.templates[0].responsivePreviews, expected);
+ assert.deepEqual(result.selectableCatalog.templates[0].variants[0].responsivePreviews, expected);
+});
+
+test('SPA variants preserve responsive overrides, legacy overrides, inheritance and empty lists', async (t) => {
+ const dir = tempDir();
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const variantPreviews = [{
+ id: 'invoices', displayName: 'Invoices',
+ desktop: 'spa/supplier-portal/variants/vue/wide.png',
+ mobile: 'templates/spa/supplier-portal/variants/vue/narrow.png',
+ }];
+ const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: SHA, cacheRoot: dir }, {
+ requestJson: async () => ({
+ templates: [{
+ ...VALID_TEMPLATE_FAMILY,
+ responsivePreviews: RESPONSIVE_PREVIEWS,
+ variants: {
+ react: {},
+ vue: { responsivePreviews: variantPreviews, previewImages: ['legacy.png'] },
+ angular: { previewImages: ['angular-legacy.png'] },
+ astro: { responsivePreviews: [] },
+ },
+ }],
+ }),
+ });
+ assert.equal(result.ok, true, result.error);
+ const family = result.selectableCatalog.templates[0];
+ const [react, vue, angular, astro] = family.variants;
+ assert.equal(family.previewImages, undefined);
+ assert.deepEqual(react.responsivePreviews, family.responsivePreviews);
+ assert.deepEqual(vue.responsivePreviews, [{
+ ...variantPreviews[0],
+ desktop: `templates/${variantPreviews[0].desktop}`,
+ }]);
+ assert.equal(vue.previewImages, undefined);
+ assert.deepEqual(angular.previewImages, ['templates/angular-legacy.png']);
+ assert.equal(angular.responsivePreviews, undefined);
+ assert.deepEqual(astro.responsivePreviews, []);
+ const emptyFamily = normalizeCatalogFamilies({
+ templates: [{ ...VALID_TEMPLATE_FAMILY, responsivePreviews: [], variants: { react: {}, vue: { previewImages: [] } } }],
+ })[0];
+ assert.deepEqual(emptyFamily.responsivePreviews, []);
+ assert.deepEqual(emptyFamily.variants[0].responsivePreviews, []);
+ assert.deepEqual(emptyFamily.variants[1].previewImages, []);
+});
+
function fakeZipWithLocalFile(name) {
const nameBytes = Buffer.from(name, 'utf8');
const header = Buffer.alloc(30);
diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.md
index 1c61306e6..6ed9eb84c 100644
--- a/plugins/power-pages/skills/create-site/SKILL.md
+++ b/plugins/power-pages/skills/create-site/SKILL.md
@@ -177,14 +177,20 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read
5. Render `TEMPLATE_PREVIEW_FAMILIES` for browser preview:
- - Download each `previewImages` artifact into the SHA-keyed cache before rendering:
+ - For each SPA family and variant, prefer `responsivePreviews` when present, including an empty array.
+ Each page has `{ id, displayName, desktop, mobile }`; download both device artifacts into the SHA-keyed cache before rendering:
```bash
node "${PLUGIN_ROOT}/scripts/fetch-template-artifact.js" --sha "<catalog-sha>" --artifactPath "<preview-image-path>"
```
- Replace each preview image path with the returned `localUrl`. If a preview download returns `ok: false`, omit that one image from the gallery and continue; a missing preview should not block using an otherwise-valid template.
+ Replace each device path with the returned `localUrl`, preserving the page's `id` and `displayName`.
+ If either download returns `ok: false`, explain the unavailable preview and omit that page from the gallery; previews must not block an otherwise-valid template.
+ Use legacy `previewImages` only when `responsivePreviews` is absent, replacing each path with its downloaded `localUrl` and omitting failed images.
+ A variant's own preview definition overrides the family's, even if the variant uses legacy `previewImages`.
+ Inherit family previews only when the variant defines neither field.
+ Reuse cached downloads for inherited paths.
- Write a temporary JSON file containing a `TEMPLATES_JSON` array with the templates the user
should preview. Preserve `kind` so the HTML shows `SPA` or `Non-SPA` beside every template
- name. Include SPA variants and cached `previewImages`; include non-SPA responsive `previews`
+ name. Include SPA variants with their effective cached `responsivePreviews` or legacy `previewImages`; include non-SPA responsive `previews`
unchanged. Keep the browser read-only.
- Run:
```bash
@@ -441,14 +447,18 @@ Write the file with the `Write` tool (atomic overwrite). You do not need to read
--templateName "<SELECTED_TEMPLATE.displayName>" \
--templateDescription "<SELECTED_TEMPLATE.description>" \
--statusPath "<temp-import-status-dir>/status.json" \
- --previewImagesJson '<JSON array of SELECTED_TEMPLATE.previewImages localUrl values from the template browser step>' \
+ --responsivePreviewsJson '<JSON array of SELECTED_TEMPLATE_VARIANT.responsivePreviews with cached desktop/mobile localUrl values from the template browser step>' \
--solutionCount "<TEMPLATE_SOLUTIONS_TO_IMPORT.length, or SELECTED_TEMPLATE_SOLUTIONS.length when imports are skipped>" \
--outputPath "<temp-import-status-dir>/index.html"
node "${PLUGIN_ROOT}/scripts/serve-static-dir.js" --root "<temp-import-status-dir>" --urlFile "<temp-import-status-dir>/url.txt" --cleanupRoot
node "${PLUGIN_ROOT}/scripts/open-url.js" --url "<url from <temp-import-status-dir>/url.txt>"
```
+ When the selected variant has only legacy `previewImages`, replace `--responsivePreviewsJson` with `--previewImagesJson` and pass that variant's cached URL array.
+ Use the selected variant's effective previews, including inherited family previews resolved in the browser step.
Reuse the already-downloaded local preview image URLs from the browser step; do not fetch preview images again for this page.
- Name device-specific captures `desktop-<page>.<ext>` and `mobile-<page>.<ext>` so the status page can pair them. Unprefixed images count as desktop previews, and the Mobile control appears only when a mobile-prefixed image is present.
+ Structured previews use explicit page/device fields regardless of filenames.
+ For legacy `previewImages` only, name device-specific captures `desktop-<page>.<ext>` and `mobile-<page>.<ext>` so the status page can pair them.
+ Unprefixed legacy images count as desktop previews; the Mobile control appears when the selected page has a mobile image.
The server command returns only after the listener is ready. It removes the temporary status directory after a successful redirect, after the browser stops polling, or when the maximum lifetime expires.
7. Unless `SKIP_TEMPLATE_SOLUTION_IMPORT = true`, mark **Import template supporting solutions** as `in_progress`. Process `TEMPLATE_SOLUTIONS_TO_IMPORT` sequentially in its existing case-insensitive lexical unique-name order. For each entry, set `CURRENT_TEMPLATE_SOLUTION` and prepare its unmanaged solution for import:
```bash