A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
EDM (enhanced data-model) site support in ALM discovery (#192)
T-Nid8e8df683ddc0
diff --git a/plugins/power-pages/.claude-plugin/plugin.json b/plugins/power-pages/.claude-plugin/plugin.jsonindex 3021445a0..25996f2b7 100644--- a/plugins/power-pages/.claude-plugin/plugin.json+++ b/plugins/power-pages/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "power-pages",- "version": "2.2.0",+ "version": "2.3.0","description": "Create and deploy Power Pages sites using modern development approaches. Supports code sites (SPAs) with React, Angular, Vue, or Astro. Includes ALM orchestration (plan-alm) with a solution-splitting decision tree, per-solution pipelines, Azure Blob asset advisory, manifest schema v2 for multi-solution deployments, and force-link remediation for cross-host pipeline migrations.","author": {"name": "Microsoft",diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.mdindex 1772137c8..899cfad71 100644--- a/plugins/power-pages/AGENTS.md+++ b/plugins/power-pages/AGENTS.md@@ -186,7 +186,7 @@ Shared utility scripts live at `scripts/` and are referenced by multiple skills- `generate-uuid.js`: Generates a random UUID v4. Self-contained, no dependencies. Used by `create-webroles` and the main agent when creating table permission / site setting files from the `webapi-permissions` agent plan.- `update-skill-tracking.js`: Updates skill usage tracking site settings. Takes `--projectRoot`, `--skillName`, and `--authoringTool` args. The agent passes its own name as `--authoringTool` (e.g., `ClaudeCode`, `GitHubCopilot`). Creates/increments a per-skill counter (`Site-AI-<SkillName>.sitesetting.yml`) and records the authoring tool (`Site-AI-AuthoringTool.sitesetting.yml`). Exits silently if `.powerpages-site/site-settings/` does not exist. Used by every user-invocable skill (each skill calls it in its final phase per the skill-tracking convention).-- `check-activation-status.js`: Checks whether a Power Pages site is already activated (provisioned) in the environment. Takes `--projectRoot` arg. Reads `siteName` from `powerpages.config.json`, looks up `websiteRecordId` via `pac pages list`, queries the Power Platform GET websites API, and matches by both `websiteRecordId` and `name`. Outputs JSON: `{ activated: true/false, siteName, websiteRecordId, websiteUrl }` or `{ error }`. Used by `deploy-site` and `activate-site`.+- `check-activation-status.js`: Checks whether a Power Pages site is already activated (provisioned) in the environment. Takes `--projectRoot` arg. **Site-identity resolution (`resolveSiteIdentity()`, exported + injectable for tests): (1) `powerpages.config.json` (code/SPA sites) → `siteName` + optional `websiteRecordId`; (2) else `.powerpages-site/website.yml` (declarative/data-model sites) → `name`→`siteName`, `id`→`websiteRecordId`; (3) `pac pages list` ONLY when the GUID is still unknown** — declarative sites (and code sites whose config included the GUID) skip the `pac pages list` exec entirely. Then queries the Power Platform GET websites API and matches by both `websiteRecordId` and `name`. Outputs JSON: `{ activated: true/false, siteName, websiteRecordId, websiteUrl }` or `{ error }`. The CLI flow is guarded by `require.main === module`; `module.exports = { resolveSiteIdentity, getWebsites }`. Used by `deploy-site` and `activate-site`.- `poll-async-operation.js`: Polls a Dataverse `asyncoperations` record until it reaches a terminal state (Succeeded/Failed/Canceled) or times out. Args: `--asyncJobId`, `--envUrl`, `--token` (optional, refreshed via Azure CLI if omitted), `--intervalMs` (default 5000), `--maxAttempts` (default 60). Outputs JSON status. Used by `export-solution` and `import-solution`.- `encode-solution-file.js`: Base64-encodes a solution zip file for use in Dataverse OData request bodies (`ImportSolutionAsync`, `StageSolution`). Args: `--zipPath`. Outputs `{ encoded, fileSizeBytes, fileName }`. Used by `import-solution`.- `parse-deployment-errors.js`: Parses PAC CLI stderr output or OData error JSON into structured findings array. Each finding has `{ patternId, type, severity, message, rawMatch, autoFixAvailable, suggestedFix }`. Reads from `--input`, `--file`, or stdin. Used by `diagnose-deployment`.@@ -196,7 +196,7 @@ Shared lib modules live at `scripts/lib/` and are imported by other scripts via#### ALM Prerequisites & Context- `scripts/lib/verify-alm-prerequisites.js`: Verifies all prerequisites for ALM skills — PAC CLI installed + authenticated (`pac env who`), Azure CLI installed + logged in, Dataverse API reachable (`WhoAmI`). Args: `--envUrl` (opt, overrides env from PAC CLI), `--require-manifest` (fails if `.solution-manifest.json` not found). Output: `{ envUrl, token, userId, organizationId, tenantId }`. Exit 0 on success, exit 1 on any failure. Used by `setup-solution`, `export-solution`, `import-solution`, `setup-pipeline`, `deploy-pipeline`, `plan-alm`.-- `scripts/lib/detect-project-context.js`: Reads Power Pages project context files from the project root — `powerpages.config.json`, `.solution-manifest.json`, and `.datamodel-manifest.json`. Args: `--projectRoot` (opt, auto-discovered from cwd if omitted). Output: `{ projectRoot, siteName, websiteRecordId, environmentUrl, solutionManifest, datamodelManifest }`. Exit 0 on success, exit 1 if `powerpages.config.json` not found.+- `scripts/lib/detect-project-context.js`: Reads Power Pages project context from the project root. The `siteType` discriminator is the **build axis** — code/SPA vs declarative (design-studio) site — NOT the Dataverse data-model axis (a declarative site can be on the standard OR enhanced data model; both download to a `.powerpages-site/` tree). `siteType: "data-model"` is the (compat-named) declarative bucket; a future pass may rename it `"declarative"`. Resolves identity in order: (1) `powerpages.config.json` → `siteType: "code"` (code/SPA sites); (2) `.powerpages-site/` → `siteType: "data-model"` (declarative design-studio sites — standard or enhanced data model — which have **no** `powerpages.config.json`). The **authoritative declarative marker is the `.powerpages-site/.portalconfig/` directory** (only declarative sites have it); `website.yml` is the identity source (`id`→`websiteRecordId`, `name`→`siteName`) but is NOT a reliable declarative signal alone because **both** site types carry it. `environmentUrl: null` for declarative sites (no env URL in the local files — callers re-confirm via `pac env who`). Also reads `.solution-manifest.json` and `.datamodel-manifest.json`. Args: `--projectRoot` (opt). Output: `{ projectRoot, siteType, siteName, websiteRecordId, environmentUrl, solutionManifest, datamodelManifest }`. Exit 0 on success, exit 1 only if neither `powerpages.config.json` nor a `.powerpages-site/` (`.portalconfig/`/`website.yml`) marker is found. Note: `findProjectRoot` (in `validation-helpers.js`) likewise treats a `.powerpages-site/` directory as a project-root marker.- `scripts/lib/alm-paths.js`: Single source of truth for ALM artifact paths. Exports `ALM_DIR` (always `docs/alm`), `FILE_NAMES` (frozen object mapping logical key → filename for all 14 ALM artifacts), `almDir(projectRoot) → path`, `almPath(projectRoot, key) → path`, `ensureAlmDir(projectRoot) → path` (mkdir -p idempotent). Every ALM-only state file (5 plan/decision JSONs + 9 `last-*.json` skill-run markers including `last-export.json`) writes under `<projectRoot>/docs/alm/`. **Always resolve through this helper** — never inline a raw `docs/alm/...` path in a script. Files intentionally NOT moved here (and not in `FILE_NAMES`): `.solution-manifest.json`, `.datamodel-manifest.json`, `.alm-config.json`, `.alm-deferred`, `deployment-settings.json`. Adding a new ALM marker means adding its key + filename to `FILE_NAMES` first; `almPath` throws on unknown keys to catch typos at call-site.- `scripts/lib/check-alm-plan.js`: Phase 0 gate helper used by every ALM skill to detect (a) whether an ALM plan exists for this project, (b) whether the user has explicitly deferred ALM via the `.alm-deferred` marker, and (c) whether an existing plan is stale (the source solution was modified after the plan was generated). Args: `--projectRoot`, `--envUrl` (opt — required for staleness check), `--token` (opt), `--solutionId` (opt — required for staleness check). Output: `{ exists, deferred, deferral, planPath, htmlPath, stale, staleness: { reason, detail }, generatedAt, planStatus, solution: {...} }`. Without env/solution context the helper does an existence-only check; with them it queries Dataverse for `solutions(solutionId)?$select=modifiedon` and compares against `planData.generatedAt`. Used by `setup-solution`, `setup-pipeline`, `deploy-pipeline`, `export-solution`, `import-solution`, `configure-env-variables`, `ensure-pipelines-host`, `force-link-environment` Phase 0 gates — the "fail closed when no plan" pattern.- `scripts/lib/resolve-target-solution.js`: Resolves "which solution should this new Dataverse record land in?" Implements the strict 3-step order from the ALM-aware-by-default principle: (1) explicit `--solutionUniqueName` (or equivalent caller arg) wins; (2) `.solution-manifest.json` in the project root; (3) neither → throw `NoSolutionConfiguredError`. **The module NEVER auto-picks from Dataverse** — interactive prompt UX is the caller's responsibility (catch the error, present an `AskUserQuestion` list, re-invoke with `explicit` populated). Callers that need to confirm the solution still exists in Dataverse can pass `verifyExists: true`; the module then enriches the result with `{ solutionId, version, ismanaged }`. Component-creation scripts must require this helper and pass through `--solutionUniqueName` so records land in the user's solution instead of `Default`.diff --git a/plugins/power-pages/scripts/check-activation-status.js b/plugins/power-pages/scripts/check-activation-status.jsindex f49537186..1b3b2962c 100644--- a/plugins/power-pages/scripts/check-activation-status.js+++ b/plugins/power-pages/scripts/check-activation-status.js@@ -16,74 +16,141 @@ const fs = require('fs');const path = require('path');const { execSync } = require('child_process');const { findPath, getPacAuthInfo, getAuthToken, makeRequest, CLOUD_TO_API } = require('./lib/validation-helpers');+const { readWebsiteYml } = require('./lib/detect-project-context');function output(obj) {process.stdout.write(JSON.stringify(obj));process.exit(0);}-// --- Parse --projectRoot argument ----const args = process.argv.slice(2);-const rootIdx = args.indexOf('--projectRoot');-const projectRoot = rootIdx !== -1 ? args[rootIdx + 1] : process.cwd();+// Resolve site identity (siteName + websiteRecordId) from the project root.+//+// Resolution order:+// 1. powerpages.config.json (code/SPA sites) — siteName + (optional) websiteRecordId.+// 2. .powerpages-site/website.yml (declarative "data-model" sites — standard or+// enhanced data model — which have no powerpages.config.json) — `name` -> siteName,+// `id` -> websiteRecordId.+// 3. `pac pages list` — ONLY when the GUID is still unknown (e.g. a code site whose+// config omitted websiteRecordId). Declarative sites already have it from+// website.yml, so they skip this exec entirely (`usedPacList` reports whether it ran).+//+// Returns `{ siteName, websiteRecordId, source, usedPacList }` on success, or+// `{ error }` when no site identity can be resolved. Dependencies are injectable so+// the resolution (incl. the skip-exec optimization) is unit-testable without PAC CLI.+function resolveSiteIdentity(projectRoot, deps = {}) {+ const _findPath = deps.findPath || findPath;+ const _readWebsiteYml = deps.readWebsiteYml || readWebsiteYml;+ const _execSync = deps.execSync || execSync;+ const _readFileSync = deps.readFileSync || fs.readFileSync;-// --- Read siteName from powerpages.config.json ----const configPath = findPath(projectRoot, 'powerpages.config.json');-if (!configPath) {- output({ error: 'powerpages.config.json not found' });-}+ let siteName = null;+ let websiteRecordId = null;+ let source = null;-let siteName;-try {- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));- siteName = config.siteName;-} catch {- output({ error: 'Failed to parse powerpages.config.json' });-}-if (!siteName) {- output({ error: 'siteName not found in powerpages.config.json' });-}+ const configPath = _findPath(projectRoot, 'powerpages.config.json');+ if (configPath) {+ try {+ const config = JSON.parse(_readFileSync(configPath, 'utf8'));+ siteName = config.siteName;+ websiteRecordId = config.websiteRecordId || null;+ source = 'config';+ } catch {+ return { error: 'Failed to parse powerpages.config.json' };+ }+ } else {+ const websiteYmlPath = _findPath(projectRoot, path.join('.powerpages-site', 'website.yml'));+ const site = websiteYmlPath ? _readWebsiteYml(websiteYmlPath) : null;+ if (site) {+ siteName = site.name;+ websiteRecordId = site.id || null;+ source = 'website.yml';+ }+ }++ if (!siteName) {+ return { error: 'Site name not found — looked in powerpages.config.json and .powerpages-site/website.yml' };+ }-// --- Get websiteRecordId from pac pages list ----let websiteRecordId = null;-try {- const pacOutput = execSync('pac pages list', { encoding: 'utf8', timeout: 15000 });- // pac pages list outputs a table with columns. Find the row matching siteName.- // Column headers vary but Website Record ID is always a GUID column.- const lines = pacOutput.split(/\r?\n/).filter((l) => l.trim());- for (const line of lines) {- // Skip header/separator lines- if (line.includes('----') || line.toLowerCase().includes('website name')) continue;- // Check if this line contains our site name (case-insensitive)- if (line.toLowerCase().includes(siteName.toLowerCase())) {- // Extract GUID from the line- const guidMatch = line.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);- if (guidMatch) {- websiteRecordId = guidMatch[0];+ // Only hit `pac pages list` when the GUID isn't already known. Declarative sites (and code+ // sites whose config included websiteRecordId) skip this entirely.+ let usedPacList = false;+ if (!websiteRecordId) {+ usedPacList = true;+ try {+ const pacOutput = _execSync('pac pages list', { encoding: 'utf8', timeout: 15000 });+ // pac pages list outputs a table with columns. Find the row matching siteName.+ // Column headers vary but Website Record ID is always a GUID column.+ const lines = pacOutput.split(/\r?\n/).filter((l) => l.trim());+ for (const line of lines) {+ // Skip header/separator lines+ if (line.includes('----') || line.toLowerCase().includes('website name')) continue;+ // Check if this line contains our site name (case-insensitive)+ if (line.toLowerCase().includes(siteName.toLowerCase())) {+ // Extract GUID from the line+ const guidMatch = line.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);+ if (guidMatch) {+ websiteRecordId = guidMatch[0];+ }+ break;+ }}- break;+ } catch {+ // pac pages list failed — continue without websiteRecordId}}-} catch {- // pac pages list failed — continue without websiteRecordId++ return { siteName, websiteRecordId, source, usedPacList };}-// --- Get PAC auth info ----const pacInfo = getPacAuthInfo();-if (!pacInfo) {- output({ error: 'PAC CLI not authenticated' });+async function getWebsites(ppApiBaseUrl, token, environmentId) {+ try {+ const result = await makeRequest({+ url: `${ppApiBaseUrl}/powerpages/environments/${environmentId}/websites?api-version=2022-03-01-preview`,+ headers: {+ Authorization: `Bearer ${token}`,+ Accept: 'application/json',+ },+ timeout: 15000,+ });+ if (result.error || result.statusCode !== 200) return null;+ const parsed = JSON.parse(result.body);+ const value = parsed.value;+ if (!value) return [];+ return Array.isArray(value) ? value : [value];+ } catch {+ return null;+ }}-const ppApiBaseUrl = CLOUD_TO_API[pacInfo.cloud] || CLOUD_TO_API['Public'];+async function main() {+ // --- Parse --projectRoot argument ---+ const args = process.argv.slice(2);+ const rootIdx = args.indexOf('--projectRoot');+ const projectRoot = rootIdx !== -1 ? args[rootIdx + 1] : process.cwd();-// --- Get Azure CLI token ----const token = getAuthToken(ppApiBaseUrl);-if (!token) {- output({ error: 'Azure CLI token not available' });-}+ // --- Resolve site identity (config -> website.yml -> pac pages list) ---+ const identity = resolveSiteIdentity(projectRoot);+ if (identity.error) {+ output({ error: identity.error });+ }+ const { siteName } = identity;+ let { websiteRecordId } = identity;++ // --- Get PAC auth info ---+ const pacInfo = getPacAuthInfo();+ if (!pacInfo) {+ output({ error: 'PAC CLI not authenticated' });+ }++ const ppApiBaseUrl = CLOUD_TO_API[pacInfo.cloud] || CLOUD_TO_API['Public'];++ // --- Get Azure CLI token ---+ const token = getAuthToken(ppApiBaseUrl);+ if (!token) {+ output({ error: 'Azure CLI token not available' });+ }-// --- Query websites API ----(async () => {+ // --- Query websites API ---const websites = await getWebsites(ppApiBaseUrl, token, pacInfo.environmentId);if (websites === null) {output({ error: 'Websites API call failed' });@@ -114,24 +181,10 @@ if (!token) {websiteRecordId,});}-})();+}-async function getWebsites(ppApiBaseUrl, token, environmentId) {- try {- const result = await makeRequest({- url: `${ppApiBaseUrl}/powerpages/environments/${environmentId}/websites?api-version=2022-03-01-preview`,- headers: {- Authorization: `Bearer ${token}`,- Accept: 'application/json',- },- timeout: 15000,- });- if (result.error || result.statusCode !== 200) return null;- const parsed = JSON.parse(result.body);- const value = parsed.value;- if (!value) return [];- return Array.isArray(value) ? value : [value];- } catch {- return null;- }+if (require.main === module) {+ main();}++module.exports = { resolveSiteIdentity, getWebsites };diff --git a/plugins/power-pages/scripts/lib/detect-project-context.js b/plugins/power-pages/scripts/lib/detect-project-context.jsindex 2d74329fb..6c4174f41 100644--- a/plugins/power-pages/scripts/lib/detect-project-context.js+++ b/plugins/power-pages/scripts/lib/detect-project-context.js@@ -1,7 +1,27 @@#!/usr/bin/env node// Reads Power Pages project context files from the project root.-// Locates powerpages.config.json, .solution-manifest.json, and .datamodel-manifest.json.+// Locates powerpages.config.json (code/SPA sites) OR a .powerpages-site/ config tree+// (declarative "data-model" sites — Power Pages design-studio sites), plus+// .solution-manifest.json and .datamodel-manifest.json.+//+// NOTE on terminology: the discriminator here is the BUILD axis — code/SPA site vs+// declarative (design-studio) site — NOT the Dataverse data-model axis. A declarative+// site can be on the standard OR the enhanced data model ("EDM"); both download to a+// .powerpages-site/ tree via `pac pages download`. siteType "data-model" names that+// declarative bucket (kept for compatibility with plan-alm); a future pass may rename+// it to "declarative".+//+// Site identity resolution order (first match wins):+// 1. powerpages.config.json -> siteType "code" (code/SPA sites; has siteName,+// websiteRecordId, environmentUrl)+// 2. .powerpages-site/ (.portalconfig/ + website.yml) -> siteType "data-model"+// (declarative design-studio sites; standard or+// enhanced data model. website.yml carries `id` and+// `name` but no environment URL — callers re-confirm+// via `pac env who`. `.portalconfig/` is the positive+// declarative marker; BOTH site types carry website.yml,+// so it isn't a reliable "declarative" signal alone.)//// Usage: node detect-project-context.js [--projectRoot <path>]//@@ -11,14 +31,16 @@// Output (JSON to stdout):// {// "projectRoot": "...",+// "siteType": "code" | "data-model",// "siteName": "...",// "websiteRecordId": "...",-// "environmentUrl": "...",+// "environmentUrl": "..." | null,// "solutionManifest": { ... } | null,// "datamodelManifest": { ... } | null// }//-// Exit 0 on success, exit 1 if powerpages.config.json not found.+// Exit 0 on success, exit 1 if neither powerpages.config.json nor+// .powerpages-site/website.yml is found (not a Power Pages project).'use strict';@@ -45,6 +67,50 @@ function readJsonFile(filePath) {}}+// Minimal reader for the flat `.powerpages-site/website.yml` (a simple `key: value`+// per line — no nesting). Returns { id, name } or null. Zero-dependency by design+// (the plugin ships no YAML library); only the two identity keys are needed here.+function readWebsiteYml(filePath) {+ let raw;+ try {+ raw = fs.readFileSync(filePath, 'utf8');+ } catch {+ return null;+ }+ const out = {};+ for (const line of raw.split(/\r?\n/)) {+ const m = /^([A-Za-z0-9_]+):\s*(.*)$/.exec(line);+ if (!m) continue;+ const key = m[1];+ let value = m[2].trim();+ // Strip an inline YAML comment ( ` #...` preceded by whitespace) on UNQUOTED+ // values — `id: abc # note` -> `abc`. A `#` inside quotes, or with no leading+ // space, is left intact. (pac-downloaded website.yml is flat + uncommented, so+ // this is defensive — but cheap, and stops a stray comment from corrupting the+ // site identity.)+ const looksQuoted = (value.startsWith('"') && value.endsWith('"')) ||+ (value.startsWith("'") && value.endsWith("'"));+ if (!looksQuoted) {+ value = value.replace(/\s+#.*$/, '').trim();+ }+ // Strip surrounding quotes a YAML writer may add.+ if ((value.startsWith('"') && value.endsWith('"')) ||+ (value.startsWith("'") && value.endsWith("'"))) {+ value = value.slice(1, -1);+ }+ if (key === 'id' || key === 'name') out[key] = value;+ }+ return (out.id || out.name) ? out : null;+}++function isDirectory(p) {+ try {+ return fs.statSync(p).isDirectory();+ } catch {+ return false;+ }+}+function detectProjectContext(options = {}) {const startDir = options.projectRoot || process.cwd();const projectRoot = options.projectRoot@@ -53,31 +119,67 @@ function detectProjectContext(options = {}) {if (!projectRoot) {throw new Error(- 'powerpages.config.json not found. Run this command from a Power Pages project directory.'+ 'No Power Pages project found. Run this command from a site project directory ' ++ '(one containing powerpages.config.json for a code site, or .powerpages-site/ ' ++ 'for a data-model site).');}+ const solutionManifest = readJsonFile(path.join(projectRoot, '.solution-manifest.json'));+ const datamodelManifest = readJsonFile(path.join(projectRoot, '.datamodel-manifest.json'));++ // 1. Code/SPA site — powerpages.config.json is the source of truth.const configPath = path.join(projectRoot, 'powerpages.config.json');- if (!fs.existsSync(configPath)) {- throw new Error(`powerpages.config.json not found at: ${configPath}`);+ if (fs.existsSync(configPath)) {+ const config = readJsonFile(configPath);+ if (!config) {+ throw new Error(`Failed to parse powerpages.config.json at: ${configPath}`);+ }+ return {+ projectRoot,+ siteType: 'code',+ siteName: config.siteName || null,+ websiteRecordId: config.websiteRecordId || null,+ environmentUrl: config.environmentUrl || null,+ solutionManifest,+ datamodelManifest,+ };}- const config = readJsonFile(configPath);- if (!config) {- throw new Error(`Failed to parse powerpages.config.json at: ${configPath}`);+ // 2. Declarative ("data-model") site — a Power Pages design-studio site+ // (`pac pages download`; standard or enhanced data model), as opposed to a+ // code/SPA site. The authoritative positive marker is the+ // `.powerpages-site/.portalconfig/` directory (only declarative sites have it).+ // Identity (`id` -> websiteRecordId, `name` -> siteName) is read from website.yml —+ // but BOTH site types carry website.yml, so it's an identity source, not proof of+ // "declarative" on its own (a `.portalconfig/` site with no website.yml is still+ // declarative; its identity resolves at runtime). No environment URL in the local+ // files — callers re-confirm via `pac env who`.+ const portalConfigDir = path.join(projectRoot, '.powerpages-site', '.portalconfig');+ const websiteYmlPath = path.join(projectRoot, '.powerpages-site', 'website.yml');+ if (isDirectory(portalConfigDir) || fs.existsSync(websiteYmlPath)) {+ let site = null;+ if (fs.existsSync(websiteYmlPath)) {+ site = readWebsiteYml(websiteYmlPath);+ if (!site) {+ throw new Error(`Could not read site id/name from: ${websiteYmlPath}`);+ }+ }+ return {+ projectRoot,+ siteType: 'data-model',+ siteName: site ? (site.name || null) : null,+ websiteRecordId: site ? (site.id || null) : null,+ environmentUrl: null,+ solutionManifest,+ datamodelManifest,+ };}- const solutionManifest = readJsonFile(path.join(projectRoot, '.solution-manifest.json'));- const datamodelManifest = readJsonFile(path.join(projectRoot, '.datamodel-manifest.json'));-- return {- projectRoot,- siteName: config.siteName || null,- websiteRecordId: config.websiteRecordId || null,- environmentUrl: config.environmentUrl || null,- solutionManifest,- datamodelManifest,- };+ throw new Error(+ `No site identity found at ${projectRoot}: neither powerpages.config.json nor ` ++ '.powerpages-site/website.yml is present.'+ );}// CLI entry point@@ -94,4 +196,4 @@ if (require.main === module) {}}-module.exports = { detectProjectContext };+module.exports = { detectProjectContext, readWebsiteYml };diff --git a/plugins/power-pages/scripts/lib/validation-helpers.js b/plugins/power-pages/scripts/lib/validation-helpers.jsindex c36d89e81..28037792e 100644--- a/plugins/power-pages/scripts/lib/validation-helpers.js+++ b/plugins/power-pages/scripts/lib/validation-helpers.js@@ -89,14 +89,24 @@ function findPath(dir, target) {}/**- * Finds the project root directory (containing powerpages.config.json).+ * Finds the project root directory of a Power Pages site.+ *+ * A project root is marked by EITHER:+ * - `powerpages.config.json` — code/SPA sites (`pac pages download-code-site`), OR+ * - a `.powerpages-site/` directory — declarative ("data-model") design-studio sites+ * (`pac pages download`; standard or enhanced data model). These have NO+ * `powerpages.config.json`.+ *+ * Code sites have both markers; declarative sites have only+ * `.powerpages-site/`. Checking for either makes root discovery work for both site types.+ ** @returns {string|null} Project root path, or null*/function findProjectRoot(dir) {let current = path.resolve(dir);while (true) {- const configPath = path.join(current, 'powerpages.config.json');- if (fs.existsSync(configPath)) {+ if (fs.existsSync(path.join(current, 'powerpages.config.json')) ||+ fs.existsSync(path.join(current, '.powerpages-site'))) {return current;}@@ -107,8 +117,11 @@ function findProjectRoot(dir) {current = parent;}+ // Fallback: search subdirectories for either marker (config first, then .powerpages-site/).const fallbackConfigPath = findPath(dir, 'powerpages.config.json');- return fallbackConfigPath ? path.dirname(fallbackConfigPath) : null;+ if (fallbackConfigPath) return path.dirname(fallbackConfigPath);+ const fallbackSiteDir = findPath(dir, '.powerpages-site');+ return fallbackSiteDir ? path.dirname(fallbackSiteDir) : null;}/**diff --git a/plugins/power-pages/scripts/tests/check-activation-status.test.js b/plugins/power-pages/scripts/tests/check-activation-status.test.jsnew file mode 100644index 000000000..56a529d1e--- /dev/null+++ b/plugins/power-pages/scripts/tests/check-activation-status.test.js@@ -0,0 +1,90 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const os = require('os');+const path = require('path');++const { resolveSiteIdentity } = require('../check-activation-status');++function tempDir() {+ return fs.mkdtempSync(path.join(os.tmpdir(), 'check-activation-test-'));+}+const GUID = '11111111-2222-3333-4444-555555555555';+// Fails the test if invoked — used to assert pac pages list is NOT shelled out.+const throwExec = () => { throw new Error('pac pages list must NOT be called'); };++test('EDM site: resolves identity from .powerpages-site/website.yml and SKIPS pac pages list', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.mkdirSync(path.join(dir, '.powerpages-site'), { recursive: true });+ fs.writeFileSync(path.join(dir, '.powerpages-site', 'website.yml'), `id: ${GUID}\nname: ContosoEDM\n`);++ const r = resolveSiteIdentity(dir, { execSync: throwExec });+ assert.equal(r.error, undefined);+ assert.equal(r.siteName, 'ContosoEDM');+ assert.equal(r.websiteRecordId, GUID);+ assert.equal(r.source, 'website.yml');+ assert.equal(r.usedPacList, false, 'EDM site must NOT shell out to pac pages list');+});++test('EDM website.yml with an inline comment is parsed cleanly (comment stripped)', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.mkdirSync(path.join(dir, '.powerpages-site'), { recursive: true });+ fs.writeFileSync(path.join(dir, '.powerpages-site', 'website.yml'), `id: ${GUID} # site guid\nname: ContosoEDM\n`);++ const r = resolveSiteIdentity(dir, { execSync: throwExec });+ assert.equal(r.websiteRecordId, GUID, 'inline comment must not corrupt the GUID');+});++test('code site with websiteRecordId in config: resolves from config, skips pac pages list', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(dir, 'powerpages.config.json'), JSON.stringify({ siteName: 'ContosoSPA', websiteRecordId: GUID }));++ const r = resolveSiteIdentity(dir, { execSync: throwExec });+ assert.equal(r.siteName, 'ContosoSPA');+ assert.equal(r.websiteRecordId, GUID);+ assert.equal(r.source, 'config');+ assert.equal(r.usedPacList, false);+});++test('code site WITHOUT websiteRecordId: falls back to pac pages list to find the GUID', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(dir, 'powerpages.config.json'), JSON.stringify({ siteName: 'ContosoSPA' }));++ const fakePac = () => `Website Name Website Record ID\n---------- ----------\nContosoSPA ${GUID}\n`;+ const r = resolveSiteIdentity(dir, { execSync: fakePac });+ assert.equal(r.siteName, 'ContosoSPA');+ assert.equal(r.websiteRecordId, GUID);+ assert.equal(r.usedPacList, true, 'code site without a GUID must consult pac pages list');+});++test('neither marker present: returns a "Site name not found" error (no crash)', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const r = resolveSiteIdentity(dir, { execSync: throwExec });+ assert.match(r.error, /Site name not found/);+ assert.match(r.error, /website\.yml/);+});++test('malformed powerpages.config.json: returns a parse error (does not throw)', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(dir, 'powerpages.config.json'), '{not valid json,,,');+ const r = resolveSiteIdentity(dir, { execSync: throwExec });+ assert.match(r.error, /Failed to parse/);+});++test('pac pages list failure is non-fatal: identity returns with null websiteRecordId', (t) => {+ const dir = tempDir();+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ fs.writeFileSync(path.join(dir, 'powerpages.config.json'), JSON.stringify({ siteName: 'ContosoSPA' }));+ const r = resolveSiteIdentity(dir, { execSync: () => { throw new Error('pac not installed'); } });+ assert.equal(r.siteName, 'ContosoSPA');+ assert.equal(r.websiteRecordId, null);+ assert.equal(r.usedPacList, true);+});diff --git a/plugins/power-pages/scripts/tests/detect-project-context.test.js b/plugins/power-pages/scripts/tests/detect-project-context.test.jsindex be5279751..2a682cb36 100644--- a/plugins/power-pages/scripts/tests/detect-project-context.test.js+++ b/plugins/power-pages/scripts/tests/detect-project-context.test.js@@ -4,19 +4,95 @@ const fs = require('fs');const os = require('os');const path = require('path');-const { detectProjectContext } = require('../lib/detect-project-context');+const { detectProjectContext, readWebsiteYml } = require('../lib/detect-project-context');const { createTempProject, writeProjectFile } = require('./test-utils');-test('detectProjectContext throws when powerpages.config.json is missing', (t) => {+test('detectProjectContext throws when neither config nor .powerpages-site/website.yml exists', (t) => {const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctx-test-'));t.after(() => fs.rmSync(dir, { recursive: true, force: true }));assert.throws(() => detectProjectContext({ projectRoot: dir }),- /powerpages.config.json not found/+ /neither powerpages\.config\.json nor/);});+test('detectProjectContext: code site (powerpages.config.json) reports siteType "code"', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', JSON.stringify({+ siteName: 'Code Site',+ websiteRecordId: 'aabbccdd-1234-5678-abcd-00000000000c',+ environmentUrl: 'https://org.crm.dynamics.com',+ }));++ const result = detectProjectContext({ projectRoot });+ assert.equal(result.siteType, 'code');+ assert.equal(result.siteName, 'Code Site');+});++test('detectProjectContext: declarative (data-model) site resolves identity from .powerpages-site/website.yml', (t) => {+ const projectRoot = createTempProject(t);+ // No powerpages.config.json — this is a declarative ("data-model") design-studio site.+ writeProjectFile(+ projectRoot,+ '.powerpages-site/website.yml',+ [+ 'defaultlanguage: 32cc32f6-8665-f111-a826-000d3a5a7777',+ 'id: 2ecc32f6-8665-f111-a826-000d3a5a7777',+ 'name: Application processing EDM site - permitapplication-elyyn',+ 'statecode: 0',+ '',+ ].join('\n')+ );++ const result = detectProjectContext({ projectRoot });+ assert.equal(result.siteType, 'data-model');+ assert.equal(result.websiteRecordId, '2ecc32f6-8665-f111-a826-000d3a5a7777');+ assert.equal(result.siteName, 'Application processing EDM site - permitapplication-elyyn');+ // Data-model sites carry no environment URL locally — callers re-confirm via `pac env who`.+ assert.equal(result.environmentUrl, null);+});++test('detectProjectContext: .powerpages-site/.portalconfig/ is the positive declarative signal (even without website.yml)', (t) => {+ const projectRoot = createTempProject(t);+ // A declarative site identified by its .portalconfig/ marker, with no website.yml+ // (rare, but .portalconfig is the authoritative signal — identity resolves at runtime).+ writeProjectFile(projectRoot, '.powerpages-site/.portalconfig/manifest.yml', 'foo: bar\n');++ const result = detectProjectContext({ projectRoot });+ assert.equal(result.siteType, 'data-model', '.portalconfig/ marks a declarative site');+ assert.equal(result.siteName, null);+ assert.equal(result.websiteRecordId, null);+ assert.equal(result.environmentUrl, null);+});++test('detectProjectContext: config site wins over website.yml when both exist (code-site precedence)', (t) => {+ const projectRoot = createTempProject(t);+ writeProjectFile(projectRoot, 'powerpages.config.json', JSON.stringify({+ siteName: 'Code Wins',+ websiteRecordId: 'config-guid',+ environmentUrl: 'https://org.crm.dynamics.com',+ }));+ writeProjectFile(projectRoot, '.powerpages-site/website.yml', 'id: yml-guid\nname: YAML Name\n');++ const result = detectProjectContext({ projectRoot });+ assert.equal(result.siteType, 'code');+ assert.equal(result.websiteRecordId, 'config-guid');+});++test('readWebsiteYml: extracts id + name, strips quotes, ignores other keys', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'yml-test-'));+ const p = path.join(dir, 'website.yml');+ fs.writeFileSync(p, 'id: "abc-123"\nname: \'Quoted Site\'\nstatecode: 0\n');+ try {+ const site = readWebsiteYml(p);+ assert.deepEqual(site, { id: 'abc-123', name: 'Quoted Site' });+ assert.equal(readWebsiteYml(path.join(dir, 'missing.yml')), null);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }+});+test('detectProjectContext returns siteName and websiteRecordId from config', (t) => {const projectRoot = createTempProject(t);writeProjectFile(projectRoot, 'powerpages.config.json', JSON.stringify({diff --git a/plugins/power-pages/scripts/tests/validation-helpers.test.js b/plugins/power-pages/scripts/tests/validation-helpers.test.jsindex 620e3a107..9b7e2dc87 100644--- a/plugins/power-pages/scripts/tests/validation-helpers.test.js+++ b/plugins/power-pages/scripts/tests/validation-helpers.test.js@@ -33,3 +33,43 @@ test('getAuthToken calls az account get-access-token without --allow-no-subscrip);assert.match(capturedCommand, /--resource "https:\/\/example\.crm\.dynamics\.com"/);});++// --- findProjectRoot: EDM / data-model site awareness ------------------------++test('findProjectRoot: recognizes a .powerpages-site/ directory as a project root (data-model/EDM sites)', (t) => {+ const fs = require('fs');+ const os = require('os');+ const { findProjectRoot } = require(helpersPath);++ // EDM/data-model site: .powerpages-site/ present, NO powerpages.config.json.+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fpr-edm-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.mkdirSync(path.join(root, '.powerpages-site'), { recursive: true });+ fs.writeFileSync(path.join(root, '.powerpages-site', 'website.yml'), 'id: x\nname: y\n');++ assert.equal(findProjectRoot(root), path.resolve(root));+});++test('findProjectRoot: still recognizes powerpages.config.json (code sites)', (t) => {+ const fs = require('fs');+ const os = require('os');+ const { findProjectRoot } = require(helpersPath);++ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fpr-code-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));+ fs.writeFileSync(path.join(root, 'powerpages.config.json'), '{}');++ assert.equal(findProjectRoot(root), path.resolve(root));+});++test('findProjectRoot: returns null when neither marker is present', (t) => {+ const fs = require('fs');+ const os = require('os');+ const { findProjectRoot } = require(helpersPath);++ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'fpr-none-'));+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));++ assert.equal(findProjectRoot(root), null);+});+