microsoft/power-platform-skills / plugins/power-pages/skills/compare-site-configurations
compare-site-configurations
UnverifiedCompare Power Pages site configurations between two environments, such as dev, test and production, or between a local download and the live site, and explain which differences change site behavior. Use when a site works in one environment but not another (for example, works in dev but fails in test), to check configuration drift before promoting or deploying, or to see what changed between two sites. Produces a shareable HTML report and a JSON file that VS Code can import.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 7.8 KB |
| references/explain-differences.md | markdown | 3.7 KB |
| references/remote-sites.md | markdown | 2.9 KB |
| scripts/compare-site-configurations.js | script | 84.3 KB |
| scripts/tests/site-configuration-comparison.test.js | script | 27.2 KB |
scripts/compare-site-configurations.js
View on GitHub#!/usr/bin/env node
/*
Copyright (c) Microsoft Corporation.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { pathToFileURL } = require('node:url');
const { parseArgs, assertOutsideSite, within } = require('../../../scripts/lib/non-spa-site-style-context');
const { openInDefaultBrowser } = require('../../../scripts/lib/default-browser');
const { readWebsiteIdentity } = require('../../create-site/scripts/validate-site');
const { readPluginManifest } = require('../../../scripts/check-version');
// The original renderer uses VS Code filesystem APIs and the extension version.
// Supply those values locally so its comparison and HTML functions stay unchanged.
const tools = (() => {
const vscode = {
Uri: { file: fsPath => ({ fsPath }) },
workspace: { fs: {
stat: uri => fs.promises.stat(uri.fsPath),
readFile: uri => fs.promises.readFile(uri.fsPath),
} },
};
// Report branding deviates from the extension: the subtitle and footer name
// this plugin, the footer links to it, and the header shows the installed
// plugin version instead of an extension version.
const getExtensionVersion = () => readPluginManifest()?.version || 'unknown';
const PLUGIN_URL = 'https://github.com/microsoft/power-platform-skills/tree/main/plugins/power-pages';
const Constants = { Strings: {
"HTML_REPORT_TITLE": "Site Comparison Report",
"HTML_REPORT_SUBTITLE": "Power Pages AI Plugin - Power Platform Skills",
"HTML_REPORT_TOTAL_CHANGES": "Total Changes",
"HTML_REPORT_ADDED": "Added Locally",
"HTML_REPORT_MODIFIED": "Modified",
"HTML_REPORT_DELETED": "Deleted Locally",
"HTML_REPORT_COMPARISON_DETAILS": "Comparison Details",
"HTML_REPORT_LOCAL_SECTION": "Local",
"HTML_REPORT_REMOTE_SECTION": "Remote",
"HTML_REPORT_SITE_NAME_LABEL": "Site Name:",
"HTML_REPORT_ENVIRONMENT_LABEL": "Environment:",
"HTML_REPORT_WEBSITE_ID_LABEL": "Website ID:",
"HTML_REPORT_WEBSITE_URL_LABEL": "Website URL:",
"HTML_REPORT_SITE_VISIBILITY_LABEL": "Site Visibility:",
"HTML_REPORT_CREATOR_LABEL": "Creator:",
"HTML_REPORT_CREATED_ON_LABEL": "Created On:",
"HTML_REPORT_GENERATED_LABEL": "Generated:",
"HTML_REPORT_EXTENSION_VERSION_LABEL": "Plugin Version:",
"HTML_REPORT_TOTAL_FILES_LABEL": "Total Files:",
"HTML_REPORT_CHANGED_FILES": "Changed Files",
"HTML_REPORT_CLICK_TO_EXPAND": "(click to expand diff)",
"HTML_REPORT_EXPAND_ALL": "Expand All",
"HTML_REPORT_COLLAPSE_ALL": "Collapse All",
"HTML_REPORT_TAB_ALL": "All",
"HTML_REPORT_NO_FILES_IN_CATEGORY": "No files in this category",
"HTML_REPORT_GENERATED_BY": "Generated by",
"HTML_REPORT_EXTENSION_NAME": "Power Pages AI Plugin",
"HTML_REPORT_STATUS_MODIFIED": "Modified",
"HTML_REPORT_STATUS_ADDED": "Added Locally",
"HTML_REPORT_STATUS_DELETED": "Deleted Locally",
"HTML_REPORT_STATUS_UNKNOWN": "Unknown",
"HTML_REPORT_BINARY_FILE_MESSAGE": "Binary file - content comparison not available",
"HTML_REPORT_UNABLE_TO_READ_CONTENTS": "Unable to read file contents",
"HTML_REPORT_UNABLE_TO_READ_LOCAL": "Unable to read local file",
"HTML_REPORT_UNABLE_TO_READ_REMOTE": "Unable to read remote file",
"HTML_REPORT_UNABLE_TO_READ_BOTH": "Unable to read one or both files",
"HTML_REPORT_FILE_TOO_LARGE_MESSAGE": "File is too large to display diff (exceeds 5MB)",
"HTML_REPORT_LARGE_FILE_MESSAGE": "File is too large for detailed diff comparison",
"HTML_REPORT_REMOTE_LINES": "Remote",
"HTML_REPORT_LOCAL_LINES": "Local",
"HTML_REPORT_LINES": "lines",
"HTML_REPORT_LINE_DIFFERENCE": "Difference"
} };
/**
* Constants for file comparison status values
*/
const FileComparisonStatus = {
MODIFIED: "modified",
ADDED: "added",
DELETED: "deleted"
};
const POWERPAGES_SITE_FOLDER = ".powerpages-site";
/**
* Common binary file extensions that cannot be diffed in the text diff viewer
*/
const BINARY_FILE_EXTENSIONS = new Set([
// Images
".png", ".jpg", ".jpeg", ".gif", ".ico", ".webp", ".bmp", ".tiff", ".tif",
// Fonts
".woff", ".woff2", ".ttf", ".otf", ".eot",
// Media
".mp4", ".mp3", ".wav", ".ogg", ".webm", ".avi", ".mov",
// Documents
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
// Archives
".zip", ".rar", ".7z", ".tar", ".gz",
// Other binary
".exe", ".dll", ".so", ".dylib"
]);
/**
* Checks if a file is a binary file based on its extension.
* Binary files cannot be meaningfully diffed as text.
* @param filePath The file path to check
* @param includeSvg Whether to treat SVG as binary (true for diff viewing, false for export since SVG is text)
* @returns True if the file is binary, false otherwise
*/
function isBinaryFile(filePath, includeSvg = true) {
const lowerPath = filePath.toLowerCase();
const lastDotIndex = lowerPath.lastIndexOf(".");
if (lastDotIndex === -1) {
return false;
}
const extension = lowerPath.substring(lastDotIndex);
// SVG is text-based but may be treated as binary for diff viewing purposes
if (extension === ".svg") {
return includeSvg;
}
return BINARY_FILE_EXTENSIONS.has(extension);
}
/**
* Recursively collects all files from a directory
* @param dir Directory to scan
* @param baseDir Base directory for calculating relative paths
* @returns Map of relative path to absolute path
*/
function getAllFiles(dir, baseDir = dir) {
const files = new Map();
if (!fs.existsSync(dir)) {
return files;
}
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
// Skip folders starting with '.' like .github, .portalconfig etc.
if (entry.name.startsWith(".")) {
continue;
}
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
const subFiles = getAllFiles(fullPath, baseDir);
subFiles.forEach((value, key) => files.set(key, value));
}
else if (entry.isFile()) {
const relativePath = path.relative(baseDir, fullPath);
files.set(relativePath, fullPath);
}
}
return files;
}
const GITIGNORE_FILE_NAME = ".gitignore";
const POWERPAGES_CONFIG_FILE_NAME = "powerpages.config.json";
/**
* Patterns that are always ignored when comparing source files in code sites.
* These match the patterns used in the PAC CLI for code site uploads.
*/
const ALWAYS_IGNORE_PATTERNS = [
".git/**",
".github/**",
"node_modules/**",
`${POWERPAGES_SITE_FOLDER}/**`
];
/**
* Reads and parses the powerpages.config.json file from the given directory
* @param rootPath The root directory containing the config file
* @returns The parsed config or undefined if not found or invalid
*/
function readPowerPagesConfig(rootPath) {
const configPath = path.join(rootPath, POWERPAGES_CONFIG_FILE_NAME);
if (!fs.existsSync(configPath)) {
return undefined;
}
try {
const configContent = fs.readFileSync(configPath, "utf8");
return JSON.parse(configContent);
}
catch {
// Invalid JSON or read error - return undefined
return undefined;
}
}
/**
* Normalizes a gitignore pattern for regex conversion
* @param pattern The raw pattern from .gitignore
* @returns Normalized pattern
*/
function normalizePattern(pattern) {
let normalized = pattern.replace(/\\/g, "/");
if (normalized.startsWith("./")) {
normalized = normalized.substring(2);
}
if (normalized.startsWith("/")) {
normalized = normalized.substring(1);
}
if (normalized.endsWith("/")) {
normalized += "**";
}
return normalized;
}
/**
* Converts a glob pattern to a regular expression
* @param pattern The glob pattern to convert
* @returns Regular expression matching the glob pattern
*/
function globToRegex(pattern) {
const regexPattern = pattern
.replace(/[.+^${}()|[\]\\]/g, "\\$&") // Escape special regex chars except * and ?
.replace(/\*\*/g, "{{DOUBLE_STAR}}") // Temporarily replace ** to avoid conflict
.replace(/\*/g, "[^/]*") // * matches anything except /
.replace(/\?/g, "[^/]") // ? matches single char except /
.replace(/\{\{DOUBLE_STAR\}\}/g, ".*"); // ** matches anything including /
return new RegExp("^" + regexPattern + "$", "i");
}
/**
* Parses a gitignore line and adds it to the rules list
* @param rawPattern The raw line from .gitignore
* @param rules The list of rules to add to
*/
function addGitIgnoreRule(rawPattern, rules) {
const line = rawPattern.trim();
// Skip empty lines and comments
if (!line || line.startsWith("#")) {
return;
}
const isNegation = line.startsWith("!");
const pattern = isNegation ? line.substring(1) : line;
const normalizedPattern = normalizePattern(pattern);
const regex = globToRegex(normalizedPattern);
rules.push({ pattern: regex, isNegation });
}
/**
* Checks if a relative path is ignored according to the gitignore rules
* @param relativePath The relative path to check
* @param rules The list of gitignore rules
* @returns True if the path should be ignored
*/
function isIgnored(relativePath, rules) {
const normalizedPath = relativePath.replace(/\\/g, "/");
let ignored = false;
for (const { pattern, isNegation } of rules) {
if (pattern.test(normalizedPath)) {
ignored = !isNegation;
}
}
return ignored;
}
/**
* Gets all files from a directory filtered by gitignore rules and powerpages.config.json settings.
* This is used for comparing source files in code sites.
* @param rootPath The root directory to scan
* @param config Optional PowerPagesConfig with sourceExcludePatterns
* @returns Map of relative path to absolute path for non-ignored files
*/
function getFilteredSourceFiles(rootPath, config) {
const files = new Map();
if (!fs.existsSync(rootPath)) {
return files;
}
// Build gitignore rules
const rules = [];
// Read .gitignore if it exists
const gitignorePath = path.join(rootPath, GITIGNORE_FILE_NAME);
if (fs.existsSync(gitignorePath)) {
const gitignoreContent = fs.readFileSync(gitignorePath, "utf8");
const lines = gitignoreContent.split(/\r?\n/);
for (const line of lines) {
addGitIgnoreRule(line, rules);
}
}
// Add always-ignored patterns (at the end, so they override .gitignore)
for (const pattern of ALWAYS_IGNORE_PATTERNS) {
addGitIgnoreRule(pattern, rules);
}
// Add sourceExcludePatterns from powerpages.config.json if provided
if (config?.sourceExcludePatterns) {
for (const pattern of config.sourceExcludePatterns) {
addGitIgnoreRule(pattern, rules);
}
}
// Recursively get all files
const getAllFilesRecursive = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
const relativePath = path.relative(rootPath, fullPath).replace(/\\/g, "/");
if (entry.isDirectory()) {
// Check if directory should be ignored before recursing
// Add trailing slash for directory matching
if (!isIgnored(relativePath + "/", rules) && !isIgnored(relativePath, rules)) {
getAllFilesRecursive(fullPath);
}
}
else if (entry.isFile()) {
if (!isIgnored(relativePath, rules)) {
files.set(relativePath, fullPath);
}
}
}
};
getAllFilesRecursive(rootPath);
return files;
}
/**
* Gets all files from the .powerpages-site folder, including it even though it starts with a dot.
* @param rootPath The root directory containing the .powerpages-site folder
* @returns Map of relative path to absolute path for files in .powerpages-site
*/
function getPowerPagesSiteFiles(rootPath) {
const powerPagesSitePath = path.join(rootPath, POWERPAGES_SITE_FOLDER);
const files = new Map();
if (!fs.existsSync(powerPagesSitePath)) {
return files;
}
// Get all files from .powerpages-site, but use getAllFiles with base at .powerpages-site
// Then prefix the relative paths with .powerpages-site/
const siteFiles = getAllFiles(powerPagesSitePath);
for (const [relativePath, absolutePath] of siteFiles) {
const prefixedPath = path.join(POWERPAGES_SITE_FOLDER, relativePath).replace(/\\/g, "/");
files.set(prefixedPath, absolutePath);
}
return files;
}
/**
* Checks if a downloaded code site has source code (files outside .powerpages-site folder)
* @param downloadedSitePath Path to the downloaded site
* @returns True if the site has source code, false if it only has .powerpages-site folder
*/
function hasSourceCode(downloadedSitePath) {
if (!fs.existsSync(downloadedSitePath)) {
return false;
}
const entries = fs.readdirSync(downloadedSitePath, { withFileTypes: true });
for (const entry of entries) {
// Skip the .powerpages-site folder and other dot folders
if (entry.name.startsWith(".")) {
continue;
}
// Any non-dot file or folder means there's source code
return true;
}
return false;
}
/**
* Compares files between downloaded site and local workspace
* @param downloadedSitePath Path to the downloaded site
* @param localSitePath Path to the local site
* @param options Optional comparison options for code site handling
* @returns Array of file comparison results
*
* Comparison logic for code sites:
* 1. Code site (remote) vs non-code site (local): Compare remote's .powerpages-site with entire local site
* 2. Non-code site (remote) vs non-code site (local): Compare everything
* 3. Code site (remote) vs code site (local):
* a. If remote has no source code (only .powerpages-site): Compare only .powerpages-site folders
* b. If remote has source code: Compare .powerpages-site folders AND filtered source files
*/
function compareFiles(downloadedSitePath, localSitePath, options) {
const results = [];
const isRemoteCodeSite = options?.isRemoteCodeSite ?? false;
const isLocalCodeSite = options?.isLocalCodeSite ?? false;
const localCodeSiteRootPath = options?.localCodeSiteRootPath;
// Determine comparison mode based on code site status
if (isRemoteCodeSite && isLocalCodeSite) {
// Case 3: Both are code sites
const remoteHasSourceCode = hasSourceCode(downloadedSitePath);
// Always compare .powerpages-site folders when both are code sites
const remotePowerPagesFiles = getPowerPagesSiteFiles(downloadedSitePath);
const localPowerPagesPath = localCodeSiteRootPath || path.dirname(localSitePath);
const localPowerPagesFiles = getPowerPagesSiteFiles(localPowerPagesPath);
compareFileMaps(remotePowerPagesFiles, localPowerPagesFiles, downloadedSitePath, localPowerPagesPath, results);
if (remoteHasSourceCode) {
// Case 3b: Remote has source code - also compare filtered source files
// Only read powerpages.config.json from local site - remote files are already filtered during upload
const localSourcePath = localCodeSiteRootPath || path.dirname(localSitePath);
const localConfig = readPowerPagesConfig(localSourcePath);
const remoteSourceFiles = getFilteredSourceFiles(downloadedSitePath);
const localSourceFiles = getFilteredSourceFiles(localSourcePath, localConfig);
compareFileMaps(remoteSourceFiles, localSourceFiles, downloadedSitePath, localSourcePath, results);
}
// Case 3a: Remote only has .powerpages-site - already compared above
}
else if (isRemoteCodeSite && !isLocalCodeSite) {
// Case 1: Remote is code site, local is not
// Compare remote's .powerpages-site folder with entire local site
const effectiveRemotePath = path.join(downloadedSitePath, POWERPAGES_SITE_FOLDER);
const downloadedFiles = getAllFiles(effectiveRemotePath);
const localFiles = getAllFiles(localSitePath);
compareFileMaps(downloadedFiles, localFiles, effectiveRemotePath, localSitePath, results);
}
else if (!isRemoteCodeSite && isLocalCodeSite) {
// Case 2 (inverse): Remote is not code site, local is code site
// Compare entire remote with local's .powerpages-site folder (localSitePath already points there)
const downloadedFiles = getAllFiles(downloadedSitePath);
const localFiles = getAllFiles(localSitePath);
compareFileMaps(downloadedFiles, localFiles, downloadedSitePath, localSitePath, results);
}
else {
// Case 4: Neither is code site - compare everything (default behavior)
const downloadedFiles = getAllFiles(downloadedSitePath);
const localFiles = getAllFiles(localSitePath);
compareFileMaps(downloadedFiles, localFiles, downloadedSitePath, localSitePath, results);
}
return results;
}
/**
* Normalizes line endings in a text buffer so that CRLF and lone CR are treated
* the same as LF. CR (0x0D) and LF (0x0A) are single-byte ASCII characters that
* never appear as UTF-8 continuation bytes, so decoding as UTF-8 before normalizing
* is safe for multi-byte content.
* @param content The file content buffer
* @returns The content as a string with normalized (LF) line endings
*/
function normalizeLineEndings(content) {
return content.toString("utf8").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
}
/**
* Determines whether two file contents are equal for diff purposes.
* Binary files are compared byte-for-byte. Text files are first compared
* byte-for-byte and, if that fails, compared again after normalizing line
* endings so that files differing only by CRLF vs LF are not reported as modified.
* @param localContent The local file content buffer
* @param remoteContent The remote file content buffer
* @param relativePath The relative path of the file (used to detect binary files)
* @returns True if the contents are considered equal, false otherwise
*/
function areFileContentsEqual(localContent, remoteContent, relativePath) {
if (localContent.equals(remoteContent)) {
return true;
}
// SVG is text-based, so treat it as text (includeSvg=false) for content comparison
if (isBinaryFile(relativePath, false)) {
return false;
}
return normalizeLineEndings(localContent) === normalizeLineEndings(remoteContent);
}
/**
* Compares two file maps and adds results to the results array.
* File path comparison is case-insensitive to handle Windows file system behavior.
* @param remoteFiles Map of remote files (relative path -> absolute path)
* @param localFiles Map of local files (relative path -> absolute path)
* @param remoteBasePath Base path for remote files (for constructing paths)
* @param localBasePath Base path for local files (for constructing paths)
* @param results Array to add comparison results to
*/
function compareFileMaps(remoteFiles, localFiles, remoteBasePath, localBasePath, results) {
// Create case-insensitive lookup maps
const localFilesLowerCase = new Map();
for (const [relativePath, absolutePath] of localFiles) {
localFilesLowerCase.set(relativePath.toLowerCase(), { originalPath: relativePath, absolutePath });
}
const remoteFilesLowerCase = new Map();
for (const [relativePath, absolutePath] of remoteFiles) {
remoteFilesLowerCase.set(relativePath.toLowerCase(), { originalPath: relativePath, absolutePath });
}
// Check for modified and deleted files (files in remote but may differ locally or not exist)
for (const [relativePath, remotePath] of remoteFiles) {
const lowerCasePath = relativePath.toLowerCase();
const localEntry = localFilesLowerCase.get(lowerCasePath);
if (localEntry) {
// File exists in both - check if content differs
const remoteContent = fs.readFileSync(remotePath);
const localContent = fs.readFileSync(localEntry.absolutePath);
if (!areFileContentsEqual(localContent, remoteContent, localEntry.originalPath)) {
// Check if we already have a result for this path (case-insensitive)
if (!results.some(r => r.relativePath.toLowerCase() === lowerCasePath)) {
results.push({
localPath: localEntry.absolutePath,
remotePath,
relativePath: localEntry.originalPath, // Use local path casing for display
status: FileComparisonStatus.MODIFIED
});
}
}
}
else {
// File exists in remote but not locally - deleted locally
if (!results.some(r => r.relativePath.toLowerCase() === lowerCasePath)) {
results.push({
localPath: path.join(localBasePath, relativePath),
remotePath,
relativePath,
status: FileComparisonStatus.DELETED
});
}
}
}
// Check for added files (files in local but not in remote)
for (const [relativePath, localPath] of localFiles) {
const lowerCasePath = relativePath.toLowerCase();
if (!remoteFilesLowerCase.has(lowerCasePath)) {
if (!results.some(r => r.relativePath.toLowerCase() === lowerCasePath)) {
results.push({
localPath,
remotePath: path.join(remoteBasePath, relativePath),
relativePath,
status: FileComparisonStatus.ADDED
});
}
}
}
}
/**
* Maximum file size in bytes to include content in the report (5MB)
* Files larger than this will be marked as too large to diff
*/
const MAX_FILE_SIZE_FOR_DIFF = 5 * 1024 * 1024;
/**
* Maximum number of lines to process in the LCS diff algorithm
* Files with more lines will use a simplified diff display
*/
const MAX_LINES_FOR_LCS_DIFF = 20000;
/**
* Formats a date for use in a file name (YYYY-MM-DD-HHmmss)
*/
function formatDateForFileName(date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
return `${year}-${month}-${day}-${hours}${minutes}${seconds}`;
}
/**
* Formats a date for display in the report (includes timezone)
*/
function formatDateForDisplay(date) {
const options = {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
timeZoneName: "short"
};
return date.toLocaleString(undefined, options);
}
/**
* Checks if a file is too large to include in the diff report
*/
async function isFileTooLarge(filePath) {
try {
const uri = vscode.Uri.file(filePath);
const stat = await vscode.workspace.fs.stat(uri);
return stat.size > MAX_FILE_SIZE_FOR_DIFF;
}
catch {
return false; // If we can't stat, let it try to read
}
}
/**
* Reads file contents for all comparison results
* Skips binary files, large files, and handles missing files gracefully
*/
async function readFileContents(comparisonResults) {
const fileContents = [];
for (const result of comparisonResults) {
const isBinary = isBinaryFile(result.relativePath);
if (isBinary) {
fileContents.push({
result,
localContent: null,
remoteContent: null,
isBinary: true,
isTooLarge: false
});
continue;
}
// Check if files are too large
let localTooLarge = false;
let remoteTooLarge = false;
if (result.status !== FileComparisonStatus.DELETED) {
localTooLarge = await isFileTooLarge(result.localPath);
}
if (result.status !== FileComparisonStatus.ADDED) {
remoteTooLarge = await isFileTooLarge(result.remotePath);
}
if (localTooLarge || remoteTooLarge) {
fileContents.push({
result,
localContent: null,
remoteContent: null,
isBinary: false,
isTooLarge: true
});
continue;
}
let localContent = null;
let remoteContent = null;
try {
if (result.status !== FileComparisonStatus.DELETED) {
const localUri = vscode.Uri.file(result.localPath);
const localData = await vscode.workspace.fs.readFile(localUri);
localContent = new TextDecoder().decode(localData);
}
}
catch {
// File may not exist or be readable
localContent = null;
}
try {
if (result.status !== FileComparisonStatus.ADDED) {
const remoteUri = vscode.Uri.file(result.remotePath);
const remoteData = await vscode.workspace.fs.readFile(remoteUri);
remoteContent = new TextDecoder().decode(remoteData);
}
}
catch {
// File may not exist or be readable
remoteContent = null;
}
fileContents.push({
result,
localContent,
remoteContent,
isBinary: false,
isTooLarge: false
});
}
return fileContents;
}
/**
* Gets the status display text
*/
function getStatusText(status) {
switch (status) {
case FileComparisonStatus.MODIFIED:
return Constants.Strings.HTML_REPORT_STATUS_MODIFIED;
case FileComparisonStatus.ADDED:
return Constants.Strings.HTML_REPORT_STATUS_ADDED;
case FileComparisonStatus.DELETED:
return Constants.Strings.HTML_REPORT_STATUS_DELETED;
default:
return Constants.Strings.HTML_REPORT_STATUS_UNKNOWN;
}
}
/**
* Gets the CSS class for a status badge
*/
function getStatusClass(status) {
switch (status) {
case FileComparisonStatus.MODIFIED:
return "status-modified";
case FileComparisonStatus.ADDED:
return "status-added";
case FileComparisonStatus.DELETED:
return "status-deleted";
default:
return "";
}
}
/**
* Groups comparison results by status
*/
function groupByStatus(results) {
const grouped = new Map();
for (const result of results) {
const existing = grouped.get(result.status) || [];
existing.push(result);
grouped.set(result.status, existing);
}
return grouped;
}
/**
* Mapping of folder names to display names for component types
*/
const componentTypeDisplayNames = {
"website-languages": "Site Languages",
"web-pages": "Web Pages",
"content-snippets": "Content Snippets",
"web-files": "Web Files",
"site-settings": "Site Settings",
"weblink-sets": "Web Links",
"site-markers": "Site Markers",
"basic-forms": "Basic Forms",
"advanced-forms": "Advanced Forms",
"web-templates": "Web Templates",
"page-templates": "Page Templates",
"lists": "Lists",
"table-permissions": "Permissions",
"polls": "Polls",
"poll-placements": "Poll Placements",
"others": "Others"
};
const componentTypeAliases = {
"site-languages": "website-languages"
};
/**
* Ordered list of component types for consistent tab ordering
*/
const componentTypeOrder = [
"website-languages",
"web-pages",
"content-snippets",
"web-files",
"site-settings",
"weblink-sets",
"site-markers",
"basic-forms",
"advanced-forms",
"web-templates",
"page-templates",
"lists",
"table-permissions",
"polls",
"poll-placements",
"others"
];
/**
* Gets the component type from a file's relative path
* @internal Exported for testing
*/
function getComponentTypeFromPath(relativePath) {
// Normalize path separators
const normalizedPath = relativePath.replace(/\\/g, "/");
const pathSegments = normalizedPath.split("/").filter(Boolean);
const firstFolder = pathSegments[0] === POWERPAGES_SITE_FOLDER ? pathSegments[1] : pathSegments[0];
const componentType = componentTypeAliases[firstFolder] || firstFolder;
// Check if it's a known component type
if (componentTypeDisplayNames[componentType] && componentType !== "others") {
return componentType;
}
return "others";
}
/**
* Gets the display name for a component type
* @internal Exported for testing
*/
function getComponentTypeDisplayName(componentType) {
return componentTypeDisplayNames[componentType] || componentType;
}
/**
* Groups file content comparisons by component type
*/
function groupByComponentType(fileContents) {
const grouped = new Map();
for (const fc of fileContents) {
const componentType = getComponentTypeFromPath(fc.result.relativePath);
const existing = grouped.get(componentType) || [];
existing.push(fc);
grouped.set(componentType, existing);
}
// Sort the map by the predefined order
const sortedMap = new Map();
for (const componentType of componentTypeOrder) {
const files = grouped.get(componentType);
if (files && files.length > 0) {
sortedMap.set(componentType, files);
}
}
// Add any remaining types that weren't in the predefined order
for (const [componentType, files] of grouped.entries()) {
if (!sortedMap.has(componentType)) {
sortedMap.set(componentType, files);
}
}
return sortedMap;
}
/**
* Generates a simple line-by-line diff HTML
*/
function generateDiffHtml(fileContent) {
if (fileContent.isBinary) {
return `<div class="diff-binary">${escapeHtml(Constants.Strings.HTML_REPORT_BINARY_FILE_MESSAGE)}</div>`;
}
if (fileContent.isTooLarge) {
return `<div class="diff-binary">${escapeHtml(Constants.Strings.HTML_REPORT_FILE_TOO_LARGE_MESSAGE)}</div>`;
}
const { localContent, remoteContent, result } = fileContent;
// Handle cases where content couldn't be read
if (localContent === null && remoteContent === null) {
return `<div class="diff-error">${escapeHtml(Constants.Strings.HTML_REPORT_UNABLE_TO_READ_CONTENTS)}</div>`;
}
// For added files, show all lines as additions
if (result.status === FileComparisonStatus.ADDED) {
if (localContent === null) {
return `<div class="diff-error">${escapeHtml(Constants.Strings.HTML_REPORT_UNABLE_TO_READ_LOCAL)}</div>`;
}
const lines = localContent.split("\n");
const diffLines = lines.map((line, idx) => `<div class="diff-line diff-added"><span class="line-number"></span><span class="line-number">${idx + 1}</span><span class="line-content">+ ${escapeHtml(line)}</span></div>`).join("");
return `<div class="diff-content">${diffLines}</div>`;
}
// For deleted files, show all lines as deletions
if (result.status === FileComparisonStatus.DELETED) {
if (remoteContent === null) {
return `<div class="diff-error">${escapeHtml(Constants.Strings.HTML_REPORT_UNABLE_TO_READ_REMOTE)}</div>`;
}
const lines = remoteContent.split("\n");
const diffLines = lines.map((line, idx) => `<div class="diff-line diff-deleted"><span class="line-number">${idx + 1}</span><span class="line-number"></span><span class="line-content">- ${escapeHtml(line)}</span></div>`).join("");
return `<div class="diff-content">${diffLines}</div>`;
}
// For modified files, compute a simple diff
if (localContent === null || remoteContent === null) {
return `<div class="diff-error">${escapeHtml(Constants.Strings.HTML_REPORT_UNABLE_TO_READ_BOTH)}</div>`;
}
const diffLines = computeSimpleDiff(remoteContent, localContent);
return `<div class="diff-content">${diffLines}</div>`;
}
/**
* Generates a summary diff display for very large files
* Shows basic statistics instead of full line-by-line diff
*/
function generateLargeFileDiffSummary(oldLines, newLines) {
const oldLineCount = oldLines.length;
const newLineCount = newLines.length;
const lineDiff = newLineCount - oldLineCount;
const lineDiffText = lineDiff > 0 ? `+${lineDiff}` : lineDiff.toString();
const summaryHtml = `
<div class="diff-binary">
<p><strong>${escapeHtml(Constants.Strings.HTML_REPORT_LARGE_FILE_MESSAGE)}</strong></p>
<p>${escapeHtml(Constants.Strings.HTML_REPORT_REMOTE_LINES)}: ${oldLineCount} ${escapeHtml(Constants.Strings.HTML_REPORT_LINES)}</p>
<p>${escapeHtml(Constants.Strings.HTML_REPORT_LOCAL_LINES)}: ${newLineCount} ${escapeHtml(Constants.Strings.HTML_REPORT_LINES)}</p>
<p>${escapeHtml(Constants.Strings.HTML_REPORT_LINE_DIFFERENCE)}: ${lineDiffText} ${escapeHtml(Constants.Strings.HTML_REPORT_LINES)}</p>
</div>`;
return summaryHtml;
}
/**
* Computes a simple line-by-line diff between two texts
* Uses a basic longest common subsequence approach
* Falls back to a simpler display for very large files
*/
function computeSimpleDiff(oldText, newText) {
const oldLines = oldText.split("\n");
const newLines = newText.split("\n");
// For very large files, skip the LCS algorithm and show a summary
if (oldLines.length > MAX_LINES_FOR_LCS_DIFF || newLines.length > MAX_LINES_FOR_LCS_DIFF) {
return generateLargeFileDiffSummary(oldLines, newLines);
}
// Simple diff using LCS
const lcs = computeLCS(oldLines, newLines);
const result = [];
let oldIdx = 0;
let newIdx = 0;
let oldLineNum = 1;
let newLineNum = 1;
for (const commonLine of lcs) {
// Output deletions (lines in old but not in common)
while (oldIdx < oldLines.length && oldLines[oldIdx] !== commonLine) {
result.push(`<div class="diff-line diff-deleted"><span class="line-number">${oldLineNum}</span><span class="line-number"></span><span class="line-content">- ${escapeHtml(oldLines[oldIdx])}</span></div>`);
oldIdx++;
oldLineNum++;
}
// Output additions (lines in new but not in common)
while (newIdx < newLines.length && newLines[newIdx] !== commonLine) {
result.push(`<div class="diff-line diff-added"><span class="line-number"></span><span class="line-number">${newLineNum}</span><span class="line-content">+ ${escapeHtml(newLines[newIdx])}</span></div>`);
newIdx++;
newLineNum++;
}
// Output the common line
result.push(`<div class="diff-line diff-unchanged"><span class="line-number">${oldLineNum}</span><span class="line-number">${newLineNum}</span><span class="line-content"> ${escapeHtml(commonLine)}</span></div>`);
oldIdx++;
newIdx++;
oldLineNum++;
newLineNum++;
}
// Output remaining deletions
while (oldIdx < oldLines.length) {
result.push(`<div class="diff-line diff-deleted"><span class="line-number">${oldLineNum}</span><span class="line-number"></span><span class="line-content">- ${escapeHtml(oldLines[oldIdx])}</span></div>`);
oldIdx++;
oldLineNum++;
}
// Output remaining additions
while (newIdx < newLines.length) {
result.push(`<div class="diff-line diff-added"><span class="line-number"></span><span class="line-number">${newLineNum}</span><span class="line-content">+ ${escapeHtml(newLines[newIdx])}</span></div>`);
newIdx++;
newLineNum++;
}
return result.join("");
}
/**
* Computes the longest common subsequence of two string arrays
*/
function computeLCS(arr1, arr2) {
const m = arr1.length;
const n = arr2.length;
// Create DP table
const dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(0));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (arr1[i - 1] === arr2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
// Backtrack to find LCS
const lcs = [];
let i = m;
let j = n;
while (i > 0 && j > 0) {
if (arr1[i - 1] === arr2[j - 1]) {
lcs.unshift(arr1[i - 1]);
i--;
j--;
}
else if (dp[i - 1][j] > dp[i][j - 1]) {
i--;
}
else {
j--;
}
}
return lcs;
}
/**
* Generates the HTML content for the report
*
* Deviation from the VS Code renderer: the Remote "Data Model" field is
* omitted. The extension always knows the remote site's model, but this skill
* can compare two local folders where it is unknown, and the original code
* labels an unknown model as Enhanced. The comparison itself never uses it.
* Second deviation: the extension passes one website ID and repeats it in both
* columns; `localWebsiteId` lets the Local column show the first site's own ID.
* Third: the Environment row renders only when an environment is known.
* Fourth: each file row toggles through a keyboard-operable button that keeps
* `aria-expanded` in sync; the same change is being made in the extension, so
* drop this note once its renderer matches.
* Fifth: component tabs form a vertical list beside the files, because the
* extension's single horizontal row overflows the card once all component
* types are listed. The extension is getting the same layout; drop this note
* once its renderer matches.
*/
function generateHtmlContent(fileContents, localSiteName, siteName, environmentName, websiteId, websiteUrl, siteVisibility, creator, createdOn, localWebsiteId) {
const generatedDate = formatDateForDisplay(new Date());
const extensionVersion = getExtensionVersion();
const comparisonResults = fileContents.map(fc => fc.result);
const groupedResults = groupByStatus(comparisonResults);
const addedCount = groupedResults.get(FileComparisonStatus.ADDED)?.length || 0;
const modifiedCount = groupedResults.get(FileComparisonStatus.MODIFIED)?.length || 0;
const deletedCount = groupedResults.get(FileComparisonStatus.DELETED)?.length || 0;
const visibilityDisplayName = siteVisibility ? siteVisibility.charAt(0).toUpperCase() + siteVisibility.slice(1).toLowerCase() : undefined;
const createdOnFormatted = createdOn ? formatDateForDisplay(new Date(createdOn)) : undefined;
// Sort results by path
const sortedFileContents = [...fileContents].sort((a, b) => a.result.relativePath.localeCompare(b.result.relativePath));
// Group file contents by component type
const componentGroups = groupByComponentType(sortedFileContents);
// Generate file rows for each group with unique index prefix
const generateFileRowsForGroup = (files, indexPrefix) => {
if (files.length === 0) {
return `<div class="no-files-message">${escapeHtml(Constants.Strings.HTML_REPORT_NO_FILES_IN_CATEGORY)}</div>`;
}
return files.map((fc, index) => {
const result = fc.result;
const diffHtml = generateDiffHtml(fc);
const uniqueId = `${indexPrefix}-${index}`;
return `
<div class="file-item">
<button type="button" class="file-header" aria-expanded="false" aria-controls="diff-${uniqueId}" onclick="toggleDiff('diff-${uniqueId}')">
<span class="file-path">${escapeHtml(result.relativePath)}</span>
<span class="status-badge ${getStatusClass(result.status)}">${escapeHtml(getStatusText(result.status))}</span>
<span class="toggle-icon" id="icon-${uniqueId}" aria-hidden="true">▶</span>
</button>
<div class="diff-container" id="diff-${uniqueId}" style="display: none;">
${diffHtml}
</div>
</div>`;
}).join("");
};
// Generate "All" tab content first
const allFileRows = generateFileRowsForGroup(sortedFileContents, "all");
// Generate tabs HTML - "All" tab first, then all component type tabs (even empty ones)
const allTabButton = `<button class="tab-button active" onclick="switchTab('all')" data-tab="all">${escapeHtml(Constants.Strings.HTML_REPORT_TAB_ALL)} (${sortedFileContents.length})</button>`;
// Generate tabs for ALL component types, not just ones with files
const componentTabButtons = componentTypeOrder
.filter(key => key !== "others") // Handle "others" separately if it has files
.map(key => {
const files = componentGroups.get(key) || [];
const displayName = getComponentTypeDisplayName(key);
const count = files.length;
const disabledClass = count === 0 ? " disabled" : "";
const onclickAttr = count === 0 ? "" : `onclick="switchTab('${escapeHtml(key)}')"`;
return `<button class="tab-button${disabledClass}" ${onclickAttr} data-tab="${escapeHtml(key)}">${escapeHtml(displayName)} (${count})</button>`;
}).join("");
// Add "Others" tab only if there are files in it
const othersFiles = componentGroups.get("others") || [];
const othersTabButton = othersFiles.length > 0
? `<button class="tab-button" onclick="switchTab('others')" data-tab="others">${escapeHtml(getComponentTypeDisplayName("others"))} (${othersFiles.length})</button>`
: "";
const tabButtons = allTabButton + componentTabButtons + othersTabButton;
const allTabContent = `<div class="tab-content active" id="tab-all">${allFileRows}</div>`;
// Generate tab content for ALL component types (even empty ones for consistency)
const componentTabContents = componentTypeOrder
.filter(key => key !== "others")
.map(key => {
const files = componentGroups.get(key) || [];
const fileRows = generateFileRowsForGroup(files, key);
return `<div class="tab-content" id="tab-${escapeHtml(key)}">${fileRows}</div>`;
}).join("");
// Add "Others" tab content only if there are files in it
const othersTabContent = othersFiles.length > 0
? `<div class="tab-content" id="tab-others">${generateFileRowsForGroup(othersFiles, "others")}</div>`
: "";
const tabContents = allTabContent + componentTabContents + othersTabContent;
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${escapeHtml(Constants.Strings.HTML_REPORT_TITLE)} - ${escapeHtml(siteName)}</title>
<style>
:root {
--primary-color: #0078d4;
--success-color: #107c10;
--warning-color: #ca5010;
--danger-color: #d13438;
--background-color: #f3f2f1;
--card-background: #ffffff;
--text-color: #323130;
--text-secondary: #605e5c;
--border-color: #edebe9;
--diff-added-bg: #dff6dd;
--diff-deleted-bg: #fde7e9;
--diff-unchanged-bg: #ffffff;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: var(--background-color);
color: var(--text-color);
line-height: 1.6;
padding: 20px;
}
.container {
max-width: 1400px;
margin: 0 auto;
}
.header {
background: linear-gradient(135deg, var(--primary-color), #106ebe);
color: white;
padding: 30px;
border-radius: 8px;
margin-bottom: 24px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.header h1 {
font-size: 28px;
font-weight: 600;
margin-bottom: 8px;
}
.header-subtitle {
opacity: 0.9;
font-size: 14px;
}
.header-separator {
border: none;
border-top: 1px solid rgba(255, 255, 255, 0.3);
margin: 16px 0;
}
.header-info {
display: flex;
flex-wrap: wrap;
gap: 32px;
font-size: 14px;
opacity: 0.9;
}
.header-info-item {
display: flex;
align-items: center;
gap: 6px;
}
.header-info-label {
font-weight: 600;
}
.summary-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
margin-bottom: 24px;
}
.summary-card {
background: var(--card-background);
padding: 20px;
border-radius: 8px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
text-align: left;
border-left: 4px solid transparent;
}
.summary-card.total {
border-left-color: var(--primary-color);
}
.summary-card.modified {
border-left-color: var(--warning-color);
}
.summary-card.added {
border-left-color: var(--success-color);
}
.summary-card.deleted {
border-left-color: var(--danger-color);
}
.summary-card .label {
font-size: 12px;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 8px;
}
.summary-card .count {
font-size: 36px;
font-weight: 700;
}
.summary-card.total .count {
color: var(--primary-color);
}
.summary-card.added .count {
color: var(--success-color);
}
.summary-card.modified .count {
color: var(--warning-color);
}
.summary-card.deleted .count {
color: var(--danger-color);
}
.info-section {
background: var(--card-background);
padding: 24px;
border-radius: 8px;
margin-bottom: 24px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}
.info-section h2 {
font-size: 18px;
font-weight: 600;
margin-bottom: 20px;
color: var(--primary-color);
}
.comparison-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 24px;
}
@media (max-width: 768px) {
.comparison-grid {
grid-template-columns: 1fr;
}
}
.comparison-column {
background: var(--background-color);
border-radius: 8px;
padding: 20px;
}
.comparison-column h3 {
font-size: 16px;
font-weight: 600;
margin-bottom: 16px;
color: var(--text-color);
padding-bottom: 8px;
border-bottom: 2px solid var(--primary-color);
}
.comparison-column.local h3 {
border-bottom-color: var(--success-color);
}
.comparison-column.remote h3 {
border-bottom-color: var(--primary-color);
}
.info-grid {
display: flex;
flex-direction: column;
gap: 12px;
}
.info-item {
display: flex;
align-items: flex-start;
}
.info-label {
font-weight: 600;
min-width: 110px;
color: var(--text-secondary);
flex-shrink: 0;
}
.info-value {
color: var(--text-color);
word-break: break-word;
}
.files-section {
background: var(--card-background);
border-radius: 8px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
overflow: hidden;
}
.files-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
border-bottom: 1px solid var(--border-color);
}
.files-header h2 {
font-size: 18px;
font-weight: 600;
color: var(--primary-color);
margin: 0;
}
.expand-buttons {
display: flex;
gap: 8px;
}
.expand-btn {
padding: 6px 12px;
font-size: 12px;
font-weight: 500;
color: var(--primary-color);
background-color: transparent;
border: 1px solid var(--primary-color);
border-radius: 4px;
cursor: pointer;
transition: all 0.2s;
}
.expand-btn:hover {
background-color: var(--primary-color);
color: white;
}
.files-section > h2 {
font-size: 18px;
font-weight: 600;
padding: 20px;
border-bottom: 1px solid var(--border-color);
color: var(--primary-color);
}
.file-item {
border-bottom: 1px solid var(--border-color);
}
.file-item:last-child {
border-bottom: none;
}
.file-header {
display: flex;
align-items: center;
padding: 12px 20px;
cursor: pointer;
transition: background-color 0.2s;
gap: 12px;
width: 100%;
border: none;
background: none;
font: inherit;
color: inherit;
text-align: left;
}
.file-header:hover {
background-color: #faf9f8;
}
.file-header:focus-visible {
outline: 2px solid var(--primary-color);
outline-offset: -2px;
}
.file-path {
font-family: 'Consolas', 'Monaco', monospace;
font-size: 13px;
word-break: break-all;
flex: 1;
}
.status-badge {
display: inline-block;
padding: 4px 12px;
border-radius: 12px;
font-size: 12px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.3px;
flex-shrink: 0;
}
.status-added {
background-color: #dff6dd;
color: var(--success-color);
}
.status-modified {
background-color: #fff4ce;
color: var(--warning-color);
}
.status-deleted {
background-color: #fde7e9;
color: var(--danger-color);
}
.toggle-icon {
font-size: 12px;
color: var(--text-secondary);
transition: transform 0.2s;
flex-shrink: 0;
}
.toggle-icon.expanded {
transform: rotate(90deg);
}
.diff-container {
border-top: 1px solid var(--border-color);
background-color: #fafafa;
}
.diff-content {
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
font-size: 12px;
line-height: 1.5;
overflow-x: auto;
max-height: 500px;
overflow-y: auto;
}
.diff-line {
display: flex;
white-space: pre;
}
.diff-line .line-number {
min-width: 50px;
padding: 0 8px;
text-align: right;
color: var(--text-secondary);
background-color: rgba(0, 0, 0, 0.03);
border-right: 1px solid var(--border-color);
user-select: none;
}
.diff-line .line-content {
padding: 0 12px;
flex: 1;
}
.diff-added {
background-color: var(--diff-added-bg);
}
.diff-added .line-content {
color: var(--success-color);
}
.diff-deleted {
background-color: var(--diff-deleted-bg);
}
.diff-deleted .line-content {
color: var(--danger-color);
}
.diff-unchanged {
background-color: var(--diff-unchanged-bg);
}
.diff-binary, .diff-error {
padding: 20px;
text-align: center;
color: var(--text-secondary);
font-style: italic;
}
.footer {
text-align: center;
padding: 20px;
color: var(--text-secondary);
font-size: 12px;
}
.footer a {
color: var(--primary-color);
text-decoration: none;
}
.footer a:hover {
text-decoration: underline;
}
@media print {
body {
background-color: white;
padding: 0;
}
.header {
background: var(--primary-color);
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.summary-card,
.info-section,
.files-section {
box-shadow: none;
border: 1px solid var(--border-color);
}
.diff-container {
display: block !important;
}
.toggle-icon {
display: none;
}
}
@media (max-width: 600px) {
.header {
padding: 20px;
}
.header h1 {
font-size: 22px;
}
.summary-cards {
grid-template-columns: repeat(2, 1fr);
}
.file-header {
padding: 10px 12px;
}
}
.tabs-container {
display: flex;
align-items: stretch;
}
.tabs-header {
display: flex;
flex-direction: column;
flex-shrink: 0;
width: 220px;
border-right: 1px solid var(--border-color);
background-color: #faf9f8;
padding: 8px 0;
}
.tabs-panels {
flex: 1;
min-width: 0;
}
.tab-button {
padding: 10px 20px;
border: none;
border-left: 3px solid transparent;
background-color: transparent;
cursor: pointer;
font-size: 14px;
font-weight: 500;
color: var(--text-secondary);
text-align: left;
transition: all 0.2s ease;
}
.tab-button:hover {
color: var(--primary-color);
background-color: rgba(0, 120, 212, 0.05);
}
.tab-button.active {
color: var(--primary-color);
border-left-color: var(--primary-color);
background-color: var(--card-background);
}
.tab-button.disabled {
color: var(--text-secondary);
opacity: 0.5;
cursor: default;
}
.tab-button.disabled:hover {
color: var(--text-secondary);
background-color: transparent;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
/* Below tablet width a 220px sidebar leaves file paths too little room, so the tabs wrap into rows above the files. */
@media (max-width: 768px) {
.tabs-container {
flex-direction: column;
}
.tabs-header {
flex-direction: row;
flex-wrap: wrap;
width: auto;
border-right: none;
border-bottom: 1px solid var(--border-color);
padding: 0;
}
.tab-button {
flex: 1 1 auto;
min-width: 80px;
text-align: center;
border-left: none;
border-bottom: 2px solid transparent;
}
.tab-button.active {
border-bottom-color: var(--primary-color);
}
}
.no-files-message {
padding: 40px 20px;
text-align: center;
color: var(--text-secondary);
font-style: italic;
}
</style>
<script>
function toggleDiff(diffId) {
const diffContainer = document.getElementById(diffId);
const iconId = diffId.replace('diff-', 'icon-');
const icon = document.getElementById(iconId);
const header = document.querySelector('[aria-controls="' + diffId + '"]');
if (diffContainer.style.display === 'none') {
diffContainer.style.display = 'block';
icon.classList.add('expanded');
header.setAttribute('aria-expanded', 'true');
} else {
diffContainer.style.display = 'none';
icon.classList.remove('expanded');
header.setAttribute('aria-expanded', 'false');
}
}
function expandAll() {
// Expand all diffs across all tabs
document.querySelectorAll('.diff-container').forEach(el => el.style.display = 'block');
document.querySelectorAll('.toggle-icon').forEach(el => el.classList.add('expanded'));
document.querySelectorAll('.file-header').forEach(el => el.setAttribute('aria-expanded', 'true'));
}
function collapseAll() {
// Collapse all diffs across all tabs
document.querySelectorAll('.diff-container').forEach(el => el.style.display = 'none');
document.querySelectorAll('.toggle-icon').forEach(el => el.classList.remove('expanded'));
document.querySelectorAll('.file-header').forEach(el => el.setAttribute('aria-expanded', 'false'));
}
function switchTab(tabId) {
// Remove active class from all tabs and contents
document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
// Add active class to selected tab and content
const selectedButton = document.querySelector('[data-tab="' + tabId + '"]');
const selectedContent = document.getElementById('tab-' + tabId);
if (selectedButton) selectedButton.classList.add('active');
if (selectedContent) selectedContent.classList.add('active');
}
</script>
</head>
<body>
<div class="container">
<header class="header">
<h1>${escapeHtml(Constants.Strings.HTML_REPORT_TITLE)}</h1>
<p class="header-subtitle">${escapeHtml(Constants.Strings.HTML_REPORT_SUBTITLE)}</p>
<hr class="header-separator" />
<div class="header-info">
<div class="header-info-item">
<span class="header-info-label"><strong>${escapeHtml(Constants.Strings.HTML_REPORT_GENERATED_LABEL)}</strong></span>
<span>${escapeHtml(generatedDate)}</span>
</div>${extensionVersion ? `
<div class="header-info-item">
<span class="header-info-label"><strong>${escapeHtml(Constants.Strings.HTML_REPORT_EXTENSION_VERSION_LABEL)}</strong></span>
<span>${escapeHtml(extensionVersion)}</span>
</div>` : ""}
</div>
</header>
<section class="summary-cards">
<div class="summary-card total">
<div class="label">${escapeHtml(Constants.Strings.HTML_REPORT_TOTAL_CHANGES)}</div>
<div class="count">${comparisonResults.length}</div>
</div>
<div class="summary-card modified">
<div class="label">${escapeHtml(Constants.Strings.HTML_REPORT_MODIFIED)}</div>
<div class="count">${modifiedCount}</div>
</div>
<div class="summary-card added">
<div class="label">${escapeHtml(Constants.Strings.HTML_REPORT_ADDED)}</div>
<div class="count">${addedCount}</div>
</div>
<div class="summary-card deleted">
<div class="label">${escapeHtml(Constants.Strings.HTML_REPORT_DELETED)}</div>
<div class="count">${deletedCount}</div>
</div>
</section>
<section class="info-section">
<h2>${escapeHtml(Constants.Strings.HTML_REPORT_COMPARISON_DETAILS)}</h2>
<div class="comparison-grid">
<div class="comparison-column local">
<h3>${escapeHtml(Constants.Strings.HTML_REPORT_LOCAL_SECTION)}</h3>
<div class="info-grid">
<div class="info-item">
<span class="info-label">${escapeHtml(Constants.Strings.HTML_REPORT_SITE_NAME_LABEL)}</span>
<span class="info-value">${escapeHtml(localSiteName)}</span>
</div>
<div class="info-item">
<span class="info-label">${escapeHtml(Constants.Strings.HTML_REPORT_WEBSITE_ID_LABEL)}</span>
<span class="info-value">${escapeHtml(localWebsiteId ?? websiteId)}</span>
</div>
</div>
</div>
<div class="comparison-column remote">
<h3>${escapeHtml(Constants.Strings.HTML_REPORT_REMOTE_SECTION)}</h3>
<div class="info-grid">
<div class="info-item">
<span class="info-label">${escapeHtml(Constants.Strings.HTML_REPORT_SITE_NAME_LABEL)}</span>
<span class="info-value">${escapeHtml(siteName)}</span>
</div>
<div class="info-item">
<span class="info-label">${escapeHtml(Constants.Strings.HTML_REPORT_WEBSITE_ID_LABEL)}</span>
<span class="info-value">${escapeHtml(websiteId)}</span>
</div>${environmentName ? `
<div class="info-item">
<span class="info-label">${escapeHtml(Constants.Strings.HTML_REPORT_ENVIRONMENT_LABEL)}</span>
<span class="info-value">${escapeHtml(environmentName)}</span>
</div>` : ""}${websiteUrl ? `
<div class="info-item">
<span class="info-label">${escapeHtml(Constants.Strings.HTML_REPORT_WEBSITE_URL_LABEL)}</span>
<span class="info-value"><a href="${escapeHtml(websiteUrl)}" target="_blank" rel="noopener noreferrer">${escapeHtml(websiteUrl)}</a></span>
</div>` : ""}${visibilityDisplayName ? `
<div class="info-item">
<span class="info-label">${escapeHtml(Constants.Strings.HTML_REPORT_SITE_VISIBILITY_LABEL)}</span>
<span class="info-value">${escapeHtml(visibilityDisplayName)}</span>
</div>` : ""}${creator ? `
<div class="info-item">
<span class="info-label">${escapeHtml(Constants.Strings.HTML_REPORT_CREATOR_LABEL)}</span>
<span class="info-value">${escapeHtml(creator)}</span>
</div>` : ""}${createdOnFormatted ? `
<div class="info-item">
<span class="info-label">${escapeHtml(Constants.Strings.HTML_REPORT_CREATED_ON_LABEL)}</span>
<span class="info-value">${escapeHtml(createdOnFormatted)}</span>
</div>` : ""}
</div>
</div>
</div>
</section>
<section class="files-section">
<div class="files-header">
<h2>${escapeHtml(Constants.Strings.HTML_REPORT_CHANGED_FILES)} <span style="font-weight: normal; font-size: 14px;">${escapeHtml(Constants.Strings.HTML_REPORT_CLICK_TO_EXPAND)}</span></h2>
<div class="expand-buttons">
<button onclick="expandAll()" class="expand-btn">${escapeHtml(Constants.Strings.HTML_REPORT_EXPAND_ALL)}</button>
<button onclick="collapseAll()" class="expand-btn">${escapeHtml(Constants.Strings.HTML_REPORT_COLLAPSE_ALL)}</button>
</div>
</div>
<div class="tabs-container">
<div class="tabs-header">
${tabButtons}
</div>
<div class="tabs-panels">
${tabContents}
</div>
</div>
</section>
<footer class="footer">
${escapeHtml(Constants.Strings.HTML_REPORT_GENERATED_BY)} <a href="${PLUGIN_URL}" target="_blank" rel="noopener noreferrer">${escapeHtml(Constants.Strings.HTML_REPORT_EXTENSION_NAME)}</a>
</footer>
</div>
</body>
</html>`;
}
/**
* Escapes HTML special characters to prevent XSS
*/
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
return { compareFiles, compareFileMaps, getAllFiles, getFilteredSourceFiles, getPowerPagesSiteFiles, readPowerPagesConfig, hasSourceCode, readFileContents, generateHtmlContent, getComponentTypeFromPath, getComponentTypeDisplayName, escapeHtml, isBinaryFile };
})();
const GUID_RE = /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
// Deviation from the extension, which compares every non-hidden file in a
// non-SPA site folder: this skill compares Power Pages site configuration only.
// PAC writes configuration as one folder per table plus aggregate YAML files at
// the site root (website.yml, sitesetting.yml, webrole.yml, ...). Other files in
// the folder, such as docs/ written by other tools or a README, never reach the
// site, so their differences are reported as skipped rather than as changes.
// Folder names follow the PAC portal schema as the extension maps it
// (FOLDER_TO_ENTITIES_ADX in actions-hub/ActionsHubUtils.ts), including its
// "website-accesss" spelling, plus the alternate names the extension's report
// and this plugin's site validator recognize.
const CONFIGURATION_FOLDERS = new Set([
'ad-placements', 'ads', 'advanced-forms', 'basic-forms', 'blogs', 'bot-consumers',
'cloud-flow-consumer', 'cloud-flow-definitions', 'column-permission-profiles',
'content-snippets', 'forums', 'lists', 'page-templates', 'poll-placements', 'polls',
'publishing-state-transition-rules', 'publishing-states', 'redirects', 'server-logics',
'shortcuts', 'site-languages', 'site-markers', 'site-settings', 'sitemarkers',
'source-files', 'table-permissions', 'ux-components', 'web-files', 'web-link-sets',
'web-pages', 'web-roles', 'web-templates', 'webpage-rules', 'website-accesss',
'website-languages', 'weblink-sets',
]);
// Relative paths use the host separator and, for SPA sites, start with
// ".powerpages-site/", e.g. ".powerpages-site\web-pages\home\Home.webpage.yml".
function splitSitePath(relativePath) {
const segments = relativePath.split(/[\\/]/).filter(Boolean);
const prefix = segments[0] === '.powerpages-site' ? `${segments.shift()}/` : '';
return { prefix, segments };
}
function isSiteConfiguration(relativePath) {
const { segments } = splitSitePath(relativePath);
if (segments.length === 1) return /\.yml$/i.test(segments[0]);
return CONFIGURATION_FOLDERS.has(segments[0].toLowerCase());
}
function summarizeSkipped(files) {
const groups = new Map();
for (const file of files) {
const { prefix, segments } = splitSitePath(file.relativePath);
const name = prefix + segments[0] + (segments.length > 1 ? '/' : '');
groups.set(name, (groups.get(name) || 0) + 1);
}
// Code-point order, so the summary is identical on every platform and locale.
return [...groups].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([name, count]) => ({ path: name, files: count }));
}
function projectRootOf(metadataRoot) {
return path.basename(metadataRoot) === '.powerpages-site' ? path.dirname(metadataRoot) : metadataRoot;
}
function resolveSite(input, codeSite) {
if (!input) throw new Error('Both --source and --target site directories are required.');
const requested = path.resolve(input);
if (fs.lstatSync(requested).isSymbolicLink()) throw new Error('Select the actual site directory, not a symlink.');
const candidates = [requested, path.join(requested, '.powerpages-site')]
.filter(root => fs.existsSync(path.join(root, 'website.yml')));
if (candidates.length !== 1) {
throw new Error(`Select one site containing website.yml, directly or in .powerpages-site: ${input}`);
}
const root = candidates[0];
if (fs.lstatSync(root).isSymbolicLink() || !fs.lstatSync(path.join(root, 'website.yml')).isFile() ||
!fs.readFileSync(path.join(root, 'website.yml'), 'utf8').trim()) {
throw new Error(`Expected a regular, nonempty website.yml in an actual metadata directory: ${root}`);
}
const metadataRoot = fs.realpathSync(root);
const projectRoot = projectRootOf(metadataRoot);
const isCodeSite = codeSite ?? fs.existsSync(path.join(projectRoot, 'powerpages.config.json'));
if (isCodeSite && path.basename(metadataRoot) !== '.powerpages-site') {
throw new Error('A code site must contain its metadata in .powerpages-site.');
}
return { metadataRoot, projectRoot, isCodeSite };
}
function websiteIdFromFile(site) {
return readWebsiteIdentity(path.join(site.metadataRoot, 'website.yml')).id || '';
}
function resolveMetadataRoot(input) {
return resolveSite(input).metadataRoot;
}
function compareMetadata(source, target, options = {}) {
const local = resolveSite(source, options.sourceCodeSite);
const remote = resolveSite(target, options.targetCodeSite);
// The first input is the extension's local side; the second is its remote
// baseline. Keep its status direction as well as all code-site branches.
let files;
if (local.isCodeSite && remote.isCodeSite) {
// Deviation from the extension: when the second SPA folder also holds
// application source, its compareFiles diffs that source as well (its
// case 3b). This skill compares site metadata only, so two SPA sites use
// the extension's .powerpages-site comparison (case 3a) unconditionally.
files = [];
tools.compareFileMaps(tools.getPowerPagesSiteFiles(remote.projectRoot), tools.getPowerPagesSiteFiles(local.projectRoot),
remote.projectRoot, local.projectRoot, files);
} else {
files = tools.compareFiles(
remote.isCodeSite ? remote.projectRoot : remote.metadataRoot,
local.metadataRoot,
{
isRemoteCodeSite: remote.isCodeSite,
isLocalCodeSite: local.isCodeSite,
localCodeSiteRootPath: local.isCodeSite ? local.projectRoot : undefined,
}
);
}
const counts = { added: 0, modified: 0, deleted: 0 };
const skipped = files.filter(file => !isSiteConfiguration(file.relativePath));
files = files.filter(file => isSiteConfiguration(file.relativePath));
for (const file of files) counts[file.status] += 1;
return {
schemaVersion: 3,
sourceRoot: local.metadataRoot,
targetRoot: remote.metadataRoot,
sourceProjectRoot: local.projectRoot,
targetProjectRoot: remote.projectRoot,
sourceWebsiteId: options.sourceWebsiteId,
targetWebsiteId: options.targetWebsiteId,
counts,
files,
skipped: summarizeSkipped(skipped),
report: {
localSiteName: options.sourceName || path.basename(local.projectRoot),
siteName: options.targetName || path.basename(remote.projectRoot),
// Only a downloaded site has an environment; a local folder leaves it
// empty so the report hides the row instead of mislabeling a path.
environmentName: options.targetEnvironment || '',
environmentId: options.targetEnvironmentId || '',
// Explicit IDs were already checked against website.yml; otherwise read
// each side's own website.yml so local folders show their IDs too.
websiteId: options.targetWebsiteId || websiteIdFromFile(remote),
localWebsiteId: options.sourceWebsiteId || websiteIdFromFile(local),
websiteUrl: options.targetUrl,
},
};
}
function receiptPath(output) {
return output.replace(/\.html$/i, '.receipt.json');
}
function exportPath(output) {
return output.replace(/\.html$/i, '.json');
}
// Writes the JSON the extension produces with "Export as JSON" and reads with
// "Import Comparison" (IMetadataDiffExport, format 1.0), so a teammate can open
// this comparison in VS Code. See ExportMetadataDiffHandler.ts and
// ImportMetadataDiffHandler.ts under src/client/power-pages/actions-hub/handlers/metadata-diff
// in https://github.com/microsoft/powerplatform-vscode.
// Import rejects a file whose extensionVersion is newer than the installed
// extension, so record 2.0.115, the first release that imports this format.
// It also requires GUID website and environment IDs; two local folders have no
// environment, so they use the nil GUID, which import accepts as a key.
const EXPORT_FORMAT_VERSION = '1.0';
const MIN_IMPORT_EXTENSION_VERSION = '2.0.115';
const MAX_FILE_SIZE_FOR_EXPORT = 20 * 1024 * 1024;
const NIL_GUID = '00000000-0000-0000-0000-000000000000';
function buildExport(comparison) {
const { report } = comparison;
if (!GUID_RE.test(report.localWebsiteId || '') || !GUID_RE.test(report.websiteId || '')) {
return { reason: 'VS Code import needs a website ID in both sites\' website.yml.' };
}
// Like the extension: raw bytes as base64, null for binary, oversized or absent sides.
const content = (file, side) => {
if (tools.isBinaryFile(file.relativePath, false)) return null;
if (side === 'local' ? file.status === 'deleted' : file.status === 'added') return null;
const filePath = side === 'local' ? file.localPath : file.remotePath;
return fs.statSync(filePath).size <= MAX_FILE_SIZE_FOR_EXPORT ? fs.readFileSync(filePath).toString('base64') : null;
};
return {
data: {
version: EXPORT_FORMAT_VERSION,
extensionVersion: MIN_IMPORT_EXTENSION_VERSION,
exportedAt: new Date().toISOString(),
localWebsiteId: report.localWebsiteId,
localWebsiteName: report.localSiteName,
remoteWebsiteId: report.websiteId,
remoteWebsiteName: report.siteName,
environmentId: report.environmentId || NIL_GUID,
environmentName: report.environmentName || 'Local folder',
...(report.websiteUrl ? { websiteUrl: report.websiteUrl } : {}),
files: comparison.files.map(file => ({
relativePath: file.relativePath,
status: file.status,
localContent: content(file, 'local'),
remoteContent: content(file, 'remote'),
})),
},
};
}
async function writeReport(comparison, output) {
if (!output || path.extname(output).toLowerCase() !== '.html') throw new Error('--output must name a new .html file.');
const absolute = path.resolve(output);
for (const root of [comparison.sourceRoot, comparison.targetRoot, comparison.sourceProjectRoot, comparison.targetProjectRoot]) {
assertOutsideSite(root, absolute);
}
if (fs.existsSync(absolute) || fs.existsSync(receiptPath(absolute)) || fs.existsSync(exportPath(absolute))) {
throw new Error(`Report, verification receipt or export already exists; choose a new output path: ${output}`);
}
// Upstream catches read failures for its interactive viewer. A standalone
// report must instead fail explicitly when an expected snapshot is unreadable.
for (const file of comparison.files) {
if (file.status !== 'deleted') fs.accessSync(file.localPath, fs.constants.R_OK);
if (file.status !== 'added') fs.accessSync(file.remotePath, fs.constants.R_OK);
}
const fileContents = await tools.readFileContents(comparison.files);
for (const file of fileContents) {
if (!file.isBinary && !file.isTooLarge &&
((file.result.status !== 'deleted' && file.localContent === null) ||
(file.result.status !== 'added' && file.remoteContent === null))) {
throw new Error(`Could not read comparison content: ${file.result.relativePath}`);
}
}
const report = comparison.report;
const html = tools.generateHtmlContent(
fileContents, report.localSiteName, report.siteName, report.environmentName,
report.websiteId, report.websiteUrl, undefined, undefined, undefined, report.localWebsiteId
);
const exported = buildExport(comparison);
const exportText = exported.data ? JSON.stringify(exported.data, null, 2) : undefined;
const receipt = {
...comparison,
htmlSha256: crypto.createHash('sha256').update(html).digest('hex'),
...(exported.data
? { export: path.basename(exportPath(absolute)), exportSha256: crypto.createHash('sha256').update(exportText).digest('hex') }
: { exportSkipped: exported.reason }),
};
fs.mkdirSync(path.dirname(absolute), { recursive: true, mode: 0o700 });
fs.writeFileSync(absolute, html, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
if (exportText) {
fs.writeFileSync(exportPath(absolute), exportText, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
}
// Verification data is a sidecar, never injected into the upstream HTML.
fs.writeFileSync(receiptPath(absolute), JSON.stringify(receipt, null, 2) + '\n', {
encoding: 'utf8', flag: 'wx', mode: 0o600,
});
return absolute;
}
// The export must be byte-for-byte what was written beside the report, as the
// HTML is, and list exactly the verified files in order, so a teammate who
// imports it sees the same comparison as the report.
function verifyExport(receipt, output) {
if (receipt.export === undefined) {
if (typeof receipt.exportSkipped !== 'string') throw new Error('Report receipt has no export record.');
return { exportSkipped: receipt.exportSkipped };
}
if (typeof receipt.export !== 'string' || path.basename(receipt.export) !== receipt.export) {
throw new Error('Report receipt names an invalid export file.');
}
const file = path.join(path.dirname(output), receipt.export);
const text = fs.readFileSync(file);
if (receipt.exportSha256 !== crypto.createHash('sha256').update(text).digest('hex')) {
throw new Error('Export does not match the verified report.');
}
const data = JSON.parse(text.toString('utf8'));
if (data.version !== EXPORT_FORMAT_VERSION || !Array.isArray(data.files) || data.files.length !== receipt.files.length ||
data.files.some((entry, i) => entry.relativePath !== receipt.files[i].relativePath || entry.status !== receipt.files[i].status)) {
throw new Error('Export does not match the verified report.');
}
return { export: file };
}
function verifyReport(source, target, output) {
const html = fs.readFileSync(output);
const receipt = JSON.parse(fs.readFileSync(receiptPath(output), 'utf8'));
if (receipt.schemaVersion !== 3 || receipt.sourceRoot !== resolveMetadataRoot(source) ||
receipt.targetRoot !== resolveMetadataRoot(target) || !Array.isArray(receipt.files) || !Array.isArray(receipt.skipped)) {
throw new Error('Report does not match the selected local and remote metadata roots.');
}
if (receipt.htmlSha256 !== crypto.createHash('sha256').update(html).digest('hex')) {
throw new Error('Report content does not match the verification receipt.');
}
for (const status of ['added', 'modified', 'deleted']) {
if (!Number.isSafeInteger(receipt.counts?.[status]) || receipt.counts[status] < 0 ||
receipt.files.filter(file => file.status === status).length !== receipt.counts[status]) {
throw new Error(`Report has inconsistent ${status} counts.`);
}
}
const changed = receipt.counts.added + receipt.counts.modified + receipt.counts.deleted;
if (receipt.files.length !== changed) throw new Error('Report has unexpected file entries.');
// The HTML hash does not cover the sidecar's file list, yet the explanation
// step reads the files it names. Require each entry to be a path the verified
// report renders (escaped, as the renderer writes it) and to point inside the
// selected sites, so the explanation reads exactly the files in the report.
const htmlText = html.toString('utf8');
const sourceProject = projectRootOf(receipt.sourceRoot);
const targetProject = projectRootOf(receipt.targetRoot);
for (const file of receipt.files) {
if (typeof file?.relativePath !== 'string' || !file.relativePath ||
!htmlText.includes(tools.escapeHtml(file.relativePath)) ||
typeof file.localPath !== 'string' || !within(sourceProject, path.resolve(file.localPath)) ||
typeof file.remotePath !== 'string' || !within(targetProject, path.resolve(file.remotePath))) {
throw new Error(`Report has a file entry outside the verified report or selected sites: ${file?.relativePath}`);
}
}
const absolute = path.resolve(output);
return {
output: absolute,
receipt: receiptPath(absolute),
...verifyExport(receipt, absolute),
...receipt.counts,
skipped: receipt.skipped,
};
}
async function main(argv = process.argv.slice(2), deps = {}) {
const args = parseArgs(argv, [
'source', 'target', 'output', 'open', 'verify', 'sourceWebsiteId', 'targetWebsiteId',
'sourceCodeSite', 'targetCodeSite', 'sourceName', 'targetName', 'targetEnvironment', 'targetEnvironmentId', 'targetUrl',
]);
for (const name of ['open', 'verify', 'sourceCodeSite', 'targetCodeSite']) {
if (args[name] !== undefined && !['true', 'false'].includes(args[name])) {
throw new Error(`--${name} must be true or false.`);
}
}
if (!args.source || !args.target || !args.output) {
throw new Error('Usage: compare-site-configurations.js --source <site-folder> --target <site-folder> --output <report.html> [--open true] [--verify true]');
}
if (args.targetEnvironmentId !== undefined && !GUID_RE.test(args.targetEnvironmentId)) {
throw new Error('--targetEnvironmentId must be the Power Platform environment ID (a GUID).');
}
if (args.targetUrl !== undefined) {
const url = new URL(args.targetUrl);
if (url.protocol !== 'https:' || url.username || url.password) throw new Error('--targetUrl must be an HTTPS website URL without credentials.');
}
for (const side of ['source', 'target']) {
const expected = args[`${side}WebsiteId`];
if (expected !== undefined) {
const root = resolveMetadataRoot(args[side]);
const identity = readWebsiteIdentity(path.join(root, 'website.yml'));
if (!GUID_RE.test(expected) ||
identity.id?.toLowerCase() !== expected.toLowerCase()) {
throw new Error(`${side} website.yml identity is missing, conflicting, or does not match the selected website record ID.`);
}
}
}
if (args.verify !== 'true') {
console.error('Comparing Power Pages site configurations.');
const comparison = compareMetadata(args.source, args.target, {
...args,
sourceCodeSite: args.sourceCodeSite === undefined ? undefined : args.sourceCodeSite === 'true',
targetCodeSite: args.targetCodeSite === undefined ? undefined : args.targetCodeSite === 'true',
});
await writeReport(comparison, args.output);
}
const verified = verifyReport(args.source, args.target, args.output);
const { output } = verified;
const result = { status: 'ok', ...verified };
// Persist the report before launching. Headless/remote hosts can still return
// the exact artifact path, but must not claim that a browser opened.
if (args.open === 'true') {
try {
(deps.openInDefaultBrowser || openInDefaultBrowser)(pathToFileURL(output).href);
} catch (error) {
throw new Error(`Report saved at ${output}, but the default browser could not be opened: ${error.message}`);
}
}
console.log(JSON.stringify(result));
return result;
}
if (require.main === module) {
main().catch(error => {
console.error(error.message);
process.exitCode = 1;
});
}
module.exports = { main, compareMetadata, resolveMetadataRoot, writeReport, verifyReport, tools };
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |