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.

[Pages] Fix skill frontmatter names and site activation (#18)

Priyanshu Agrawal8270d87814dd
diff --git a/README.md b/README.md
index 06ea6acaa..62c856a73 100644
--- a/README.md
+++ b/README.md
@@ -93,12 +93,6 @@ To develop and test plugins locally, follow these steps:
claude --plugin-dir /path/to/power-platform-skills/plugins/power-apps
```
-1. Launch Copilot with plugin path:
-
- ```bash
- copilot --plugin-dir /path/to/power-platform-skills/plugins/power-pages
- ```
-
## Running Without Interruption
Plugins in this repo may invoke multiple tools (file edits, shell commands, MCP servers) during a session, which can result in frequent approval prompts. Use the options below to reduce or eliminate these interruptions.
diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.md
index 794901885..a2abc4428 100644
--- a/plugins/power-pages/AGENTS.md
+++ b/plugins/power-pages/AGENTS.md
@@ -27,6 +27,7 @@ agents/
webapi-permissions.md ← Agent: proposes Web API permissions plan (read-only)
scripts/
generate-uuid.js ← Shared UUID v4 generator (used by multiple skills)
+ check-activation-status.js ← Checks if site is already activated (used by deploy-site, activate-site)
references/ ← Shared reference docs used by multiple skills
odata-common.md ← Auth headers, token refresh, error handling, retry patterns
dataverse-prerequisites.md ← PAC CLI check, Azure CLI token, API access verification
@@ -52,6 +53,7 @@ skills/
scripts/validate-seo.js ← Node script validating SEO assets (robots.txt, sitemap.xml, meta tags)
activate-site/
SKILL.md ← Site activation/provisioning skill definition
+ scripts/activate-site.js ← Activates a site via PP API + polls status
scripts/generate-subdomain.js ← Random subdomain suggestion generator
scripts/validate-activation.js ← Validates site was provisioned via PP API
create-webroles/
@@ -85,7 +87,7 @@ User-invocable via `/power-pages:<skill-name>`:
- `deploy-site`: 6-step workflow — verify PAC CLI, authenticate, confirm environment, upload via `pac pages upload-code-site`, verify deployment (confirm `.powerpages-site` folder, commit, offer activation), handle blocked JS attachments
- `setup-datamodel`: 7-step workflow — verify prerequisites, invoke data-model-architect agent, review proposal, pre-creation checks, create tables & columns via OData API, create relationships, publish & verify. Writes `.datamodel-manifest.json` for hook validation.
- `add-sample-data`: 6-step workflow — verify prerequisites, discover tables (from `.datamodel-manifest.json` or OData API), select tables & configure record count, generate & review sample data plan, insert records via OData API with relationship handling, verify & summarize.
-- `activate-site`: 6-step workflow — verify prerequisites (PAC CLI auth + Azure CLI token + cloud-aware API URL resolution), gather parameters (site name, subdomain, website record ID), confirm with user, POST to Power Platform websites API, poll provisioning status, present summary with site URL.
+- `activate-site`: 5-step workflow — verify prerequisites (PAC CLI auth + Azure CLI token + cloud-aware API URL resolution + activation status check via shared script), gather parameters (site name, subdomain, website record ID), confirm with user, activate & poll via `skills/activate-site/scripts/activate-site.js`, present summary with site URL.
- `add-seo`: 7-step workflow — verify site exists, gather SEO config (production URL, exclusions, meta description), plan & approve, create robots.txt, generate sitemap.xml from discovered routes, add meta tags (title, description, viewport, Open Graph, Twitter Card, favicon) to index.html, verify via Playwright & commit.
- `create-webroles`: 6-step workflow — verify `.powerpages-site/web-roles/` exists (redirect to deploy-site if missing), discover existing roles, determine new roles needed, create web role YAML files with UUIDs from shared `scripts/generate-uuid.js`, verify web roles (validate files, UUIDs, uniqueness constraints), review & prompt deployment via deploy-site skill.
- `integrate-webapi`: 7-step workflow — verify site exists, use Explore agent to analyze code and identify tables needing Web API integration, review plan with user, invoke `webapi-integration` agent per table to create API client/types/services/hooks, verify integrations (validate all files exist, project builds), invoke `webapi-permissions` agent to configure table permissions and site settings, review & deploy via `deploy-site` skill.
@@ -114,6 +116,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 all 9 skills.
+- `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`.
### Shared References
diff --git a/plugins/power-pages/scripts/check-activation-status.js b/plugins/power-pages/scripts/check-activation-status.js
new file mode 100644
index 000000000..f49537186
--- /dev/null
+++ b/plugins/power-pages/scripts/check-activation-status.js
@@ -0,0 +1,137 @@
+#!/usr/bin/env node
+
+// Checks whether a Power Pages site is already activated (provisioned) in the environment.
+// Used by deploy-site and activate-site skills to avoid unnecessary activation prompts
+// or redundant activation attempts.
+//
+// Usage:
+// node check-activation-status.js --projectRoot "<path>"
+//
+// Output (JSON to stdout):
+// { "activated": true, "siteName": "...", "websiteRecordId": "...", "websiteUrl": "..." }
+// { "activated": false, "siteName": "...", "websiteRecordId": "..." }
+// { "error": "..." } — when prerequisites are missing (PAC CLI, Azure CLI, config, etc.)
+
+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');
+
+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();
+
+// --- Read siteName from powerpages.config.json ---
+const configPath = findPath(projectRoot, 'powerpages.config.json');
+if (!configPath) {
+ output({ error: 'powerpages.config.json not found' });
+}
+
+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' });
+}
+
+// --- 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];
+ }
+ break;
+ }
+ }
+} catch {
+ // pac pages list failed — continue without websiteRecordId
+}
+
+// --- 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 () => {
+ const websites = await getWebsites(ppApiBaseUrl, token, pacInfo.environmentId);
+ if (websites === null) {
+ output({ error: 'Websites API call failed' });
+ }
+
+ // --- Match by websiteRecordId or siteName ---
+ const match = websites.find((w) => {
+ if (websiteRecordId && w.websiteRecordId && w.websiteRecordId.toLowerCase() === websiteRecordId.toLowerCase()) {
+ return true;
+ }
+ if (siteName && w.name && w.name.toLowerCase() === siteName.toLowerCase()) {
+ return true;
+ }
+ return false;
+ });
+
+ if (match) {
+ output({
+ activated: true,
+ siteName: match.name || siteName,
+ websiteRecordId: match.websiteRecordId || websiteRecordId,
+ websiteUrl: match.websiteUrl || null,
+ });
+ } else {
+ output({
+ activated: false,
+ siteName,
+ 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;
+ }
+}
diff --git a/plugins/power-pages/scripts/lib/validation-helpers.js b/plugins/power-pages/scripts/lib/validation-helpers.js
index 0e0a3717b..a4501b327 100644
--- a/plugins/power-pages/scripts/lib/validation-helpers.js
+++ b/plugins/power-pages/scripts/lib/validation-helpers.js
@@ -22,12 +22,12 @@ const block = (reason) => {
function runValidation(callback) {
let inputData = '';
process.stdin.on('data', chunk => (inputData += chunk));
- process.stdin.on('end', () => {
+ process.stdin.on('end', async () => {
try {
const input = JSON.parse(inputData);
const cwd = input.cwd;
if (!cwd) approve();
- callback(cwd);
+ await callback(cwd);
} catch {
approve();
}
@@ -126,6 +126,53 @@ function getPacAuthInfo() {
}
}
+/**
+ * Makes an HTTP/HTTPS request using Node.js built-in modules (cross-platform, no PowerShell).
+ * Returns a Promise — callers must use `await`.
+ * @param {object} options
+ * @param {string} options.url - Full URL to request
+ * @param {string} [options.method='GET'] - HTTP method
+ * @param {object} [options.headers={}] - Request headers
+ * @param {string} [options.body=null] - Request body (string)
+ * @param {boolean} [options.includeHeaders=false] - Include response headers in result
+ * @param {number} [options.timeout=15000] - Timeout in ms
+ * @returns {Promise<{ statusCode: number, body: string, headers?: object } | { error: string }>}
+ */
+function makeRequest({ url, method = 'GET', headers = {}, body = null, includeHeaders = false, timeout = 15000 }) {
+ return new Promise((resolve) => {
+ const https = require('https');
+ const http = require('http');
+ const u = new URL(url);
+ const mod = u.protocol === 'https:' ? https : http;
+ const req = mod.request(
+ {
+ method,
+ headers,
+ hostname: u.hostname,
+ port: u.port || undefined,
+ path: u.pathname + u.search,
+ timeout,
+ },
+ (res) => {
+ let data = '';
+ res.on('data', (chunk) => (data += chunk));
+ res.on('end', () => {
+ const result = { statusCode: res.statusCode, body: data };
+ if (includeHeaders) result.headers = res.headers;
+ resolve(result);
+ });
+ }
+ );
+ req.on('error', (e) => resolve({ error: e.message }));
+ req.on('timeout', () => {
+ req.destroy();
+ resolve({ error: 'Request timed out' });
+ });
+ if (body) req.write(body);
+ req.end();
+ });
+}
+
/** Cloud → Power Platform API base URL mapping */
const CLOUD_TO_API = {
'Public': 'https://api.powerplatform.com',
@@ -135,6 +182,15 @@ const CLOUD_TO_API = {
'China': 'https://api.powerplatform.partner.microsoftonline.cn',
};
+/** Cloud → Power Pages site URL domain mapping */
+const CLOUD_TO_SITE_DOMAIN = {
+ 'Public': 'powerappsportals.com',
+ 'UsGov': 'powerappsportals.us',
+ 'UsGovHigh': 'high.powerappsportals.us',
+ 'UsGovDod': 'appsplatform.us',
+ 'China': 'powerappsportals.cn',
+};
+
module.exports = {
approve,
block,
@@ -144,7 +200,9 @@ module.exports = {
findPowerPagesSiteDir,
UUID_REGEX,
getAuthToken,
+ makeRequest,
getEnvironmentUrl,
getPacAuthInfo,
CLOUD_TO_API,
+ CLOUD_TO_SITE_DOMAIN,
};
diff --git a/plugins/power-pages/skills/activate-site/SKILL.md b/plugins/power-pages/skills/activate-site/SKILL.md
index caad8e20e..654d51276 100644
--- a/plugins/power-pages/skills/activate-site/SKILL.md
+++ b/plugins/power-pages/skills/activate-site/SKILL.md
@@ -1,5 +1,5 @@
---
-name: activate-power-pages-site
+name: activate-site
description: >
This skill should be used when the user asks to "activate site",
"provision website", "activate a Power Pages website", "activate portal",
@@ -18,7 +18,7 @@ hooks:
- type: prompt
prompt: >
If a Power Pages website was being activated in this session (via /power-pages:activate-site),
- verify before allowing stop: 1) Prerequisites were verified (PAC CLI auth + Azure CLI token),
+ verify before allowing stop: 1) Prerequisites were verified (PAC CLI auth + Azure CLI login),
2) Site name was read from config or user input, 3) The subdomain generator script was run AND the user was asked (via AskUserQuestion) whether to use the generated subdomain or enter a custom one,
4) The user confirmed activation parameters, 5) The POST to the websites API was made,
6) Provisioning status was polled to completion, 7) A summary with the site URL was presented.
@@ -35,25 +35,24 @@ Provision a new Power Pages website in a Power Platform environment via the Powe
## Core Principles
- **Cloud-aware URL resolution** — Never hardcode API base URLs or site URL domains. Always derive them from the Cloud value returned by `pac auth who`.
-- **Token freshness** — Azure CLI tokens expire quickly. Re-acquire before any API call that follows a user interaction or polling delay.
+- **Token handling** — Scripts acquire and refresh Azure CLI tokens internally. The agent only needs to verify the user is logged in to Azure CLI.
- **Confirm before mutating** — Always present the full activation parameters to the user and get explicit approval before POSTing to the websites API.
**Initial request:** $ARGUMENTS
## Workflow
-1. **Phase 1: Verify Prerequisites** — PAC CLI auth + Azure CLI token for the Power Platform API
+1. **Phase 1: Verify Prerequisites** — PAC CLI auth + Azure CLI login + activation status check
2. **Phase 2: Gather Parameters** — Site name, subdomain, website record ID
3. **Phase 3: Confirm** — Present all parameters to user for approval
-4. **Phase 4: Activate** — POST to the Power Platform websites API
-5. **Phase 5: Poll Status** — Poll provisioning status until completion
-6. **Phase 6: Present Summary** — Show site URL, suggest next steps
+4. **Phase 4: Activate & Poll** — Run activation script (POST + poll provisioning status)
+5. **Phase 5: Present Summary** — Show site URL, suggest next steps
---
## Phase 1: Verify Prerequisites
-**Goal:** Ensure PAC CLI is installed and authenticated, resolve the correct Power Platform API base URL for the user's cloud, and acquire a valid Azure CLI token.
+**Goal:** Ensure PAC CLI is installed and authenticated, and verify the user is logged in to Azure CLI (scripts handle token acquisition internally).
### Actions
@@ -91,49 +90,40 @@ pac auth who
**If not authenticated**: Follow the same authentication flow as `deploy-site` — ask the user for their environment URL and run `pac auth create --environment "<URL>"`.
-#### 1.3 Resolve Power Platform API Base URL
+#### 1.3 Verify Azure CLI Login
-Map the **Cloud** value from `pac auth who` to the correct Power Platform API base URL. **CRITICAL: Never hardcode the base URL — always derive it from the Cloud value.**
-
-| Cloud value | PP API Base URL |
-|---|---|
-| `Public` | `https://api.powerplatform.com` |
-| `UsGov` | `https://api.gov.powerplatform.microsoft.us` |
-| `UsGovHigh` | `https://api.high.powerplatform.microsoft.us` |
-| `UsGovDod` | `https://api.appsplatform.us` |
-| `China` | `https://api.powerplatform.partner.microsoftonline.cn` |
-
-Store the resolved URL as `$ppApiBaseUrl`.
-
-#### 1.4 Acquire Azure CLI Token
-
-Get an access token scoped to the Power Platform API base URL:
+Verify the user is logged in to Azure CLI (the activation scripts acquire tokens internally):
```powershell
-$token = az account get-access-token --resource "$ppApiBaseUrl" --query accessToken -o tsv
+az account show
```
**If `az` is not installed or not logged in**: Instruct the user to install Azure CLI and run `az login`.
-#### 1.5 Verify Token
+#### 1.4 Check If Already Activated
-Make a lightweight GET to verify the token works:
+Before gathering parameters, check whether the site is already activated by running the shared activation status script:
```powershell
-$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }
-Invoke-RestMethod -Uri "$ppApiBaseUrl/powerpages/environments/$environmentId/websites?api-version=2022-03-01-preview" -Headers $headers
+node "${CLAUDE_PLUGIN_ROOT}/scripts/check-activation-status.js" --projectRoot "<PROJECT_ROOT>"
```
-**If 401/403**: The token may not have the right scope. Ask the user to verify they have the Power Platform admin or website creator role.
+Where `<PROJECT_ROOT>` is the directory containing `powerpages.config.json` (use `Glob` with `**/powerpages.config.json` to locate it if not already known).
-**If successful**: Proceed to Phase 2.
+The script reads `siteName` from `powerpages.config.json`, looks up the `websiteRecordId` via `pac pages list`, queries the Power Platform GET websites API, and matches the response against **both** the `websiteRecordId` (exact GUID match) and `name` (case-insensitive). It outputs a JSON result to stdout.
+
+Evaluate the result:
+
+- **If `activated` is `true`**: The site is already provisioned. Inform the user: "Your site **<siteName>** is already activated at **<websiteUrl>**. No further provisioning is needed." Suggest next steps (Phase 5.3) and stop — do NOT proceed to Phase 2.
+- **If `activated` is `false`**: Proceed to Phase 2.
+- **If `error` is present**: The check could not complete. Proceed to Phase 2 (do not block the activation flow due to a failed check).
### Output
- PAC CLI installed and authenticated
- Environment ID, Organization ID, and Cloud value extracted
-- `$ppApiBaseUrl` resolved from Cloud value
-- Azure CLI token acquired and verified
+- Azure CLI login confirmed
+- Activation status checked (already activated → stop early, not activated → continue)
---
@@ -209,7 +199,7 @@ Present all activation parameters to the user using `AskUserQuestion`:
| Question | Header | Options |
|----------|--------|---------|
-| Ready to activate your Power Pages site with these settings:\n\n- **Site name**: `<siteName>`\n- **Subdomain**: `<subdomain>.powerappsportals.com`\n- **Environment ID**: `<environmentId>`\n- **Template**: DefaultPortalTemplate\n- **Language**: English (1033)\n\nProceed with activation? | Activate | Yes, activate the site (Recommended), No, cancel |
+| Ready to activate your Power Pages site with these settings:\n\n- **Site name**: `<siteName>`\n- **Subdomain**: `<subdomain>.powerappsportals.com`\n- **Environment ID**: `<environmentId>`\n\nProceed with activation? | Activate | Yes, activate the site (Recommended), No, cancel |
**If "No"**: Stop the skill and inform the user they can re-run it later.
@@ -221,158 +211,76 @@ Present all activation parameters to the user using `AskUserQuestion`:
---
-## Phase 4: Activate
+## Phase 4: Activate & Poll
-**Goal:** POST to the Power Platform websites API to start provisioning and capture the Operation-Location header for polling.
+**Goal:** POST to the Power Platform websites API to start provisioning, poll until completion, and report the result.
### Actions
-#### 4.1 Refresh Token
+#### 4.1 Run Activation Script
-Re-acquire the Azure CLI token in case it has expired since Phase 1:
+Run the shared activation script, passing all parameters gathered in Phases 1–2:
```powershell
-$token = az account get-access-token --resource "$ppApiBaseUrl" --query accessToken -o tsv
-```
-
-#### 4.2 Build Request Body
-
-Construct the JSON body for the activation API call:
-
-```json
-{
- "name": "<siteName>",
- "subdomain": "<subdomain>",
- "templateName": "DefaultPortalTemplate",
- "dataverseOrganizationId": "<organizationId>",
- "selectedBaseLanguage": 1033,
- "websiteRecordId": "<websiteRecordId or null>"
-}
+node "${CLAUDE_PLUGIN_ROOT}/skills/activate-site/scripts/activate-site.js" --siteName "<siteName>" --subdomain "<subdomain>" --organizationId "<organizationId>" --environmentId "<environmentId>" --cloud "<cloud>" --websiteRecordId "<websiteRecordId>"
```
-If `websiteRecordId` is null/empty, **omit** the field from the body entirely (do not send `null`).
+Omit `--websiteRecordId` if it is null/empty.
-#### 4.3 POST to Websites API
+The script acquires an Azure CLI token, POSTs to the websites API, extracts the `Operation-Location` header, and polls every 10 seconds for up to 5 minutes (refreshing the token periodically). It outputs a JSON result to stdout.
-Use `Invoke-WebRequest` (NOT `Invoke-RestMethod`) to capture response headers — specifically the `Operation-Location` header needed for polling:
+> **Note:** This script may run for up to 5 minutes while polling. Use a Bash timeout of at least 360 seconds (6 minutes).
-```powershell
-$body = @{
- name = "$siteName"
- subdomain = "$subdomain"
- templateName = "DefaultPortalTemplate"
- dataverseOrganizationId = "$organizationId"
- selectedBaseLanguage = 1033
-} | ConvertTo-Json
-
-$response = Invoke-WebRequest -Method Post `
- -Uri "$ppApiBaseUrl/powerpages/environments/$environmentId/websites?api-version=2022-03-01-preview" `
- -Headers @{ Authorization = "Bearer $token"; "Content-Type" = "application/json"; Accept = "application/json" } `
- -Body $body
-
-$response.StatusCode
-$response.Headers["Operation-Location"]
-```
+#### 4.2 Handle Results
-Add the `websiteRecordId` field to the `$body` hashtable only if it is not null.
+Evaluate the JSON output:
-#### 4.4 Handle Responses
-
-| Status Code | Meaning | Action |
+| `status` value | `statusCode` / `errorCode` | Action |
|---|---|---|
-| **202 Accepted** | Provisioning started | Extract `Operation-Location` header, proceed to Phase 5 |
-| **400 Bad Request** | Likely subdomain already taken | Parse error message. If subdomain conflict, loop back to Phase 2 action 2.2 for a new subdomain |
-| **401 Unauthorized** | Token expired or invalid | Refresh token and retry once |
-| **403 Forbidden** | Insufficient permissions | Inform user they need the "Power Pages site creator" or "System Administrator" role |
-| **409 Conflict** | Website already exists | Inform user a site already exists in this environment and suggest using `/power-pages:deploy-site` instead |
-| **429 / 5xx** | Throttling or server error | Wait 5 seconds and retry once |
+| **`Succeeded`** | — | Provisioning complete. The result includes `siteUrl`. Proceed to Phase 5. |
+| **`Failed`** | `400` + `SubdomainConflict` (or error message mentions subdomain) | Subdomain already taken. Loop back to Phase 2 action 2.2 for a new subdomain, then re-run the script. |
+| **`Failed`** | `401` | Token expired. Ask the user to run `az login` and retry. |
+| **`Failed`** | `403` | Insufficient permissions. Inform user they need the "Power Pages site creator" or "System Administrator" role. |
+| **`Failed`** | `409` | Website already exists. Inform user and suggest using `/power-pages:deploy-site` instead. |
+| **`Failed`** | `429` or `5xx` | Throttling or server error. Wait 5 seconds and re-run the script once. |
+| **`Failed`** | other | Present the error to the user and help troubleshoot. |
+| **`Running`** | — | Provisioning still in progress after 5 minutes. Inform the user it may take up to 15 minutes and suggest checking the Power Platform admin center. |
+| `error` field | — | Prerequisite failure (missing args, no token). Present the error and help troubleshoot. |
### Output
-- API returned 202 Accepted
-- `Operation-Location` URL captured for polling
+- Provisioning status resolved (Succeeded with `siteUrl`, Failed with error details, or Running with timeout advisory)
---
-## Phase 5: Poll Status
-
-**Goal:** Poll the provisioning operation until it succeeds, fails, or times out.
-
-### Actions
-
-#### 5.1 Poll Operation-Location
-
-The `Operation-Location` header from Phase 4 contains a URL to poll for provisioning status. Poll every 10 seconds for up to 5 minutes (30 polls max):
-
-```powershell
-$operationUrl = $response.Headers["Operation-Location"]
-$maxAttempts = 30
-$attempt = 0
-
-do {
- Start-Sleep -Seconds 10
- $attempt++
-
- # Refresh token every ~60 seconds (every 6 polls)
- if ($attempt % 6 -eq 0) {
- $token = az account get-access-token --resource "$ppApiBaseUrl" --query accessToken -o tsv
- }
-
- $status = Invoke-RestMethod -Uri $operationUrl -Headers @{ Authorization = "Bearer $token"; Accept = "application/json" }
- $status.status
-} while ($status.status -eq "Running" -and $attempt -lt $maxAttempts)
-```
-
-#### 5.2 Handle Poll Results
-
-| Status | Action |
-|---|---|
-| **Succeeded** | Provisioning complete — proceed to Phase 6 |
-| **Failed** | Report the error from `$status.error` to the user. Suggest checking the Power Platform admin center for details. |
-| **Running (timeout)** | After 5 minutes, inform the user that provisioning is still in progress. It may take up to 15 minutes. Suggest they check the Power Platform admin center for status. |
-
-### Output
-
-- Provisioning status resolved (Succeeded, Failed, or Running with timeout advisory)
-
----
-
-## Phase 6: Present Summary
+## Phase 5: Present Summary
**Goal:** Show the user the final site URL and suggest next steps.
### Actions
-#### 6.1 Show Results
+#### 5.1 Show Results
-Present the activation summary to the user:
+Present the activation summary using the `siteUrl` from the script output:
```
Power Pages site activated successfully!
Site Name: <siteName>
- Site URL: https://<subdomain>.powerappsportals.com
+ Site URL: <siteUrl>
Environment: <environmentName> (<environmentId>)
Status: Provisioned
```
-**Note:** The site URL domain varies by cloud:
-
-| Cloud | Site URL Domain |
-|---|---|
-| `Public` | `powerappsportals.com` |
-| `UsGov` | `powerappsportals.us` |
-| `UsGovHigh` | `high.powerappsportals.us` |
-| `UsGovDod` | `appsplatform.us` |
-| `China` | `powerappsportals.cn` |
+The script already resolves the correct cloud-specific site URL domain, so use the `siteUrl` value directly.
-#### 6.2 Record Skill Usage
+#### 5.2 Record Skill Usage
> Reference: `${CLAUDE_PLUGIN_ROOT}/references/skill-tracking-reference.md`
Follow the skill tracking instructions in the reference to record this skill's usage. Use `--skillName "ActivateSite"`.
-#### 6.3 Suggest Next Steps
+#### 5.3 Suggest Next Steps
After the summary, suggest:
- Set up the data model: `/power-pages:setup-datamodel`
@@ -381,7 +289,7 @@ After the summary, suggest:
### Output
-- Activation summary presented with correct cloud-specific site URL
+- Activation summary presented with site URL
- Next steps suggested to the user
---
@@ -394,22 +302,22 @@ Use `TaskCreate` at the start to track progress through each phase:
| Task | Description |
|------|-------------|
-| Phase 1 | Verify Prerequisites — PAC CLI auth, Cloud detection, API base URL, Azure CLI token |
+| Phase 1 | Verify Prerequisites — PAC CLI auth, Cloud detection, Azure CLI login, activation status check |
| Phase 2 | Gather Parameters — site name, subdomain, website record ID |
| Phase 3 | Confirm — user approval of activation parameters |
-| Phase 4 | Activate — POST to websites API, capture Operation-Location |
-| Phase 5 | Poll Status — poll provisioning until completion |
-| Phase 6 | Present Summary — show site URL and next steps |
+| Phase 4 | Activate & Poll — run activation script, handle result |
+| Phase 5 | Present Summary — show site URL and next steps |
Mark each task complete with `TaskUpdate` as you finish each phase.
### Key Decision Points
- **Phase 1.2**: If not authenticated, must authenticate before proceeding — cannot skip.
+- **Phase 1.4**: If site is already activated, stop early — do NOT proceed to Phase 2.
- **Phase 2.2**: User may accept the generated subdomain or provide a custom one — validate custom input.
- **Phase 3**: User must explicitly approve activation. If declined, stop the skill entirely.
-- **Phase 4.4**: On 400 (subdomain taken), loop back to Phase 2 action 2.2 — do not abort.
-- **Phase 4.4**: On 409 (site already exists), redirect user to `/power-pages:deploy-site` instead.
-- **Phase 5.2**: On timeout (still Running after 5 minutes), do not treat as failure — advise user to check admin center.
+- **Phase 4.2**: On 400 (subdomain taken), loop back to Phase 2 action 2.2 and re-run the script — do not abort.
+- **Phase 4.2**: On 409 (site already exists), redirect user to `/power-pages:deploy-site` instead.
+- **Phase 4.2**: On timeout (still Running after 5 minutes), do not treat as failure — advise user to check admin center.
**Begin with Phase 1: Verify Prerequisites**
diff --git a/plugins/power-pages/skills/activate-site/scripts/activate-site.js b/plugins/power-pages/skills/activate-site/scripts/activate-site.js
new file mode 100644
index 000000000..bb3611489
--- /dev/null
+++ b/plugins/power-pages/skills/activate-site/scripts/activate-site.js
@@ -0,0 +1,196 @@
+#!/usr/bin/env node
+
+// Activates (provisions) a Power Pages site via the Power Platform websites API.
+// Handles the POST request, polls the Operation-Location header for status, and
+// refreshes the Azure CLI token during long polling cycles.
+//
+// Usage:
+// node activate-site.js --siteName "My Site" --subdomain "my-site" --organizationId "<guid>" --environmentId "<guid>" --cloud "Public" [--websiteRecordId "<guid>"]
+//
+// Output (JSON to stdout):
+// { "status": "Succeeded", "siteUrl": "https://...", "siteName": "...", "subdomain": "..." }
+// { "status": "Failed", "statusCode": 400, "errorCode": "SubdomainConflict", "error": "..." }
+// { "status": "Running", "message": "Provisioning still in progress after 5 minutes" }
+// { "error": "..." } — when prerequisites are missing or unexpected errors occur
+
+const { getAuthToken, makeRequest, CLOUD_TO_API, CLOUD_TO_SITE_DOMAIN } = require('../../../scripts/lib/validation-helpers');
+
+// --- Helpers ---
+
+function output(obj) {
+ process.stdout.write(JSON.stringify(obj));
+ process.exit(0);
+}
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function parseArgs(argv) {
+ const args = {};
+ const keys = ['--siteName', '--subdomain', '--organizationId', '--environmentId', '--cloud', '--websiteRecordId'];
+ for (const key of keys) {
+ const idx = argv.indexOf(key);
+ if (idx !== -1 && idx + 1 < argv.length) {
+ args[key.replace('--', '')] = argv[idx + 1];
+ }
+ }
+ return args;
+}
+
+// --- Parse arguments ---
+
+const args = parseArgs(process.argv.slice(2));
+
+if (!args.siteName) output({ error: 'Missing required argument: --siteName' });
+if (!args.subdomain) output({ error: 'Missing required argument: --subdomain' });
+if (!args.organizationId) output({ error: 'Missing required argument: --organizationId' });
+if (!args.environmentId) output({ error: 'Missing required argument: --environmentId' });
+
+const cloud = args.cloud || 'Public';
+const ppApiBaseUrl = CLOUD_TO_API[cloud] || CLOUD_TO_API['Public'];
+const siteDomain = CLOUD_TO_SITE_DOMAIN[cloud] || CLOUD_TO_SITE_DOMAIN['Public'];
+const siteUrl = `https://${args.subdomain}.${siteDomain}`;
+
+// --- Acquire token ---
+
+let token = getAuthToken(ppApiBaseUrl);
+if (!token) {
+ output({ error: 'Azure CLI token not available. Run "az login" first.' });
+}
+
+// --- Build request body ---
+
+const body = {
+ name: args.siteName,
+ subdomain: args.subdomain,
+ templateName: 'DefaultPortalTemplate',
+ dataverseOrganizationId: args.organizationId,
+ selectedBaseLanguage: 1033,
+};
+if (args.websiteRecordId) {
+ body.websiteRecordId = args.websiteRecordId;
+}
+
+// --- POST to websites API and poll for completion ---
+
+const apiUrl = `${ppApiBaseUrl}/powerpages/environments/${args.environmentId}/websites?api-version=2022-03-01-preview`;
+
+(async () => {
+ const postResult = await makeRequest({
+ method: 'POST',
+ url: apiUrl,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ body: JSON.stringify(body),
+ includeHeaders: true,
+ timeout: 30000,
+ });
+
+ if (postResult.error) {
+ output({ error: `POST request failed: ${postResult.error}` });
+ }
+
+ const statusCode = postResult.statusCode;
+
+ // --- Handle non-202 responses ---
+
+ if (statusCode !== 202) {
+ let errorCode = null;
+ let errorMessage = postResult.body || 'Unknown error';
+
+ try {
+ const parsed = JSON.parse(postResult.body);
+ errorCode = parsed.error?.code || parsed.code || null;
+ errorMessage = parsed.error?.message || parsed.message || errorMessage;
+ } catch {
+ // Body is not JSON, use raw
+ }
+
+ output({
+ status: 'Failed',
+ statusCode,
+ errorCode,
+ error: errorMessage,
+ });
+ }
+
+ // --- 202 Accepted: extract Operation-Location and poll ---
+
+ const operationLocation = postResult.headers?.['operation-location'] || null;
+
+ if (!operationLocation) {
+ output({ error: 'POST returned 202 but no Operation-Location header was found' });
+ }
+
+ // Ensure the poll URL includes api-version (some endpoints omit it from Operation-Location)
+ let pollUrl = operationLocation;
+ if (pollUrl && !pollUrl.includes('api-version')) {
+ pollUrl += (pollUrl.includes('?') ? '&' : '?') + 'api-version=2022-03-01-preview';
+ }
+
+ const maxAttempts = 30; // 30 × 10s = 5 minutes
+ const pollIntervalMs = 10000;
+ const tokenRefreshEvery = 6; // refresh every ~60s
+
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ await sleep(pollIntervalMs);
+
+ // Refresh token periodically
+ if (attempt % tokenRefreshEvery === 0) {
+ const refreshed = getAuthToken(ppApiBaseUrl);
+ if (refreshed) token = refreshed;
+ }
+
+ let pollStatus;
+ try {
+ const pollResult = await makeRequest({
+ url: pollUrl,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/json',
+ },
+ timeout: 15000,
+ });
+ if (pollResult.error || !pollResult.body) continue;
+ pollStatus = JSON.parse(pollResult.body);
+ } catch {
+ // Single poll failure — continue to next attempt
+ continue;
+ }
+
+ const status = pollStatus.operationStatus || pollStatus.status || pollStatus.Status;
+
+ if (status === 'OperationComplete') {
+ output({
+ status: 'Succeeded',
+ siteUrl: pollStatus.websiteUrl || siteUrl,
+ siteName: args.siteName,
+ subdomain: args.subdomain,
+ });
+ }
+
+ if (status === 'OperationFailed') {
+ const errMsg = pollStatus.error?.message || pollStatus.Error?.message || JSON.stringify(pollStatus);
+ output({
+ status: 'Failed',
+ statusCode: 200,
+ error: `Provisioning failed: ${errMsg}`,
+ });
+ }
+
+ // "OperationInProgress" / "OperationNotStarted" — continue polling
+ }
+
+ // Timed out
+ output({
+ status: 'Running',
+ message: 'Provisioning still in progress after 5 minutes. Check the Power Platform admin center for status.',
+ siteUrl,
+ siteName: args.siteName,
+ subdomain: args.subdomain,
+ });
+})();
diff --git a/plugins/power-pages/skills/activate-site/scripts/validate-activation.js b/plugins/power-pages/skills/activate-site/scripts/validate-activation.js
index d024b7b3d..b708f1659 100644
--- a/plugins/power-pages/skills/activate-site/scripts/validate-activation.js
+++ b/plugins/power-pages/skills/activate-site/scripts/validate-activation.js
@@ -2,54 +2,41 @@
// Validates Power Pages site activation output.
// Runs as a Stop hook to verify the website was provisioned in the environment.
-// Calls the Power Platform GET Websites API to check if the site exists.
+// Calls the shared check-activation-status.js script to query the Power Platform API
+// instead of relying on an intermediate file.
-const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
-const { approve, block, runValidation, findPath, getAuthToken, getPacAuthInfo, CLOUD_TO_API } = require('../../../scripts/lib/validation-helpers');
+const { approve, block, runValidation, findPath } = require('../../../scripts/lib/validation-helpers');
-runValidation((cwd) => {
+runValidation(async (cwd) => {
const configPath = findPath(cwd, 'powerpages.config.json');
if (!configPath) approve(); // Not a Power Pages project, skip
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
- const siteName = config.siteName;
- if (!siteName) approve();
+ const projectRoot = path.dirname(configPath);
+ const checkScript = path.resolve(__dirname, '../../../scripts/check-activation-status.js');
- const pacInfo = getPacAuthInfo();
- if (!pacInfo) approve(); // PAC CLI not authenticated, don't block
-
- const ppApiBaseUrl = CLOUD_TO_API[pacInfo.cloud] || CLOUD_TO_API['Public'];
-
- const token = getAuthToken(ppApiBaseUrl);
- if (!token) approve(); // Auth not available, don't block
-
- const websites = getWebsites(ppApiBaseUrl, token, pacInfo.environmentId);
- if (websites === null) approve(); // API call failed, don't block
+ let result;
+ try {
+ const output = execSync(`node "${checkScript}" --projectRoot "${projectRoot}"`, {
+ encoding: 'utf8',
+ timeout: 30000,
+ });
+ result = JSON.parse(output);
+ } catch {
+ approve(); // Auth/transient failure — don't block
+ }
- const found = websites.some(
- (w) => w.name && w.name.toLowerCase() === siteName.toLowerCase()
- );
+ if (result.activated === true) {
+ approve();
+ }
- if (!found) {
+ if (result.activated === false) {
block(
- `Power Pages activation validation failed:\n- Website "${siteName}" not found in environment ${pacInfo.environmentId}. The site may not have been provisioned successfully.`
+ `Power Pages activation validation failed:\n- Site '${result.siteName || 'unknown'}' is not activated. The site may not have been provisioned successfully.`
);
}
+ // Error or unexpected shape — don't block
approve();
});
-
-function getWebsites(ppApiBaseUrl, token, environmentId) {
- try {
- const output = execSync(
- `powershell -NoProfile -Command "(Invoke-RestMethod -Uri '${ppApiBaseUrl}/powerpages/environments/${environmentId}/websites?api-version=2022-03-01-preview' -Headers @{ Authorization = 'Bearer ${token}'; Accept = 'application/json' }).value | ConvertTo-Json -Compress"`,
- { encoding: 'utf8', timeout: 15000 }
- );
- const parsed = JSON.parse(output.trim());
- return Array.isArray(parsed) ? parsed : [parsed];
- } catch {
- return null;
- }
-}
diff --git a/plugins/power-pages/skills/create-site/SKILL.md b/plugins/power-pages/skills/create-site/SKILL.md
index 2c77259bb..227de2302 100644
--- a/plugins/power-pages/skills/create-site/SKILL.md
+++ b/plugins/power-pages/skills/create-site/SKILL.md
@@ -1,5 +1,5 @@
---
-name: create-power-pages-site
+name: create-site
description: This skill should be used when the user asks to "create a power pages site", "build a code site", "scaffold a website", "create a portal", "make a new site", or wants to create a new Power Pages code site (SPA) using React, Angular, Vue, or Astro.
user-invocable: true
argument-hint: Optional site description
@@ -52,11 +52,12 @@ Guide the user through creating a complete, production-quality Power Pages code
| Which frontend framework? | Framework | React (Recommended), Vue, Angular, Astro |
| What is the site's purpose? | Purpose | Company Portal, Blog/Content, Dashboard, Landing Page |
| Who is the target audience? | Audience | Internal (employees, partners), External (public-facing customers) |
- | Where should the project be created? | Location | Current Directory, New folder in current directory (Recommended), Choose a different directory |
+ | Where should the project be created? | Location | Current directory, New folder in current directory (Recommended), Any other directory |
4. Resolve the project location:
+ - **If "Current directory"**: Project root = `<cwd>`.
- **If "New folder in current directory"**: Create a folder named `__SITE_NAME__` inside the cwd. Project root = `<cwd>/__SITE_NAME__/`.
- - **If "Choose a different directory"**: Ask for the full path. Verify/create it. Project root = provided path.
+ - **If "Any other directory"**: Ask for the full path. Verify/create it. Project root = provided path.
After resolving, confirm: "The site will be created at `<resolved path>`."
diff --git a/plugins/power-pages/skills/deploy-site/SKILL.md b/plugins/power-pages/skills/deploy-site/SKILL.md
index e2f2f1d27..6f275d876 100644
--- a/plugins/power-pages/skills/deploy-site/SKILL.md
+++ b/plugins/power-pages/skills/deploy-site/SKILL.md
@@ -1,5 +1,5 @@
---
-name: deploy-power-pages-site
+name: deploy-site
description: This skill should be used when the user asks to "deploy to power pages", "upload site", "publish site", "deploy site", "push to power pages", "upload code site", or wants to deploy/upload an existing Power Pages code site to a Power Pages environment using PAC CLI.
user-invocable: true
allowed-tools: ["Read", "Bash", "AskUserQuestion", "Glob", "Grep", "TaskCreate", "TaskUpdate", "TaskList"]
@@ -222,35 +222,23 @@ git commit -m "Deploy site to Power Pages"
### 5.5 Check Activation Status
-Before asking about activation, check whether the site is already activated by querying the Power Platform websites API. This avoids prompting the user unnecessarily when the site is already live.
+Before asking about activation, check whether the site is already activated by running the shared activation status script. This avoids prompting the user unnecessarily when the site is already live.
-#### 5.5.1 Resolve API Base URL
-
-Map the **Cloud** value extracted from `pac auth who` (Phase 2) to the Power Platform API base URL:
-
-| Cloud value | PP API Base URL |
-|---|---|
-| `Public` | `https://api.powerplatform.com` |
-| `UsGov` | `https://api.gov.powerplatform.microsoft.us` |
-| `UsGovHigh` | `https://api.high.powerplatform.microsoft.us` |
-| `UsGovDod` | `https://api.appsplatform.us` |
-| `China` | `https://api.powerplatform.partner.microsoftonline.cn` |
-
-#### 5.5.2 Query Websites API
-
-Attempt to acquire an Azure CLI token and call the GET websites API:
+Run the check-activation-status script, passing the project root (determined in Phase 4.1):
```powershell
-$token = az account get-access-token --resource "$ppApiBaseUrl" --query accessToken -o tsv
-$headers = @{ Authorization = "Bearer $token"; Accept = "application/json" }
-$websites = Invoke-RestMethod -Uri "$ppApiBaseUrl/powerpages/environments/$environmentId/websites?api-version=2022-03-01-preview" -Headers $headers
+node "${CLAUDE_PLUGIN_ROOT}/scripts/check-activation-status.js" --projectRoot "<PROJECT_ROOT>"
```
-- **If the API call succeeds and the response contains one or more websites**: The site is already activated. Inform the user: "Your site is already activated — no further provisioning needed." Skip to [Suggest Next Steps](#suggest-next-steps). Do NOT ask about activation.
-- **If the API call succeeds but the response is empty (no websites returned)**: The site is not yet activated. Proceed to step 5.5.3.
-- **If the API call fails** (Azure CLI not installed, not logged in, token error, or any other failure): Fall back to step 5.5.3. Do not block the deployment flow due to a failed activation check.
+The script reads `siteName` from `powerpages.config.json`, looks up the `websiteRecordId` via `pac pages list`, queries the Power Platform GET websites API, and matches the response against **both** the `websiteRecordId` (exact GUID match) and `name` (case-insensitive). It outputs a JSON result to stdout.
+
+Evaluate the result:
+
+- **If `activated` is `true`**: This site is already activated. Inform the user: "Your site **<siteName>** is already activated — no further provisioning needed." If the result includes a `websiteUrl`, show it to the user. Skip to [Suggest Next Steps](#suggest-next-steps). Do NOT ask about activation.
+- **If `activated` is `false`**: This site is not yet activated. Proceed to step 5.5.1.
+- **If `error` is present**: The check could not complete (e.g., Azure CLI not installed, PAC CLI not authenticated, config not found). Fall back to step 5.5.1. Do not block the deployment flow due to a failed activation check.
-#### 5.5.3 Ask About Activation (only if site is NOT already activated)
+#### 5.5.1 Ask About Activation (only if site is NOT already activated)
Ask the user if they want to activate the site using `AskUserQuestion`:
diff --git a/plugins/power-pages/skills/setup-datamodel/scripts/validate-datamodel.js b/plugins/power-pages/skills/setup-datamodel/scripts/validate-datamodel.js
index ca9a40612..0e7f2d78f 100644
--- a/plugins/power-pages/skills/setup-datamodel/scripts/validate-datamodel.js
+++ b/plugins/power-pages/skills/setup-datamodel/scripts/validate-datamodel.js
@@ -7,10 +7,9 @@
const fs = require('fs');
const path = require('path');
-const { execSync } = require('child_process');
-const { approve, block, runValidation, findPath, getAuthToken, getEnvironmentUrl } = require('../../../scripts/lib/validation-helpers');
+const { approve, block, runValidation, findPath, getAuthToken, makeRequest, getEnvironmentUrl } = require('../../../scripts/lib/validation-helpers');
-runValidation((cwd) => {
+runValidation(async (cwd) => {
const manifestPath = findPath(cwd, '.datamodel-manifest.json');
if (!manifestPath) approve(); // Not a data model session, skip
@@ -26,14 +25,14 @@ runValidation((cwd) => {
const errors = [];
for (const table of manifest.tables) {
- const tableExists = checkTableExists(envUrl, token, table.logicalName);
+ const tableExists = await checkTableExists(envUrl, token, table.logicalName);
if (!tableExists) {
errors.push(`Missing table: ${table.logicalName} (${table.displayName || 'unknown'})`);
continue;
}
if (table.columns && table.columns.length > 0) {
- const existingColumns = getTableColumns(envUrl, token, table.logicalName);
+ const existingColumns = await getTableColumns(envUrl, token, table.logicalName);
for (const col of table.columns) {
if (!existingColumns.includes(col.logicalName)) {
errors.push(`Missing column: ${table.logicalName}.${col.logicalName}`);
@@ -49,25 +48,35 @@ runValidation((cwd) => {
approve();
});
-function checkTableExists(envUrl, token, logicalName) {
+async function checkTableExists(envUrl, token, logicalName) {
try {
- execSync(
- `powershell -NoProfile -Command "Invoke-RestMethod -Uri '${envUrl}/api/data/v9.2/EntityDefinitions(LogicalName=''${logicalName}'')' -Headers @{ Authorization = 'Bearer ${token}'; Accept = 'application/json' } | Out-Null"`,
- { encoding: 'utf8', timeout: 15000 }
- );
- return true;
+ const result = await makeRequest({
+ url: `${envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${logicalName}')`,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/json',
+ },
+ timeout: 15000,
+ });
+ return result.statusCode === 200;
} catch {
return false;
}
}
-function getTableColumns(envUrl, token, logicalName) {
+async function getTableColumns(envUrl, token, logicalName) {
try {
- const output = execSync(
- `powershell -NoProfile -Command "(Invoke-RestMethod -Uri '${envUrl}/api/data/v9.2/EntityDefinitions(LogicalName=''${logicalName}'')/Attributes?$select=LogicalName' -Headers @{ Authorization = 'Bearer ${token}'; Accept = 'application/json' }).value.LogicalName -join ',' "`,
- { encoding: 'utf8', timeout: 15000 }
- );
- return output.trim().split(',').filter(Boolean);
+ const result = await makeRequest({
+ url: `${envUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${logicalName}')/Attributes?$select=LogicalName`,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ Accept: 'application/json',
+ },
+ timeout: 15000,
+ });
+ if (result.error || result.statusCode !== 200) return [];
+ const parsed = JSON.parse(result.body);
+ return (parsed.value || []).map((a) => a.LogicalName).filter(Boolean);
} catch {
return [];
}