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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { EventEmitter } = require('events');
const { PassThrough } = require('stream');
const {
buildRawUrl,
buildGitRemoteUrl,
cacheDirForSha,
artifactCachePath,
ensurePrivateCacheRoot,
requestJson,
downloadFile,
fetchCatalog,
downloadArtifact,
downloadTemplateVariant,
downloadSeedDataDirectory,
validateZipContainsSolution,
validateWebsiteCodeDirectory,
validateUnpackedSolutionDirectory,
repositoryDirectoryCheckoutRoot,
inspectTemplateSolutions,
templateFamilyRoot,
templateVariantRoot,
zipFileNames,
validateCatalogShape,
assertValidSha,
resolveRefToSha,
normalizeCatalogFamilies,
applySolutionSettings,
} = require('../lib/template-catalog');
const { parseArgs: parseCatalogArgs } = require('../fetch-template-catalog');
const { parseArgs: parseVariantArgs } = require('../fetch-template-variant');
const { parseArgs: parseArtifactArgs } = require('../fetch-template-artifact');
const { parseArgs: parseSeedArgs } = require('../fetch-template-seed-data');
const { parseTemplateRepoArgs, formatJsonResult, runBestEffortJsonCli } = require('../lib/template-cli-args');
function tempDir() {
return fs.mkdtempSync(path.join(os.tmpdir(), 'template-catalog-test-'));
}
const SHA = '1234567890abcdef1234567890abcdef12345678';
const VALID_TEMPLATE = {
id: 'company-portal',
displayName: 'Company Portal',
description: 'Internal portal',
kind: 'spa',
framework: 'react',
keywords: ['portal'],
audience: ['makers', 'developers'],
requiredDataverseLanguages: [1033],
previewImages: ['templates/spa/company-portal/previews/home.png'],
author: 'Microsoft',
};
const VALID_TEMPLATE_FAMILY = {
id: 'supplier-portal',
displayName: 'Supplier Portal',
description: 'Supplier invoice portal',
kind: 'spa',
keywords: ['supplier', 'invoice'],
audience: ['makers', 'developers'],
requiredDataverseLanguages: [1033],
previewImages: ['templates/spa/supplier-portal/previews/home.png'],
seedDataPath: 'templates/spa/supplier-portal/seed-data/data.json',
author: 'Microsoft',
variants: {
react: {},
vue: {
previewImages: ['templates/spa/supplier-portal/variants/vue/previews/home.png'],
},
},
};
const VALID_TRADITIONAL_TEMPLATE_FAMILY = {
id: 'customer-self-service',
displayName: 'Customer self-service',
description: 'A traditional Power Pages website template',
kind: 'traditional',
keywords: ['customer-service'],
audience: ['makers'],
requiredDataverseLanguages: [1033],
previewImages: [],
author: 'Microsoft',
variants: {
none: {},
},
};
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);
header.writeUInt32LE(0x04034b50, 0);
header.writeUInt16LE(nameBytes.length, 26);
header.writeUInt16LE(0, 28);
return Buffer.concat([header, nameBytes]);
}
function writeUnpackedSolution(solutionPath, uniqueName, options = {}) {
const other = path.join(solutionPath, 'Other');
fs.mkdirSync(other, { recursive: true });
fs.writeFileSync(
path.join(other, 'Solution.xml'),
`<ImportExportXml><SolutionManifest><UniqueName>${uniqueName}</UniqueName><Version>${options.version || '1.0.0.0'}</Version><Managed>0</Managed></SolutionManifest></ImportExportXml>`
);
fs.writeFileSync(
path.join(other, 'Customizations.xml'),
options.websiteComponents
? '<ImportExportXml><powerpagecomponents /></ImportExportXml>'
: '<ImportExportXml />'
);
}
test('builds raw and git remote URLs from repo and template-relative paths', () => {
assert.equal(buildGitRemoteUrl({ owner: 'microsoft', repo: 'power-pages-samples' }), 'https://github.com/microsoft/power-pages-samples.git');
assert.equal(
buildRawUrl({ owner: 'microsoft', repo: 'power-pages-samples', sha: SHA, filePath: 'templates/spa/hr portal/manifest.json' }),
`https://raw.githubusercontent.com/microsoft/power-pages-samples/${SHA}/templates/spa/hr%20portal/manifest.json`
);
});
test('rejects non-commit refs where a pinned sha is required', () => {
assert.throws(() => assertValidSha('main'), /Expected an immutable 40-character commit sha/);
assert.throws(
() => buildRawUrl({ owner: 'o', repo: 'r', sha: '../escape', filePath: 'templates/manifest.json' }),
/Expected an immutable 40-character commit sha/
);
});
test('resolveRefToSha resolves refs with git ls-remote', async () => {
const seen = [];
const sha = resolveRefToSha({ owner: 'o', repo: 'r', ref: 'main' }, {
execFileSync: (cmd, args) => {
seen.push([cmd, args]);
return `${SHA}\trefs/heads/main\n`;
},
});
assert.equal(sha, SHA);
assert.deepEqual(seen, [['git', ['ls-remote', 'https://github.com/o/r.git', 'main']]]);
});
test('fetchCatalog resolves the latest release to a sha, fetches the catalog at that sha, and creates a sha cache dir', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const seen = [];
const gitCalls = [];
const catalog = { manifestVersion: '1.0', templates: [VALID_TEMPLATE] };
const result = await fetchCatalog({ owner: 'o', repo: 'r', cacheRoot: dir }, {
execFileSync: (cmd, args) => {
gitCalls.push([cmd, args]);
assert.deepEqual(args, ['ls-remote', '--tags', 'https://github.com/o/r.git']);
return [
`${'0'.repeat(40)}\trefs/tags/templates-v0.9.0`,
`${SHA}\trefs/tags/templates-v1.0.0`,
].join('\n');
},
requestJson: async (url) => {
seen.push(url);
if (url === `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`) return catalog;
throw new Error(`unexpected url: ${url}`);
},
});
assert.deepEqual(result, {
ok: true,
owner: 'o',
repo: 'r',
ref: 'latest-release',
resolvedRef: 'templates-v1.0.0',
sha: SHA,
releaseName: 'templates-v1.0.0',
releaseUrl: 'https://github.com/o/r/releases/tag/templates-v1.0.0',
catalogPath: 'templates/manifest.json',
catalogLocalPath: path.join(dir, SHA, 'templates/manifest.json'),
cacheDir: path.join(dir, SHA),
catalog,
selectableCatalog: {
...catalog,
templates: normalizeCatalogFamilies(catalog),
},
});
assert.deepEqual(gitCalls, [['git', ['ls-remote', '--tags', 'https://github.com/o/r.git']]]);
assert.deepEqual(seen, [
`https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`,
]);
assert.equal(fs.existsSync(path.join(dir, SHA)), true);
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, SHA, 'templates/manifest.json'), 'utf8')), catalog);
});
test('fetchCatalog rejects a symlinked catalog cache file without modifying its target', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
ensurePrivateCacheRoot(dir);
const catalogPath = path.join(dir, SHA, 'templates', 'manifest.json');
const outsidePath = path.join(dir, 'outside.json');
fs.mkdirSync(path.dirname(catalogPath), { recursive: true });
fs.writeFileSync(outsidePath, 'do not overwrite');
try {
fs.symlinkSync(outsidePath, catalogPath);
} catch (err) {
if (err.code === 'EPERM' || err.code === 'EACCES') {
t.skip(`symlinks are unavailable: ${err.code}`);
return;
}
throw err;
}
const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'main', cacheRoot: dir }, {
execFileSync: () => `${SHA}\trefs/heads/main\n`,
requestJson: async () => ({ manifestVersion: '1.0', templates: [VALID_TEMPLATE] }),
});
assert.equal(result.ok, false);
assert.match(result.error, /cache file must be a regular file/);
assert.equal(fs.readFileSync(outsidePath, 'utf8'), 'do not overwrite');
});
test('fetchCatalog rejects symlinked directories inside the catalog cache path', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
ensurePrivateCacheRoot(dir);
const outsideDir = path.join(dir, 'outside');
const templatesPath = path.join(dir, SHA, 'templates');
fs.mkdirSync(path.dirname(templatesPath), { recursive: true });
fs.mkdirSync(outsideDir);
try {
fs.symlinkSync(outsideDir, templatesPath, process.platform === 'win32' ? 'junction' : 'dir');
} catch (err) {
if (err.code === 'EPERM' || err.code === 'EACCES') {
t.skip(`symlinks are unavailable: ${err.code}`);
return;
}
throw err;
}
const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'main', cacheRoot: dir }, {
execFileSync: () => `${SHA}\trefs/heads/main\n`,
requestJson: async () => ({ manifestVersion: '1.0', templates: [VALID_TEMPLATE] }),
});
assert.equal(result.ok, false);
assert.match(result.error, /cache path must contain only real directories/);
assert.equal(fs.existsSync(path.join(outsideDir, 'manifest.json')), false);
});
test('fetchCatalog resolves non-derived artifact paths relative to the catalog folder', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const catalog = {
manifestVersion: '1.0',
templates: [{
...VALID_TEMPLATE,
previewImages: ['spa/company-portal/previews/home.png', 'templates/spa/company-portal/previews/already-rooted.png'],
seedDataPath: 'spa/company-portal/seed/data.json',
}],
};
const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'templates-v1.0.0', cacheRoot: dir }, {
execFileSync: (cmd, args) => {
assert.deepEqual([cmd, args], ['git', ['ls-remote', 'https://github.com/o/r.git', 'templates-v1.0.0']]);
return `${SHA}\trefs/tags/templates-v1.0.0\n`;
},
requestJson: async (url) => {
if (url === `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`) return catalog;
throw new Error(`unexpected url: ${url}`);
},
});
assert.equal(result.ok, true);
assert.deepEqual(result.catalog.templates[0].previewImages, [
'templates/spa/company-portal/previews/home.png',
'templates/spa/company-portal/previews/already-rooted.png',
]);
assert.equal(result.catalog.templates[0].seedDataPath, 'templates/spa/company-portal/seed/data.json');
});
test('validateCatalogShape accepts nested template families with framework variants', () => {
assert.equal(validateCatalogShape({ manifestVersion: '2.0', templates: [VALID_TEMPLATE_FAMILY] }), null);
});
test('validateCatalogShape rejects manifest paths that are derived from template identity', () => {
const traditionalFlatTemplate = {
...VALID_TEMPLATE,
id: 'traditional-flat-template',
kind: 'traditional',
framework: 'none',
};
assert.equal(
validateCatalogShape({
manifestVersion: '2.0',
templates: [VALID_TEMPLATE_FAMILY, VALID_TRADITIONAL_TEMPLATE_FAMILY, traditionalFlatTemplate],
}),
null
);
assert.match(
validateCatalogShape({
manifestVersion: '2.0',
templates: [{
...VALID_TEMPLATE_FAMILY,
variants: {
react: {
solutionPath: 'templates/spa/supplier-portal/variants/react/solution',
},
},
}],
}),
/must not define derivable solutionPath or websiteCodePath/
);
assert.match(
validateCatalogShape({
manifestVersion: '2.0',
templates: [{
...VALID_TRADITIONAL_TEMPLATE_FAMILY,
variants: {
none: {
websiteCodePath: 'templates/traditional/customer-self-service/variants/none/website-code',
},
},
}],
}),
/must not define derivable solutionPath or websiteCodePath/
);
});
test('fetchCatalog keeps traditional entries but exposes only SPA templates for selection', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const catalog = {
manifestVersion: '2.0',
templates: [
VALID_TEMPLATE_FAMILY,
VALID_TRADITIONAL_TEMPLATE_FAMILY,
],
};
const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'templates-v2.0.0', cacheRoot: dir }, {
execFileSync: () => `${SHA}\trefs/tags/templates-v2.0.0\n`,
requestJson: async () => catalog,
});
assert.equal(result.ok, true);
assert.equal(result.catalog.templates.length, 2);
assert.deepEqual(result.selectableCatalog.templates.map((template) => template.id), ['supplier-portal']);
assert.deepEqual(
result.selectableCatalog.templates[0].variants.map((variant) => variant.variantKey),
['react', 'vue']
);
assert.equal(result.catalog.templates[1].variants.none.websiteCodePath, undefined);
assert.equal(result.catalog.templates[1].variants.none.solutionPath, undefined);
});
test('validateCatalogShape rejects duplicate framework variants in a family', () => {
const family = {
...VALID_TEMPLATE_FAMILY,
variants: {
react: VALID_TEMPLATE_FAMILY.variants.react,
React: VALID_TEMPLATE_FAMILY.variants.react,
},
};
assert.match(
validateCatalogShape({ templates: [family] }),
/duplicate framework variant/i
);
assert.match(
validateCatalogShape({
templates: [{
...VALID_TEMPLATE_FAMILY,
variants: {
react: {
solutions: [{ uniqueName: 'SupplierPortal', publishChanges: true }],
},
},
}],
}),
/family level/
);
});
test('validateCatalogShape accepts strict solution-level publish settings', () => {
assert.equal(validateCatalogShape({
templates: [{
...VALID_TEMPLATE_FAMILY,
solutions: [
{ uniqueName: 'SupplierBase', publishChanges: false },
{ uniqueName: 'SupplierPortal', publishChanges: true },
],
}],
}), null);
for (const solutions of [
{},
[{ uniqueName: 'SupplierPortal' }],
[{ uniqueName: 'SupplierPortal', publishChanges: 'true' }],
[{ uniqueName: 'SupplierPortal', publishChanges: true, extra: true }],
[
{ uniqueName: 'SupplierPortal', publishChanges: true },
{ uniqueName: 'supplierportal', publishChanges: false },
],
]) {
assert.notEqual(validateCatalogShape({
templates: [{ ...VALID_TEMPLATE_FAMILY, solutions }],
}), null);
}
});
test('normalization preserves family solution settings for every variant', () => {
const solutions = [{ uniqueName: 'SupplierPortal', publishChanges: true }];
const [family] = normalizeCatalogFamilies({
templates: [{ ...VALID_TEMPLATE_FAMILY, solutions }],
});
assert.deepEqual(family.solutions, solutions);
assert.ok(family.variants.every(variant => variant.solutions === solutions));
});
test('solution settings default to false and reject unknown manifest entries', () => {
const discovered = [
{ uniqueName: 'SupplierBase', version: '1.0.0.0', solutionPath: '/base' },
{ uniqueName: 'SupplierPortal', version: '2.0.0.0', solutionPath: '/portal' },
];
assert.deepEqual(applySolutionSettings(discovered, [
{ uniqueName: 'SupplierPortal', publishChanges: true },
]), [
{ ...discovered[0], publishChanges: false },
{ ...discovered[1], publishChanges: true },
]);
assert.throws(() => applySolutionSettings(discovered, [
{ uniqueName: 'MissingSolution', publishChanges: true },
]), /unknown solution/);
assert.throws(() => applySolutionSettings(discovered, [
{ uniqueName: 'supplierportal', publishChanges: true },
]), /unknown solution/);
});
test('fetchCatalog materializes nested preview and seed artifact paths', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const catalog = {
manifestVersion: '2.0',
templates: [{
...VALID_TEMPLATE_FAMILY,
previewImages: ['spa/supplier-portal/previews/home.png'],
seedDataPath: 'spa/supplier-portal/seed-data/data.json',
variants: {
react: {},
vue: {
previewImages: ['spa/supplier-portal/variants/vue/previews/home.png'],
seedDataPath: 'spa/supplier-portal/variants/vue/seed-data/data.json',
},
},
}],
};
const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'templates-v2.0.0', cacheRoot: dir }, {
execFileSync: () => `${SHA}\trefs/tags/templates-v2.0.0\n`,
requestJson: async () => catalog,
});
assert.equal(result.ok, true);
assert.deepEqual(result.catalog.templates[0].previewImages, ['templates/spa/supplier-portal/previews/home.png']);
assert.equal(result.catalog.templates[0].seedDataPath, 'templates/spa/supplier-portal/seed-data/data.json');
assert.deepEqual(result.catalog.templates[0].variants.vue.previewImages, ['templates/spa/supplier-portal/variants/vue/previews/home.png']);
assert.equal(result.catalog.templates[0].variants.vue.seedDataPath, 'templates/spa/supplier-portal/variants/vue/seed-data/data.json');
});
test('normalizeCatalogFamilies exposes exact variant records with family metadata', () => {
const families = normalizeCatalogFamilies({ templates: [VALID_TEMPLATE_FAMILY] });
assert.deepEqual(families, [{
id: 'supplier-portal',
displayName: 'Supplier Portal',
description: 'Supplier invoice portal',
kind: 'spa',
keywords: ['supplier', 'invoice'],
audience: ['makers', 'developers'],
requiredDataverseLanguages: [1033],
previewImages: ['templates/spa/supplier-portal/previews/home.png'],
seedDataPath: 'templates/spa/supplier-portal/seed-data/data.json',
author: 'Microsoft',
variants: [
{
familyId: 'supplier-portal',
variantKey: 'react',
variantId: 'supplier-portal/react',
displayName: 'Supplier Portal',
description: 'Supplier invoice portal',
kind: 'spa',
framework: 'react',
keywords: ['supplier', 'invoice'],
audience: ['makers', 'developers'],
requiredDataverseLanguages: [1033],
previewImages: ['templates/spa/supplier-portal/previews/home.png'],
seedDataPath: 'templates/spa/supplier-portal/seed-data/data.json',
author: 'Microsoft',
},
{
familyId: 'supplier-portal',
variantKey: 'vue',
variantId: 'supplier-portal/vue',
displayName: 'Supplier Portal',
description: 'Supplier invoice portal',
kind: 'spa',
framework: 'vue',
keywords: ['supplier', 'invoice'],
audience: ['makers', 'developers'],
requiredDataverseLanguages: [1033],
previewImages: ['templates/spa/supplier-portal/variants/vue/previews/home.png'],
seedDataPath: 'templates/spa/supplier-portal/seed-data/data.json',
author: 'Microsoft',
},
],
}]);
});
test('fetchCatalog falls back to main when no semver tags exist yet', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const catalog = { manifestVersion: '1.0', templates: [VALID_TEMPLATE] };
const seen = [];
const gitCalls = [];
const result = await fetchCatalog({ owner: 'o', repo: 'r', cacheRoot: dir }, {
execFileSync: (cmd, args) => {
gitCalls.push([cmd, args]);
if (args[1] === '--tags') return '';
assert.deepEqual(args, ['ls-remote', 'https://github.com/o/r.git', 'main']);
return `${SHA}\trefs/heads/main\n`;
},
requestJson: async (url) => {
seen.push(url);
if (url === `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`) return catalog;
throw new Error(`unexpected url: ${url}`);
},
});
assert.equal(result.ok, true);
assert.equal(result.ref, 'latest-release');
assert.equal(result.resolvedRef, 'main');
assert.deepEqual(gitCalls, [
['git', ['ls-remote', '--tags', 'https://github.com/o/r.git']],
['git', ['ls-remote', 'https://github.com/o/r.git', 'main']],
]);
assert.deepEqual(seen, [
`https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`,
]);
});
test('fetchCatalog still accepts an explicit ref override for tests or pinned rollouts', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const catalog = { manifestVersion: '1.0', templates: [VALID_TEMPLATE] };
const seen = [];
const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'templates-v0.9.0', cacheRoot: dir }, {
execFileSync: (cmd, args) => {
assert.deepEqual([cmd, args], ['git', ['ls-remote', 'https://github.com/o/r.git', 'templates-v0.9.0']]);
return `${SHA}\trefs/tags/templates-v0.9.0\n`;
},
requestJson: async (url) => {
seen.push(url);
if (url === `https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`) return catalog;
throw new Error(`unexpected url: ${url}`);
},
});
assert.equal(result.ok, true);
assert.equal(result.ref, 'templates-v0.9.0');
assert.equal(result.resolvedRef, 'templates-v0.9.0');
assert.deepEqual(seen, [
`https://raw.githubusercontent.com/o/r/${SHA}/templates/manifest.json`,
]);
});
test('fetchCatalog returns ok:false so create-site can fall back when the catalog is unreachable', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'main', cacheRoot: dir }, {
execFileSync: () => `${SHA}\trefs/heads/main\n`,
requestJson: async (url) => {
throw new Error('network unavailable');
},
});
assert.equal(result.ok, false);
assert.equal(result.owner, 'o');
assert.equal(result.repo, 'r');
assert.equal(result.ref, 'main');
assert.match(result.error, /network unavailable/);
assert.equal(fs.existsSync(path.join(dir, SHA)), false, 'failed catalog fetch must not leave a sha cache dir');
});
test('fetchCatalog treats malformed catalogs as ok:false without creating a sha cache dir', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'main', cacheRoot: dir }, {
execFileSync: () => `${SHA}\trefs/heads/main\n`,
requestJson: async (url) => {
return { manifestVersion: '1.0' };
},
});
assert.equal(result.ok, false);
assert.match(result.error, /malformed/);
assert.equal(fs.existsSync(path.join(dir, SHA)), false, 'malformed catalog must not leave a sha cache dir');
});
test('fetchCatalog treats malformed template entries as ok:false without creating a sha cache dir', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const result = await fetchCatalog({ owner: 'o', repo: 'r', ref: 'main', cacheRoot: dir }, {
execFileSync: () => `${SHA}\trefs/heads/main\n`,
requestJson: async (url) => {
return { manifestVersion: '1.0', templates: [{ id: 'missing-fields' }] };
},
});
assert.equal(result.ok, false);
assert.match(result.error, /missing string field/);
assert.equal(fs.existsSync(path.join(dir, SHA)), false, 'malformed entries must not leave a sha cache dir');
});
test('validateCatalogShape accepts a complete template entry and rejects broken entries', () => {
assert.equal(validateCatalogShape({ templates: [VALID_TEMPLATE] }), null);
assert.equal(validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, previewImages: [] }] }), null);
assert.match(validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, previewImages: 'templates/spa/company/home.png' }] }), /previewImages/);
assert.match(validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, keywords: 'portal' }] }), /keywords/);
assert.match(validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, requiredDataverseLanguages: [] }] }), /requiredDataverseLanguages/);
assert.match(validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, requiredDataverseLanguages: ['1033'] }] }), /requiredDataverseLanguages/);
assert.match(
validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, websiteCodePath: '' }] }),
/must not define derivable solutionPath or websiteCodePath/
);
assert.match(
validateCatalogShape({ templates: [{ ...VALID_TEMPLATE, solutionPath: 'templates/spa/company-portal/solution.zip' }] }),
/must not define derivable solutionPath or websiteCodePath/
);
});
// Regression: the published manifest declares `audience` as an array of personas
// (see templates/schemas/templates-manifest.schema.json in power-pages-samples).
// An earlier validator required a plain string, which rejected every real
// template and silently forced create-site down the from-scratch path.
test('validateCatalogShape accepts the 311 Portal audience array and rejects non-array shapes', () => {
const portal311 = {
...VALID_TEMPLATE,
id: '311-portal',
displayName: '311 Portal',
description: 'Citizen service request portal',
keywords: ['311', 'citizen-services'],
audience: ['makers', 'developers'],
previewImages: ['spa/311-portal/previews/home.png'],
};
assert.equal(validateCatalogShape({ templates: [portal311] }), null);
assert.match(
validateCatalogShape({ templates: [{ ...portal311, audience: 'internal' }] }),
/audience must be a non-empty array of strings/,
);
assert.match(validateCatalogShape({ templates: [{ ...portal311, audience: [] }] }), /audience/);
assert.match(validateCatalogShape({ templates: [{ ...portal311, audience: ['makers', ''] }] }), /audience/);
});
test('requestJson uses an injected https boundary and parses response JSON', async () => {
const fakeHttps = {
get(url, options, callback) {
assert.equal(url, 'https://example.test/catalog.json');
assert.equal(options.headers['User-Agent'], 'power-pages-template-catalog');
const req = new EventEmitter();
req.destroy = (err) => req.emit('error', err);
process.nextTick(() => {
const res = new PassThrough();
res.statusCode = 200;
callback(res);
res.end('{"templates":[{"id":"portal"}]}');
});
return req;
},
};
assert.deepEqual(await requestJson('https://example.test/catalog.json', { https: fakeHttps }), {
templates: [{ id: 'portal' }],
});
});
test('downloadFile streams through injected https and fs boundaries', async () => {
const writes = [];
let renamed = null;
const suffix = '0011223344556677';
const temporaryPath = `/cache/template.zip.partial-${process.pid}-${suffix}`;
const fakeFs = {
mkdirSync(dir) { writes.push(['mkdir', dir]); },
createWriteStream(dest, options) {
writes.push(['stream', dest, options]);
const stream = new PassThrough();
stream.close = (callback) => callback();
return stream;
},
renameSync(from, to) { renamed = [from, to]; },
rmSync() {},
};
const fakeHttps = {
get(url, options, callback) {
assert.equal(url, 'https://example.test/template.zip');
assert.equal(options.headers['User-Agent'], 'power-pages-template-catalog');
const req = new EventEmitter();
req.destroy = (err) => req.emit('error', err);
process.nextTick(() => {
const res = new PassThrough();
res.statusCode = 200;
callback(res);
res.end(Buffer.from([0x50, 0x4b]));
});
return req;
},
};
const output = await downloadFile('https://example.test/template.zip', '/cache/template.zip', {
fs: fakeFs,
https: fakeHttps,
randomBytes: () => Buffer.from(suffix, 'hex'),
});
assert.equal(output, '/cache/template.zip');
assert.deepEqual(writes, [
['mkdir', '/cache'],
['stream', temporaryPath, { flags: 'wx', mode: 0o600 }],
]);
assert.deepEqual(renamed, [temporaryPath, '/cache/template.zip']);
});
test('downloadFile does not follow a pre-existing temporary-file symlink', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const outputPath = path.join(dir, 'template.zip');
const outsidePath = path.join(dir, 'outside.zip');
const suffix = '0011223344556677';
const temporaryPath = `${outputPath}.partial-${process.pid}-${suffix}`;
fs.writeFileSync(outsidePath, 'outside');
try {
fs.symlinkSync(outsidePath, temporaryPath);
} catch (err) {
if (err.code === 'EPERM' || err.code === 'EACCES') {
t.skip(`symlinks are unavailable: ${err.code}`);
return;
}
throw err;
}
const fakeHttps = {
get() {
const req = new EventEmitter();
req.destroy = (err) => req.emit('error', err);
return req;
},
};
await assert.rejects(
() => downloadFile('https://example.test/template.zip', outputPath, {
https: fakeHttps,
randomBytes: () => Buffer.from(suffix, 'hex'),
}),
/EEXIST|file already exists/i
);
assert.equal(fs.readFileSync(outsidePath, 'utf8'), 'outside');
});
test('downloadFile rejects and removes the temporary file when final rename fails', async () => {
const removed = [];
const suffix = '0011223344556677';
const temporaryPath = `/cache/template.zip.partial-${process.pid}-${suffix}`;
const fakeFs = {
mkdirSync() {},
createWriteStream() {
const stream = new PassThrough();
stream.close = (callback) => callback();
return stream;
},
renameSync() {
throw new Error('rename denied');
},
rmSync(target) {
removed.push(target);
},
};
const fakeHttps = {
get(_url, _options, callback) {
const req = new EventEmitter();
req.destroy = (err) => req.emit('error', err);
process.nextTick(() => {
const res = new PassThrough();
res.statusCode = 200;
callback(res);
res.end(Buffer.from([0x50, 0x4b]));
});
return req;
},
};
await assert.rejects(
() => downloadFile('https://example.test/template.zip', '/cache/template.zip', {
fs: fakeFs,
https: fakeHttps,
randomBytes: () => Buffer.from(suffix, 'hex'),
}),
/rename denied/
);
assert.deepEqual(removed, [temporaryPath]);
});
test('downloadArtifact caches artifacts under the pinned sha and skips download when already cached', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const artifactPath = 'templates/spa/company/solution/Company_1_0_0_0.zip';
const expectedPath = artifactCachePath({ cacheRoot: dir, sha: SHA, artifactPath });
let downloads = 0;
const first = await downloadArtifact({ owner: 'o', repo: 'r', sha: SHA, artifactPath, cacheRoot: dir }, {
downloadFile: async (url, dest) => {
downloads++;
assert.equal(url, `https://raw.githubusercontent.com/o/r/${SHA}/${artifactPath}`);
fs.mkdirSync(path.dirname(dest), { recursive: true });
fs.writeFileSync(dest, 'zip-bytes');
},
});
const second = await downloadArtifact({ owner: 'o', repo: 'r', sha: SHA, artifactPath, cacheRoot: dir }, {
downloadFile: async () => { throw new Error('must not download cached artifact'); },
});
assert.deepEqual(first, { localPath: expectedPath, cached: false });
assert.deepEqual(second, { localPath: expectedPath, cached: true });
assert.equal(downloads, 1);
});
test('template cache root is private and carries an ownership marker', (t) => {
const parent = tempDir();
const dir = path.join(parent, 'cache');
t.after(() => fs.rmSync(parent, { recursive: true, force: true }));
assert.equal(ensurePrivateCacheRoot(dir), path.resolve(dir));
const markerPath = path.join(dir, '.powerpages-template-cache.json');
assert.deepEqual(JSON.parse(fs.readFileSync(markerPath, 'utf8')), {
schemaVersion: 1,
ownerUid: typeof process.getuid === 'function' ? process.getuid() : null,
});
if (process.platform !== 'win32') {
assert.equal(fs.statSync(dir).mode & 0o077, 0);
assert.equal(fs.statSync(markerPath).mode & 0o077, 0);
}
});
test('template cache rejects an unclaimed pre-populated root', (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
fs.writeFileSync(path.join(dir, 'preplanted.txt'), 'untrusted');
assert.throws(
() => ensurePrivateCacheRoot(dir),
/cache root is not owned by this tool/
);
});
test('template cache rejects roots accessible to other users', (t) => {
if (process.platform === 'win32') {
t.skip('POSIX permission bits are not meaningful on Windows');
return;
}
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
fs.chmodSync(dir, 0o755);
assert.throws(
() => ensurePrivateCacheRoot(dir),
/cache root must be private to the current user/
);
});
test('downloadArtifact rejects cached symlinks and non-files', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
ensurePrivateCacheRoot(dir);
const artifactPath = 'templates/spa/company/previews/home.png';
const cachedPath = artifactCachePath({ cacheRoot: dir, sha: SHA, artifactPath });
fs.mkdirSync(path.dirname(cachedPath), { recursive: true });
const target = path.join(dir, 'outside.png');
fs.writeFileSync(target, 'outside');
try {
fs.symlinkSync(target, cachedPath);
} catch (err) {
if (err.code === 'EPERM' || err.code === 'EACCES') {
t.skip(`symlinks are unavailable: ${err.code}`);
return;
}
throw err;
}
await assert.rejects(
() => downloadArtifact({ owner: 'o', repo: 'r', sha: SHA, artifactPath, cacheRoot: dir }),
/regular file/
);
});
test('artifactCachePath rejects paths that escape the sha cache directory', () => {
assert.throws(
() => artifactCachePath({ cacheRoot: '/tmp/cache', sha: SHA, artifactPath: '../secret.zip' }),
/must stay under the templates cache/
);
assert.throws(
() => artifactCachePath({ cacheRoot: '/tmp/cache', sha: SHA, artifactPath: '/tmp/secret.zip' }),
/must stay under the templates cache/
);
});
test('downloadTemplateVariant combines variant website code with family solutions in stable order', (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const variantPath = 'templates/spa/company/variants/react';
const solutionsPath = 'templates/spa/company/solutions';
const calls = [];
let partialRoot;
const result = downloadTemplateVariant({
owner: 'o',
repo: 'r',
sha: SHA,
kind: 'spa',
templateId: 'company',
variant: 'react',
cacheRoot: dir,
solutionSettings: [{ uniqueName: 'CompanyPortal', publishChanges: true }],
}, {
execFileSync(command, args) {
calls.push([command, args]);
if (args[0] === 'init') partialRoot = args[2];
if (args.includes('checkout')) {
const localVariant = path.join(partialRoot, ...variantPath.split('/'));
const localSolutions = path.join(partialRoot, ...solutionsPath.split('/'));
const localWebsiteCode = path.join(localVariant, 'website-code');
fs.mkdirSync(path.join(localWebsiteCode, '.powerpages-site'), { recursive: true });
fs.writeFileSync(path.join(localWebsiteCode, '.powerpages-site', 'website.yml'), 'adx_name: Company\n');
fs.writeFileSync(path.join(localWebsiteCode, 'powerpages.config.json'), '{}');
fs.writeFileSync(path.join(localWebsiteCode, 'package.json'), '{}');
fs.writeFileSync(path.join(localWebsiteCode, '.npmrc'), 'omit-lockfile-registry-resolved=true\n');
writeUnpackedSolution(path.join(localSolutions, 'CompanyBase'), 'CompanyBase', { version: '1.0.0.0' });
writeUnpackedSolution(path.join(localSolutions, 'CompanyPortal'), 'CompanyPortal', { version: '2.0.0.0' });
}
return '';
},
});
const cached = downloadTemplateVariant({
owner: 'o',
repo: 'r',
sha: SHA,
kind: 'spa',
templateId: 'company',
variant: 'react',
cacheRoot: dir,
solutionSettings: [{ uniqueName: 'CompanyPortal', publishChanges: true }],
}, {
execFileSync() {
throw new Error('cached variant must not run git');
},
});
assert.equal(result.ok, true);
assert.equal(result.cached, false);
assert.equal(
result.variantPath,
repositoryDirectoryCheckoutRoot({ cacheRoot: dir, sha: SHA, directoryPath: variantPath })
);
const localSolutionsPath = repositoryDirectoryCheckoutRoot({
cacheRoot: dir,
sha: SHA,
directoryPath: solutionsPath,
});
assert.equal(result.websiteCodePath, path.join(result.variantPath, 'website-code'));
assert.deepEqual(result.solutions, [
{
uniqueName: 'CompanyBase',
version: '1.0.0.0',
solutionPath: path.join(localSolutionsPath, 'CompanyBase'),
publishChanges: false,
},
{
uniqueName: 'CompanyPortal',
version: '2.0.0.0',
solutionPath: path.join(localSolutionsPath, 'CompanyPortal'),
publishChanges: true,
},
]);
assert.deepEqual(cached, { ...result, cached: true });
assert.equal(calls.filter(([, args]) => args.includes('sparse-checkout')).length, 2);
assert.equal(calls.some(([, args]) => args.join(' ').includes(`sparse-checkout set --cone -- ${variantPath}`)), true);
assert.equal(calls.some(([, args]) => args.join(' ').includes(`sparse-checkout set --cone -- ${solutionsPath}`)), true);
});
test('downloadTemplateVariant replaces a symlinked checkout root instead of trusting its contents', (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
ensurePrivateCacheRoot(dir);
const variantPath = 'templates/spa/company/variants/react';
const solutionsPath = 'templates/spa/company/solutions';
const checkoutRoot = repositoryDirectoryCheckoutRoot({
cacheRoot: dir,
sha: SHA,
directoryPath: variantPath,
});
const outsideDir = path.join(dir, 'outside-variant');
fs.mkdirSync(path.join(outsideDir, 'website-code'), { recursive: true });
fs.writeFileSync(path.join(outsideDir, 'sentinel.txt'), 'outside');
fs.mkdirSync(path.dirname(checkoutRoot), { recursive: true });
try {
fs.symlinkSync(outsideDir, checkoutRoot, process.platform === 'win32' ? 'junction' : 'dir');
} catch (err) {
if (err.code === 'EPERM' || err.code === 'EACCES') {
t.skip(`symlinks are unavailable: ${err.code}`);
return;
}
throw err;
}
let partialRoot;
let gitCalls = 0;
const result = downloadTemplateVariant({
owner: 'o',
repo: 'r',
sha: SHA,
kind: 'spa',
templateId: 'company',
variant: 'react',
cacheRoot: dir,
}, {
execFileSync(command, args) {
gitCalls++;
if (args[0] === 'init') partialRoot = args[2];
if (args.includes('checkout')) {
const localWebsiteCode = path.join(partialRoot, ...variantPath.split('/'), 'website-code');
fs.mkdirSync(path.join(localWebsiteCode, '.powerpages-site'), { recursive: true });
fs.writeFileSync(path.join(localWebsiteCode, '.powerpages-site', 'website.yml'), 'adx_name: Company\n');
fs.writeFileSync(path.join(localWebsiteCode, 'powerpages.config.json'), '{}');
fs.writeFileSync(path.join(localWebsiteCode, 'package.json'), '{}');
fs.writeFileSync(path.join(localWebsiteCode, '.npmrc'), 'omit-lockfile-registry-resolved=true\n');
writeUnpackedSolution(
path.join(partialRoot, ...solutionsPath.split('/'), 'CompanyPortal'),
'CompanyPortal'
);
}
return '';
},
});
assert.equal(result.ok, true);
assert.equal(result.cached, false);
assert.ok(gitCalls > 0);
assert.equal(fs.readFileSync(path.join(outsideDir, 'sentinel.txt'), 'utf8'), 'outside');
assert.equal(fs.lstatSync(checkoutRoot).isSymbolicLink(), false);
});
test('downloadTemplateVariant rejects a symlinked checkout parent directory', (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
ensurePrivateCacheRoot(dir);
const outsideDir = path.join(dir, 'outside-checkouts');
const symlinkedParent = path.join(dir, SHA, '.directory-checkouts', 'templates', 'spa');
fs.mkdirSync(path.dirname(symlinkedParent), { recursive: true });
fs.mkdirSync(outsideDir);
try {
fs.symlinkSync(outsideDir, symlinkedParent, process.platform === 'win32' ? 'junction' : 'dir');
} catch (err) {
if (err.code === 'EPERM' || err.code === 'EACCES') {
t.skip(`symlinks are unavailable: ${err.code}`);
return;
}
throw err;
}
let gitCalled = false;
const result = downloadTemplateVariant({
owner: 'o',
repo: 'r',
sha: SHA,
kind: 'spa',
templateId: 'company',
variant: 'react',
cacheRoot: dir,
}, {
execFileSync() {
gitCalled = true;
return '';
},
});
assert.equal(result.ok, false);
assert.match(result.error, /cache path must contain only real directories/);
assert.equal(gitCalled, false);
});
test('downloadTemplateVariant accepts traditional website source with family solution components', (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const variantPath = 'templates/traditional/customer-self-service/variants/none';
const solutionsPath = 'templates/traditional/customer-self-service/solutions';
let partialRoot;
const result = downloadTemplateVariant({
owner: 'o',
repo: 'r',
sha: SHA,
kind: 'traditional',
templateId: 'customer-self-service',
variant: 'none',
cacheRoot: dir,
}, {
execFileSync(command, args) {
if (args[0] === 'init') partialRoot = args[2];
if (args.includes('checkout')) {
const localVariant = path.join(partialRoot, ...variantPath.split('/'));
const localSolutions = path.join(partialRoot, ...solutionsPath.split('/'));
const localWebsiteCode = path.join(localVariant, 'website-code');
fs.mkdirSync(path.join(localWebsiteCode, '.powerpages-site'), { recursive: true });
fs.writeFileSync(
path.join(localWebsiteCode, '.powerpages-site', 'website.yml'),
'adx_name: Customer self-service\n'
);
writeUnpackedSolution(
path.join(localSolutions, 'CustomerSelfService'),
'CustomerSelfService',
{ websiteComponents: true }
);
}
return '';
},
});
assert.equal(result.ok, true);
assert.equal(result.websiteCodePath, path.join(result.variantPath, 'website-code'));
assert.equal(result.solutions[0].uniqueName, 'CustomerSelfService');
});
test('template family and variant roots derive fixed paths from catalog identity', () => {
assert.equal(
templateFamilyRoot({
catalogPath: 'templates/manifest.json',
kind: 'spa',
templateId: 'company',
}),
'templates/spa/company'
);
assert.equal(
templateVariantRoot({
catalogPath: 'templates/manifest.json',
kind: 'spa',
templateId: 'company',
variant: 'React',
}),
'templates/spa/company/variants/react'
);
assert.throws(
() => templateVariantRoot({
catalogPath: 'templates/manifest.json',
kind: 'spa',
templateId: '../company',
variant: 'react',
}),
/Invalid template id/
);
});
test('downloadTemplateVariant rejects variant-local solutions when family solutions are missing', (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const variantPath = 'templates/spa/company/variants/react';
let partialRoot;
const result = downloadTemplateVariant({
owner: 'o',
repo: 'r',
sha: SHA,
kind: 'spa',
templateId: 'company',
variant: 'react',
cacheRoot: dir,
}, {
execFileSync(command, args) {
if (args[0] === 'init') partialRoot = args[2];
if (args.includes('checkout')) {
const localVariant = path.join(partialRoot, ...variantPath.split('/'));
const localWebsiteCode = path.join(localVariant, 'website-code');
fs.mkdirSync(path.join(localWebsiteCode, '.powerpages-site'), { recursive: true });
fs.writeFileSync(path.join(localWebsiteCode, '.powerpages-site', 'website.yml'), 'adx_name: Company\n');
fs.writeFileSync(path.join(localWebsiteCode, 'powerpages.config.json'), '{}');
fs.writeFileSync(path.join(localWebsiteCode, 'package.json'), '{}');
fs.writeFileSync(path.join(localWebsiteCode, '.npmrc'), 'omit-lockfile-registry-resolved=true\n');
writeUnpackedSolution(path.join(localVariant, 'solutions', 'CompanyPortal'), 'CompanyPortal');
}
return '';
},
});
assert.equal(result.ok, false);
assert.match(result.error, /Template is missing solutions/);
});
test('inspectTemplateSolutions rejects folder and Solution.xml unique-name drift', (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
writeUnpackedSolution(path.join(dir, 'WrongFolder'), 'ActualUniqueName');
const result = inspectTemplateSolutions(dir, 'spa');
assert.equal(result.ok, false);
assert.match(result.error, /WrongFolder must match .* ActualUniqueName/);
});
test('inspectTemplateSolutions requires a non-empty solutions directory containing only solution folders', (t) => {
const missingDir = path.join(tempDir(), 'missing');
t.after(() => fs.rmSync(path.dirname(missingDir), { recursive: true, force: true }));
assert.match(inspectTemplateSolutions(missingDir, 'spa').error, /missing solutions/);
const emptyDir = tempDir();
t.after(() => fs.rmSync(emptyDir, { recursive: true, force: true }));
assert.match(inspectTemplateSolutions(emptyDir, 'spa').error, /at least one solution/);
fs.writeFileSync(path.join(emptyDir, 'README.md'), 'not a solution');
assert.match(inspectTemplateSolutions(emptyDir, 'spa').error, /non-directory entry: README\.md/);
});
test('unpacked solution validation can allow website artifacts for traditional templates', (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
assert.match(validateUnpackedSolutionDirectory(dir), /missing Other[/\\]Solution.xml/);
const other = path.join(dir, 'Other');
fs.mkdirSync(other);
fs.writeFileSync(
path.join(other, 'Solution.xml'),
'<ImportExportXml><SolutionManifest><Managed>0</Managed></SolutionManifest></ImportExportXml>'
);
fs.writeFileSync(path.join(other, 'Customizations.xml'), '<ImportExportXml />');
assert.equal(validateUnpackedSolutionDirectory(dir), null);
fs.writeFileSync(path.join(other, 'Solution.xml'), '<SolutionManifest><Managed>1</Managed></SolutionManifest>');
assert.match(validateUnpackedSolutionDirectory(dir), /unmanaged/);
fs.writeFileSync(path.join(other, 'Solution.xml'), '<SolutionManifest><Managed>0</Managed></SolutionManifest>');
fs.writeFileSync(path.join(other, 'Customizations.xml'), '<ImportExportXml><powerpagecomponents /></ImportExportXml>');
assert.match(validateUnpackedSolutionDirectory(dir), /website components/);
assert.equal(validateUnpackedSolutionDirectory(dir, { allowWebsiteComponents: true }), null);
fs.writeFileSync(path.join(other, 'Customizations.xml'), '<ImportExportXml />');
fs.writeFileSync(path.join(dir, 'committed.zip'), 'zip');
assert.match(validateUnpackedSolutionDirectory(dir), /committed zip/);
});
test('website code validation handles SPA and traditional source layouts', (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
fs.mkdirSync(path.join(dir, '.powerpages-site'));
fs.writeFileSync(path.join(dir, '.powerpages-site', 'website.yml'), 'adx_name: Company\n');
fs.writeFileSync(path.join(dir, 'powerpages.config.json'), '{}');
fs.writeFileSync(path.join(dir, 'package.json'), '{}');
assert.match(validateWebsiteCodeDirectory(dir, { kind: 'spa' }), /missing \.npmrc/);
fs.writeFileSync(path.join(dir, '.npmrc'), 'omit-lockfile-registry-resolved=true\n');
fs.mkdirSync(path.join(dir, 'node_modules'));
assert.match(validateWebsiteCodeDirectory(dir, { kind: 'spa' }), /generated or local-only/);
const traditionalDir = tempDir();
t.after(() => fs.rmSync(traditionalDir, { recursive: true, force: true }));
fs.mkdirSync(path.join(traditionalDir, '.powerpages-site'));
fs.writeFileSync(
path.join(traditionalDir, '.powerpages-site', 'website.yml'),
'adx_name: Traditional Site\n'
);
assert.equal(validateWebsiteCodeDirectory(traditionalDir, { kind: 'traditional' }), null);
});
test('website code validation rejects a symlinked root', (t) => {
const dir = tempDir();
const target = tempDir();
t.after(() => {
fs.rmSync(dir, { recursive: true, force: true });
fs.rmSync(target, { recursive: true, force: true });
});
const link = path.join(dir, 'website-code');
try {
fs.symlinkSync(target, link, 'dir');
} catch (err) {
if (err.code === 'EPERM' || err.code === 'EACCES') {
t.skip(`directory symlinks are unavailable: ${err.code}`);
return;
}
throw err;
}
assert.match(validateWebsiteCodeDirectory(link, { kind: 'spa' }), /regular directory/);
});
test('downloadSeedDataDirectory downloads a seed JSON file and its referenced __files attachments without tree API', async (t) => {
const dir = tempDir();
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const downloaded = [];
const result = await downloadSeedDataDirectory({
owner: 'o',
repo: 'r',
sha: SHA,
seedDataPath: 'templates/spa/company/seed/data.json',
cacheRoot: dir,
}, {
requestJson: async () => {
throw new Error('tree API should not be called for seed JSON paths');
},
downloadFile: async (_url, dest) => {
downloaded.push(path.basename(dest));
fs.mkdirSync(path.dirname(dest), { recursive: true });
if (dest.endsWith('data.json')) {
fs.writeFileSync(dest, JSON.stringify({
entitySetName: 'cr123_invoices',
records: [
{ __files: { cr123_invoicepdf: 'files/invoice.pdf' } },
{ __files: { cr123_metadata: 'files/metadata.json' } },
{ __files: { cr123_terms: 'files/terms.docx' } },
],
}));
} else {
fs.writeFileSync(dest, 'file-bytes');
}
},
});
assert.equal(result.ok, true);
assert.equal(result.localDir, path.join(dir, SHA, 'templates/spa/company/seed'));
assert.equal(result.seedFile, path.join(dir, SHA, 'templates/spa/company/seed/data.json'));
assert.deepEqual(downloaded, ['data.json', 'invoice.pdf', 'metadata.json', 'terms.docx']);
});
test('downloadSeedDataDirectory rejects directory seed paths without calling the GitHub tree API', async () => {
const result = await downloadSeedDataDirectory({
owner: 'o',
repo: 'r',
sha: SHA,
seedDataPath: 'templates/spa/company/seed-data',
}, {
requestJson: async () => {
throw new Error('tree API should not be called');
},
});
assert.deepEqual(result, {
ok: false,
seedDataPath: 'templates/spa/company/seed-data',
error: 'Seed data path must point to a JSON file: templates/spa/company/seed-data',
});
});
test('fetch-template-seed-data CLI parser accepts seed data path', () => {
assert.deepEqual(parseSeedArgs([
'--owner', 'contoso',
'--repo', 'samples',
'--sha', SHA,
'--seedDataPath', 'templates/spa/company/seed/data.json',
'--cacheRoot', '/tmp/cache',
]), {
owner: 'contoso',
repo: 'samples',
sha: SHA,
seedDataPath: 'templates/spa/company/seed/data.json',
cacheRoot: '/tmp/cache',
});
});
test('validateZipContainsSolution recognizes solution.xml without requiring external unzip', () => {
assert.deepEqual(zipFileNames(fakeZipWithLocalFile('solution.xml')), ['solution.xml']);
assert.equal(validateZipContainsSolution('/tmp/ok.zip', {
fs: { readFileSync: () => fakeZipWithLocalFile('solution.xml') },
}), true);
assert.equal(validateZipContainsSolution('/tmp/nope.zip', {
fs: { readFileSync: () => fakeZipWithLocalFile('customizations.xml') },
}), false);
assert.equal(validateZipContainsSolution('/tmp/nested.zip', {
fs: { readFileSync: () => fakeZipWithLocalFile('folder/solution.xml') },
}), false);
assert.equal(validateZipContainsSolution('/tmp/broken.zip', {
fs: { readFileSync: () => { throw new Error('not a zip'); } },
}), false);
});
test('fetch-template-catalog CLI parser accepts repo/ref/cache options', () => {
assert.deepEqual(parseCatalogArgs([
'--owner', 'contoso',
'--repo', 'samples',
'--ref', 'release/v1',
'--catalogPath', 'templates/custom.json',
'--cacheRoot', '/tmp/cache',
]), {
owner: 'contoso',
repo: 'samples',
ref: 'release/v1',
catalogPath: 'templates/custom.json',
cacheRoot: '/tmp/cache',
});
});
test('fetch-template-catalog CLI parser defaults ref to latest-release', () => {
assert.equal(parseCatalogArgs([]).ref, 'latest-release');
});
test('fetch-template-variant CLI parser accepts derivable variant identity', () => {
assert.deepEqual(parseVariantArgs([
'--owner', 'contoso',
'--repo', 'samples',
'--sha', SHA,
'--kind', 'spa',
'--templateId', 'company',
'--variant', 'react',
'--solutionSettingsJson', '[{"uniqueName":"CompanyPortal","publishChanges":true}]',
'--catalogPath', 'templates/manifest.json',
'--cacheRoot', '/tmp/cache',
]), {
owner: 'contoso',
repo: 'samples',
sha: SHA,
kind: 'spa',
templateId: 'company',
variant: 'react',
solutionSettings: [{ uniqueName: 'CompanyPortal', publishChanges: true }],
catalogPath: 'templates/manifest.json',
cacheRoot: '/tmp/cache',
});
});
test('fetch-template-artifact CLI parser maps artifactPath to the shared artifact option', () => {
assert.deepEqual(parseArtifactArgs([
'--owner', 'contoso',
'--repo', 'samples',
'--sha', SHA,
'--artifactPath', 'templates/spa/company/previews/home.png',
'--cacheRoot', '/tmp/cache',
]), {
owner: 'contoso',
repo: 'samples',
sha: SHA,
artifactPath: 'templates/spa/company/previews/home.png',
cacheRoot: '/tmp/cache',
});
});
test('shared template CLI arg parser handles common repo/cache and path flags', () => {
assert.deepEqual(parseTemplateRepoArgs([
'--owner', 'contoso',
'--repo', 'samples',
'--ref', 'main',
'--sha', SHA,
'--cacheRoot', '/tmp/cache',
'--solutionPath', 'templates/spa/company/solution',
], '--solutionPath'), {
owner: 'contoso',
repo: 'samples',
ref: 'main',
sha: SHA,
cacheRoot: '/tmp/cache',
artifactPath: 'templates/spa/company/solution',
});
});
test('shared JSON CLI runner formats success and fail-open errors', async () => {
const writes = [];
const processes = [{}, {}];
await runBestEffortJsonCli(async () => ({ ok: true, value: 1 }), {
stdout: { write: (value) => writes.push(value) },
process: processes[0],
});
await runBestEffortJsonCli(async () => { throw new Error('boom'); }, {
stdout: { write: (value) => writes.push(value) },
process: processes[1],
});
assert.equal(formatJsonResult({ ok: true }), '{\n "ok": true\n}\n');
assert.deepEqual(processes.map((proc) => proc.exitCode), [0, 0]);
assert.match(writes[0], /"value": 1/);
assert.match(writes[1], /"ok": false/);
assert.match(writes[1], /"error": "boom"/);
});