Skip to content

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

53.2 KB
Raw Blame
'use strict';

const crypto = require('crypto');
const fs = require('fs');
const https = require('https');
const os = require('os');
const path = require('path');
const { execFileSync } = require('child_process');
const { inspectSolutionDirectory } = require('./template-reinstall-policy');

const DEFAULT_OWNER = 'microsoft';
const DEFAULT_REPO = 'power-pages-samples';
const DEFAULT_REF = 'latest-release';
const DEFAULT_CATALOG_PATH = 'templates/manifest.json';
const FRAMEWORKS = new Set(['react', 'vue', 'angular', 'astro', 'none', 'other']);
const TEMPLATE_KINDS = new Set(['spa', 'traditional', 'non-spa']);
const ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const IDENTIFIER_PATTERN = /^[a-z_][a-z0-9_]*$/i;
const CACHE_MARKER_FILE = '.powerpages-template-cache.json';
const CACHE_MARKER_VERSION = 1;

function getDefaultCacheRoot() {
  return path.join(os.homedir(), '.power-platform-skills', 'template-cache');
}

function encodePath(filePath) {
  return filePath.split('/').map(encodeURIComponent).join('/');
}

function buildRawUrl({ owner = DEFAULT_OWNER, repo = DEFAULT_REPO, sha, filePath }) {
  if (!sha) throw new Error('sha is required');
  assertValidSha(sha);
  if (!filePath) throw new Error('filePath is required');
  return `https://raw.githubusercontent.com/${owner}/${repo}/${sha}/${encodePath(filePath)}`;
}

function buildGitRemoteUrl({ owner = DEFAULT_OWNER, repo = DEFAULT_REPO }) {
  return `https://github.com/${owner}/${repo}.git`;
}

function cacheDirForSha(cacheRoot, sha) {
  assertValidSha(sha);
  return path.join(cacheRoot || getDefaultCacheRoot(), sha);
}

function artifactCachePath({ cacheRoot, sha, artifactPath }) {
  if (path.isAbsolute(artifactPath) || artifactPath.split(/[\\/]+/).includes('..')) {
    throw new Error(`Template artifact path must stay under the templates cache: ${artifactPath}`);
  }
  return path.join(cacheDirForSha(cacheRoot, sha), artifactPath);
}

function isPathInside(rootPath, candidatePath) {
  const relative = path.relative(rootPath, candidatePath);
  return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
}

function assertOwnedPrivateCacheEntry(entryPath, stat, entryType) {
  if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {
    throw new Error(`Template cache ${entryType} must be owned by the current user: ${entryPath}`);
  }
  // POSIX permission bits are not meaningful on Windows. On POSIX, cached
  // package metadata and website source must not be readable or writable by
  // another local account because npm later executes content from this cache.
  if (process.platform !== 'win32' && (stat.mode & 0o077) !== 0) {
    throw new Error(`Template cache ${entryType} must be private to the current user: ${entryPath}`);
  }
}

function ensurePrivateCacheRoot(cacheRoot, fsImpl = fs) {
  const resolvedCacheRoot = path.resolve(cacheRoot || getDefaultCacheRoot());
  fsImpl.mkdirSync(resolvedCacheRoot, { recursive: true, mode: 0o700 });
  const rootStat = fsImpl.lstatSync(resolvedCacheRoot);
  if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
    throw new Error(`Template cache root must be a real directory: ${resolvedCacheRoot}`);
  }
  assertOwnedPrivateCacheEntry(resolvedCacheRoot, rootStat, 'root');

  const markerPath = path.join(resolvedCacheRoot, CACHE_MARKER_FILE);
  if (!fsImpl.existsSync(markerPath)) {
    const existingEntries = fsImpl.readdirSync(resolvedCacheRoot);
    if (existingEntries.length > 0) {
      throw new Error(`Template cache root is not owned by this tool: ${resolvedCacheRoot}`);
    }

    let markerDescriptor;
    try {
      markerDescriptor = fsImpl.openSync(markerPath, 'wx', 0o600);
      fsImpl.writeFileSync(markerDescriptor, JSON.stringify({
        schemaVersion: CACHE_MARKER_VERSION,
        ownerUid: typeof process.getuid === 'function' ? process.getuid() : null,
      }), 'utf8');
      fsImpl.closeSync(markerDescriptor);
      markerDescriptor = undefined;
    } catch (err) {
      // A concurrent template command may have initialized the same private
      // cache between the existence check and exclusive marker creation.
      if (err.code !== 'EEXIST') throw err;
    } finally {
      if (markerDescriptor !== undefined) {
        try { fsImpl.closeSync(markerDescriptor); } catch { /* best-effort */ }
      }
    }
  }

  const markerStat = fsImpl.lstatSync(markerPath);
  if (markerStat.isSymbolicLink() || !markerStat.isFile()) {
    throw new Error(`Template cache ownership marker must be a regular file: ${markerPath}`);
  }
  assertOwnedPrivateCacheEntry(markerPath, markerStat, 'ownership marker');

  let marker;
  try {
    marker = JSON.parse(fsImpl.readFileSync(markerPath, 'utf8'));
  } catch {
    throw new Error(`Template cache ownership marker is malformed: ${markerPath}`);
  }
  const currentUid = typeof process.getuid === 'function' ? process.getuid() : null;
  if (
    marker.schemaVersion !== CACHE_MARKER_VERSION ||
    marker.ownerUid !== currentUid
  ) {
    throw new Error(`Template cache ownership marker is invalid: ${markerPath}`);
  }

  return resolvedCacheRoot;
}

function ensureSafeCacheDirectory(cacheRoot, directoryPath, fsImpl = fs) {
  const resolvedCacheRoot = ensurePrivateCacheRoot(cacheRoot, fsImpl);
  const resolvedDirectory = path.resolve(directoryPath);
  if (!isPathInside(resolvedCacheRoot, resolvedDirectory)) {
    throw new Error(`Template cache directory must stay under the cache root: ${resolvedDirectory}`);
  }

  const canonicalCacheRoot = fsImpl.realpathSync(resolvedCacheRoot);

  let currentPath = resolvedCacheRoot;
  const relativeDirectory = path.relative(resolvedCacheRoot, resolvedDirectory);
  for (const segment of relativeDirectory ? relativeDirectory.split(path.sep) : []) {
    currentPath = path.join(currentPath, segment);
    if (!fsImpl.existsSync(currentPath)) {
      fsImpl.mkdirSync(currentPath);
    }
    const currentStat = fsImpl.lstatSync(currentPath);
    if (currentStat.isSymbolicLink() || !currentStat.isDirectory()) {
      throw new Error(`Template cache path must contain only real directories: ${currentPath}`);
    }
    const canonicalCurrentPath = fsImpl.realpathSync(currentPath);
    if (!isPathInside(canonicalCacheRoot, canonicalCurrentPath)) {
      throw new Error(`Template cache path resolves outside the cache root: ${currentPath}`);
    }
  }

  return resolvedDirectory;
}

function writeCacheFileAtomic(cacheRoot, filePath, content, fsImpl = fs) {
  const cacheDirectory = ensureSafeCacheDirectory(cacheRoot, path.dirname(filePath), fsImpl);
  if (fsImpl.existsSync(filePath)) {
    const existingStat = fsImpl.lstatSync(filePath);
    if (existingStat.isSymbolicLink() || !existingStat.isFile()) {
      throw new Error(`Template cache file must be a regular file: ${filePath}`);
    }
  }

  // Exclusive creation prevents a pre-planted symlink from redirecting the write.
  // Rename replaces the cache entry itself, so a destination swapped after the
  // lstat check is never opened or followed.
  const temporaryPath = path.join(
    cacheDirectory,
    `.${path.basename(filePath)}.partial-${process.pid}-${Date.now()}`
  );
  let fileDescriptor;
  try {
    fileDescriptor = fsImpl.openSync(temporaryPath, 'wx', 0o600);
    fsImpl.writeFileSync(fileDescriptor, content, 'utf8');
    fsImpl.closeSync(fileDescriptor);
    fileDescriptor = undefined;
    fsImpl.renameSync(temporaryPath, filePath);
  } finally {
    if (fileDescriptor !== undefined) {
      try { fsImpl.closeSync(fileDescriptor); } catch { /* best-effort */ }
    }
    try { fsImpl.rmSync(temporaryPath, { force: true }); } catch { /* best-effort */ }
  }
}

function isNonEmptyString(value) {
  return typeof value === 'string' && value.trim().length > 0;
}

function validateSolutionSettings(solutions, templateId) {
  if (solutions === undefined) return null;
  if (!Array.isArray(solutions)) return `template ${templateId} solutions must be an array`;
  const names = new Set();
  for (const [index, solution] of solutions.entries()) {
    if (!solution || typeof solution !== 'object' || Array.isArray(solution)) {
      return `template ${templateId} solution at index ${index} is not an object`;
    }
    const keys = Object.keys(solution);
    if (keys.some((key) => !['uniqueName', 'publishChanges'].includes(key))) {
      return `template ${templateId} solution ${solution.uniqueName || index} has unsupported fields`;
    }
    if (!isNonEmptyString(solution.uniqueName) || !IDENTIFIER_PATTERN.test(solution.uniqueName)) {
      return `template ${templateId} solution ${index} uniqueName must be a Dataverse identifier`;
    }
    if (typeof solution.publishChanges !== 'boolean') {
      return `template ${templateId} solution ${solution.uniqueName} publishChanges must be boolean`;
    }
    const normalizedName = solution.uniqueName.toLowerCase();
    if (names.has(normalizedName)) {
      return `template ${templateId} has duplicate solution uniqueName: ${solution.uniqueName}`;
    }
    names.add(normalizedName);
  }
  return null;
}

function isNestedFamilyTemplate(template) {
  return template && typeof template.variants === 'object' && template.variants && !Array.isArray(template.variants);
}

function isSpaTemplate(template) {
  return template && template.kind === 'spa';
}

function isCreateWebsiteApiTemplate(template) {
  return template?.kind === 'non-spa' &&
    template?.provisioning?.type === 'create-website-api';
}

function assertValidSha(sha) {
  if (!/^[0-9a-f]{40}$/i.test(sha || '')) {
    throw new Error(`Expected an immutable 40-character commit sha, got: ${sha}`);
  }
}

function validateResponsivePreviews(previews, context) {
  if (!Array.isArray(previews)) return `${context} responsivePreviews must be an array`;
  const ids = new Set();
  for (const preview of previews) {
    if (!preview || typeof preview !== 'object' || Array.isArray(preview)) {
      return `${context} responsive preview must be an object`;
    }
    for (const field of ['id', 'displayName', 'desktop', 'mobile']) {
      if (!isNonEmptyString(preview[field])) return `${context} responsive preview missing string field: ${field}`;
    }
    if (ids.has(preview.id)) return `${context} has duplicate responsive preview id: ${preview.id}`;
    ids.add(preview.id);
  }
  return null;
}

function validateCatalogShape(catalog) {
  // Raw `templates/manifest.json` shape:
  //   { "$schema": "./schemas/templates-manifest.schema.json", "templates": [
  //     { "id": "311-portal", "displayName": "311 Portal",
  //       "description": "…", "kind": "spa", "framework": "react",
  //       "keywords": ["311", "citizen-services"],
  //       "audience": ["makers", "developers"],
  //       "requiredDataverseLanguages": [1033],
  //       "responsivePreviews": [{ "id": "home", "displayName": "Home",
  //         "desktop": "spa/311-portal/previews/desktop-home.png",
  //         "mobile": "spa/311-portal/previews/mobile-home.png" }],
  //       "seedDataPath": "spa/311-portal/seed/data.json",
  //       "author": "Microsoft" }
  //   ] }
  // `audience` here is the *template's* target persona list (admins/developers/
  // makers/partners) and is an array per the upstream schema at
  // https://github.com/microsoft/power-pages-samples/blob/main/templates/schemas/templates-manifest.schema.json
  // Do not confuse it with create-site's internal/external site audience, which
  // comes from Phase 1 discovery and is what the telemetry event records.
  // Keep this structural, not semantic: the samples repo owns the full JSON
  // Schema, while create-site only needs enough validation to fail open before
  // previewing malformed entries or caching artifacts under a pinned SHA.
  if (!catalog || !Array.isArray(catalog.templates)) {
    return 'expected a templates array';
  }
  for (const [index, template] of catalog.templates.entries()) {
    if (!template || typeof template !== 'object') return `template at index ${index} is not an object`;
    const requiredStringFields = isNestedFamilyTemplate(template) || isCreateWebsiteApiTemplate(template)
      ? ['id', 'displayName', 'description', 'kind', 'author']
      : [
          'id', 'displayName', 'description', 'kind', 'framework',
          'author',
        ];
    const missing = requiredStringFields.filter((field) => !isNonEmptyString(template[field]));
    if (missing.length > 0) return `template ${template.id || index} missing string field(s): ${missing.join(', ')}`;
    if (!TEMPLATE_KINDS.has(template.kind)) return `template ${template.id} has unsupported kind: ${template.kind}`;
    if (template.solutionPath !== undefined || template.websiteCodePath !== undefined) {
      return `template ${template.id || index} must not define derivable solutionPath or websiteCodePath`;
    }
    if (!ID_PATTERN.test(template.id)) return `template ${template.id} id must be kebab-case`;
    if (!Array.isArray(template.audience) || template.audience.length === 0 || !template.audience.every(isNonEmptyString)) {
      return `template ${template.id} audience must be a non-empty array of strings`;
    }
    if (!Array.isArray(template.keywords)) return `template ${template.id} keywords must be an array`;
    const solutionSettingsError = validateSolutionSettings(template.solutions, template.id);
    if (solutionSettingsError) return solutionSettingsError;
    if (template.responsivePreviews !== undefined) {
      const error = validateResponsivePreviews(template.responsivePreviews, `template ${template.id}`);
      if (error) return error;
    }
    if (isCreateWebsiteApiTemplate(template)) {
      if (!isNonEmptyString(template.provisioning.templateName)) {
        return `template ${template.id} provisioning.templateName must be a non-empty string`;
      }
      for (const field of ['capabilities', 'requirements', 'responsivePreviews']) {
        if (!Array.isArray(template[field])) return `template ${template.id} ${field} must be an array`;
      }
      for (const field of ['previewImages', 'requiredDataverseLanguages', 'seedDataPath', 'variants']) {
        if (template[field] !== undefined) return `template ${template.id} create-website-api must not define ${field}`;
      }
    } else {
      if (
        !Array.isArray(template.requiredDataverseLanguages) ||
        template.requiredDataverseLanguages.length === 0 ||
        !template.requiredDataverseLanguages.every((id) => Number.isInteger(id) && id > 0)
      ) {
        return `template ${template.id} requiredDataverseLanguages must be a non-empty array of positive integers`;
      }
      if (template.previewImages !== undefined && !Array.isArray(template.previewImages)) {
        return `template ${template.id} previewImages must be an array`;
      }
      if (template.responsivePreviews === undefined && template.previewImages === undefined) {
        return `template ${template.id} responsivePreviews or previewImages must be an array`;
      }
    }
    if (isNestedFamilyTemplate(template)) {
      const seenFrameworks = new Set();
      const variantEntries = Object.entries(template.variants);
      if (variantEntries.length === 0) return `template ${template.id} variants must contain at least one framework`;
      for (const [framework, variant] of variantEntries) {
        const normalizedFramework = framework.toLowerCase();
        if (seenFrameworks.has(normalizedFramework)) return `template ${template.id} has duplicate framework variant: ${framework}`;
        seenFrameworks.add(normalizedFramework);
        if (!FRAMEWORKS.has(normalizedFramework)) return `template ${template.id} variant ${framework} has unsupported framework`;
        if (!variant || typeof variant !== 'object' || Array.isArray(variant)) return `template ${template.id} variant ${framework} is not an object`;
        if (variant.solutionPath !== undefined || variant.websiteCodePath !== undefined) {
          return `template ${template.id} variant ${framework} must not define derivable solutionPath or websiteCodePath`;
        }
        if (variant.solutions !== undefined) {
          return `template ${template.id} solution settings must be defined at the family level`;
        }
        if (variant.previewImages !== undefined && !Array.isArray(variant.previewImages)) {
          return `template ${template.id} variant ${framework} previewImages must be an array`;
        }
        if (variant.responsivePreviews !== undefined) {
          const error = validateResponsivePreviews(variant.responsivePreviews, `template ${template.id} variant ${framework}`);
          if (error) return error;
        }
        if (
          variant.requiredDataverseLanguages !== undefined &&
          (
            !Array.isArray(variant.requiredDataverseLanguages) ||
            variant.requiredDataverseLanguages.length === 0 ||
            !variant.requiredDataverseLanguages.every((id) => Number.isInteger(id) && id > 0)
          )
        ) {
          return `template ${template.id} variant ${framework} requiredDataverseLanguages must be a non-empty array of positive integers`;
        }
      }
    }
  }
  return null;
}

function catalogBasePath(catalogPath) {
  const dir = path.posix.dirname(catalogPath || '');
  return dir === '.' ? '' : dir.replace(/\/+$/, '');
}

function resolveCatalogArtifactPath(catalogPath, artifactPath) {
  if (!isNonEmptyString(artifactPath)) return artifactPath;
  const base = catalogBasePath(catalogPath);
  if (!base || artifactPath === base || artifactPath.startsWith(`${base}/`)) {
    return artifactPath;
  }
  return `${base}/${artifactPath.replace(/^\/+/, '')}`;
}

function materializeResponsivePreviews(previews, catalogPath) {
  return previews.map((preview) => ({
    ...preview,
    desktop: resolveCatalogArtifactPath(catalogPath, preview.desktop),
    mobile: resolveCatalogArtifactPath(catalogPath, preview.mobile),
  }));
}

function effectivePreviewFields(source, fallback) {
  // A variant's legacy list still overrides family previews during migration.
  // Explicit empty lists mean no previews, not permission to inherit another list.
  if (source.responsivePreviews !== undefined) return { responsivePreviews: source.responsivePreviews };
  if (source.previewImages !== undefined) return { previewImages: source.previewImages };
  return fallback ? effectivePreviewFields(fallback) : { previewImages: [] };
}

function materializeCatalogArtifactPaths(catalog, catalogPath) {
  return {
    ...catalog,
    templates: catalog.templates.map((template) => {
      // Manifest artifact paths are authored relative to the manifest folder.
      // For the default `templates/manifest.json`, a raw entry like:
      //   "previewImages": ["spa/311-portal/previews/home.png"]
      // must download from:
      //   templates/spa/311-portal/previews/home.png
      // Do this once after validation so the rest of create-site can treat every
      // artifact path as repository-root-relative.
      const materialized = {
        ...template,
        ...(Array.isArray(template.previewImages) ? {
          previewImages: template.previewImages.map((imagePath) => resolveCatalogArtifactPath(catalogPath, imagePath)),
        } : {}),
      };
      if (Array.isArray(template.responsivePreviews)) {
        materialized.responsivePreviews = materializeResponsivePreviews(template.responsivePreviews, catalogPath);
      }
      if (template.seedDataPath) {
        materialized.seedDataPath = resolveCatalogArtifactPath(catalogPath, template.seedDataPath);
      }
      if (isNestedFamilyTemplate(template)) {
        materialized.variants = Object.fromEntries(Object.entries(template.variants).map(([framework, variant]) => {
          const materializedVariant = { ...variant };
          if (Array.isArray(variant.previewImages)) {
            materializedVariant.previewImages = variant.previewImages.map((imagePath) => resolveCatalogArtifactPath(catalogPath, imagePath));
          }
          if (Array.isArray(variant.responsivePreviews)) {
            materializedVariant.responsivePreviews = materializeResponsivePreviews(variant.responsivePreviews, catalogPath);
          }
          if (variant.seedDataPath) {
            materializedVariant.seedDataPath = resolveCatalogArtifactPath(catalogPath, variant.seedDataPath);
          }
          return [framework.toLowerCase(), materializedVariant];
        }));
      }
      return materialized;
    }),
  };
}

function normalizeCatalogFamilies(catalog = {}) {
  const templates = Array.isArray(catalog.templates) ? catalog.templates : [];
  return templates.map((template) => {
    if (!isNestedFamilyTemplate(template)) {
      return {
        id: template.id,
        displayName: template.displayName,
        description: template.description,
        kind: template.kind,
        keywords: template.keywords || [],
        audience: template.audience || [],
        requiredDataverseLanguages: template.requiredDataverseLanguages || [],
        ...effectivePreviewFields(template),
        ...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),
        ...(template.solutions?.length ? { solutions: template.solutions } : {}),
        author: template.author,
        variants: [{
          familyId: template.id,
          variantKey: template.framework,
          variantId: `${template.id}/${template.framework}`,
          displayName: template.displayName,
          description: template.description,
          kind: template.kind,
          framework: template.framework,
          keywords: template.keywords || [],
          audience: template.audience || [],
          requiredDataverseLanguages: template.requiredDataverseLanguages || [],
          ...effectivePreviewFields(template),
          ...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),
          ...(template.solutions?.length ? { solutions: template.solutions } : {}),
          author: template.author,
        }],
      };
    }
    return {
      id: template.id,
      displayName: template.displayName,
      description: template.description,
      kind: template.kind,
      keywords: template.keywords || [],
      audience: template.audience || [],
      requiredDataverseLanguages: template.requiredDataverseLanguages || [],
      ...effectivePreviewFields(template),
      ...(template.seedDataPath ? { seedDataPath: template.seedDataPath } : {}),
      ...(template.solutions?.length ? { solutions: template.solutions } : {}),
      author: template.author,
      variants: Object.entries(template.variants).map(([framework, variant]) => {
        const variantKey = framework.toLowerCase();
        return {
          familyId: template.id,
          variantKey,
          variantId: `${template.id}/${variantKey}`,
          displayName: template.displayName,
          description: template.description,
          kind: template.kind,
          framework: variantKey,
          keywords: template.keywords || [],
          audience: template.audience || [],
          requiredDataverseLanguages: variant.requiredDataverseLanguages || template.requiredDataverseLanguages || [],
          ...effectivePreviewFields(variant, template),
          ...(variant.seedDataPath || template.seedDataPath ? { seedDataPath: variant.seedDataPath || template.seedDataPath } : {}),
          ...(template.solutions?.length ? { solutions: template.solutions } : {}),
          author: template.author,
        };
      }),
    };
  });
}

function startHttpsGet({ url, headers, timeoutMs, deps, reject, onResponse }) {
  const httpsImpl = deps.https || https;
  const req = httpsImpl.get(url, {
    headers: {
      'User-Agent': 'power-pages-template-catalog',
      ...headers,
    },
    timeout: timeoutMs,
  }, onResponse);
  req.on('error', reject);
  req.on('timeout', () => {
    req.destroy(new Error(`GET ${url} timed out`));
  });
  return req;
}

function requestJson(url, deps = {}) {
  return new Promise((resolve, reject) => {
    startHttpsGet({
      url,
      headers: {
        Accept: 'application/vnd.github+json, application/json',
      },
      timeoutMs: deps.timeoutMs || 10000,
      deps,
      reject,
      onResponse: (res) => {
        res.on('error', reject);
        if (res.statusCode < 200 || res.statusCode >= 300) {
          res.resume();
          reject(new Error(`GET ${url} failed with ${res.statusCode}`));
          return;
        }
        let body = '';
        res.setEncoding('utf8');
        res.on('data', (chunk) => { body += chunk; });
        res.on('end', () => {
          try {
            resolve(JSON.parse(body));
          } catch (err) {
            reject(new Error(`GET ${url} returned invalid JSON: ${err.message}`));
          }
        });
      },
    });
  });
}

function downloadFile(url, outputPath, deps = {}) {
  const fsImpl = deps.fs || fs;
  const maxBytes = deps.maxBytes;
  if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)) {
    return Promise.reject(new Error('maxBytes must be a positive safe integer'));
  }
  return new Promise((resolve, reject) => {
    fsImpl.mkdirSync(path.dirname(outputPath), { recursive: true });
    const randomBytes = deps.randomBytes || crypto.randomBytes;
    const tmpPath = `${outputPath}.partial-${process.pid}-${randomBytes(8).toString('hex')}`;
    // `wx` maps to exclusive create. A pre-existing symlink or file makes the
    // open fail instead of redirecting downloaded bytes outside the cache.
    const file = fsImpl.createWriteStream(tmpPath, { flags: 'wx', mode: 0o600 });
    const cleanup = () => {
      try { fsImpl.rmSync(tmpPath, { force: true }); } catch { /* best-effort */ }
    };
    startHttpsGet({
      url,
      headers: {},
      timeoutMs: deps.timeoutMs || 30000,
      deps,
      reject: (err) => {
        file.destroy();
        cleanup();
        reject(err);
      },
      onResponse: (res) => {
        res.on('error', (err) => {
          file.destroy();
          cleanup();
          reject(err);
        });
        if (res.statusCode < 200 || res.statusCode >= 300) {
          res.resume();
          file.destroy();
          cleanup();
          reject(new Error(`GET ${url} failed with ${res.statusCode}`));
          return;
        }
        const contentLength = Number((res.headers || {})['content-length']);
        if (maxBytes !== undefined && Number.isFinite(contentLength) && contentLength > maxBytes) {
          res.resume();
          file.destroy();
          cleanup();
          reject(new Error(`GET ${url} exceeds the ${maxBytes}-byte download limit`));
          return;
        }
        let downloadedBytes = 0;
        if (maxBytes !== undefined) {
          res.on('data', (chunk) => {
            downloadedBytes += chunk.length;
            if (downloadedBytes > maxBytes) {
              res.destroy(new Error(`GET ${url} exceeds the ${maxBytes}-byte download limit`));
            }
          });
        }
        res.pipe(file);
        file.on('finish', () => {
          file.close((closeError) => {
            if (closeError) {
              cleanup();
              reject(closeError);
              return;
            }
            try {
              fsImpl.renameSync(tmpPath, outputPath);
              resolve(outputPath);
            } catch (err) {
              cleanup();
              reject(err);
            }
          });
        });
      },
    });
    file.on('error', (err) => {
      cleanup();
      reject(err);
    });
  });
}

function runGitLsRemote(args, deps = {}) {
  const execFile = deps.execFileSync || execFileSync;
  return execFile('git', ['ls-remote', ...args], { encoding: 'utf8', timeout: 15000 });
}

function resolveRefToSha({ owner = DEFAULT_OWNER, repo = DEFAULT_REPO, ref = DEFAULT_REF }, deps = {}) {
  const remoteUrl = buildGitRemoteUrl({ owner, repo });
  const output = runGitLsRemote([remoteUrl, ref], deps);
  // `git ls-remote <remote> <ref>` returns tab-delimited rows:
  //   49b0e74b386206c7682019110434f034fca2e129\trefs/heads/main
  // A release tag can return multiple rows for annotated tags; any leading
  // 40-character SHA is enough because raw.githubusercontent.com accepts the
  // object id for immutable content fetches.
  const match = String(output || '').match(/^([0-9a-f]{40})\s+/im);
  if (!match) {
    throw new Error(`git ls-remote did not resolve ${owner}/${repo}@${ref}`);
  }
  return match[1];
}

function versionKey(tagName) {
  const match = String(tagName || '').match(/(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?/);
  if (!match) return null;
  return match.slice(1).map((part) => Number(part || 0));
}

function compareVersionKeys(left, right) {
  for (let i = 0; i < Math.max(left.length, right.length); i++) {
    const diff = (left[i] || 0) - (right[i] || 0);
    if (diff !== 0) return diff;
  }
  return 0;
}

function parseRemoteTags(output) {
  const byTag = new Map();
  for (const line of String(output || '').split(/\r?\n/)) {
    const match = line.match(/^([0-9a-f]{40})\s+refs\/tags\/(.+?)(\^\{\})?$/i);
    if (!match) continue;
    const [, sha, tagName, peeled] = match;
    const existing = byTag.get(tagName) || {};
    byTag.set(tagName, peeled ? { ...existing, peeledSha: sha } : { ...existing, sha });
  }
  return [...byTag.entries()]
    .map(([tagName, value]) => ({ tagName, sha: value.peeledSha || value.sha, version: versionKey(tagName) }))
    .filter((entry) => entry.sha && entry.version);
}

function resolveLatestRelease(options = {}, deps = {}) {
  const remoteUrl = buildGitRemoteUrl(options);
  const tags = parseRemoteTags(runGitLsRemote(['--tags', remoteUrl], deps));
  if (tags.length === 0) {
    return { ref: 'main', sha: resolveRefToSha({ ...options, ref: 'main' }, deps) };
  }
  tags.sort((a, b) => compareVersionKeys(b.version, a.version) || a.tagName.localeCompare(b.tagName));
  const latest = tags[0];
  return { ref: latest.tagName, sha: latest.sha, releaseName: latest.tagName, releaseUrl: `https://github.com/${options.owner || DEFAULT_OWNER}/${options.repo || DEFAULT_REPO}/releases/tag/${encodeURIComponent(latest.tagName)}` };
}

function resolveCatalogRef(options = {}, deps = {}) {
  const ref = options.ref || DEFAULT_REF;
  if (ref === 'latest-release') {
    return resolveLatestRelease(options, deps);
  }
  if (/^[0-9a-f]{40}$/i.test(ref)) {
    return { ref, sha: ref };
  }
  return { ref, sha: resolveRefToSha({ ...options, ref }, deps) };
}

async function fetchCatalog(options = {}, deps = {}) {
  const {
    owner = DEFAULT_OWNER,
    repo = DEFAULT_REPO,
    ref = DEFAULT_REF,
    catalogPath = DEFAULT_CATALOG_PATH,
    cacheRoot = getDefaultCacheRoot(),
  } = options;
  const fsImpl = deps.fs || fs;
  const request = deps.requestJson || ((url) => requestJson(url, deps));

  try {
    const resolved = resolveCatalogRef({ owner, repo, ref }, deps);
    const { sha } = resolved;
    const cacheDir = cacheDirForSha(cacheRoot, sha);
    const rawCatalog = await request(buildRawUrl({ owner, repo, sha, filePath: catalogPath }));
    const catalogError = validateCatalogShape(rawCatalog);
    if (catalogError) throw new Error(`Template catalog is malformed: ${catalogError}`);
    const catalog = materializeCatalogArtifactPaths(rawCatalog, catalogPath);
    // Keep the normalized selectable view SPA-only for SPA consumers.
    // Non-SPA Create Website API consumers read the validated full catalog
    // below because they do not download website code or solution artifacts.
    const selectableCatalog = {
      ...catalog,
      templates: normalizeCatalogFamilies({
        templates: catalog.templates.filter(isSpaTemplate),
      }),
    };
    const catalogLocalPath = artifactCachePath({ cacheRoot, sha, artifactPath: catalogPath });
    writeCacheFileAtomic(cacheRoot, catalogLocalPath, JSON.stringify(catalog, null, 2), fsImpl);
    return {
      ok: true,
      owner,
      repo,
      ref,
      resolvedRef: resolved.ref,
      sha,
      releaseName: resolved.releaseName,
      releaseUrl: resolved.releaseUrl,
      catalogPath,
      catalogLocalPath,
      cacheDir,
      catalog,
      selectableCatalog,
    };
  } catch (err) {
    return { ok: false, owner, repo, ref, catalogPath, error: err.message };
  }
}

function validateZipContainsSolution(zipPath, deps = {}) {
  try {
    const fsImpl = deps.fs || fs;
    return zipFileNames(fsImpl.readFileSync(zipPath)).some((name) => name.toLowerCase() === 'solution.xml');
  } catch {
    return false;
  }
}

function zipFileNames(buffer) {
  // ZIP stores each filename in local file headers:
  //   50 4b 03 04 ... [fileNameLength at +26] [extraLength at +28] [name at +30]
  // and again in central directory headers:
  //   50 4b 01 02 ... [fileNameLength at +28] [extraLength at +30] [commentLength at +32] [name at +46]
  // Read both forms so this remains independent of the host OS having `unzip`
  // installed. That matters in plugin hosts and CI images where external tools
  // are not guaranteed.
  const data = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
  const names = [];
  for (let i = 0; i <= data.length - 4; i++) {
    const signature = data.readUInt32LE(i);
    if (signature === 0x04034b50 && i + 30 <= data.length) {
      const fileNameLength = data.readUInt16LE(i + 26);
      const extraLength = data.readUInt16LE(i + 28);
      const nameStart = i + 30;
      const nameEnd = nameStart + fileNameLength;
      if (nameEnd <= data.length) names.push(data.subarray(nameStart, nameEnd).toString('utf8'));
      i = Math.max(i, nameEnd + extraLength - 1);
    } else if (signature === 0x02014b50 && i + 46 <= data.length) {
      const fileNameLength = data.readUInt16LE(i + 28);
      const extraLength = data.readUInt16LE(i + 30);
      const commentLength = data.readUInt16LE(i + 32);
      const nameStart = i + 46;
      const nameEnd = nameStart + fileNameLength;
      if (nameEnd <= data.length) names.push(data.subarray(nameStart, nameEnd).toString('utf8'));
      i = Math.max(i, nameEnd + extraLength + commentLength - 1);
    }
  }
  return names;
}

async function downloadArtifact(options = {}, deps = {}) {
  const {
    owner = DEFAULT_OWNER,
    repo = DEFAULT_REPO,
    sha,
    artifactPath,
    cacheRoot = getDefaultCacheRoot(),
  } = options;
  if (!sha) throw new Error('sha is required');
  if (!artifactPath) throw new Error('artifactPath is required');
  const fsImpl = deps.fs || fs;
  const localPath = artifactCachePath({ cacheRoot, sha, artifactPath });
  ensureSafeCacheDirectory(cacheRoot, path.dirname(localPath), fsImpl);
  if (fsImpl.existsSync(localPath)) {
    const cachedStat = fsImpl.lstatSync(localPath);
    if (cachedStat.isSymbolicLink() || !cachedStat.isFile()) {
      throw new Error(`Cached template artifact must be a regular file: ${localPath}`);
    }
    return { localPath, cached: true };
  }
  const download = deps.downloadFile || ((url, dest) => downloadFile(url, dest, deps));
  await download(buildRawUrl({ owner, repo, sha, filePath: artifactPath }), localPath);
  const downloadedStat = fsImpl.lstatSync(localPath);
  if (downloadedStat.isSymbolicLink() || !downloadedStat.isFile()) {
    throw new Error(`Downloaded template artifact must be a regular file: ${localPath}`);
  }
  return { localPath, cached: false };
}

function validateRepositoryDirectoryPath(directoryPath, fieldName, label) {
  if (!isNonEmptyString(directoryPath)) return `${fieldName} is required`;
  if (path.isAbsolute(directoryPath) || directoryPath.includes('\\')) {
    return `${label} must be a repository-relative POSIX directory`;
  }
  const segments = directoryPath.split('/');
  if (segments.some((segment) => !segment || segment === '.' || segment === '..' || segment === '.git')) {
    return `${label} must stay inside the template repository`;
  }
  if (segments.some((segment) => !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(segment))) {
    return `${label} contains unsupported characters`;
  }
  return null;
}

function validateWebsiteCodeDirectory(localPath, options = {}, deps = {}) {
  const fsImpl = deps.fs || fs;
  if (!fsImpl.existsSync(localPath)) return 'Website code directory is missing';
  const rootStat = fsImpl.lstatSync(localPath);
  if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
    return 'Website code directory must be a regular directory';
  }
  // Both non-SPA and SPA sites keep PAC website source under
  // `.powerpages-site/website.yml`. SPA sites also carry the package metadata
  // and project-local npm configuration needed to build and upload the SPA.
  // See: https://learn.microsoft.com/power-platform/developer/cli/reference/pages#pac-pages-download
  const requiredFiles = options.kind === 'non-spa' || options.kind === 'traditional'
    ? []
    : ['powerpages.config.json', 'package.json', '.npmrc'];
  for (const requiredFile of requiredFiles) {
    const requiredPath = path.join(localPath, requiredFile);
    if (!fsImpl.existsSync(requiredPath)) {
      return `Website code directory is missing ${requiredFile}`;
    }
    const requiredStat = fsImpl.lstatSync(requiredPath);
    if (requiredStat.isSymbolicLink() || !requiredStat.isFile()) {
      return `Website code directory is missing ${requiredFile}`;
    }
  }
  const websiteMetadataPath = path.join(localPath, '.powerpages-site', 'website.yml');
  if (!fsImpl.existsSync(websiteMetadataPath)) {
    return 'Website code directory is missing .powerpages-site/website.yml';
  }
  const metadataStat = fsImpl.lstatSync(websiteMetadataPath);
  if (metadataStat.isSymbolicLink() || !metadataStat.isFile()) {
    return 'Website code directory is missing .powerpages-site/website.yml';
  }

  const queue = [localPath];
  while (queue.length > 0) {
    const current = queue.pop();
    for (const entry of fsImpl.readdirSync(current, { withFileTypes: true })) {
      if (entry.isSymbolicLink()) {
        return `Website code directory contains a symbolic link: ${path.relative(localPath, path.join(current, entry.name))}`;
      }
      if (entry.name === '.git' || entry.name === 'node_modules' || entry.name === '.DS_Store' || entry.name.endsWith('.tsbuildinfo')) {
        return `Website code directory contains generated or local-only content: ${path.relative(localPath, path.join(current, entry.name))}`;
      }
      if (entry.isDirectory()) queue.push(path.join(current, entry.name));
    }
  }
  return null;
}

function validateUnpackedSolutionDirectory(localPath, deps = {}) {
  const fsImpl = deps.fs || fs;
  if (!fsImpl.existsSync(localPath)) {
    return 'Template solution source is not a directory';
  }
  const rootStat = fsImpl.lstatSync(localPath);
  if (rootStat.isSymbolicLink()) {
    return 'Template solution source must not be a symbolic link';
  }
  if (!rootStat.isDirectory()) return 'Template solution source is not a directory';

  // `pac solution unpack` uses the SolutionPackager source layout and places
  // solution metadata under `Other/`.
  // See: https://learn.microsoft.com/power-platform/developer/cli/reference/solution#pac-solution-unpack
  const solutionXmlPath = path.join(localPath, 'Other', 'Solution.xml');
  const customizationsXmlPath = path.join(localPath, 'Other', 'Customizations.xml');
  const queue = [localPath];
  while (queue.length > 0) {
    const current = queue.pop();
    for (const entry of fsImpl.readdirSync(current, { withFileTypes: true })) {
      const entryPath = path.join(current, entry.name);
      const relativePath = path.relative(localPath, entryPath);
      if (entry.isSymbolicLink()) {
        return `Template solution source contains a symbolic link: ${relativePath}`;
      }
      if (
        entry.name === '.git' ||
        entry.name === 'node_modules' ||
        entry.name === '.DS_Store' ||
        entry.name.endsWith('.tsbuildinfo')
      ) {
        return `Template solution source contains generated or local-only content: ${relativePath}`;
      }
      if (entry.isFile() && path.extname(entry.name).toLowerCase() === '.zip') {
        return `Template solution source must not contain committed zip files: ${relativePath}`;
      }
      if (entry.isDirectory()) queue.push(entryPath);
    }
  }

  for (const requiredPath of [solutionXmlPath, customizationsXmlPath]) {
    if (!fsImpl.existsSync(requiredPath) || !fsImpl.lstatSync(requiredPath).isFile()) {
      return `Template solution source is missing ${path.relative(localPath, requiredPath)}`;
    }
  }

  const solutionXml = fsImpl.readFileSync(solutionXmlPath, 'utf8');
  if (!/<Managed>\s*0\s*<\/Managed>/i.test(solutionXml)) {
    return 'Template solution source must describe an unmanaged solution';
  }
  const customizationsXml = fsImpl.readFileSync(customizationsXmlPath, 'utf8');
  if (!deps.allowWebsiteComponents && /<powerpagecomponents(?:\s|>)/i.test(customizationsXml)) {
    return 'Template supporting solution must not contain Power Pages website components';
  }
  return null;
}

function repositoryDirectoryCheckoutRoot({ cacheRoot = getDefaultCacheRoot(), sha, directoryPath }) {
  assertValidSha(sha);
  const pathError = validateRepositoryDirectoryPath(
    directoryPath,
    'directoryPath',
    'Repository directory path'
  );
  if (pathError) throw new Error(pathError);
  // Keep cached content under a reserved leaf so a cached parent path and one of
  // its descendants cannot overwrite each other.
  return path.join(
    cacheDirForSha(cacheRoot, sha),
    '.directory-checkouts',
    ...directoryPath.split('/'),
    '.checkout'
  );
}

function runGitCheckoutCommand(args, deps = {}) {
  const execFile = deps.execFileSync || execFileSync;
  return execFile('git', args, {
    encoding: 'utf8',
    timeout: deps.gitTimeoutMs || 120000,
    stdio: ['ignore', 'pipe', 'pipe'],
  });
}

function downloadRepositoryDirectory(options = {}, validateDirectory, deps = {}) {
  const {
    owner = DEFAULT_OWNER,
    repo = DEFAULT_REPO,
    sha,
    directoryPath,
    cacheRoot = getDefaultCacheRoot(),
  } = options;
  const fsImpl = deps.fs || fs;
  assertValidSha(sha);
  const pathError = validateRepositoryDirectoryPath(
    directoryPath,
    'directoryPath',
    'Repository directory path'
  );
  if (pathError) throw new Error(pathError);
  const checkoutRoot = repositoryDirectoryCheckoutRoot({ cacheRoot, sha, directoryPath });
  const localPath = checkoutRoot;
  ensureSafeCacheDirectory(cacheRoot, path.dirname(checkoutRoot), fsImpl);
  if (fsImpl.existsSync(checkoutRoot)) {
    const checkoutStat = fsImpl.lstatSync(checkoutRoot);
    if (checkoutStat.isSymbolicLink() || !checkoutStat.isDirectory()) {
      fsImpl.rmSync(checkoutRoot, { recursive: true, force: true });
    } else {
      const canonicalCacheRoot = fsImpl.realpathSync(path.resolve(cacheRoot));
      const canonicalCheckoutRoot = fsImpl.realpathSync(checkoutRoot);
      if (!isPathInside(canonicalCacheRoot, canonicalCheckoutRoot)) {
        throw new Error(`Template checkout resolves outside the cache root: ${checkoutRoot}`);
      }
      const cachedError = validateDirectory(localPath);
      if (!cachedError) return { localPath, cached: true };
      fsImpl.rmSync(checkoutRoot, { recursive: true, force: true });
    }
  }

  const partialRoot = `${checkoutRoot}.partial-${process.pid}-${Date.now()}`;
  fsImpl.rmSync(partialRoot, { recursive: true, force: true });
  try {
    runGitCheckoutCommand(['init', '--quiet', partialRoot], deps);
    runGitCheckoutCommand(['-C', partialRoot, 'remote', 'add', 'origin', buildGitRemoteUrl({ owner, repo })], deps);
    runGitCheckoutCommand(['-C', partialRoot, 'sparse-checkout', 'set', '--cone', '--', directoryPath], deps);
    runGitCheckoutCommand(['-C', partialRoot, 'fetch', '--quiet', '--depth', '1', 'origin', sha], deps);
    runGitCheckoutCommand(['-C', partialRoot, 'checkout', '--quiet', '--detach', 'FETCH_HEAD'], deps);
    const partialPath = path.join(partialRoot, ...directoryPath.split('/'));
    const validationError = validateDirectory(partialPath);
    if (validationError) throw new Error(validationError);
    fsImpl.renameSync(partialPath, checkoutRoot);
    const checkoutStat = fsImpl.lstatSync(checkoutRoot);
    if (checkoutStat.isSymbolicLink() || !checkoutStat.isDirectory()) {
      throw new Error(`Downloaded template checkout must be a real directory: ${checkoutRoot}`);
    }
    const canonicalCacheRoot = fsImpl.realpathSync(path.resolve(cacheRoot));
    const canonicalCheckoutRoot = fsImpl.realpathSync(checkoutRoot);
    if (!isPathInside(canonicalCacheRoot, canonicalCheckoutRoot)) {
      throw new Error(`Downloaded template checkout resolves outside the cache root: ${checkoutRoot}`);
    }
    fsImpl.rmSync(partialRoot, { recursive: true, force: true });
  } catch (err) {
    fsImpl.rmSync(partialRoot, { recursive: true, force: true });
    throw err;
  }
  return { localPath, cached: false };
}

function templateFamilyRoot({ catalogPath = DEFAULT_CATALOG_PATH, kind, templateId }) {
  if (!TEMPLATE_KINDS.has(kind)) throw new Error(`Unsupported template kind: ${kind}`);
  if (!ID_PATTERN.test(templateId || '')) throw new Error(`Invalid template id: ${templateId}`);
  return path.posix.join(catalogBasePath(catalogPath), kind, templateId);
}

function templateVariantRoot({ catalogPath = DEFAULT_CATALOG_PATH, kind, templateId, variant }) {
  const normalizedVariant = String(variant || '').toLowerCase();
  if (!FRAMEWORKS.has(normalizedVariant)) throw new Error(`Unsupported template variant: ${variant}`);
  return path.posix.join(
    templateFamilyRoot({ catalogPath, kind, templateId }),
    'variants',
    normalizedVariant
  );
}

function compareCaseInsensitivePathNames(left, right) {
  const normalizedLeft = left.toLowerCase();
  const normalizedRight = right.toLowerCase();
  if (normalizedLeft < normalizedRight) return -1;
  if (normalizedLeft > normalizedRight) return 1;
  if (left < right) return -1;
  if (left > right) return 1;
  return 0;
}

function inspectTemplateSolutions(localSolutionsPath, kind, deps = {}) {
  const fsImpl = deps.fs || fs;
  if (!fsImpl.existsSync(localSolutionsPath)) {
    return { ok: false, error: 'Template is missing solutions/' };
  }
  const rootStat = fsImpl.lstatSync(localSolutionsPath);
  if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
    return { ok: false, error: 'Template solutions/ must be a directory and not a symbolic link' };
  }

  const entries = fsImpl.readdirSync(localSolutionsPath, { withFileTypes: true })
    .sort((left, right) => compareCaseInsensitivePathNames(left.name, right.name));
  if (entries.length === 0) {
    return { ok: false, error: 'Template solutions/ must contain at least one solution' };
  }

  const seenUniqueNames = new Set();
  const solutions = [];
  for (const entry of entries) {
    if (!entry.isDirectory() || entry.isSymbolicLink()) {
      return { ok: false, error: `Template solutions/ contains a non-directory entry: ${entry.name}` };
    }
    const solutionPath = path.join(localSolutionsPath, entry.name);
    const solutionError = validateUnpackedSolutionDirectory(solutionPath, {
      ...deps,
      fs: fsImpl,
      allowWebsiteComponents: kind === 'non-spa' || kind === 'traditional',
    });
    if (solutionError) return { ok: false, error: `${entry.name}: ${solutionError}` };

    const inspected = inspectSolutionDirectory(solutionPath, { ...deps, fs: fsImpl });
    if (!inspected.ok) return { ok: false, error: `${entry.name}: ${inspected.error}` };
    if (entry.name !== inspected.uniqueName) {
      return {
        ok: false,
        error: `Solution folder ${entry.name} must match the Solution.xml unique name ${inspected.uniqueName}`,
      };
    }
    const normalizedUniqueName = inspected.uniqueName.toLowerCase();
    if (seenUniqueNames.has(normalizedUniqueName)) {
      return { ok: false, error: `Template contains duplicate solution unique name: ${inspected.uniqueName}` };
    }
    seenUniqueNames.add(normalizedUniqueName);
    solutions.push({
      uniqueName: inspected.uniqueName,
      version: inspected.version,
      solutionPath,
    });
  }
  return { ok: true, solutions };
}

function inspectTemplateVariantDirectory(localVariantPath, kind, deps = {}) {
  const websiteCodePath = path.join(localVariantPath, 'website-code');
  const websiteCodeError = validateWebsiteCodeDirectory(websiteCodePath, { kind }, deps);
  if (websiteCodeError) return { ok: false, error: websiteCodeError };
  return {
    ok: true,
    websiteCodePath,
  };
}

function applySolutionSettings(solutions, solutionSettings = []) {
  const settingsByName = new Map(solutionSettings.map((solution) => [
    solution.uniqueName,
    solution,
  ]));
  const discoveredNames = new Set(solutions.map((solution) => solution.uniqueName));
  for (const setting of solutionSettings) {
    if (!discoveredNames.has(setting.uniqueName)) {
      throw new Error(`Template manifest declares unknown solution: ${setting.uniqueName}`);
    }
  }
  return solutions.map((solution) => ({
    ...solution,
    publishChanges: settingsByName.get(solution.uniqueName)?.publishChanges || false,
  }));
}

function validateTemplateVariantDirectory(localVariantPath, kind, deps = {}) {
  const result = inspectTemplateVariantDirectory(localVariantPath, kind, deps);
  return result.ok ? null : result.error;
}

function downloadTemplateVariant(options = {}, deps = {}) {
  const {
    catalogPath = DEFAULT_CATALOG_PATH,
    kind,
    templateId,
    variant,
    solutionSettings = [],
  } = options;
  try {
    const familyRoot = templateFamilyRoot({ catalogPath, kind, templateId });
    const variantRoot = templateVariantRoot({ catalogPath, kind, templateId, variant });
    const solutionsRoot = path.posix.join(familyRoot, 'solutions');
    const variantResult = downloadRepositoryDirectory(
      { ...options, directoryPath: variantRoot },
      (localPath) => validateTemplateVariantDirectory(localPath, kind, deps),
      deps
    );
    const solutionsResult = downloadRepositoryDirectory(
      { ...options, directoryPath: solutionsRoot },
      (localPath) => {
        const inspected = inspectTemplateSolutions(localPath, kind, deps);
        return inspected.ok ? null : inspected.error;
      },
      deps
    );
    const inspectedVariant = inspectTemplateVariantDirectory(variantResult.localPath, kind, deps);
    if (!inspectedVariant.ok) throw new Error(inspectedVariant.error);
    const inspectedSolutions = inspectTemplateSolutions(solutionsResult.localPath, kind, deps);
    if (!inspectedSolutions.ok) throw new Error(inspectedSolutions.error);
    return {
      ok: true,
      variantPath: variantResult.localPath,
      websiteCodePath: inspectedVariant.websiteCodePath,
      solutions: applySolutionSettings(inspectedSolutions.solutions, solutionSettings),
      cached: variantResult.cached && solutionsResult.cached,
    };
  } catch (err) {
    return { ok: false, kind, templateId, variant, error: err.message };
  }
}

async function downloadSeedDataDirectory(options = {}, deps = {}) {
  const {
    owner = DEFAULT_OWNER,
    repo = DEFAULT_REPO,
    sha,
    seedDataPath,
    cacheRoot = getDefaultCacheRoot(),
  } = options;
  if (!sha) throw new Error('sha is required');
  assertValidSha(sha);
  if (!seedDataPath) return { ok: true, localDir: null, files: [] };
  if (path.isAbsolute(seedDataPath) || seedDataPath.split(/[\\/]+/).includes('..')) {
    return { ok: false, seedDataPath, error: `Seed data path must stay under templates: ${seedDataPath}` };
  }
  const fsImpl = deps.fs || fs;
  try {
    if (path.posix.extname(seedDataPath).toLowerCase() === '.json') {
      const seedFile = (await downloadArtifact({ owner, repo, sha, artifactPath: seedDataPath, cacheRoot }, deps)).localPath;
      const seedRoot = path.posix.dirname(seedDataPath);
      const parsed = JSON.parse(fsImpl.readFileSync(seedFile, 'utf8'));
      const attachmentPaths = collectSeedAttachmentPaths(parsed)
        .map((relativePath) => {
          if (path.posix.isAbsolute(relativePath) || relativePath.split(/[\\/]+/).includes('..')) {
            throw new Error(`Seed attachment path must stay under seed-data root: ${relativePath}`);
          }
          return `${seedRoot}/${relativePath.replace(/^\/+/, '')}`;
        })
        .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
      const downloaded = [seedFile];
      for (const artifactPath of attachmentPaths) {
        downloaded.push((await downloadArtifact({ owner, repo, sha, artifactPath, cacheRoot }, deps)).localPath);
      }
      return {
        ok: true,
        localDir: path.dirname(seedFile),
        seedFile,
        files: downloaded,
      };
    }
    return { ok: false, seedDataPath, error: `Seed data path must point to a JSON file: ${seedDataPath}` };
  } catch (err) {
    return { ok: false, seedDataPath, error: err.message };
  }
}

function collectSeedAttachmentPaths(seedData) {
  const paths = new Set();
  for (const fileExport of Array.isArray(seedData.fileExports) ? seedData.fileExports : []) {
    if (fileExport && typeof fileExport.path === 'string' && fileExport.path.trim()) paths.add(fileExport.path);
  }
  for (const record of Array.isArray(seedData.records) ? seedData.records : []) {
    if (!record || typeof record !== 'object' || !record.__files || typeof record.__files !== 'object' || Array.isArray(record.__files)) {
      continue;
    }
    for (const value of Object.values(record.__files)) {
      if (typeof value === 'string' && value.trim()) paths.add(value);
    }
  }
  return [...paths];
}

module.exports = {
  DEFAULT_OWNER,
  DEFAULT_REPO,
  DEFAULT_REF,
  DEFAULT_CATALOG_PATH,
  getDefaultCacheRoot,
  ensurePrivateCacheRoot,
  buildRawUrl,
  buildGitRemoteUrl,
  cacheDirForSha,
  artifactCachePath,
  requestJson,
  downloadFile,
  resolveRefToSha,
  resolveLatestRelease,
  parseRemoteTags,
  resolveCatalogRef,
  fetchCatalog,
  validateZipContainsSolution,
  downloadArtifact,
  downloadTemplateVariant,
  downloadSeedDataDirectory,
  validateWebsiteCodeDirectory,
  validateUnpackedSolutionDirectory,
  repositoryDirectoryCheckoutRoot,
  templateFamilyRoot,
  templateVariantRoot,
  inspectTemplateSolutions,
  applySolutionSettings,
  inspectTemplateVariantDirectory,
  validateTemplateVariantDirectory,
  validateCatalogShape,
  normalizeCatalogFamilies,
  effectivePreviewFields,
  validateResponsivePreviews,
  isSpaTemplate,
  isCreateWebsiteApiTemplate,
  zipFileNames,
  assertValidSha,
};